Afegint smart pointers

Actualitzat Resources
Actualitzades les classes Sprite i derivades
Afegida nova tipografia
Actualitzat Asset
Actualitzat Text
This commit is contained in:
2025-02-24 14:09:29 +01:00
parent 48971cd5d1
commit e6f101ece6
42 changed files with 2669 additions and 3158 deletions

BIN
data/font/8bithud.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

194
data/font/8bithud.txt Normal file
View File

@@ -0,0 +1,194 @@
# box width
8
# box height
8
# 32 espacio ( )
2
# 33 !
2
# 34 "
5
# 35 #
6
# 36 $
6
# 37 %
6
# 38 &
6
# 39 '
2
# 40 (
3
# 41 )
3
# 42 *
4
# 43 +
3
# 44 ,
2
# 45 -
3
# 46 .
2
# 47 /
4
# 48 0
6
# 49 1
6
# 50 2
6
# 51 3
6
# 52 4
6
# 53 5
6
# 54 6
6
# 55 7
6
# 56 8
6
# 57 9
6
# 58 :
2
# 59 ;
2
# 60 <
4
# 61 =
3
# 62 >
4
# 63 ?
6
# 64 @
8
# 65 A
6
# 66 B
6
# 67 C
6
# 68 D
6
# 69 E
6
# 70 F
6
# 71 G
6
# 72 H
6
# 73 I
6
# 74 J
6
# 75 K
6
# 76 L
6
# 77 M
6
# 78 N
6
# 79 O
6
# 80 P
6
# 81 Q
6
# 82 R
6
# 83 S
6
# 84 T
6
# 85 U
6
# 86 V
5
# 87 W
6
# 88 X
6
# 89 Y
6
# 90 Z
6
# 91 [
3
# 92 \
5
# 93 ]
3
# 94 ^
4
# 95 _
6
# 96 `
2
# 97 a
5
# 98 b
5
# 99 c
5
# 100 d
5
# 101 e
5
# 102 f
5
# 103 g
5
# 104 h
5
# 105 i
4
# 106 j
5
# 107 k
5
# 108 l
5
# 109 m
6
# 110 n
5
# 111 o
5
# 112 p
5
# 113 q
5
# 114 r
5
# 115 s
5
# 116 t
4
# 117 u
5
# 118 v
5
# 119 w
6
# 120 x
4
# 121 y
4
# 122 z
5
# 123 {
3
# 124 |
2
# 125 }
3
# 126 ~
3

250
source/animated_sprite.cpp Normal file
View File

@@ -0,0 +1,250 @@
#include "animated_sprite.h"
#include <stddef.h> // Para size_t
#include <fstream> // Para basic_ostream, basic_istream, operator<<, basic...
#include <iostream> // Para cout, cerr
#include <sstream> // Para basic_stringstream
#include <stdexcept> // Para runtime_error
#include "texture.h" // Para Texture
#include "utils.h" // Para printWithDots
// Carga las animaciones en un vector(Animations) desde un fichero
AnimationsFileBuffer loadAnimationsFromFile(const std::string &file_path)
{
std::ifstream file(file_path);
if (!file)
{
std::cerr << "Error: Fichero no encontrado " << file_path << std::endl;
throw std::runtime_error("Fichero no encontrado: " + file_path);
}
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))
{
if (!line.empty())
buffer.push_back(line);
}
return buffer;
}
// Constructor
AnimatedSprite::AnimatedSprite(std::shared_ptr<Texture> texture, const std::string &file_path)
: MovingSprite(texture)
{
// Carga las animaciones
if (!file_path.empty())
{
AnimationsFileBuffer v = loadAnimationsFromFile(file_path);
loadFromAnimationsFileBuffer(v);
}
}
// Constructor
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)
{
auto index = -1;
for (const auto &a : animations_)
{
index++;
if (a.name == name)
{
return index;
}
}
std::cout << "** Warning: could not find \"" << name.c_str() << "\" animation" << std::endl;
return -1;
}
// Calcula el frame correspondiente a la animación
void AnimatedSprite::animate()
{
if (animations_[current_animation_].speed == 0)
{
return;
}
// Calcula el frame actual a partir del contador
animations_[current_animation_].current_frame = animations_[current_animation_].counter / animations_[current_animation_].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 (animations_[current_animation_].current_frame >= (int)animations_[current_animation_].frames.size())
{
if (animations_[current_animation_].loop == -1)
{ // Si no hay loop, deja el último frame
animations_[current_animation_].current_frame = animations_[current_animation_].frames.size();
animations_[current_animation_].completed = true;
}
else
{ // Si hay loop, vuelve al frame indicado
animations_[current_animation_].counter = 0;
animations_[current_animation_].current_frame = animations_[current_animation_].loop;
}
}
// En caso contrario
else
{
// Escoge el frame correspondiente de la animación
setClip(animations_[current_animation_].frames[animations_[current_animation_].current_frame]);
// Incrementa el contador de la animacion
animations_[current_animation_].counter++;
}
}
// Comprueba si ha terminado la animación
bool AnimatedSprite::animationIsCompleted()
{
return animations_[current_animation_].completed;
}
// Establece la animacion actual
void AnimatedSprite::setCurrentAnimation(const std::string &name)
{
const auto new_animation = getIndex(name);
if (current_animation_ != new_animation)
{
current_animation_ = new_animation;
animations_[current_animation_].current_frame = 0;
animations_[current_animation_].counter = 0;
animations_[current_animation_].completed = false;
}
}
// Establece la animacion actual
void AnimatedSprite::setCurrentAnimation(int index)
{
const auto new_animation = index;
if (current_animation_ != new_animation)
{
current_animation_ = new_animation;
animations_[current_animation_].current_frame = 0;
animations_[current_animation_].counter = 0;
animations_[current_animation_].completed = false;
}
}
// Actualiza las variables del objeto
void AnimatedSprite::update()
{
animate();
MovingSprite::update();
}
// Reinicia la animación
void AnimatedSprite::resetAnimation()
{
animations_[current_animation_].current_frame = 0;
animations_[current_animation_].counter = 0;
animations_[current_animation_].completed = false;
}
// Carga la animación desde un vector de cadenas
void AnimatedSprite::loadFromAnimationsFileBuffer(const AnimationsFileBuffer &source)
{
int frame_width = 1;
int frame_height = 1;
int frames_per_row = 1;
int max_tiles = 1;
size_t index = 0;
while (index < source.size())
{
std::string line = source.at(index);
// Parsea el fichero para buscar variables y valores
if (line != "[animation]")
{
// Encuentra la posición del caracter '='
size_t pos = line.find("=");
// Procesa las dos subcadenas
if (pos != std::string::npos)
{
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;
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;
}
}
// Si la linea contiene el texto [animation] se realiza el proceso de carga de una animación
if (line == "[animation]")
{
Animation animation;
do
{
index++;
line = source.at(index);
size_t pos = line.find("=");
if (pos != std::string::npos)
{
std::string key = line.substr(0, pos);
std::string value = line.substr(pos + 1);
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(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);
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 " << key << std::endl;
}
} while (line != "[/animation]");
// Añade la animación al vector de animaciones
animations_.emplace_back(animation);
}
// Una vez procesada la linea, aumenta el indice para pasar a la siguiente
index++;
}
// Pone un valor por defecto
setWidth(frame_width);
setHeight(frame_height);
}

66
source/animated_sprite.h Normal file
View File

@@ -0,0 +1,66 @@
#pragma once
#include <SDL2/SDL_rect.h> // Para SDL_Rect
#include <memory> // Para shared_ptr
#include <string> // Para string
#include <vector> // Para vector
#include "moving_sprite.h" // Para MovingSprite
class Texture; // lines 9-9
struct Animation
{
std::string name; // Nombre de la animacion
std::vector<SDL_Rect> frames; // Cada uno de los frames que componen la animación
int speed; // Velocidad de la animación
int loop; // Indica a que frame vuelve la animación al terminar. -1 para que no vuelva
bool completed; // Indica si ha finalizado la animación
int current_frame; // Frame actual
int counter; // Contador para las animaciones
Animation() : name(std::string()), speed(5), loop(0), completed(false), current_frame(0), counter(0) {}
};
using AnimationsFileBuffer = std::vector<std::string>;
// Carga las animaciones en un vector(Animations) desde un fichero
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_ = 0; // Animacion activa
// Calcula el frame correspondiente a la animación actual
void animate();
// 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 AnimationsFileBuffer &animations);
explicit AnimatedSprite(std::shared_ptr<Texture> texture)
: MovingSprite(texture) {}
// Destructor
virtual ~AnimatedSprite() = default;
// Actualiza las variables del objeto
void update() override;
// Comprueba si ha terminado la animación
bool animationIsCompleted();
// Obtiene el indice de la animación a partir del nombre
int getIndex(const std::string &name);
// Establece la animacion actual
void setCurrentAnimation(const std::string &name = "default");
void setCurrentAnimation(int index = 0);
// Reinicia la animación
void resetAnimation();
};

View File

@@ -1,538 +0,0 @@
#include "animatedsprite.h"
#include <fstream> // Para basic_ostream, operator<<, basic_istream, basic...
#include <iostream> // Para cout
#include <sstream> // Para basic_stringstream
#include "texture.h" // Para Texture
// Carga la animación desde un fichero
animatedSprite_t loadAnimationFromFile(Texture *texture, std::string filePath, bool verbose)
{
// Inicializa variables
animatedSprite_t as;
as.texture = texture;
int framesPerRow = 0;
int frameWidth = 0;
int frameHeight = 0;
int maxTiles = 0;
const std::string filename = filePath.substr(filePath.find_last_of("\\/") + 1);
std::ifstream file(filePath);
std::string line;
// El fichero se puede abrir
if (file.good())
{
// Procesa el fichero linea a linea
if (verbose)
{
std::cout << "Animation loaded: " << filename << std::endl;
}
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;
buffer.counter = 0;
buffer.currentFrame = 0;
buffer.completed = false;
do
{
std::getline(file, line);
// Encuentra la posición del caracter '='
int pos = line.find("=");
// Procesa las dos subcadenas
if (pos != (int)line.npos)
{
if (line.substr(0, pos) == "name")
{
buffer.name = line.substr(pos + 1, line.length());
}
else if (line.substr(0, pos) == "speed")
{
buffer.speed = std::stoi(line.substr(pos + 1, line.length()));
}
else if (line.substr(0, pos) == "loop")
{
buffer.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, frameWidth, frameHeight};
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);
rect.x = (numTile % framesPerRow) * frameWidth;
rect.y = (numTile / framesPerRow) * frameHeight;
buffer.frames.push_back(rect);
}
}
else
{
std::cout << "Warning: file " << filename.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
as.animations.push_back(buffer);
}
// 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) == "framesPerRow")
{
framesPerRow = std::stoi(line.substr(pos + 1, line.length()));
}
else if (line.substr(0, pos) == "frameWidth")
{
frameWidth = std::stoi(line.substr(pos + 1, line.length()));
}
else if (line.substr(0, pos) == "frameHeight")
{
frameHeight = std::stoi(line.substr(pos + 1, line.length()));
}
else
{
std::cout << "Warning: file " << filename.c_str() << "\n, unknown parameter \"" << line.substr(0, pos).c_str() << "\"" << std::endl;
}
// Normaliza valores
if (framesPerRow == 0 && frameWidth > 0)
{
framesPerRow = texture->getWidth() / frameWidth;
}
if (maxTiles == 0 && frameWidth > 0 && frameHeight > 0)
{
const int w = texture->getWidth() / frameWidth;
const int h = texture->getHeight() / frameHeight;
maxTiles = w * h;
}
}
}
}
// Cierra el fichero
file.close();
}
// El fichero no se puede abrir
else
{
if (verbose)
{
std::cout << "Warning: Unable to open " << filename.c_str() << " file" << std::endl;
}
}
return as;
}
// Constructor
AnimatedSprite::AnimatedSprite(Texture *texture, SDL_Renderer *renderer, std::string file, std::vector<std::string> *buffer)
{
// Copia los punteros
setTexture(texture);
setRenderer(renderer);
// Carga las animaciones
if (file != "")
{
animatedSprite_t as = loadAnimationFromFile(texture, file);
// Copia los datos de las animaciones
for (auto animation : as.animations)
{
this->animation.push_back(animation);
}
}
else if (buffer)
{
loadFromVector(buffer);
}
// Inicializa variables
currentAnimation = 0;
}
// Constructor
AnimatedSprite::AnimatedSprite(SDL_Renderer *renderer, animatedSprite_t *animation)
{
// Copia los punteros
setTexture(animation->texture);
setRenderer(renderer);
// Inicializa variables
currentAnimation = 0;
// Copia los datos de las animaciones
for (auto a : animation->animations)
{
this->animation.push_back(a);
}
}
// Destructor
AnimatedSprite::~AnimatedSprite()
{
for (auto &a : animation)
{
a.frames.clear();
}
animation.clear();
}
// Obtiene el indice de la animación a partir del nombre
int AnimatedSprite::getIndex(std::string name)
{
int index = -1;
for (auto a : animation)
{
index++;
if (a.name == name)
{
return index;
}
}
std::cout << "** Warning: could not find \"" << name.c_str() << "\" animation" << std::endl;
return -1;
}
// Calcula el frame correspondiente a la animación
void AnimatedSprite::animate()
{
if (!enabled_ || animation[currentAnimation].speed == 0)
{
return;
}
// Calcula el frame actual a partir del contador
animation[currentAnimation].currentFrame = animation[currentAnimation].counter / animation[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 (animation[currentAnimation].loop == -1)
{ // Si no hay loop, deja el último frame
animation[currentAnimation].currentFrame = animation[currentAnimation].frames.size();
animation[currentAnimation].completed = true;
}
else
{ // Si hay loop, vuelve al frame indicado
animation[currentAnimation].counter = 0;
animation[currentAnimation].currentFrame = animation[currentAnimation].loop;
}
}
// En caso contrario
else
{
// Escoge el frame correspondiente de la animación
setClip(animation[currentAnimation].frames[animation[currentAnimation].currentFrame]);
// Incrementa el contador de la animacion
animation[currentAnimation].counter++;
}
}
// Obtiene el numero de frames de la animación actual
int AnimatedSprite::getNumFrames()
{
return (int)animation[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())
{
num = 0;
}
// Cambia el valor de la variable
animation[currentAnimation].currentFrame = num;
animation[currentAnimation].counter = 0;
// Escoge el frame correspondiente de la animación
setClip(animation[currentAnimation].frames[animation[currentAnimation].currentFrame]);
}
// Establece el valor del contador
void AnimatedSprite::setAnimationCounter(std::string name, int num)
{
animation[getIndex(name)].counter = num;
}
// Establece la velocidad de una animación
void AnimatedSprite::setAnimationSpeed(std::string name, int speed)
{
animation[getIndex(name)].counter = speed;
}
// Establece la velocidad de una animación
void AnimatedSprite::setAnimationSpeed(int index, int speed)
{
animation[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;
}
// Establece si la animación se reproduce en bucle
void AnimatedSprite::setAnimationLoop(int index, int loop)
{
animation[index].loop = loop;
}
// Establece el valor de la variable
void AnimatedSprite::setAnimationCompleted(std::string name, bool value)
{
animation[getIndex(name)].completed = value;
}
// OLD - Establece el valor de la variable
void AnimatedSprite::setAnimationCompleted(int index, bool value)
{
animation[index].completed = value;
}
// Comprueba si ha terminado la animación
bool AnimatedSprite::animationIsCompleted()
{
return animation[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];
}
// Devuelve el rectangulo de una animación y frame concreto
SDL_Rect AnimatedSprite::getAnimationClip(int indexA, Uint8 indexF)
{
return animation[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;
// Indicador de éxito en el proceso
bool success = true;
std::string line;
// Recorre todo el vector
int 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_t buffer;
buffer.counter = 0;
buffer.currentFrame = 0;
buffer.completed = false;
do
{
// Aumenta el indice para leer la siguiente linea
index++;
line = source->at(index);
// Encuentra la posición del caracter '='
int pos = line.find("=");
// Procesa las dos subcadenas
if (pos != (int)line.npos)
{
if (line.substr(0, pos) == "name")
{
buffer.name = line.substr(pos + 1, line.length());
}
else if (line.substr(0, pos) == "speed")
{
buffer.speed = std::stoi(line.substr(pos + 1, line.length()));
}
else if (line.substr(0, pos) == "loop")
{
buffer.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, frameWidth, frameHeight};
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);
rect.x = (numTile % framesPerRow) * frameWidth;
rect.y = (numTile / framesPerRow) * frameHeight;
buffer.frames.push_back(rect);
}
}
else
{
std::cout << "Warning: unknown parameter " << line.substr(0, pos).c_str() << std::endl;
success = false;
}
}
} while (line != "[/animation]");
// Añade la animación al vector de animaciones
animation.push_back(buffer);
}
// 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) == "framesPerRow")
{
framesPerRow = std::stoi(line.substr(pos + 1, line.length()));
}
else if (line.substr(0, pos) == "frameWidth")
{
frameWidth = std::stoi(line.substr(pos + 1, line.length()));
}
else if (line.substr(0, pos) == "frameHeight")
{
frameHeight = 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 (framesPerRow == 0 && frameWidth > 0)
{
framesPerRow = texture_->getWidth() / frameWidth;
}
if (maxTiles == 0 && frameWidth > 0 && frameHeight > 0)
{
const int w = texture_->getWidth() / frameWidth;
const int h = texture_->getHeight() / frameHeight;
maxTiles = w * h;
}
}
}
// Una vez procesada la linea, aumenta el indice para pasar a la siguiente
index++;
}
// Pone un valor por defecto
setRect({0, 0, frameWidth, frameHeight});
return success;
}
// Establece la animacion actual
void AnimatedSprite::setCurrentAnimation(std::string name)
{
const int newAnimation = getIndex(name);
if (currentAnimation != newAnimation)
{
currentAnimation = newAnimation;
animation[currentAnimation].currentFrame = 0;
animation[currentAnimation].counter = 0;
animation[currentAnimation].completed = false;
}
}
// Establece la animacion actual
void AnimatedSprite::setCurrentAnimation(int index)
{
const int newAnimation = index;
if (currentAnimation != newAnimation)
{
currentAnimation = newAnimation;
animation[currentAnimation].currentFrame = 0;
animation[currentAnimation].counter = 0;
animation[currentAnimation].completed = false;
}
}
// Actualiza las variables del objeto
void AnimatedSprite::update()
{
animate();
MovingSprite::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});
}
// OLD - Establece el contador para todas las animaciones
void AnimatedSprite::setAnimationCounter(int value)
{
for (auto &a : animation)
{
a.counter = value;
}
}
// Reinicia la animación
void AnimatedSprite::resetAnimation()
{
animation[currentAnimation].currentFrame = 0;
animation[currentAnimation].counter = 0;
animation[currentAnimation].completed = false;
}

View File

@@ -1,98 +0,0 @@
#pragma once
#include <SDL2/SDL_rect.h> // Para SDL_Rect
#include <SDL2/SDL_render.h> // Para SDL_Renderer
#include <SDL2/SDL_stdinc.h> // Para Uint8
#include <string> // Para string
#include <vector> // Para vector
#include "movingsprite.h" // Para MovingSprite
class Texture;
struct animation_t
{
std::string name; // Nombre de la animacion
std::vector<SDL_Rect> frames; // Cada uno de los frames que componen la animación
int speed; // Velocidad de la animación
int loop; // Indica a que frame vuelve la animación al terminar. -1 para que no vuelva
bool completed; // Indica si ha finalizado la animación
int currentFrame; // Frame actual
int counter; // Contador para las animaciones
};
struct animatedSprite_t
{
std::vector<animation_t> animations; // Vector con las diferentes animaciones
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);
class AnimatedSprite : public MovingSprite
{
private:
// Variables
std::vector<animation_t> animation; // Vector con las diferentes animaciones
int currentAnimation; // Animacion activa
public:
// Constructor
AnimatedSprite(Texture *texture = nullptr, SDL_Renderer *renderer = nullptr, std::string file = "", std::vector<std::string> *buffer = nullptr);
AnimatedSprite(SDL_Renderer *renderer, animatedSprite_t *animation);
// Destructor
~AnimatedSprite();
// Calcula el frame correspondiente a la animación actual
void animate();
// Obtiene el numero de frames de la animación actual
int getNumFrames();
// Establece el frame actual de la animación
void setCurrentFrame(int num);
// Establece el valor del contador
void setAnimationCounter(std::string name, int num);
// Establece la velocidad de una animación
void setAnimationSpeed(std::string name, int speed);
void setAnimationSpeed(int index, int speed);
// Establece el frame al que vuelve la animación al finalizar
void setAnimationLoop(std::string name, int loop);
void setAnimationLoop(int index, int loop);
// Establece el valor de la variable
void setAnimationCompleted(std::string name, bool value);
void setAnimationCompleted(int index, bool value);
// Comprueba si ha terminado la animación
bool animationIsCompleted();
// Devuelve el rectangulo de una animación y frame concreto
SDL_Rect getAnimationClip(std::string name = "default", Uint8 index = 0);
SDL_Rect getAnimationClip(int indexA = 0, Uint8 indexF = 0);
// Obtiene el indice de la animación a partir del nombre
int getIndex(std::string name);
// Carga la animación desde un vector
bool loadFromVector(std::vector<std::string> *source);
// Establece la animacion actual
void setCurrentAnimation(std::string name = "default");
void setCurrentAnimation(int index = 0);
// Actualiza las variables del objeto
void update();
// OLD - Establece el rectangulo para un frame de una animación
void setAnimationFrames(Uint8 index_animation, Uint8 index_frame, int x, int y, int w, int h);
// OLD - Establece el contador para todas las animaciones
void setAnimationCounter(int value);
// Reinicia la animación
void resetAnimation();
};

View File

@@ -1,86 +1,77 @@
#include "asset.h" #include "asset.h"
#include <SDL2/SDL_rwops.h> // Para SDL_RWFromFile, SDL_RWclose, SDL_RWops #include <algorithm> // Para find_if, max
#include <SDL2/SDL_stdinc.h> // Para SDL_max #include <fstream> // Para basic_ostream, operator<<, basic_ifstream, endl
#include <stddef.h> // Para size_t #include <iostream> // Para cout
#include <iostream> // Para basic_ostream, operator<<, cout, endl #include <string> // Para allocator, char_traits, string, operator+, oper...
#include "utils.h" // Para getFileName, printWithDots
// [SINGLETON] Hay que definir las variables estáticas, desde el .h sólo la hemos declarado // [SINGLETON] Hay que definir las variables estáticas, desde el .h sólo la hemos declarado
Asset *Asset::asset_ = nullptr; Asset *Asset::asset_ = nullptr;
// [SINGLETON] Crearemos el objeto con esta función estática // [SINGLETON] Crearemos el objeto asset con esta función estática
void Asset::init(const std::string &executable_path) void Asset::init(const std::string &executable_path)
{ {
Asset::asset_ = new Asset(executable_path); Asset::asset_ = new Asset(executable_path);
} }
// [SINGLETON] Destruiremos el objeto con esta función estática // [SINGLETON] Destruiremos el objeto asset con esta función estática
void Asset::destroy() void Asset::destroy()
{ {
delete Asset::asset_; delete Asset::asset_;
} }
// [SINGLETON] Con este método obtenemos el objeto y podemos trabajar con él // [SINGLETON] Con este método obtenemos el objeto asset y podemos trabajar con él
Asset *Asset::get() Asset *Asset::get()
{ {
return Asset::asset_; return Asset::asset_;
} }
// Añade un elemento a la lista // Añade un elemento a la lista
void Asset::add(std::string file, enum assetType type, bool required, bool absolute) void Asset::add(const std::string &file, AssetType type, bool required, bool absolute)
{ {
item_t temp; file_list_.emplace_back(absolute ? file : executable_path_ + file, type, required);
temp.file = absolute ? file : executable_path_ + file; longest_name_ = std::max(longest_name_, static_cast<int>(file_list_.back().file.size()));
temp.type = type;
temp.required = required;
fileList.push_back(temp);
const std::string filename = file.substr(file.find_last_of("\\/") + 1);
longest_name_ = SDL_max(longest_name_, filename.size());
} }
// Devuelve el fichero de un elemento de la lista a partir de una cadena // Devuelve la ruta completa a un fichero a partir de una cadena
std::string Asset::get(std::string text) std::string Asset::get(const std::string &text) const
{ {
for (auto f : fileList) auto it = std::find_if(file_list_.begin(), file_list_.end(),
[&text](const auto &f)
{ {
const size_t lastIndex = f.file.find_last_of("/") + 1; return getFileName(f.file) == text;
const std::string file = f.file.substr(lastIndex, std::string::npos); });
if (file == text) if (it != file_list_.end())
{ {
return f.file; return it->file;
} }
} else
if (verbose_)
{ {
std::cout << "Warning: file " << text.c_str() << " not found" << std::endl; std::cout << "Warning: file " << text << " not found" << std::endl;
}
return ""; return "";
}
} }
// Comprueba que existen todos los elementos // Comprueba que existen todos los elementos
bool Asset::check() bool Asset::check() const
{ {
bool success = true; bool success = true;
if (verbose_) std::cout << "\n** CHECKING FILES" << std::endl;
{
std::cout << "\n** Checking files" << std::endl;
std::cout << "Executable path is: " << executable_path_ << std::endl; // std::cout << "Executable path is: " << executable_path_ << std::endl;
std::cout << "Sample filepath: " << fileList.back().file << std::endl; // std::cout << "Sample filepath: " << file_list_.back().file << std::endl;
}
// Comprueba la lista de ficheros clasificandolos por tipo // Comprueba la lista de ficheros clasificandolos por tipo
for (int type = 0; type < t_maxAssetType; ++type) for (int type = 0; type < static_cast<int>(AssetType::MAX_ASSET_TYPE); ++type)
{ {
// Comprueba si hay ficheros de ese tipo // Comprueba si hay ficheros de ese tipo
bool any = false; bool any = false;
for (auto f : fileList) for (const auto &f : file_list_)
{ {
if ((f.required) && (f.type == type)) if (f.required && f.type == static_cast<AssetType>(type))
{ {
any = true; any = true;
} }
@@ -89,107 +80,77 @@ bool Asset::check()
// Si hay ficheros de ese tipo, comprueba si existen // Si hay ficheros de ese tipo, comprueba si existen
if (any) if (any)
{ {
if (verbose_) std::cout << "\n>> " << getTypeName(static_cast<AssetType>(type)).c_str() << " FILES" << std::endl;
{
std::cout << "\n>> " << getTypeName(type).c_str() << " FILES" << std::endl;
}
for (auto f : fileList) for (const auto &f : file_list_)
{ {
if ((f.required) && (f.type == type)) if (f.required && f.type == static_cast<AssetType>(type))
{ {
success &= checkFile(f.file); success &= checkFile(f.file);
} }
} }
if (success)
std::cout << " All files are OK." << std::endl;
} }
} }
// Resultado // Resultado
if (verbose_) std::cout << (success ? "\n** CHECKING FILES COMPLETED.\n" : "\n** CHECKING FILES FAILED.\n") << std::endl;
{
if (success)
{
std::cout << "\n** All files OK.\n"
<< std::endl;
}
else
{
std::cout << "\n** A file is missing. Exiting.\n"
<< std::endl;
}
}
return success; return success;
} }
// Comprueba que existe un fichero // Comprueba que existe un fichero
bool Asset::checkFile(std::string path) bool Asset::checkFile(const std::string &path) const
{ {
bool success = false; std::ifstream file(path);
std::string result = "ERROR"; bool success = file.good();
file.close();
// Comprueba si existe el fichero if (!success)
const std::string filename = path.substr(path.find_last_of("\\/") + 1); printWithDots("Checking file : ", getFileName(path), "[ ERROR ]");
SDL_RWops *file = SDL_RWFromFile(path.c_str(), "rb");
if (file != nullptr)
{
result = "OK";
success = true;
SDL_RWclose(file);
}
if (verbose_)
{
std::cout.setf(std::ios::left, std::ios::adjustfield);
std::cout << "Checking file: ";
std::cout.width(longest_name_ + 2);
std::cout.fill('.');
std::cout << filename + " ";
std::cout << " [" + result + "]" << std::endl;
}
return success; return success;
} }
// Devuelve el nombre del tipo de recurso // Devuelve el nombre del tipo de recurso
std::string Asset::getTypeName(int type) std::string Asset::getTypeName(AssetType type) const
{ {
switch (type) switch (type)
{ {
case t_bitmap: case AssetType::BITMAP:
return "BITMAP"; return "BITMAP";
break; break;
case t_music: case AssetType::MUSIC:
return "MUSIC"; return "MUSIC";
break; break;
case t_sound: case AssetType::SOUND:
return "SOUND"; return "SOUND";
break; break;
case t_font: case AssetType::FONT:
return "FONT"; return "FONT";
break; break;
case t_lang: case AssetType::LANG:
return "LANG"; return "LANG";
break; break;
case t_data: case AssetType::DATA:
return "DATA"; return "DATA";
break; break;
case t_room: case AssetType::ANIMATION:
return "ROOM"; return "ANIMATION";
break; break;
case t_enemy: case AssetType::PALETTE:
return "ENEMY"; return "PALETTE";
break; break;
case t_item: case AssetType::ITEM:
return "ITEM"; return "ITEM";
break; break;
@@ -199,8 +160,18 @@ std::string Asset::getTypeName(int type)
} }
} }
// Establece si ha de mostrar texto por pantalla // Devuelve la lista de recursos de un tipo
void Asset::setVerbose(bool value) std::vector<std::string> Asset::getListByType(AssetType type) const
{ {
verbose_ = value; std::vector<std::string> list;
for (auto f : file_list_)
{
if (f.type == type)
{
list.push_back(f.file);
}
}
return list;
} }

View File

@@ -1,49 +1,52 @@
#pragma once #pragma once
#include <string> // Para string #include <string> // para string, basic_string
#include <vector> // Para vector #include <vector> // para vector
#include "utils.h" #include "utils.h"
enum assetType enum class AssetType : int
{ {
t_bitmap, BITMAP,
t_music, MUSIC,
t_sound, SOUND,
t_font, FONT,
t_lang, LANG,
t_data, DATA,
t_room, ROOM,
t_enemy, ENEMY,
t_item, ITEM,
t_maxAssetType MAX_ASSET_TYPE
}; };
// Clase Asset // Clase Asset
class Asset class Asset
{ {
private: private:
// [SINGLETON] Objeto asset privado // [SINGLETON] Objeto asset privado para Don Melitón
static Asset *asset_; static Asset *asset_;
// Estructura para definir un item // Estructura para definir un item
struct item_t struct AssetItem
{ {
std::string file; // Ruta del fichero desde la raiz del directorio std::string file; // Ruta del fichero desde la raíz del directorio
enum assetType type; // Indica el tipo de recurso AssetType type; // Indica el tipo de recurso
bool required; // Indica si es un fichero que debe de existir bool required; // Indica si es un fichero que debe de existir
// Constructor
AssetItem(const std::string &filePath, AssetType assetType, bool isRequired)
: file(filePath), type(assetType), required(isRequired) {}
}; };
// Variables // Variables
int longest_name_ = 0; // Contiene la longitud del nombre de fichero mas largo int longest_name_ = 0; // Contiene la longitud del nombre de fichero mas largo
std::vector<item_t> fileList; // Listado con todas las rutas a los ficheros std::vector<AssetItem> file_list_; // Listado con todas las rutas a los ficheros
std::string executable_path_; // Ruta al ejecutable std::string executable_path_; // Ruta al ejecutable
bool verbose_ = true; // Indica si ha de mostrar información por pantalla
// Comprueba que existe un fichero // Comprueba que existe un fichero
bool checkFile(std::string executablePath); bool checkFile(const std::string &path) const;
// Devuelve el nombre del tipo de recurso // Devuelve el nombre del tipo de recurso
std::string getTypeName(int type); std::string getTypeName(AssetType type) const;
// Constructor // Constructor
explicit Asset(const std::string &executable_path) explicit Asset(const std::string &executable_path)
@@ -63,14 +66,14 @@ public:
static Asset *get(); static Asset *get();
// Añade un elemento a la lista // Añade un elemento a la lista
void add(std::string file, enum assetType type, bool required = true, bool absolute = false); void add(const std::string &file, AssetType type, bool required = true, bool absolute = false);
// Devuelve un elemento de la lista a partir de una cadena // Devuelve la ruta completa a un fichero a partir de una cadena
std::string get(std::string text); std::string get(const std::string &text) const;
// Comprueba que existen todos los elementos // Comprueba que existen todos los elementos
bool check(); bool check() const;
// Establece si ha de mostrar texto por pantalla // Devuelve la lista de recursos de un tipo
void setVerbose(bool value); std::vector<std::string> getListByType(AssetType type) const;
}; };

View File

@@ -6,7 +6,7 @@
#include <SDL2/SDL_timer.h> // Para SDL_GetTicks #include <SDL2/SDL_timer.h> // Para SDL_GetTicks
#include <algorithm> // Para min #include <algorithm> // Para min
#include <iostream> // Para char_traits, basic_ostream, operator<< #include <iostream> // Para char_traits, basic_ostream, operator<<
#include "animatedsprite.h" // Para AnimatedSprite #include "animated_sprite.h" // Para AnimatedSprite
#include "const.h" // Para GAMECANVAS_HEIGHT, GAMECANVAS_WIDTH #include "const.h" // Para GAMECANVAS_HEIGHT, GAMECANVAS_WIDTH
#include "input.h" // Para Input, REPEAT_FALSE, inputs_e #include "input.h" // Para Input, REPEAT_FALSE, inputs_e
#include "resource.h" // Para Resource #include "resource.h" // Para Resource
@@ -27,13 +27,13 @@ Credits::Credits()
input_(Input::get()) input_(Input::get())
{ {
// Reserva memoria para los punteros // Reserva memoria para los punteros
text_ = new Text(resource_->getOffset("smb2.txt"), resource_->getTexture("smb2.png"), renderer_); text_ = resource_->getText("smb2.txt");
sprite_ = new AnimatedSprite(renderer_, resource_->getAnimation("shine.ani")); sprite_ = std::make_shared<AnimatedSprite>(resource_->getTexture("shine.png"), resource_->getAnimation("shine.ani"));
// Inicializa variables // Inicializa variables
options.section.section = Section::CREDITS; options.section.section = Section::CREDITS;
options.section.subsection = Subsection::NONE; options.section.subsection = Subsection::NONE;
sprite_->setRect({194, 174, 8, 8}); sprite_->setPosition({194, 174, 8, 8});
// Cambia el color del borde // Cambia el color del borde
screen_->setBorderColor(stringToColor(options.video.palette, "black")); screen_->setBorderColor(stringToColor(options.video.palette, "black"));
@@ -67,8 +67,6 @@ Credits::Credits()
// Destructor // Destructor
Credits::~Credits() Credits::~Credits()
{ {
delete text_;
delete sprite_;
SDL_DestroyTexture(text_texture_); SDL_DestroyTexture(text_texture_);
SDL_DestroyTexture(cover_texture_); SDL_DestroyTexture(cover_texture_);
} }
@@ -185,7 +183,7 @@ void Credits::fillTexture()
for (auto t : texts_) for (auto t : texts_)
{ {
text_->writeDX(TXT_CENTER | TXT_COLOR, PLAY_AREA_CENTER_X, i * size, t.label, 1, t.color); text_->writeDX(TEXT_CENTER | TEXT_COLOR, PLAY_AREA_CENTER_X, i * size, t.label, 1, t.color);
i++; i++;
} }

View File

@@ -5,6 +5,7 @@
#include <SDL2/SDL_stdinc.h> // Para Uint32 #include <SDL2/SDL_stdinc.h> // Para Uint32
#include <string> // Para basic_string, string #include <string> // Para basic_string, string
#include <vector> // Para vector #include <vector> // Para vector
#include <memory> // Para shared_ptr
#include "utils.h" // Para color_t #include "utils.h" // Para color_t
class AnimatedSprite; class AnimatedSprite;
class Asset; class Asset;
@@ -28,10 +29,10 @@ private:
Resource *resource_; // Objeto con los recursos Resource *resource_; // Objeto con los recursos
Asset *asset_; // Objeto con los ficheros de recursos Asset *asset_; // Objeto con los ficheros de recursos
Input *input_; // Objeto pata gestionar la entrada Input *input_; // Objeto pata gestionar la entrada
Text *text_; // Objeto para escribir texto en pantalla std::shared_ptr<Text> text_; // Objeto para escribir texto en pantalla
SDL_Texture *text_texture_; // Textura para dibujar el texto SDL_Texture *text_texture_; // Textura para dibujar el texto
SDL_Texture *cover_texture_; // Textura para cubrir el texto SDL_Texture *cover_texture_; // Textura para cubrir el texto
AnimatedSprite *sprite_; // Sprite para el brillo del corazón std::shared_ptr<AnimatedSprite> sprite_; // Sprite para el brillo del corazón
// Variables // Variables
int counter_ = 0; // Contador int counter_ = 0; // Contador

File diff suppressed because it is too large Load Diff

View File

@@ -30,9 +30,6 @@ private:
// Crea la carpeta del sistema donde guardar datos // Crea la carpeta del sistema donde guardar datos
void createSystemFolder(const std::string &folder); void createSystemFolder(const std::string &folder);
// Carga los recursos
void loadResources(SectionState section);
// Inicializa jail_audio // Inicializa jail_audio
void initJailAudio(); void initJailAudio();

View File

@@ -13,7 +13,7 @@
#include "resource.h" // Para Resource #include "resource.h" // Para Resource
#include "screen.h" // Para Screen #include "screen.h" // Para Screen
#include "sprite.h" // Para Sprite #include "sprite.h" // Para Sprite
#include "text.h" // Para Text, TXT_STROKE #include "text.h" // Para Text, TEXT_STROKE
#include "texture.h" // Para Texture #include "texture.h" // Para Texture
#include "utils.h" // Para color_t, stringToColor, options_t #include "utils.h" // Para color_t, stringToColor, options_t
#include "options.h" #include "options.h"
@@ -29,8 +29,8 @@ Ending::Ending()
input(Input::get()) input(Input::get())
{ {
// Reserva memoria para los punteros a objetos // Reserva memoria para los punteros a objetos
text = new Text(resource->getOffset("smb2.txt"), resource->getTexture("smb2.png"), renderer); text = resource->getText("smb2.txt");
music = JA_LoadMusic(asset->get("ending1.ogg").c_str()); music = resource->getMusic("ending1.ogg");
// Inicializa variables // Inicializa variables
counter = -1; counter = -1;
@@ -73,27 +73,7 @@ Ending::Ending()
Ending::~Ending() Ending::~Ending()
{ {
// Libera la memoria de los objetos // Libera la memoria de los objetos
delete text;
SDL_DestroyTexture(coverTexture); SDL_DestroyTexture(coverTexture);
for (auto st : spriteTexts)
{
delete st.sprite;
delete st.texture;
delete st.coverSprite;
delete st.coverTexture;
}
spriteTexts.clear();
for (auto sp : spritePics)
{
delete sp.sprite;
delete sp.coverSprite;
delete sp.coverTexture;
}
spritePics.clear();
JA_DeleteMusic(music);
} }
// Actualiza el objeto // Actualiza el objeto
@@ -206,13 +186,6 @@ void Ending::iniTexts()
texts.push_back({"WERE BORN...", 158}); texts.push_back({"WERE BORN...", 158});
// Crea los sprites // Crea los sprites
for (auto st : spriteTexts)
{
delete st.sprite;
delete st.texture;
delete st.coverSprite;
delete st.coverTexture;
}
spriteTexts.clear(); spriteTexts.clear();
for (auto t : texts) for (auto t : texts)
@@ -223,19 +196,19 @@ void Ending::iniTexts()
Color c = stringToColor(options.video.palette, "black"); Color c = stringToColor(options.video.palette, "black");
// Crea la texture // Crea la texture
st.texture = new Texture(renderer); st.texture = std::make_shared<Texture>(renderer);
st.texture->createBlank(renderer, width, height, SDL_TEXTUREACCESS_TARGET); st.texture->createBlank(width, height);
st.texture->setAsRenderTarget(renderer); st.texture->setAsRenderTarget(renderer);
st.texture->setBlendMode(SDL_BLENDMODE_BLEND); st.texture->setBlendMode(SDL_BLENDMODE_BLEND);
text->writeDX(TXT_STROKE, 2, 2, t.caption, 1, c, 2, c); text->writeDX(TEXT_STROKE, 2, 2, t.caption, 1, c, 2, c);
// Crea el sprite // Crea el sprite
st.sprite = new Sprite({0, 0, st.texture->getWidth(), st.texture->getHeight()}, st.texture, renderer); st.sprite = std::make_shared<Sprite>(st.texture, 0, 0, st.texture->getWidth(), st.texture->getHeight());
st.sprite->setPos({(GAMECANVAS_WIDTH - st.texture->getWidth()) / 2, t.pos}); st.sprite->setPosition((GAMECANVAS_WIDTH - st.texture->getWidth()) / 2, t.pos);
// Crea la coverTexture // Crea la coverTexture
st.coverTexture = new Texture(renderer); st.coverTexture = std::make_shared<Texture>(renderer);
st.coverTexture->createBlank(renderer, width, height + 8, SDL_TEXTUREACCESS_TARGET); st.coverTexture->createBlank(width, height + 8);
st.coverTexture->setAsRenderTarget(renderer); st.coverTexture->setAsRenderTarget(renderer);
st.coverTexture->setBlendMode(SDL_BLENDMODE_BLEND); st.coverTexture->setBlendMode(SDL_BLENDMODE_BLEND);
@@ -264,8 +237,8 @@ void Ending::iniTexts()
SDL_RenderFillRect(renderer, &rect); SDL_RenderFillRect(renderer, &rect);
// Crea el sprite // Crea el sprite
st.coverSprite = new Sprite({0, 0, st.coverTexture->getWidth(), st.coverTexture->getHeight() - 8}, st.coverTexture, renderer); st.coverSprite = std::make_shared<Sprite>(st.coverTexture, 0, 0, st.coverTexture->getWidth(), st.coverTexture->getHeight() - 8);
st.coverSprite->setPos({(GAMECANVAS_WIDTH - st.coverTexture->getWidth()) / 2, t.pos}); st.coverSprite->setPosition((GAMECANVAS_WIDTH - st.coverTexture->getWidth()) / 2, t.pos);
st.coverSprite->setClip(0, 8, -1, -1); st.coverSprite->setClip(0, 8, -1, -1);
// Inicializa variables // Inicializa variables
@@ -300,12 +273,6 @@ void Ending::iniPics()
} }
// Crea los sprites // Crea los sprites
for (auto sp : spritePics)
{
delete sp.sprite;
delete sp.coverSprite;
delete sp.coverTexture;
}
spritePics.clear(); spritePics.clear();
for (auto p : pics) for (auto p : pics)
@@ -318,12 +285,12 @@ void Ending::iniPics()
const int height = sp.texture->getHeight(); const int height = sp.texture->getHeight();
// Crea el sprite // Crea el sprite
sp.sprite = new Sprite({0, 0, width, height}, sp.texture, renderer); sp.sprite = std::make_shared<Sprite>(sp.texture, 0, 0, width, height);
sp.sprite->setPos({(GAMECANVAS_WIDTH - width) / 2, p.pos}); sp.sprite->setPosition((GAMECANVAS_WIDTH - width) / 2, p.pos);
// Crea la coverTexture // Crea la coverTexture
sp.coverTexture = new Texture(renderer); sp.coverTexture = std::make_shared<Texture>(renderer);
sp.coverTexture->createBlank(renderer, width, height + 8, SDL_TEXTUREACCESS_TARGET); sp.coverTexture->createBlank(width, height + 8);
sp.coverTexture->setAsRenderTarget(renderer); sp.coverTexture->setAsRenderTarget(renderer);
sp.coverTexture->setBlendMode(SDL_BLENDMODE_BLEND); sp.coverTexture->setBlendMode(SDL_BLENDMODE_BLEND);
@@ -352,8 +319,8 @@ void Ending::iniPics()
SDL_RenderFillRect(renderer, &rect); SDL_RenderFillRect(renderer, &rect);
// Crea el sprite // Crea el sprite
sp.coverSprite = new Sprite({0, 0, sp.coverTexture->getWidth(), sp.coverTexture->getHeight() - 8}, sp.coverTexture, renderer); sp.coverSprite = std::make_shared<Sprite>(sp.coverTexture, 0, 0, sp.coverTexture->getWidth(), sp.coverTexture->getHeight() - 8);
sp.coverSprite->setPos({(GAMECANVAS_WIDTH - sp.coverTexture->getWidth()) / 2, p.pos}); sp.coverSprite->setPosition((GAMECANVAS_WIDTH - sp.coverTexture->getWidth()) / 2, p.pos);
sp.coverSprite->setClip(0, 8, -1, -1); sp.coverSprite->setClip(0, 8, -1, -1);
// Inicializa variables // Inicializa variables
@@ -498,7 +465,7 @@ void Ending::updateSpriteCovers()
else if (spriteTexts[ti.index].clipHeight > 0) else if (spriteTexts[ti.index].clipHeight > 0)
{ {
spriteTexts[ti.index].clipHeight -= 2; spriteTexts[ti.index].clipHeight -= 2;
spriteTexts[ti.index].coverSprite->setPosY(spriteTexts[ti.index].coverSprite->getPosY() + 2); spriteTexts[ti.index].coverSprite->setY(spriteTexts[ti.index].coverSprite->getY() + 2);
} }
spriteTexts[ti.index].coverSprite->setClip(0, spriteTexts[ti.index].clipDesp, spriteTexts[ti.index].coverSprite->getWidth(), spriteTexts[ti.index].clipHeight); spriteTexts[ti.index].coverSprite->setClip(0, spriteTexts[ti.index].clipDesp, spriteTexts[ti.index].coverSprite->getWidth(), spriteTexts[ti.index].clipHeight);
} }
@@ -519,7 +486,7 @@ void Ending::updateSpriteCovers()
{ {
spritePics[scene].clipHeight = 0; spritePics[scene].clipHeight = 0;
} }
spritePics[scene].coverSprite->setPosY(spritePics[scene].coverSprite->getPosY() + 2); spritePics[scene].coverSprite->setY(spritePics[scene].coverSprite->getY() + 2);
} }
spritePics[scene].coverSprite->setClip(0, spritePics[scene].clipDesp, spritePics[scene].coverSprite->getWidth(), spritePics[scene].clipHeight); spritePics[scene].coverSprite->setClip(0, spritePics[scene].clipDesp, spritePics[scene].coverSprite->getWidth(), spritePics[scene].clipHeight);
} }

View File

@@ -5,6 +5,7 @@
#include <SDL2/SDL_stdinc.h> // Para Uint32 #include <SDL2/SDL_stdinc.h> // Para Uint32
#include <string> // Para basic_string, string #include <string> // Para basic_string, string
#include <vector> // Para vector #include <vector> // Para vector
#include <memory> // Para shared_ptr
class Asset; class Asset;
class Input; class Input;
class Resource; class Resource;
@@ -22,10 +23,10 @@ private:
// Estructuras // Estructuras
struct endingTexture_t // Estructura con dos texturas y sprites, uno para mostrar y el otro hace de cortinilla struct endingTexture_t // Estructura con dos texturas y sprites, uno para mostrar y el otro hace de cortinilla
{ {
Texture *texture; // Textura a mostrar std::shared_ptr<Texture> texture; // Textura a mostrar
Sprite *sprite; // Sprite para mostrar la textura std::shared_ptr<Sprite> sprite; // Sprite para mostrar la textura
Texture *coverTexture; // Textura que cubre a la otra textura std::shared_ptr<Texture> coverTexture; // Textura que cubre a la otra textura
Sprite *coverSprite; // Sprite para mostrar la textura que cubre a la otra textura std::shared_ptr<Sprite> coverSprite; // Sprite para mostrar la textura que cubre a la otra textura
int clipDesp; // Desplazamiento del spriteClip de la textura de cobertura int clipDesp; // Desplazamiento del spriteClip de la textura de cobertura
int clipHeight; // Altura del spriteClip de la textura de cobertura int clipHeight; // Altura del spriteClip de la textura de cobertura
}; };
@@ -55,7 +56,7 @@ private:
Resource *resource; // Objeto con los recursos Resource *resource; // Objeto con los recursos
Asset *asset; // Objeto con los ficheros de recursos Asset *asset; // Objeto con los ficheros de recursos
Input *input; // Objeto pata gestionar la entrada Input *input; // Objeto pata gestionar la entrada
Text *text; // Objeto para escribir texto en pantalla std::shared_ptr<Text> text; // Objeto para escribir texto en pantalla
SDL_Texture *coverTexture; // Textura para cubrir el texto SDL_Texture *coverTexture; // Textura para cubrir el texto
// Variables // Variables

View File

@@ -2,12 +2,12 @@
#include <SDL2/SDL_blendmode.h> // for SDL_BLENDMODE_BLEND #include <SDL2/SDL_blendmode.h> // for SDL_BLENDMODE_BLEND
#include <SDL2/SDL_timer.h> // for SDL_GetTicks #include <SDL2/SDL_timer.h> // for SDL_GetTicks
#include <algorithm> // for max, min, replace #include <algorithm> // for max, min, replace
#include "animatedsprite.h" // for AnimatedSprite #include "animated_sprite.h" // for AnimatedSprite
#include "asset.h" // for Asset #include "asset.h" // for Asset
#include "const.h" // for GAMECANVAS_HEIGHT, GAMECANVAS_CENTER_X #include "const.h" // for GAMECANVAS_HEIGHT, GAMECANVAS_CENTER_X
#include "input.h" // for Input, REPEAT_FALSE, inputs_e #include "input.h" // for Input, REPEAT_FALSE, inputs_e
#include "jail_audio.h" // for JA_SetVolume, JA_DeleteMusic, JA_Loa... #include "jail_audio.h" // for JA_SetVolume, JA_DeleteMusic, JA_Loa...
#include "movingsprite.h" // for MovingSprite #include "moving_sprite.h" // for MovingSprite
#include "resource.h" // for Resource #include "resource.h" // for Resource
#include "screen.h" // for Screen #include "screen.h" // for Screen
#include "text.h" // for Text #include "text.h" // for Text
@@ -26,8 +26,8 @@ Ending2::Ending2()
input(Input::get()) input(Input::get())
{ {
// Reserva memoria para los punteros a objetos // Reserva memoria para los punteros a objetos
text = new Text(resource->getOffset("smb2.txt"), resource->getTexture("smb2.png"), renderer); text = resource->getText("smb2.txt");
music = JA_LoadMusic(asset->get("ending2.ogg").c_str()); music = resource->getMusic("ending2.ogg");
// Inicializa variables // Inicializa variables
counterEnabled = false; counterEnabled = false;
@@ -70,18 +70,6 @@ Ending2::Ending2()
createTexts(); createTexts();
} }
// Destructor
Ending2::~Ending2()
{
// Libera la memoria de los objetos
delete text;
JA_DeleteMusic(music);
deleteSprites();
deleteSpriteTexts();
deleteTexts();
}
// Actualiza el objeto // Actualiza el objeto
void Ending2::update() void Ending2::update()
{ {
@@ -324,9 +312,6 @@ void Ending2::iniSpriteList()
// Carga todos los sprites desde una lista // Carga todos los sprites desde una lista
void Ending2::loadSprites() void Ending2::loadSprites()
{ {
// Borra la memoria ocupada por los sprites
deleteSprites();
// Inicializa variables // Inicializa variables
maxSpriteWidth = 0; maxSpriteWidth = 0;
maxSpriteHeight = 0; maxSpriteHeight = 0;
@@ -334,9 +319,9 @@ void Ending2::loadSprites()
// Carga los sprites // Carga los sprites
for (auto sl : spriteList) for (auto sl : spriteList)
{ {
sprites.push_back(new AnimatedSprite(renderer, resource->getAnimation(sl + ".ani"))); sprites.emplace_back(std::make_shared<AnimatedSprite>(renderer, resource->getAnimation(sl + ".ani")));
maxSpriteWidth = std::max(sprites.back()->getAnimationClip(0, 0).w, maxSpriteWidth); maxSpriteWidth = std::max(sprites.back()->getWidth(), maxSpriteWidth);
maxSpriteHeight = std::max(sprites.back()->getAnimationClip(0, 0).h, maxSpriteHeight); maxSpriteHeight = std::max(sprites.back()->getHeight(), maxSpriteHeight);
} }
} }
@@ -432,17 +417,17 @@ void Ending2::placeSprites()
{ {
const int x = i % 2 == 0 ? firstCol : secondCol; const int x = i % 2 == 0 ? firstCol : secondCol;
const int y = (i / 1) * (maxSpriteHeight + distSpriteText + text->getCharacterSize() + distSpriteSprite) + GAMECANVAS_HEIGHT + 40; const int y = (i / 1) * (maxSpriteHeight + distSpriteText + text->getCharacterSize() + distSpriteSprite) + GAMECANVAS_HEIGHT + 40;
const int w = sprites[i]->getAnimationClip(0, 0).w; const int w = sprites[i]->getWidth();
const int h = sprites[i]->getAnimationClip(0, 0).h; const int h = sprites[i]->getHeight();
const int dx = -(w / 2); const int dx = -(w / 2);
const int dy = i % 1 == 0 ? maxSpriteHeight - h : (int)(maxSpriteHeight * 1.5f) - h; const int dy = i % 1 == 0 ? maxSpriteHeight - h : (int)(maxSpriteHeight * 1.5f) - h;
sprites[i]->setRect({x + dx, y + dy, w, h}); sprites[i]->setPosition({x + dx, y + dy, w, h});
sprites[i]->setVelY(despSpeed); sprites[i]->setVelY(despSpeed);
} }
// Recoloca el último sprite, que es el del jugador // Recoloca el último sprite, que es el del jugador
const int w = sprites.back()->getAnimationClip(0, 0).w; const int w = sprites.back()->getWidth();
const int x = GAMECANVAS_CENTER_X - (w / 2); const int x = GAMECANVAS_CENTER_X - (w / 2);
const int y = sprites.back()->getPosY() + maxSpriteHeight * 2; const int y = sprites.back()->getPosY() + maxSpriteHeight * 2;
sprites.back()->setPosX(x); sprites.back()->setPosX(x);
@@ -453,9 +438,6 @@ void Ending2::placeSprites()
// Crea los sprites con las texturas con los textos // Crea los sprites con las texturas con los textos
void Ending2::createSpriteTexts() void Ending2::createSpriteTexts()
{ {
// Borra la memoria ocupada por los sprites con las texturas de los textos
deleteSpriteTexts();
// Crea los sprites de texto a partir de la lista // Crea los sprites de texto a partir de la lista
for (int i = 0; i < (int)spriteList.size(); ++i) for (int i = 0; i < (int)spriteList.size(); ++i)
{ {
@@ -473,24 +455,22 @@ void Ending2::createSpriteTexts()
const int X = (i == (int)spriteList.size() - 1) ? GAMECANVAS_CENTER_X - (w / 2) : x + dx; const int X = (i == (int)spriteList.size() - 1) ? GAMECANVAS_CENTER_X - (w / 2) : x + dx;
// Crea la textura // Crea la textura
Texture *texture = new Texture(renderer); auto texture = std::make_shared<Texture>(renderer);
texture->createBlank(renderer, w, h, SDL_TEXTUREACCESS_TARGET); texture->createBlank(w, h);
texture->setAsRenderTarget(renderer); texture->setAsRenderTarget(renderer);
texture->setBlendMode(SDL_BLENDMODE_BLEND); texture->setBlendMode(SDL_BLENDMODE_BLEND);
text->write(0, 0, txt); text->write(0, 0, txt);
// Crea el sprite // Crea el sprite
MovingSprite *sprite = new MovingSprite(X, y, w, h, 0.0f, despSpeed, 0.0f, 0.0f, texture, renderer); SDL_Rect pos = {X, y, w, h};
spriteTexts.push_back(sprite); spriteTexts.emplace_back(std::make_shared<MovingSprite>(texture, pos));
spriteTexts.back()->setVelY(despSpeed);
} }
} }
// Crea los sprites con las texturas con los textos del final // Crea los sprites con las texturas con los textos del final
void Ending2::createTexts() void Ending2::createTexts()
{ {
// Borra la memoria ocupada por los sprites con las texturas de los textos del final
deleteTexts();
// Crea los primeros textos // Crea los primeros textos
std::vector<std::string> list; std::vector<std::string> list;
list.push_back("STARRING"); list.push_back("STARRING");
@@ -506,15 +486,16 @@ void Ending2::createTexts()
const int y = GAMECANVAS_HEIGHT + (text->getCharacterSize() * (i * 2)); const int y = GAMECANVAS_HEIGHT + (text->getCharacterSize() * (i * 2));
// Crea la textura // Crea la textura
Texture *texture = new Texture(renderer); auto texture = std::make_shared<Texture>(renderer);
texture->createBlank(renderer, w, h, SDL_TEXTUREACCESS_TARGET); texture->createBlank(w, h);
texture->setAsRenderTarget(renderer); texture->setAsRenderTarget(renderer);
texture->setBlendMode(SDL_BLENDMODE_BLEND); texture->setBlendMode(SDL_BLENDMODE_BLEND);
text->write(0, 0, list[i]); text->write(0, 0, list[i]);
// Crea el sprite // Crea el sprite
MovingSprite *sprite = new MovingSprite(x + dx, y, w, h, 0.0f, despSpeed, 0.0f, 0.0f, texture, renderer); SDL_Rect pos = {x + dx, y, w, h};
texts.push_back(sprite); texts.emplace_back(std::make_shared<MovingSprite>(texture, pos));
texts.back()->setVelY(despSpeed);
} }
// Crea los últimos textos // Crea los últimos textos
@@ -535,49 +516,19 @@ void Ending2::createTexts()
const int y = start + (text->getCharacterSize() * (i * 2)); const int y = start + (text->getCharacterSize() * (i * 2));
// Crea la textura // Crea la textura
Texture *texture = new Texture(renderer); auto texture = std::make_shared<Texture>(renderer);
texture->createBlank(renderer, w, h, SDL_TEXTUREACCESS_TARGET); texture->createBlank(w, h);
texture->setAsRenderTarget(renderer); texture->setAsRenderTarget(renderer);
texture->setBlendMode(SDL_BLENDMODE_BLEND); texture->setBlendMode(SDL_BLENDMODE_BLEND);
text->write(0, 0, list[i]); text->write(0, 0, list[i]);
// Crea el sprite // Crea el sprite
MovingSprite *sprite = new MovingSprite(x + dx, y, w, h, 0.0f, despSpeed, 0.0f, 0.0f, texture, renderer); SDL_Rect pos = {x + dx, y, w, h};
texts.push_back(sprite); texts.emplace_back(std::make_shared<MovingSprite>(texture, pos));
texts.back()->setVelY(despSpeed);
} }
} }
// Borra la memoria ocupada por los sprites con las texturas de los textos
void Ending2::deleteSpriteTexts()
{
for (auto sprite : spriteTexts)
{
delete sprite->getTexture();
delete sprite;
}
spriteTexts.clear();
}
// Borra la memoria ocupada por los sprites
void Ending2::deleteSprites()
{
for (auto sprite : sprites)
{
delete sprite;
}
sprites.clear();
}
// Borra la memoria ocupada por los sprites con las texturas de los textos del final
void Ending2::deleteTexts()
{
for (auto text : texts)
{
delete text;
}
texts.clear();
}
// Actualiza el fade final // Actualiza el fade final
void Ending2::updateFinalFade() void Ending2::updateFinalFade()
{ {

View File

@@ -5,6 +5,7 @@
#include <SDL2/SDL_stdinc.h> // for Uint32 #include <SDL2/SDL_stdinc.h> // for Uint32
#include <string> // for string #include <string> // for string
#include <vector> // for vector #include <vector> // for vector
#include <memory> // for shared_ptr
class AnimatedSprite; // lines 9-9 class AnimatedSprite; // lines 9-9
class Asset; // lines 10-10 class Asset; // lines 10-10
class Input; // lines 11-11 class Input; // lines 11-11
@@ -26,10 +27,10 @@ private:
Resource *resource; // Objeto con los recursos Resource *resource; // Objeto con los recursos
Asset *asset; // Objeto con los ficheros de recursos Asset *asset; // Objeto con los ficheros de recursos
Input *input; // Objeto pata gestionar la entrada Input *input; // Objeto pata gestionar la entrada
Text *text; // Objeto para escribir texto en pantalla std::shared_ptr<Text> text; // Objeto para escribir texto en pantalla
std::vector<AnimatedSprite *> sprites; // Vector con todos los sprites a dibujar std::vector<std::shared_ptr<AnimatedSprite>> sprites; // Vector con todos los sprites a dibujar
std::vector<MovingSprite *> spriteTexts; // Vector con los sprites de texto de los sprites std::vector<std::shared_ptr<MovingSprite>> spriteTexts; // Vector con los sprites de texto de los sprites
std::vector<MovingSprite *> texts; // Vector con los sprites de texto std::vector<std::shared_ptr<MovingSprite>> texts; // Vector con los sprites de texto
// Variables // Variables
bool counterEnabled; // Indica si está el contador habilitado bool counterEnabled; // Indica si está el contador habilitado
@@ -97,15 +98,6 @@ private:
// Crea los sprites con las texturas con los textos del final // Crea los sprites con las texturas con los textos del final
void createTexts(); void createTexts();
// Borra la memoria ocupada por los sprites con las texturas de los textos
void deleteSpriteTexts();
// Borra la memoria ocupada por los sprites
void deleteSprites();
// Borra la memoria ocupada por los sprites con las texturas de los textos del final
void deleteTexts();
// Actualiza el fade final // Actualiza el fade final
void updateFinalFade(); void updateFinalFade();
@@ -117,7 +109,7 @@ public:
Ending2(); Ending2();
// Destructor // Destructor
~Ending2(); ~Ending2() = default;
// Bucle principal // Bucle principal
void run(); void run();

View File

@@ -1,7 +1,7 @@
#include "enemy.h" #include "enemy.h"
#include <stdlib.h> // Para rand #include <stdlib.h> // Para rand
#include <algorithm> // Para min #include <algorithm> // Para min
#include "animatedsprite.h" // Para AnimatedSprite #include "animated_sprite.h" // Para AnimatedSprite
#include "texture.h" // Para Texture #include "texture.h" // Para Texture
// Constructor // Constructor

View File

@@ -2,14 +2,14 @@
#include <SDL2/SDL_timer.h> // Para SDL_GetTicks #include <SDL2/SDL_timer.h> // Para SDL_GetTicks
#include <algorithm> // Para min, max #include <algorithm> // Para min, max
#include <string> // Para basic_string, operator+, to_string, char... #include <string> // Para basic_string, operator+, to_string, char...
#include "animatedsprite.h" // Para AnimatedSprite #include "animated_sprite.h" // Para AnimatedSprite
#include "asset.h" // Para Asset #include "asset.h" // Para Asset
#include "const.h" // Para GAMECANVAS_CENTER_X, SECTION_GAME_OVER #include "const.h" // Para GAMECANVAS_CENTER_X, SECTION_GAME_OVER
#include "input.h" // Para Input, REPEAT_FALSE, inputs_e #include "input.h" // Para Input, REPEAT_FALSE, inputs_e
#include "jail_audio.h" // Para JA_DeleteMusic, JA_LoadMusic, JA_PlayMusic #include "jail_audio.h" // Para JA_DeleteMusic, JA_LoadMusic, JA_PlayMusic
#include "resource.h" // Para Resource #include "resource.h" // Para Resource
#include "screen.h" // Para Screen #include "screen.h" // Para Screen
#include "text.h" // Para Text, TXT_CENTER, TXT_COLOR #include "text.h" // Para Text, TEXT_CENTER, TEXT_COLOR
#include "texture.h" // Para Texture #include "texture.h" // Para Texture
#include "options.h" #include "options.h"
#include "global_inputs.h" #include "global_inputs.h"
@@ -24,10 +24,10 @@ GameOver::GameOver()
input(Input::get()) input(Input::get())
{ {
// Reserva memoria para los punteros a objetos // Reserva memoria para los punteros a objetos
text = new Text(resource->getOffset("smb2.txt"), resource->getTexture("smb2.png"), renderer); text = resource->getText("smb2.txt");
playerSprite = new AnimatedSprite(renderer, resource->getAnimation("player_game_over.ani")); playerSprite = std::make_shared<AnimatedSprite>(resource->getTexture("player_game_over.png"), resource->getAnimation("player_game_over.ani"));
tvSprite = new AnimatedSprite(renderer, resource->getAnimation("tv.ani")); tvSprite = std::make_shared<AnimatedSprite>(resource->getTexture("tv.png"), resource->getAnimation("tv.ani"));
music = JA_LoadMusic(asset->get("game_over.ogg").c_str()); music = resource->getMusic("game_over.ogg");
// Inicializa variables // Inicializa variables
preCounter = 0; preCounter = 0;
@@ -41,7 +41,7 @@ GameOver::GameOver()
fadeLenght = 20; fadeLenght = 20;
playerSprite->setPosX(GAMECANVAS_CENTER_X + 10); playerSprite->setPosX(GAMECANVAS_CENTER_X + 10);
playerSprite->setPosY(30); playerSprite->setPosY(30);
tvSprite->setPosX(GAMECANVAS_CENTER_X - tvSprite->getAnimationClip(0, 0).w - 10); tvSprite->setPosX(GAMECANVAS_CENTER_X - tvSprite->getWidth() - 10);
tvSprite->setPosY(30); tvSprite->setPosY(30);
// Inicializa el vector de colores // Inicializa el vector de colores
@@ -53,16 +53,6 @@ GameOver::GameOver()
color = colors.back(); color = colors.back();
} }
// Destructor
GameOver::~GameOver()
{
// Libera la memoria de los objetos
delete text;
delete playerSprite;
delete tvSprite;
JA_DeleteMusic(music);
}
// Actualiza el objeto // Actualiza el objeto
void GameOver::update() void GameOver::update()
{ {
@@ -101,7 +91,7 @@ void GameOver::render()
screen->clean(); screen->clean();
// Escribe el texto de GAME OVER // Escribe el texto de GAME OVER
text->writeDX(TXT_CENTER | TXT_COLOR, GAMECANVAS_CENTER_X, y, "G A M E O V E R", 1, color); text->writeDX(TEXT_CENTER | TEXT_COLOR, GAMECANVAS_CENTER_X, y, "G A M E O V E R", 1, color);
// Dibuja los sprites // Dibuja los sprites
playerSprite->setPosY(y + 30); playerSprite->setPosY(y + 30);
@@ -111,12 +101,12 @@ void GameOver::render()
// Escribe el texto con las habitaciones y los items // Escribe el texto con las habitaciones y los items
const std::string itemsTxt = std::to_string(options.stats.items / 100) + std::to_string((options.stats.items % 100) / 10) + std::to_string(options.stats.items % 10); const std::string itemsTxt = std::to_string(options.stats.items / 100) + std::to_string((options.stats.items % 100) / 10) + std::to_string(options.stats.items % 10);
const std::string roomsTxt = std::to_string(options.stats.rooms / 100) + std::to_string((options.stats.rooms % 100) / 10) + std::to_string(options.stats.rooms % 10); const std::string roomsTxt = std::to_string(options.stats.rooms / 100) + std::to_string((options.stats.rooms % 100) / 10) + std::to_string(options.stats.rooms % 10);
text->writeDX(TXT_CENTER | TXT_COLOR, GAMECANVAS_CENTER_X, y + 80, "ITEMS: " + itemsTxt, 1, color); text->writeDX(TEXT_CENTER | TEXT_COLOR, GAMECANVAS_CENTER_X, y + 80, "ITEMS: " + itemsTxt, 1, color);
text->writeDX(TXT_CENTER | TXT_COLOR, GAMECANVAS_CENTER_X, y + 90, "ROOMS: " + roomsTxt, 1, color); text->writeDX(TEXT_CENTER | TEXT_COLOR, GAMECANVAS_CENTER_X, y + 90, "ROOMS: " + roomsTxt, 1, color);
// Escribe el texto con "Tu peor pesadilla" // Escribe el texto con "Tu peor pesadilla"
text->writeDX(TXT_CENTER | TXT_COLOR, GAMECANVAS_CENTER_X, y + 110, "YOUR WORST NIGHTMARE IS", 1, color); text->writeDX(TEXT_CENTER | TEXT_COLOR, GAMECANVAS_CENTER_X, y + 110, "YOUR WORST NIGHTMARE IS", 1, color);
text->writeDX(TXT_CENTER | TXT_COLOR, GAMECANVAS_CENTER_X, y + 120, options.stats.worst_nightmare, 1, color); text->writeDX(TEXT_CENTER | TEXT_COLOR, GAMECANVAS_CENTER_X, y + 120, options.stats.worst_nightmare, 1, color);
// Vuelca el contenido del renderizador en pantalla // Vuelca el contenido del renderizador en pantalla
screen->render(); screen->render();

View File

@@ -22,9 +22,9 @@ private:
Resource *resource; // Objeto con los recursos Resource *resource; // Objeto con los recursos
Asset *asset; // Objeto con los ficheros de recursos Asset *asset; // Objeto con los ficheros de recursos
Input *input; // Objeto pata gestionar la entrada Input *input; // Objeto pata gestionar la entrada
Text *text; // Objeto para escribir texto en pantalla std::shared_ptr<Text> text; // Objeto para escribir texto en pantalla
AnimatedSprite *playerSprite; // Sprite con el jugador std::shared_ptr<AnimatedSprite> playerSprite; // Sprite con el jugador
AnimatedSprite *tvSprite; // Sprite con el televisor std::shared_ptr<AnimatedSprite> tvSprite; // Sprite con el televisor
// Variables // Variables
int preCounter; // Contador previo int preCounter; // Contador previo
@@ -64,7 +64,7 @@ public:
GameOver(); GameOver();
// Destructor // Destructor
~GameOver(); ~GameOver() = default;
// Bucle principal // Bucle principal
void run(); void run();

View File

@@ -33,11 +33,11 @@ LoadingScreen::LoadingScreen()
mono_loading_screen_texture_ = resource_->getTexture("loading_screen_bn_zxarne.png"); mono_loading_screen_texture_ = resource_->getTexture("loading_screen_bn_zxarne.png");
color_loading_screen_texture_ = resource_->getTexture("loading_screen_color_zxarne.png"); color_loading_screen_texture_ = resource_->getTexture("loading_screen_color_zxarne.png");
} }
mono_loading_screen_sprite_ = new Sprite(0, 0, mono_loading_screen_texture_->getWidth(), mono_loading_screen_texture_->getHeight(), mono_loading_screen_texture_, renderer_); mono_loading_screen_sprite_ = std::make_shared<Sprite>(0, 0, mono_loading_screen_texture_->getWidth(), mono_loading_screen_texture_->getHeight(), mono_loading_screen_texture_, renderer_);
color_loading_screen_sprite_ = new Sprite(0, 0, color_loading_screen_texture_->getWidth(), color_loading_screen_texture_->getHeight(), color_loading_screen_texture_, renderer_); color_loading_screen_sprite_ = std::make_shared<Sprite>(0, 0, color_loading_screen_texture_->getWidth(), color_loading_screen_texture_->getHeight(), color_loading_screen_texture_, renderer_);
loading_sound1_ = JA_LoadMusic(asset_->get("loading_sound1.ogg").c_str()); loading_sound1_ = resource_->getMusic("loading_sound1.ogg");
loading_sound2_ = JA_LoadMusic(asset_->get("loading_sound2.ogg").c_str()); loading_sound2_ = resource_->getMusic("loading_sound2.ogg");
loading_sound3_ = JA_LoadMusic(asset_->get("loading_sound3.ogg").c_str()); loading_sound3_ = resource_->getMusic("loading_sound3.ogg");
// Inicializa variables // Inicializa variables
options.section.section = Section::LOADING_SCREEN; options.section.section = Section::LOADING_SCREEN;
@@ -66,16 +66,6 @@ LoadingScreen::LoadingScreen()
screen_->setBorderColor(stringToColor(options.video.palette, "black")); screen_->setBorderColor(stringToColor(options.video.palette, "black"));
} }
// Destructor
LoadingScreen::~LoadingScreen()
{
delete mono_loading_screen_sprite_;
delete color_loading_screen_sprite_;
JA_DeleteMusic(loading_sound1_);
JA_DeleteMusic(loading_sound2_);
JA_DeleteMusic(loading_sound3_);
}
// Comprueba el manejador de eventos // Comprueba el manejador de eventos
void LoadingScreen::checkEvents() void LoadingScreen::checkEvents()
{ {
@@ -108,7 +98,7 @@ void LoadingScreen::updateLoad()
load_rect_.x = step * (counter_ % numSteps); load_rect_.x = step * (counter_ % numSteps);
load_rect_.y = line_index_[load_counter_]; load_rect_.y = line_index_[load_counter_];
mono_loading_screen_sprite_->setClip(load_rect_); mono_loading_screen_sprite_->setClip(load_rect_);
mono_loading_screen_sprite_->setRect(load_rect_); mono_loading_screen_sprite_->setPosition(load_rect_);
} }
// Una vez actualizadas las 192 lineas, pasa a la segunda fase de la carga // Una vez actualizadas las 192 lineas, pasa a la segunda fase de la carga
else if (load_counter_ == 192) else if (load_counter_ == 192)
@@ -116,8 +106,8 @@ void LoadingScreen::updateLoad()
loading_first_part_ = false; loading_first_part_ = false;
load_counter_ = 0; load_counter_ = 0;
load_rect_ = {0, 0, 16, 8}; load_rect_ = {0, 0, 16, 8};
color_loading_screen_sprite_->setRect(load_rect_);
color_loading_screen_sprite_->setClip(load_rect_); color_loading_screen_sprite_->setClip(load_rect_);
color_loading_screen_sprite_->setPosition(load_rect_);
JA_PlayMusic(loading_sound3_); JA_PlayMusic(loading_sound3_);
} }
} }
@@ -128,7 +118,7 @@ void LoadingScreen::updateLoad()
load_rect_.x = (load_counter_ * 8) % 256; load_rect_.x = (load_counter_ * 8) % 256;
load_rect_.y = (load_counter_ / 32) * 8; load_rect_.y = (load_counter_ / 32) * 8;
color_loading_screen_sprite_->setClip(load_rect_); color_loading_screen_sprite_->setClip(load_rect_);
color_loading_screen_sprite_->setRect(load_rect_); color_loading_screen_sprite_->setPosition(load_rect_);
// Comprueba si ha terminado la intro // Comprueba si ha terminado la intro
if (load_counter_ >= 768) if (load_counter_ >= 768)
@@ -270,7 +260,7 @@ void LoadingScreen::recreateLoadingScreen()
load_rect_.x = step * (i % numSteps); load_rect_.x = step * (i % numSteps);
load_rect_.y = line_index_[load_counter_]; load_rect_.y = line_index_[load_counter_];
mono_loading_screen_sprite_->setClip(load_rect_); mono_loading_screen_sprite_->setClip(load_rect_);
mono_loading_screen_sprite_->setRect(load_rect_); mono_loading_screen_sprite_->setPosition(load_rect_);
mono_loading_screen_sprite_->render(); mono_loading_screen_sprite_->render();
} }
} }
@@ -282,7 +272,7 @@ void LoadingScreen::recreateLoadingScreen()
load_rect_.x = (i * 8) % 256; load_rect_.x = (i * 8) % 256;
load_rect_.y = (i / 32) * 8; load_rect_.y = (i / 32) * 8;
color_loading_screen_sprite_->setClip(load_rect_); color_loading_screen_sprite_->setClip(load_rect_);
color_loading_screen_sprite_->setRect(load_rect_); color_loading_screen_sprite_->setPosition(load_rect_);
color_loading_screen_sprite_->render(); color_loading_screen_sprite_->render();
} }
} }

View File

@@ -4,6 +4,7 @@
#include <SDL2/SDL_rect.h> // Para SDL_Rect #include <SDL2/SDL_rect.h> // Para SDL_Rect
#include <SDL2/SDL_render.h> // Para SDL_Renderer #include <SDL2/SDL_render.h> // Para SDL_Renderer
#include <SDL2/SDL_stdinc.h> // Para Uint32 #include <SDL2/SDL_stdinc.h> // Para Uint32
#include <memory> // Para shared_ptr
class Asset; class Asset;
class Input; class Input;
class Resource; class Resource;
@@ -23,10 +24,10 @@ private:
Resource *resource_; // Objeto con los recursos Resource *resource_; // Objeto con los recursos
Asset *asset_; // Objeto con los ficheros de recursos Asset *asset_; // Objeto con los ficheros de recursos
Input *input_; // Objeto pata gestionar la entrada Input *input_; // Objeto pata gestionar la entrada
Texture *mono_loading_screen_texture_; // Textura con la pantalla de carga en blanco y negro std::shared_ptr<Texture> mono_loading_screen_texture_; // Textura con la pantalla de carga en blanco y negro
Texture *color_loading_screen_texture_; // Textura con la pantalla de carga en color std::shared_ptr<Texture> color_loading_screen_texture_; // Textura con la pantalla de carga en color
Sprite *mono_loading_screen_sprite_; // Sprite para manejar la textura loadingScreenTexture1 std::shared_ptr<Sprite> mono_loading_screen_sprite_; // Sprite para manejar la textura loadingScreenTexture1
Sprite *color_loading_screen_sprite_; // Sprite para manejar la textura loadingScreenTexture2 std::shared_ptr<Sprite> color_loading_screen_sprite_; // Sprite para manejar la textura loadingScreenTexture2
// Variables // Variables
int pre_counter_ = 0; // Contador previo para realizar una pausa inicial int pre_counter_ = 0; // Contador previo para realizar una pausa inicial
@@ -73,7 +74,7 @@ public:
LoadingScreen(); LoadingScreen();
// Destructor // Destructor
~LoadingScreen(); ~LoadingScreen() = default;
// Bucle principal // Bucle principal
void run(); void run();

View File

@@ -26,24 +26,24 @@ Logo::Logo()
// Reserva memoria para los punteros // Reserva memoria para los punteros
jailgames_texture_ = resource_->getTexture("jailgames.png"); jailgames_texture_ = resource_->getTexture("jailgames.png");
since_1998_texture_ = resource_->getTexture("since_1998.png"); since_1998_texture_ = resource_->getTexture("since_1998.png");
since_1998_sprite_ = new Sprite((256 - since_1998_texture_->getWidth()) / 2, 83 + jailgames_texture_->getHeight() + 5, since_1998_texture_->getWidth(), since_1998_texture_->getHeight(), since_1998_texture_, renderer_); since_1998_sprite_ = std::make_shared<Sprite>((256 - since_1998_texture_->getWidth()) / 2, 83 + jailgames_texture_->getHeight() + 5, since_1998_texture_->getWidth(), since_1998_texture_->getHeight(), since_1998_texture_, renderer_);
since_1998_sprite_->setClip(0, 0, since_1998_texture_->getWidth(), since_1998_texture_->getHeight()); since_1998_sprite_->setClip(0, 0, since_1998_texture_->getWidth(), since_1998_texture_->getHeight());
since_1998_texture_->setColor(0, 0, 0); since_1998_texture_->setColor(0, 0, 0);
// Crea los sprites de cada linea // Crea los sprites de cada linea
for (int i = 0; i < jailgames_texture_->getHeight(); ++i) for (int i = 0; i < jailgames_texture_->getHeight(); ++i)
{ {
jailgames_sprite_.push_back(new Sprite(0, i, jailgames_texture_->getWidth(), 1, jailgames_texture_, renderer_)); jailgames_sprite_.push_back(std::make_shared<Sprite>(0, i, jailgames_texture_->getWidth(), 1, jailgames_texture_, renderer_));
jailgames_sprite_.back()->setClip(0, i, jailgames_texture_->getWidth(), 1); jailgames_sprite_.back()->setClip(0, i, jailgames_texture_->getWidth(), 1);
if (i % 2 == 0) if (i % 2 == 0)
{ {
jailgames_sprite_[i]->setPosX(256 + (i * 3)); jailgames_sprite_[i]->setX(256 + (i * 3));
} }
else else
{ {
jailgames_sprite_[i]->setPosX(-181 - (i * 3)); jailgames_sprite_[i]->setX(-181 - (i * 3));
} }
jailgames_sprite_[i]->setPosY(83 + i); jailgames_sprite_[i]->setY(83 + i);
} }
// Inicializa variables // Inicializa variables
@@ -60,17 +60,6 @@ Logo::Logo()
screen_->setBorderColor(stringToColor(options.video.palette, "black")); screen_->setBorderColor(stringToColor(options.video.palette, "black"));
} }
// Destructor
Logo::~Logo()
{
for (auto s : jailgames_sprite_)
{
delete s;
}
delete since_1998_sprite_;
}
// Comprueba el manejador de eventos // Comprueba el manejador de eventos
void Logo::checkEvents() void Logo::checkEvents()
{ {
@@ -96,22 +85,22 @@ void Logo::updateJAILGAMES()
{ {
const int speed = 8; const int speed = 8;
const int dest = 37; const int dest = 37;
if (jailgames_sprite_[i]->getPosX() != 37) if (jailgames_sprite_[i]->getX() != 37)
{ {
if (i % 2 == 0) if (i % 2 == 0)
{ {
jailgames_sprite_[i]->incPosX(-speed); jailgames_sprite_[i]->incX(-speed);
if (jailgames_sprite_[i]->getPosX() < dest) if (jailgames_sprite_[i]->getX() < dest)
{ {
jailgames_sprite_[i]->setPosX(dest); jailgames_sprite_[i]->setX(dest);
} }
} }
else else
{ {
jailgames_sprite_[i]->incPosX(speed); jailgames_sprite_[i]->incX(speed);
if (jailgames_sprite_[i]->getPosX() > dest) if (jailgames_sprite_[i]->getX() > dest)
{ {
jailgames_sprite_[i]->setPosX(dest); jailgames_sprite_[i]->setX(dest);
} }
} }
} }

View File

@@ -4,6 +4,7 @@
#include <SDL2/SDL_render.h> // for SDL_Renderer #include <SDL2/SDL_render.h> // for SDL_Renderer
#include <SDL2/SDL_stdinc.h> // for Uint32 #include <SDL2/SDL_stdinc.h> // for Uint32
#include <vector> // for vector #include <vector> // for vector
#include <memory> // for shared_ptr
class Asset; // lines 8-8 class Asset; // lines 8-8
class Input; // lines 9-9 class Input; // lines 9-9
class Resource; // lines 10-10 class Resource; // lines 10-10
@@ -23,10 +24,10 @@ private:
Resource *resource_; // Objeto con los recursos Resource *resource_; // Objeto con los recursos
Asset *asset_; // Objeto con los ficheros de recursos Asset *asset_; // Objeto con los ficheros de recursos
Input *input_; // Objeto pata gestionar la entrada Input *input_; // Objeto pata gestionar la entrada
Texture *jailgames_texture_; // Textura con los graficos "JAILGAMES" std::shared_ptr<Texture> jailgames_texture_; // Textura con los graficos "JAILGAMES"
Texture *since_1998_texture_; // Textura con los graficos "Since 1998" std::shared_ptr<Texture> since_1998_texture_; // Textura con los graficos "Since 1998"
std::vector<Sprite *> jailgames_sprite_; // Vector con los sprites de cada linea que forman el bitmap JAILGAMES std::vector<std::shared_ptr<Sprite>> jailgames_sprite_; // Vector con los sprites de cada linea que forman el bitmap JAILGAMES
Sprite *since_1998_sprite_; // Sprite para manejar la textura2 std::shared_ptr<Sprite> since_1998_sprite_; // Sprite para manejar la textura2
// Variables // Variables
std::vector<Color> color_; // Vector con los colores para el fade std::vector<Color> color_; // Vector con los colores para el fade
@@ -63,7 +64,7 @@ public:
Logo(); Logo();
// Destructor // Destructor
~Logo(); ~Logo() = default;
// Bucle principal // Bucle principal
void run(); void run();

230
source/moving_sprite.cpp Normal file
View File

@@ -0,0 +1,230 @@
#include "moving_sprite.h"
#include <algorithm> // Para max
#include "texture.h" // Para Texture
// Constructor
MovingSprite::MovingSprite(std::shared_ptr<Texture> texture, SDL_Rect pos, Rotate rotate, float zoom_w, float zoom_h, SDL_RendererFlip flip)
: Sprite(texture, pos),
x_(pos.x),
y_(pos.y),
rotate_(rotate),
zoom_w_(zoom_w),
zoom_h_(zoom_h),
flip_(flip) {}
MovingSprite::MovingSprite(std::shared_ptr<Texture> texture, SDL_Rect pos)
: Sprite(texture, pos),
x_(pos.x),
y_(pos.y),
rotate_(Rotate()),
zoom_w_(1.0f),
zoom_h_(1.0f),
flip_(SDL_FLIP_NONE) {}
MovingSprite::MovingSprite(std::shared_ptr<Texture> texture)
: Sprite(texture),
x_(0.0f),
y_(0.0f),
rotate_(Rotate()),
zoom_w_(1.0f),
zoom_h_(1.0f),
flip_(SDL_FLIP_NONE) { Sprite::clear(); }
// 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
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
rotate_ = Rotate(); // Inicializa la estructura
zoom_w_ = 1.0f; // Zoom aplicado a la anchura
zoom_h_ = 1.0f; // Zoom aplicado a la altura
flip_ = SDL_FLIP_NONE; // Establece como se ha de voltear el sprite
Sprite::clear();
}
// Mueve el sprite
void MovingSprite::move()
{
x_ += vx_;
y_ += vy_;
vx_ += ax_;
vy_ += ay_;
pos_.x = static_cast<int>(x_);
pos_.y = static_cast<int>(y_);
}
// Actualiza las variables internas del objeto
void MovingSprite::update()
{
move();
rotate();
}
// Muestra el sprite por pantalla
void MovingSprite::render()
{
texture_->render(pos_.x, pos_.y, &clip_, zoom_w_, zoom_h_, rotate_.angle, rotate_.center, flip_);
}
// Establece el valor de la variable
void MovingSprite::setZoomW(float value)
{
zoom_w_ = value;
}
// Establece el valor de la variable
void MovingSprite::setZoomH(float value)
{
zoom_h_ = value;
}
// Establece el valor de la variable
void MovingSprite::setAngle(double value)
{
rotate_.angle = value;
}
// Establece el valor de la variable
void MovingSprite::setRotatingCenter(SDL_Point *point)
{
rotate_.center = point;
}
// Incrementa el valor del ángulo
void MovingSprite::updateAngle()
{
rotate_.angle += rotate_.amount;
}
// Obtiene el valor de la variable
bool MovingSprite::isRotating() const
{
return rotate_.enabled;
}
// Establece la rotacion
void MovingSprite::rotate()
{
if (rotate_.enabled)
{
++rotate_.counter;
if (rotate_.counter % rotate_.speed == 0)
{
updateAngle();
rotate_.counter = 0;
}
}
}
// Activa o desactiva el efecto de rotación
void MovingSprite::setRotate(bool enable)
{
rotate_.enabled = enable;
rotate_.counter = 0;
}
// Establece el valor de la variable
void MovingSprite::setRotateSpeed(int value)
{
rotate_.speed = std::max(1, value);
}
// Establece el valor de la variable
void MovingSprite::setRotateAmount(double value)
{
rotate_.amount = value;
}
// Cambia el sentido de la rotación
void MovingSprite::switchRotate()
{
rotate_.amount *= -1;
}
// Establece el valor de la variable
void MovingSprite::setFlip(SDL_RendererFlip flip)
{
flip_ = flip;
}
// Gira el sprite horizontalmente
void MovingSprite::flip()
{
flip_ = (flip_ == SDL_FLIP_HORIZONTAL) ? SDL_FLIP_NONE : SDL_FLIP_HORIZONTAL;
}
// Obtiene el valor de la variable
SDL_RendererFlip MovingSprite::getFlip()
{
return flip_;
}
// Establece la posición y_ el tamaño del objeto
void MovingSprite::setPos(SDL_Rect rect)
{
x_ = static_cast<float>(rect.x);
y_ = static_cast<float>(rect.y);
pos_ = rect;
}
// Establece el valor de las variables
void MovingSprite::setPos(float x, float y)
{
x_ = x;
y_ = y;
pos_.x = static_cast<int>(x_);
pos_.y = static_cast<int>(y_);
}
// Establece el valor de la variable
void MovingSprite::setPosX(float value)
{
x_ = value;
pos_.x = static_cast<int>(x_);
}
// Establece el valor de la variable
void MovingSprite::setPosY(float value)
{
y_ = value;
pos_.y = static_cast<int>(y_);
}
// Establece el valor de la variable
void MovingSprite::setVelX(float value)
{
vx_ = value;
}
// Establece el valor de la variable
void MovingSprite::setVelY(float value)
{
vy_ = value;
}
// Establece el valor de la variable
void MovingSprite::setAccelX(float value)
{
ax_ = value;
}
// Establece el valor de la variable
void MovingSprite::setAccelY(float value)
{
ay_ = value;
}

122
source/moving_sprite.h Normal file
View File

@@ -0,0 +1,122 @@
#pragma once
#include <SDL2/SDL_rect.h> // Para SDL_Rect, SDL_Point
#include <SDL2/SDL_render.h> // Para SDL_RendererFlip
#include <memory> // Para shared_ptr
#include "sprite.h" // Para Sprite
class Texture; // lines 8-8
// Clase MovingSprite. Añade movimiento y efectos de rotación, zoom y flip al sprite
class MovingSprite : public Sprite
{
public:
struct Rotate
{
bool enabled; // Indica si ha de rotar
int counter; // Contador
int speed; // Velocidad de giro
double angle; // Angulo para dibujarlo
float amount; // Cantidad de grados a girar en cada iteración
SDL_Point *center; // Centro de rotación
Rotate() : enabled(false), counter(0), speed(1), angle(0.0), amount(0.0f), center(nullptr) {}
};
protected:
float x_; // Posición en el eje X
float y_; // Posición en el eje Y
float vx_ = 0.0f; // Velocidad en el eje X. Cantidad de pixeles a desplazarse
float vy_ = 0.0f; // Velocidad en el eje Y. Cantidad de pixeles a desplazarse
float ax_ = 0.0f; // Aceleración en el eje X. Variación de la velocidad
float ay_ = 0.0f; // Aceleración en el eje Y. Variación de la velocidad
Rotate rotate_; // Variables usada para controlar la rotación del sprite
float zoom_w_; // Zoom aplicado a la anchura
float zoom_h_; // Zoom aplicado a la altura
SDL_RendererFlip flip_; // Indica como se voltea el sprite
// Incrementa el valor del ángulo
void updateAngle();
// Mueve el sprite
void move();
// Rota el sprite
void rotate();
public:
// Constructor
MovingSprite(std::shared_ptr<Texture> texture, SDL_Rect pos, MovingSprite::Rotate rotate, float zoom_w, float zoom_h, SDL_RendererFlip flip);
MovingSprite(std::shared_ptr<Texture> texture, SDL_Rect pos);
explicit MovingSprite(std::shared_ptr<Texture> texture);
// Destructor
virtual ~MovingSprite() = default;
// Actualiza las variables internas del objeto
virtual void update();
// Reinicia todas las variables a cero
void clear() override;
// Muestra el sprite por pantalla
void render() override;
// Obtiene la variable
float getPosX() const { return x_; }
float getPosY() const { return y_; }
float getVelX() const { return vx_; }
float getVelY() const { return vy_; }
float getAccelX() const { return ax_; }
float getAccelY() const { return ay_; }
// Establece la variable
void setVelX(float value);
void setVelY(float value);
void setAccelX(float value);
void setAccelY(float value);
// Obten el valor de la variable
bool isRotating() const;
// Establece el valor de la variable
void setZoomW(float value);
void setZoomH(float value);
// Establece el valor de la variable
void setAngle(double vaue);
void setRotatingCenter(SDL_Point *point);
// Activa o desactiva el efecto de rotación
void setRotate(bool enable);
// Establece el valor de la variable
void setRotateSpeed(int value);
void setRotateAmount(double value);
// Cambia el sentido de la rotación
void switchRotate();
// Establece el valor de la variable
void setFlip(SDL_RendererFlip flip);
// Gira el sprite horizontalmente
void flip();
// Obtiene el valor de la variable
SDL_RendererFlip getFlip();
// Establece la posición y_ el tamaño del objeto
void setPos(SDL_Rect rect);
// Establece el valor de las variables
void setPos(float x, float y);
// Establece el valor de la variable
void setPosX(float value);
// Establece el valor de la variable
void setPosY(float value);
};

View File

@@ -1,416 +0,0 @@
#include "movingsprite.h"
#include "texture.h" // Para Texture
// Constructor
MovingSprite::MovingSprite(float x, float y, int w, int h, float velx, float vely, float accelx, float accely, Texture *texture, SDL_Renderer *renderer)
{
// Copia los punteros
this->texture_ = texture;
this->renderer_ = renderer;
// Establece el alto y el ancho del sprite
this->w_ = w;
this->h_ = h;
// Establece la posición X,Y del sprite
this->x = x;
this->y = y;
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;
// Establece el angulo con el que se dibujará
angle = (double)0;
// Establece los valores de rotacion
rotateEnabled = false;
rotateSpeed = 0;
rotateAmount = (double)0;
// Contador interno
counter = 0;
// Establece el rectangulo de donde coger la imagen
clip_ = {0, 0, w, h};
// Establece el centro de rotación
center = nullptr;
// Establece el tipo de volteado
currentFlip = SDL_FLIP_NONE;
currentFlipH = false;
currentFlipV = false;
};
// 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
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
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
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;
vx += ax;
vy += ay;
}
}
// Muestra el sprite por pantalla
void MovingSprite::render()
{
if (enabled_)
{
texture_->render(renderer_, (int)x, (int)y, &clip_, zoomW, zoomH, angle, center, currentFlip);
}
}
// Obtiene el valor de la variable
float MovingSprite::getPosX()
{
return x;
}
// Obtiene el valor de la variable
float MovingSprite::getPosY()
{
return y;
}
// Obtiene el valor de la variable
float MovingSprite::getVelX()
{
return vx;
}
// Obtiene el valor de la variable
float MovingSprite::getVelY()
{
return vy;
}
// Obtiene el valor de la variable
float MovingSprite::getAccelX()
{
return ax;
}
// Obtiene el valor de la variable
float MovingSprite::getAccelY()
{
return ay;
}
// Obtiene el valor de la variable
float MovingSprite::getZoomW()
{
return zoomW;
}
// Obtiene el valor de la variable
float MovingSprite::getZoomH()
{
return zoomH;
}
// Obtiene el valor de la variable
double MovingSprite::getAngle()
{
return angle;
}
// 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;
}
// Establece el valor de la variable
void MovingSprite::setPosX(float value)
{
x = value;
}
// Establece el valor de la variable
void MovingSprite::setPosY(float value)
{
y = value;
}
// Establece el valor de la variable
void MovingSprite::setVelX(float value)
{
vx = value;
}
// Establece el valor de la variable
void MovingSprite::setVelY(float value)
{
vy = value;
}
// Establece el valor de la variable
void MovingSprite::setAccelX(float value)
{
ax = value;
}
// Establece el valor de la variable
void MovingSprite::setAccelY(float value)
{
ay = value;
}
// Establece el valor de la variable
void MovingSprite::setZoomW(float value)
{
zoomW = value;
}
// Establece el valor de la variable
void MovingSprite::setZoomH(float value)
{
zoomH = value;
}
// Establece el valor de la variable
void MovingSprite::setAngle(double value)
{
angle = value;
}
// Incrementa el valor de la variable
void MovingSprite::incAngle(double value)
{
angle += value;
}
// Decrementa el valor de la variable
void MovingSprite::decAngle(double value)
{
angle -= value;
}
// Obtiene el valor de la variable
bool MovingSprite::getRotate()
{
return rotateEnabled;
}
// Obtiene el valor de la variable
Uint16 MovingSprite::getRotateSpeed()
{
return rotateSpeed;
}
// Establece la rotacion
void MovingSprite::rotate()
{
if (enabled_)
if (rotateEnabled)
{
if (counter % rotateSpeed == 0)
{
incAngle(rotateAmount);
}
}
}
// Establece el valor de la variable
void MovingSprite::setRotate(bool value)
{
rotateEnabled = value;
}
// Establece el valor de la variable
void MovingSprite::setRotateSpeed(int value)
{
if (value < 1)
{
rotateSpeed = 1;
}
else
{
rotateSpeed = value;
}
}
// Establece el valor de la variable
void MovingSprite::setRotateAmount(double value)
{
rotateAmount = value;
}
// Establece el valor de la variable
void MovingSprite::disableRotate()
{
rotateEnabled = false;
angle = (double)0;
}
// Actualiza las variables internas del objeto
void MovingSprite::update()
{
move();
rotate();
if (enabled_)
{
++counter %= 60000;
}
}
// Cambia el sentido de la rotación
void MovingSprite::switchRotate()
{
rotateAmount *= -1;
}
// Actualiza el valor de la variable
void MovingSprite::updateCurrentFlip()
{
if (currentFlipH && currentFlipV)
{
currentFlip = SDL_RendererFlip(SDL_FLIP_HORIZONTAL | SDL_FLIP_VERTICAL);
}
else if (currentFlipH && !currentFlipV)
{
currentFlip = SDL_FLIP_HORIZONTAL;
}
else if (!currentFlipH && currentFlipV)
{
currentFlip = SDL_FLIP_VERTICAL;
}
else if (!currentFlipH && !currentFlipV)
{
currentFlip = SDL_FLIP_NONE;
}
}
// Establece el valor de la variable
void MovingSprite::setFlipH(bool flip)
{
currentFlipH = flip;
updateCurrentFlip();
}
// Gira el sprite horizontalmente
void MovingSprite::flipH()
{
currentFlipH = !currentFlipH;
updateCurrentFlip();
}
// Establece el valor de la variable
void MovingSprite::setFlipV(bool flip)
{
currentFlipV = flip;
updateCurrentFlip();
}
// Voltea el sprite verticalmente
void MovingSprite::flipV()
{
currentFlipV = !currentFlipV;
updateCurrentFlip();
}
// Obtiene el valor de la variable
SDL_RendererFlip MovingSprite::getFlip()
{
return currentFlip;
}
// Obtiene el valor de la variable
bool MovingSprite::getFlipH()
{
return currentFlipH;
}
// Obtiene el valor de la variable
bool MovingSprite::getFlipV()
{
return currentFlipV;
}
// 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;
}

View File

@@ -1,185 +0,0 @@
#pragma once
#include <SDL2/SDL_rect.h> // Para SDL_Rect, SDL_Point
#include <SDL2/SDL_render.h> // Para SDL_RendererFlip, SDL_Renderer
#include <SDL2/SDL_stdinc.h> // Para Uint16
#include "sprite.h" // Para Sprite
class Texture;
// Clase MovingSprite. Añade posicion y velocidad en punto flotante
class MovingSprite : public Sprite
{
protected:
// Objetos y punteros
SDL_Point *center; // Centro de rotación
// Variables
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 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
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_RendererFlip currentFlip; // Indica como se voltea el sprite
bool currentFlipV;
bool currentFlipH;
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, SDL_Renderer *renderer = nullptr);
// Mueve el sprite
void move();
// Rota el sprite
void rotate();
// Actualiza las variables internas del objeto
void update();
// Reinicia todas las variables
void clear();
// Muestra el sprite por pantalla
void render();
// Obten el valor de la variable
float getPosX();
// Obten el valor de la variable
float getPosY();
// Obten el valor de la variable
float getVelX();
// Obten el valor de la variable
float getVelY();
// 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();
// Establece la posición y el tamaño del objeto
void setRect(SDL_Rect rect);
// 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.
void disableRotate();
// Cambia el sentido de la rotación
void switchRotate();
// Actualiza el valor de la variable
void updateCurrentFlip();
// Establece el valor de la variable
void setFlipH(bool flip);
// Gira el sprite horizontalmente
void flipH();
// Establece el valor de la variable
void setFlipV(bool flip);
// Voltea el sprite verticalmente
void flipV();
// Obtiene el valor de la variable
SDL_RendererFlip getFlip();
// Obtiene el valor de la variable
bool getFlipH();
// Obtiene el valor de la variable
bool getFlipV();
// 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

@@ -3,7 +3,7 @@
#include <stdlib.h> // Para rand #include <stdlib.h> // Para rand
#include <algorithm> // Para max, min #include <algorithm> // Para max, min
#include <cmath> // Para ceil, abs #include <cmath> // Para ceil, abs
#include "animatedsprite.h" // Para AnimatedSprite #include "animated_sprite.h" // Para AnimatedSprite
#include "asset.h" // Para Asset #include "asset.h" // Para Asset
#include "const.h" // Para BORDER_TOP, BLOCK, BORDER_BOTTOM, BORDER... #include "const.h" // Para BORDER_TOP, BLOCK, BORDER_BOTTOM, BORDER...
#include "debug.h" // Para Debug #include "debug.h" // Para Debug

View File

@@ -1,360 +1,355 @@
#include "resource.h" #include "resource.h"
#include <iostream> // Para basic_ostream, operator<<, cout, endl #include <algorithm> // Para find_if
#include "animatedsprite.h" // Para animatedSprite_t, loadAnimationFromFile #include <iostream> // Para basic_ostream, operator<<, endl, cout, cerr
#include "asset.h" // Para Asset #include <stdexcept> // Para runtime_error
#include "enemy.h" // Para enemy_t #include <utility> // Para pair
#include "item.h" // Para item_t #include "asset.h" // Para Asset, AssetType
#include "room.h" // Para room_t, loadRoomFile, loadRoomTileFile #include "jail_audio.h" // Para JA_LoadMusic, JA_LoadSound
#include "text.h" // Para textFile_t, LoadTextFile #include "lang.h" // Para getText
#include "texture.h" // Para Texture #include "screen.h" // Para Screen
#include "utils.h" // Para options_t #include "text.h" // Para Text, loadTextFile
#include "screen.h" struct JA_Music_t; // lines 10-10
#include "options.h" struct JA_Sound_t; // lines 11-11
// [SINGLETON] // [SINGLETON] Hay que definir las variables estáticas, desde el .h sólo la hemos declarado
Resource *Resource::resource_ = nullptr; Resource *Resource::resource_ = nullptr;
// [SINGLETON] Crearemos el objeto con esta función estática // [SINGLETON] Crearemos el objeto screen con esta función estática
void Resource::init() void Resource::init()
{ {
Resource::resource_ = new Resource(); Resource::resource_ = new Resource();
} }
// [SINGLETON] Destruiremos el objeto con esta función estática // [SINGLETON] Destruiremos el objeto screen con esta función estática
void Resource::destroy() void Resource::destroy()
{ {
delete Resource::resource_; delete Resource::resource_;
} }
// [SINGLETON] Con este método obtenemos el objeto y podemos trabajar con él // [SINGLETON] Con este método obtenemos el objeto screen y podemos trabajar con él
Resource *Resource::get() Resource *Resource::get()
{ {
return Resource::resource_; return Resource::resource_;
} }
// Carga las texturas de una lista // Constructor
void Resource::loadTextures(std::vector<std::string> list) Resource::Resource()
{ {
for (auto l : list) load();
{
if (options.console)
{
std::cout << "\nLOAD TEXTURE: " << l << std::endl;
std::cout << "png: " << Asset::get()->get(l) << std::endl;
}
res_texture_t t;
t.name = l;
t.texture = new Texture(Screen::get()->getRenderer(), Asset::get()->get(t.name), options.console);
textures_.push_back(t);
}
} }
// Vuelve a cargar las texturas // Vacia todos los vectores de recursos
void Resource::reLoadTextures() void Resource::clear()
{ {
for (auto texture : textures_) clearSounds();
{ clearMusics();
texture.texture->reLoad();
}
}
// Carga las animaciones desde una lista
void Resource::loadAnimations(std::vector<std::string> list)
{
for (auto l : list)
{
// Extrae el nombre del fichero sin la extension para crear el nombre del fichero de la textura
const std::string pngFile = l.substr(0, l.find_last_of(".")) + ".png";
if (options.console)
{
std::cout << "\nLOAD ANIMATION: " << l << std::endl;
std::cout << "png: " << Asset::get()->get(pngFile) << std::endl;
std::cout << "ani: " << Asset::get()->get(l) << std::endl;
}
res_animation_t as;
as.name = l;
as.animation = new animatedSprite_t(loadAnimationFromFile(getTexture(pngFile), Asset::get()->get(as.name), options.console));
animations_.push_back(as);
}
}
// Vuelve a cargar las animaciones
void Resource::reLoadAnimations()
{
// reLoadTextures();
for (auto &a : animations_)
{
// Extrae el nombre del fichero sin la extension para crear el nombre del fichero de la textura
const std::string pngFile = a.name.substr(0, a.name.find_last_of(".")) + ".png";
delete a.animation;
a.animation = new animatedSprite_t(loadAnimationFromFile(getTexture(pngFile), Asset::get()->get(a.name), options.console));
}
}
// Carga los offsets desde una lista
void Resource::loadOffsets(std::vector<std::string> list)
{
for (auto l : list)
{
res_textOffset_t to;
to.name = l;
to.textFile = new textFile_t(LoadTextFile(Asset::get()->get(l), options.console));
offsets_.push_back(to);
}
}
// Vuelve a cargar los offsets
void Resource::reLoadOffsets()
{
for (auto &o : offsets_)
{
delete o.textFile;
o.textFile = new textFile_t(LoadTextFile(Asset::get()->get(o.name), options.console));
}
}
// Carga los mapas de tiles desde una lista
void Resource::loadTileMaps(std::vector<std::string> list)
{
for (auto l : list)
{
res_tileMap_t tm;
tm.name = l;
tm.tileMap = new std::vector<int>(loadRoomTileFile(Asset::get()->get(l), options.console));
tile_maps_.push_back(tm);
}
}
// Vuelve a cargar los mapas de tiles
void Resource::reLoadTileMaps()
{
for (auto &tm : tile_maps_)
{
delete tm.tileMap;
tm.tileMap = new std::vector<int>(loadRoomTileFile(Asset::get()->get(tm.name), options.console));
}
}
// Carga las habitaciones desde una lista
void Resource::loadRooms(std::vector<std::string> list)
{
for (auto l : list)
{
res_room_t r;
r.name = l;
r.room = new room_t(loadRoomFile(Asset::get()->get(l), options.console));
r.room->tileMap = getTileMap(r.room->tileMapFile);
for (auto &e : r.room->enemies)
{
e.animation = getAnimation(e.animationString);
}
for (auto &i : r.room->items)
{
i.texture = getTexture(i.tileSetFile);
}
r.room->textureA = getTexture("standard.png");
r.room->textureB = getTexture("standard_zxarne.png");
rooms_.push_back(r);
}
}
// Vuelve a cargar las habitaciones
void Resource::reLoadRooms()
{
reLoadTileMaps();
for (auto &r : rooms_)
{
delete r.room;
r.room = new room_t(loadRoomFile(Asset::get()->get(r.name)));
r.room->tileMap = getTileMap(r.room->tileMapFile);
for (auto &e : r.room->enemies)
{
e.animation = getAnimation(e.animationString);
}
for (auto &i : r.room->items)
{
i.texture = getTexture(i.tileSetFile);
}
r.room->textureA = getTexture("standard.png");
r.room->textureB = getTexture("standard_zxarne.png");
}
}
// Vuelve a cargar todos los recursos
void Resource::reLoad()
{
reLoadAnimations();
reLoadOffsets();
reLoadRooms();
}
// Libera las texturas
void Resource::freeTextures()
{
for (auto texture : textures_)
{
delete texture.texture;
}
textures_.clear(); textures_.clear();
} text_files_.clear();
texts_.clear();
// Libera las animaciones
void Resource::freeAnimations()
{
for (auto a : animations_)
{
delete a.animation;
}
animations_.clear(); animations_.clear();
demos_.clear();
} }
// Libera los offsets // Carga todos los recursos
void Resource::freeOffsets() void Resource::load()
{ {
for (auto o : offsets_) std::cout << "** LOADING RESOURCES" << std::endl;
{ loadSounds();
delete o.textFile; loadMusics();
} loadTextures();
offsets_.clear(); loadTextFiles();
loadAnimations();
loadDemoData();
addPalettes();
createText();
createTextures();
std::cout << "\n** RESOURCES LOADED" << std::endl;
} }
// Libera los mapas de tiles // Recarga todos los recursos
void Resource::freeTileMaps() void Resource::reload()
{ {
for (auto t : tile_maps_) clear();
load();
}
// Obtiene el sonido a partir de un nombre
JA_Sound_t *Resource::getSound(const std::string &name)
{
auto it = std::find_if(sounds_.begin(), sounds_.end(), [&name](const auto &s)
{ return s.name == name; });
if (it != sounds_.end())
{ {
delete t.tileMap; return it->sound;
} }
std::cerr << "Error: Sonido no encontrado " << name << std::endl;
throw std::runtime_error("Sonido no encontrado: " + name);
}
// Obtiene la música a partir de un nombre
JA_Music_t *Resource::getMusic(const std::string &name)
{
auto it = std::find_if(musics_.begin(), musics_.end(), [&name](const auto &m)
{ return m.name == name; });
if (it != musics_.end())
{
return it->music;
}
std::cerr << "Error: Música no encontrada " << name << std::endl;
throw std::runtime_error("Música no encontrada: " + name);
}
// Obtiene la textura a partir de un nombre
std::shared_ptr<Texture> Resource::getTexture(const std::string &name)
{
auto it = std::find_if(textures_.begin(), textures_.end(), [&name](const auto &t)
{ return t.name == name; });
if (it != textures_.end())
{
return it->texture;
}
std::cerr << "Error: Imagen no encontrada " << name << std::endl;
throw std::runtime_error("Imagen no encontrada: " + name);
}
// Obtiene el fichero de texto a partir de un nombre
std::shared_ptr<TextFile> Resource::getTextFile(const std::string &name)
{
auto it = std::find_if(text_files_.begin(), text_files_.end(), [&name](const auto &t)
{ return t.name == name; });
if (it != text_files_.end())
{
return it->text_file;
}
std::cerr << "Error: TextFile no encontrado " << name << std::endl;
throw std::runtime_error("TextFile no encontrado: " + name);
}
// Obtiene el objeto de texto a partir de un nombre
std::shared_ptr<Text> Resource::getText(const std::string &name)
{
auto it = std::find_if(texts_.begin(), texts_.end(), [&name](const auto &t)
{ return t.name == name; });
if (it != texts_.end())
{
return it->text;
}
std::cerr << "Error: Text no encontrado " << name << std::endl;
throw std::runtime_error("Text no encontrado: " + name);
}
// Obtiene la animación a partir de un nombre
AnimationsFileBuffer &Resource::getAnimation(const std::string &name)
{
auto it = std::find_if(animations_.begin(), animations_.end(), [&name](const auto &a)
{ return a.name == name; });
if (it != animations_.end())
{
return it->animation;
}
std::cerr << "Error: Animación no encontrada " << name << std::endl;
throw std::runtime_error("Animación no encontrada: " + name);
}
// Obtiene el mapa de tiles a partir de un nombre
std::vector<int> &Resource::getTileMap(const std::string &name)
{
auto it = std::find_if(tile_maps_.begin(), tile_maps_.end(), [&name](const auto &t)
{ return t.name == name; });
if (it != tile_maps_.end())
{
return it->tileMap;
}
std::cerr << "Error: Mapa de tiles no encontrado " << name << std::endl;
throw std::runtime_error("Mapa de tiles no encontrado: " + name);
}
// Obtiene la habitación a partir de un nombre
std::shared_ptr<room_t> Resource::getRoom(const std::string &name)
{
auto it = std::find_if(rooms_.begin(), rooms_.end(), [&name](const auto &r)
{ return r.name == name; });
if (it != rooms_.end())
{
return it->room;
}
std::cerr << "Error: Habitación no encontrada " << name << std::endl;
throw std::runtime_error("Habitación no encontrada: " + name);
}
// Carga los sonidos
void Resource::loadSounds()
{
std::cout << "\n>> SOUND FILES" << std::endl;
auto list = Asset::get()->getListByType(AssetType::SOUND);
sounds_.clear();
for (const auto &l : list)
{
auto name = getFileName(l);
sounds_.emplace_back(ResourceSound(name, JA_LoadSound(l.c_str())));
printWithDots("Sound : ", name, "[ LOADED ]");
}
}
// Carga las musicas
void Resource::loadMusics()
{
std::cout << "\n>> MUSIC FILES" << std::endl;
auto list = Asset::get()->getListByType(AssetType::MUSIC);
musics_.clear();
for (const auto &l : list)
{
auto name = getFileName(l);
musics_.emplace_back(ResourceMusic(name, JA_LoadMusic(l.c_str())));
printWithDots("Music : ", name, "[ LOADED ]");
}
}
// Carga las texturas
void Resource::loadTextures()
{
std::cout << "\n>> TEXTURES" << std::endl;
auto list = Asset::get()->getListByType(AssetType::BITMAP);
textures_.clear();
for (const auto &l : list)
{
auto name = getFileName(l);
textures_.emplace_back(ResourceTexture(name, std::make_shared<Texture>(Screen::get()->getRenderer(), l)));
}
}
// Carga los ficheros de texto
void Resource::loadTextFiles()
{
std::cout << "\n>> TEXT FILES" << std::endl;
auto list = Asset::get()->getListByType(AssetType::FONT);
text_files_.clear();
for (const auto &l : list)
{
auto name = getFileName(l);
text_files_.emplace_back(ResourceTextFile(name, loadTextFile(l)));
}
}
// Carga las animaciones
void Resource::loadAnimations()
{
std::cout << "\n>> ANIMATIONS" << std::endl;
auto list = Asset::get()->getListByType(AssetType::ANIMATION);
animations_.clear();
for (const auto &l : list)
{
auto name = getFileName(l);
animations_.emplace_back(ResourceAnimation(name, loadAnimationsFromFile(l)));
}
}
// Carga los mapas de tiles
void Resource::loadTileMaps()
{
std::cout << "\n>> TILE MAPS" << std::endl;
auto list = Asset::get()->getListByType(AssetType::TILEMAP);
tile_maps_.clear(); tile_maps_.clear();
for (const auto &l : list)
{
auto name = getFileName(l);
tile_maps_.emplace_back(ResourceTileMap(name, std::make_shared<std::vector<int>>(loadRoomTileFile(l))));
}
} }
// Libera las habitaciones // Carga las habitaciones
void Resource::freeRooms() void Resource::loadRooms()
{ {
for (auto r : rooms_) std::cout << "\n>> ROOMS" << std::endl;
{ auto list = Asset::get()->getListByType(AssetType::ROOM);
delete r.room;
}
rooms_.clear(); rooms_.clear();
for (const auto &l : list)
{
auto name = getFileName(l);
rooms_.emplace_back(ResourceRoom(name, std::make_shared<room_t>(loadRoomFile(l))));
}
} }
// Libera todos los recursos void Resource::createText()
void Resource::free()
{ {
freeTextures(); struct ResourceInfo
freeAnimations(); {
freeOffsets(); std::string key; // Identificador del recurso
freeTileMaps(); std::string textureFile; // Nombre del archivo de textura
freeRooms(); std::string textFile; // Nombre del archivo de texto
// Constructor para facilitar la creación de objetos ResourceInfo
ResourceInfo(const std::string &k, const std::string &tFile, const std::string &txtFile)
: key(k), textureFile(tFile), textFile(txtFile) {}
};
std::cout << "\n>> CREATING TEXT_OBJECTS" << std::endl;
std::vector<ResourceInfo> resources = {
{"debug", "debug.png", "debug.txt"},
{"gauntlet", "gauntlet.png", "gauntlet.txt"},
{"smb2", "smb2.png", "smb2.txt"},
{"subatomic", "subatomic.png", "subatomic.txt"},
{"8bithud", "8bithud.png", "8bithud.txt"}};
for (const auto &resource : resources)
{
texts_.emplace_back(ResourceText(resource.key, std::make_shared<Text>(
getTexture(resource.textureFile),
getTextFile(resource.textFile))));
printWithDots("Text : ", resource.key, "[ DONE ]");
}
} }
// Obtiene una textura // Vacía el vector de sonidos
Texture *Resource::getTexture(std::string name) void Resource::clearSounds()
{ {
for (auto texture : textures_) // Itera sobre el vector y libera los recursos asociados a cada JA_Sound_t
for (auto &sound : sounds_)
{ {
// if (texture.name.find(name) != std::string::npos) if (sound.sound)
if (texture.name == name)
{ {
// std::cout << "\nTEXTURE REQUESTED: " << name << std::endl; JA_DeleteSound(sound.sound);
// std::cout << "served: " << texture.name << std::endl; sound.sound = nullptr;
return texture.texture;
} }
} }
sounds_.clear(); // Limpia el vector después de liberar todos los recursos
if (options.console)
{
std::cout << "NOT FOUND ON CACHE: " << name << std::endl;
}
return nullptr;
} }
// Obtiene una animación // Vacía el vector de musicas
animatedSprite_t *Resource::getAnimation(std::string name) void Resource::clearMusics()
{ {
for (auto animation : animations_) // Itera sobre el vector y libera los recursos asociados a cada JA_Music_t
for (auto &music : musics_)
{ {
// if (animation.name.find(name) != std::string::npos) if (music.music)
if (animation.name == name)
{ {
// std::cout << "\nANIMATION REQUESTED: " << name << std::endl; JA_DeleteMusic(music.music);
// std::cout << "served: " << animation.name << std::endl; music.music = nullptr;
return animation.animation;
} }
} }
musics_.clear(); // Limpia el vector después de liberar todos los recursos
if (options.console)
{
std::cout << "NOT FOUND ON CACHE: " << name << std::endl;
}
return nullptr;
}
// Obtiene un offset
textFile_t *Resource::getOffset(std::string name)
{
for (auto offset : offsets_)
{
// if (offset.name.find(name) != std::string::npos)
if (offset.name == name)
{
return offset.textFile;
}
}
if (options.console)
{
std::cout << "NOT FOUND ON CACHE: " << name << std::endl;
}
return nullptr;
}
// Obtiene un mapa de tiles
std::vector<int> *Resource::getTileMap(std::string name)
{
for (auto tileMap : tile_maps_)
{
// if (tileMap.name.find(name) != std::string::npos)
if (tileMap.name == name)
{
return tileMap.tileMap;
}
}
if (options.console)
{
std::cout << "NOT FOUND ON CACHE: " << name << std::endl;
}
return nullptr;
}
// Obtiene una habitacion
room_t *Resource::getRoom(std::string name)
{
for (auto room : rooms_)
{
// if (room.name.find(name) != std::string::npos)
if (room.name == name)
{
return room.room;
}
}
if (options.console)
{
std::cout << "NOT FOUND ON CACHE: " << name << std::endl;
}
return nullptr;
}
// Obtiene todas las habitaciones
std::vector<res_room_t> *Resource::getAllRooms()
{
return &rooms_;
} }

View File

@@ -1,141 +1,197 @@
#pragma once #pragma once
#include <SDL2/SDL_render.h> // Para SDL_Renderer #include <memory> // Para shared_ptr
#include <string> // Para string, basic_string #include <string> // Para string
#include <vector> // Para vector #include <vector> // Para vector
class Asset; #include "animated_sprite.h" // Para AnimationsFileBuffer
class Texture; #include "text.h" // Para TextFile
struct animatedSprite_t; #include "texture.h" // Para Texture
struct Options; #include "utils.h" // Para DemoData
struct room_t; #include "room.h"
struct textFile_t; struct JA_Music_t;
struct JA_Sound_t;
struct res_texture_t // Estructura para almacenar ficheros de sonido y su nombre
struct ResourceSound
{
std::string name; // Nombre del sonido
JA_Sound_t *sound; // Objeto con el sonido
// Constructor
ResourceSound(const std::string &name, JA_Sound_t *sound)
: name(name), sound(sound) {}
};
// Estructura para almacenar ficheros musicales y su nombre
struct ResourceMusic
{
std::string name; // Nombre de la musica
JA_Music_t *music; // Objeto con la música
// Constructor
ResourceMusic(const std::string &name, JA_Music_t *music)
: name(name), music(music) {}
};
// Estructura para almacenar objetos Texture y su nombre
struct ResourceTexture
{ {
std::string name; // Nombre de la textura std::string name; // Nombre de la textura
Texture *texture; // La textura std::shared_ptr<Texture> texture; // Objeto con la textura
// Constructor
ResourceTexture(const std::string &name, std::shared_ptr<Texture> texture)
: name(name), texture(texture) {}
}; };
struct res_animation_t // Estructura para almacenar ficheros TextFile y su nombre
struct ResourceTextFile
{ {
std::string name; // Nombre de la textura std::string name; // Nombre del fichero
animatedSprite_t *animation; // La animación std::shared_ptr<TextFile> text_file; // Objeto con los descriptores de la fuente de texto
// Constructor
ResourceTextFile(const std::string &name, std::shared_ptr<TextFile> text_file)
: name(name), text_file(text_file) {}
}; };
struct res_textOffset_t // Estructura para almacenar objetos Text y su nombre
struct ResourceText
{ {
std::string name; // Nombre del offset std::string name; // Nombre del objeto
textFile_t *textFile; // Los offsets de la fuente std::shared_ptr<Text> text; // Objeto
// Constructor
ResourceText(const std::string &name, std::shared_ptr<Text> text)
: name(name), text(text) {}
}; };
struct res_tileMap_t // Estructura para almacenar ficheros animaciones y su nombre
struct ResourceAnimation
{
std::string name; // Nombre del fichero
AnimationsFileBuffer animation; // Objeto con las animaciones
// Constructor
ResourceAnimation(const std::string &name, const AnimationsFileBuffer &animation)
: name(name), animation(animation) {}
};
// Estructura para almacenar ficheros con el mapa de tiles de una habitación y su nombre
struct ResourceTileMap
{ {
std::string name; // Nombre del mapa de tiles std::string name; // Nombre del mapa de tiles
std::vector<int> *tileMap; // Vector con los indices del mapa de tiles std::vector<int> tileMap; // Vector con los indices del mapa de tiles
// Constructor
ResourceTileMap(const std::string &name, const std::vector<int> &tileMap)
: name(name), tileMap(tileMap) {}
}; };
struct res_room_t // Estructura para almacenar habitaciones y su nombre
struct ResourceRoom
{ {
std::string name; // Nombre de la habitación std::string name; // Nombre de la habitación
room_t *room; // Vector con las habitaciones std::shared_ptr<room_t> room; // Habitación
// Constructor
ResourceRoom(const std::string &name, std::shared_ptr<room_t> room)
: name(name), room(room) {}
}; };
// Clase Resource. Almacena recursos de disco en memoria
class Resource class Resource
{ {
private: private:
// [SINGLETON] Objeto privado // [SINGLETON] Objeto resource privado para Don Melitón
static Resource *resource_; static Resource *resource_;
// Variables std::vector<ResourceSound> sounds_; // Vector con los sonidos
std::vector<res_texture_t> textures_; std::vector<ResourceMusic> musics_; // Vector con las musicas
std::vector<res_animation_t> animations_; std::vector<ResourceTexture> textures_; // Vector con las musicas
std::vector<res_textOffset_t> offsets_; std::vector<ResourceTextFile> text_files_; // Vector con los ficheros de texto
std::vector<res_tileMap_t> tile_maps_; std::vector<ResourceText> texts_; // Vector con los objetos de texto
std::vector<res_room_t> rooms_; std::vector<ResourceAnimation> animations_; // Vector con las animaciones
std::vector<ResourceTileMap> tile_maps_; // Vector con los mapas de tiles
std::vector<ResourceRoom> rooms_; // Vector con las habitaciones
// Carga los sonidos
void loadSounds();
// Carga las musicas
void loadMusics();
// Carga las texturas
void loadTextures();
// Carga los ficheros de texto
void loadTextFiles();
// Carga las animaciones
void loadAnimations();
// Carga los mapas de tiles
void loadTileMaps();
// Carga las habitaciones
void loadRooms();
// Crea los objetos de texto
void createText();
// Vacia todos los vectores de recursos
void clear();
// Carga todos los recursos
void load();
// Vacía el vector de sonidos
void clearSounds();
// Vacía el vector de musicas
void clearMusics();
// [SINGLETON] Ahora el constructor y el destructor son privados, para no poder crear objetos resource desde fuera
// Constructor // Constructor
Resource() = default; Resource();
// Destructor // Destructor
~Resource() = default; ~Resource() = default;
public: public:
// [SINGLETON] Crearemos el objeto con esta función estática // [SINGLETON] Crearemos el objeto resource con esta función estática
static void init(); static void init();
// [SINGLETON] Destruiremos el objeto con esta función estática // [SINGLETON] Destruiremos el objeto resource con esta función estática
static void destroy(); static void destroy();
// [SINGLETON] Con este método obtenemos el objeto y podemos trabajar con él // [SINGLETON] Con este método obtenemos el objeto resource y podemos trabajar con él
static Resource *get(); static Resource *get();
// Carga las texturas de una lista // Obtiene el sonido a partir de un nombre
void loadTextures(std::vector<std::string> list); JA_Sound_t *getSound(const std::string &name);
// Vuelve a cargar las texturas // Obtiene la música a partir de un nombre
void reLoadTextures(); JA_Music_t *getMusic(const std::string &name);
// Carga las animaciones desde una lista // Obtiene la textura a partir de un nombre
void loadAnimations(std::vector<std::string> list); std::shared_ptr<Texture> getTexture(const std::string &name);
// Vuelve a cargar las animaciones // Obtiene el fichero de texto a partir de un nombre
void reLoadAnimations(); std::shared_ptr<TextFile> getTextFile(const std::string &name);
// Carga los offsets desde una lista // Obtiene el objeto de texto a partir de un nombre
void loadOffsets(std::vector<std::string> list); std::shared_ptr<Text> getText(const std::string &name);
// Vuelve a cargar los offsets // Obtiene la animación a partir de un nombre
void reLoadOffsets(); AnimationsFileBuffer &getAnimation(const std::string &name);
// Carga los mapas de tiles desde una lista // Obtiene el mapa de tiles a partir de un nombre
void loadTileMaps(std::vector<std::string> list); std::vector<int> &getTileMap(const std::string &name);
// Vuelve a cargar los mapas de tiles // Obtiene la habitación a partir de un nombre
void reLoadTileMaps(); std::shared_ptr<room_t> getRoom(const std::string &name);
// Carga las habitaciones desde una lista // Recarga todos los recursos
void loadRooms(std::vector<std::string> list); void reload();
// Vuelve a cargar las habitaciones
void reLoadRooms();
// Vuelve a cargar todos los recursos
void reLoad();
// Libera las texturas
void freeTextures();
// Libera las animaciones
void freeAnimations();
// Libera los offsets
void freeOffsets();
// Libera los mapas de tiles
void freeTileMaps();
// Libera las habitaciones
void freeRooms();
// Libera todos los recursos
void free();
// Obtiene una textura
Texture *getTexture(std::string name);
// Obtiene una animación
animatedSprite_t *getAnimation(std::string name);
// Obtiene un offset
textFile_t *getOffset(std::string name);
// Obtiene un mapa de tiles
std::vector<int> *getTileMap(std::string name);
// Obtiene una habitacion
room_t *getRoom(std::string name);
// Obtiene todas las habitaciones
std::vector<res_room_t> *getAllRooms();
}; };

360
source/resource_old.cpp Normal file
View File

@@ -0,0 +1,360 @@
#include "resource.h"
#include <iostream> // Para basic_ostream, operator<<, cout, endl
#include "animated_sprite.h" // Para animatedSprite_t, loadAnimationFromFile
#include "asset.h" // Para Asset
#include "enemy.h" // Para enemy_t
#include "item.h" // Para item_t
#include "room.h" // Para room_t, loadRoomFile, loadRoomTileFile
#include "text.h" // Para textFile_t, LoadTextFile
#include "texture.h" // Para Texture
#include "utils.h" // Para options_t
#include "screen.h"
#include "options.h"
// [SINGLETON]
Resource *Resource::resource_ = nullptr;
// [SINGLETON] Crearemos el objeto con esta función estática
void Resource::init()
{
Resource::resource_ = new Resource();
}
// [SINGLETON] Destruiremos el objeto con esta función estática
void Resource::destroy()
{
delete Resource::resource_;
}
// [SINGLETON] Con este método obtenemos el objeto y podemos trabajar con él
Resource *Resource::get()
{
return Resource::resource_;
}
// Carga las texturas de una lista
void Resource::loadTextures(std::vector<std::string> list)
{
for (auto l : list)
{
if (options.console)
{
std::cout << "\nLOAD TEXTURE: " << l << std::endl;
std::cout << "png: " << Asset::get()->get(l) << std::endl;
}
res_texture_t t;
t.name = l;
t.texture = std::make_shared<Texture>(Screen::get()->getRenderer(), Asset::get()->get(t.name), options.console);
textures_.push_back(t);
}
}
// Vuelve a cargar las texturas
void Resource::reLoadTextures()
{
for (auto texture : textures_)
{
texture.texture->reLoad();
}
}
// Carga las animaciones desde una lista
void Resource::loadAnimations(std::vector<std::string> list)
{
for (auto l : list)
{
// Extrae el nombre del fichero sin la extension para crear el nombre del fichero de la textura
const std::string pngFile = l.substr(0, l.find_last_of(".")) + ".png";
if (options.console)
{
std::cout << "\nLOAD ANIMATION: " << l << std::endl;
std::cout << "png: " << Asset::get()->get(pngFile) << std::endl;
std::cout << "ani: " << Asset::get()->get(l) << std::endl;
}
res_animation_t as;
as.name = l;
as.animation = std::make_shared<animatedSprite_t>(loadAnimationFromFile(getTexture(pngFile), Asset::get()->get(as.name), options.console));
animations_.push_back(as);
}
}
// Vuelve a cargar las animaciones
void Resource::reLoadAnimations()
{
// reLoadTextures();
for (auto &a : animations_)
{
// Extrae el nombre del fichero sin la extension para crear el nombre del fichero de la textura
const std::string pngFile = a.name.substr(0, a.name.find_last_of(".")) + ".png";
delete a.animation;
a.animation = std::make_shared<animatedSprite_t>(loadAnimationFromFile(getTexture(pngFile), Asset::get()->get(a.name), options.console));
}
}
// Carga los offsets desde una lista
void Resource::loadOffsets(std::vector<std::string> list)
{
for (auto l : list)
{
res_textOffset_t to;
to.name = l;
to.textFile = std::make_shared<textFile_t>(LoadTextFile(Asset::get()->get(l), options.console));
offsets_.push_back(to);
}
}
// Vuelve a cargar los offsets
void Resource::reLoadOffsets()
{
for (auto &o : offsets_)
{
delete o.textFile;
o.textFile = std::make_shared<textFile_t>(LoadTextFile(Asset::get()->get(o.name), options.console));
}
}
// Carga los mapas de tiles desde una lista
void Resource::loadTileMaps(std::vector<std::string> list)
{
for (auto l : list)
{
res_tileMap_t tm;
tm.name = l;
tm.tileMap = new std::vector<int>(loadRoomTileFile(Asset::get()->get(l), options.console));
tile_maps_.push_back(tm);
}
}
// Vuelve a cargar los mapas de tiles
void Resource::reLoadTileMaps()
{
for (auto &tm : tile_maps_)
{
delete tm.tileMap;
tm.tileMap = new std::vector<int>(loadRoomTileFile(Asset::get()->get(tm.name), options.console));
}
}
// Carga las habitaciones desde una lista
void Resource::loadRooms(std::vector<std::string> list)
{
for (auto l : list)
{
res_room_t r;
r.name = l;
r.room = new room_t(loadRoomFile(Asset::get()->get(l), options.console));
r.room->tileMap = getTileMap(r.room->tileMapFile);
for (auto &e : r.room->enemies)
{
e.animation = getAnimation(e.animationString);
}
for (auto &i : r.room->items)
{
i.texture = getTexture(i.tileSetFile);
}
r.room->textureA = getTexture("standard.png");
r.room->textureB = getTexture("standard_zxarne.png");
rooms_.push_back(r);
}
}
// Vuelve a cargar las habitaciones
void Resource::reLoadRooms()
{
reLoadTileMaps();
for (auto &r : rooms_)
{
delete r.room;
r.room = new room_t(loadRoomFile(Asset::get()->get(r.name)));
r.room->tileMap = getTileMap(r.room->tileMapFile);
for (auto &e : r.room->enemies)
{
e.animation = getAnimation(e.animationString);
}
for (auto &i : r.room->items)
{
i.texture = getTexture(i.tileSetFile);
}
r.room->textureA = getTexture("standard.png");
r.room->textureB = getTexture("standard_zxarne.png");
}
}
// Vuelve a cargar todos los recursos
void Resource::reLoad()
{
reLoadAnimations();
reLoadOffsets();
reLoadRooms();
}
// Libera las texturas
void Resource::freeTextures()
{
for (auto texture : textures_)
{
delete texture.texture;
}
textures_.clear();
}
// Libera las animaciones
void Resource::freeAnimations()
{
for (auto a : animations_)
{
delete a.animation;
}
animations_.clear();
}
// Libera los offsets
void Resource::freeOffsets()
{
for (auto o : offsets_)
{
delete o.textFile;
}
offsets_.clear();
}
// Libera los mapas de tiles
void Resource::freeTileMaps()
{
for (auto t : tile_maps_)
{
delete t.tileMap;
}
tile_maps_.clear();
}
// Libera las habitaciones
void Resource::freeRooms()
{
for (auto r : rooms_)
{
delete r.room;
}
rooms_.clear();
}
// Libera todos los recursos
void Resource::free()
{
freeTextures();
freeAnimations();
freeOffsets();
freeTileMaps();
freeRooms();
}
// Obtiene una textura
Texture *Resource::getTexture(std::string name)
{
for (auto texture : textures_)
{
// if (texture.name.find(name) != std::string::npos)
if (texture.name == name)
{
// std::cout << "\nTEXTURE REQUESTED: " << name << std::endl;
// std::cout << "served: " << texture.name << std::endl;
return texture.texture;
}
}
if (options.console)
{
std::cout << "NOT FOUND ON CACHE: " << name << std::endl;
}
return nullptr;
}
// Obtiene una animación
animatedSprite_t *Resource::getAnimation(std::string name)
{
for (auto animation : animations_)
{
// if (animation.name.find(name) != std::string::npos)
if (animation.name == name)
{
// std::cout << "\nANIMATION REQUESTED: " << name << std::endl;
// std::cout << "served: " << animation.name << std::endl;
return animation.animation;
}
}
if (options.console)
{
std::cout << "NOT FOUND ON CACHE: " << name << std::endl;
}
return nullptr;
}
// Obtiene un offset
textFile_t *Resource::getOffset(std::string name)
{
for (auto offset : offsets_)
{
// if (offset.name.find(name) != std::string::npos)
if (offset.name == name)
{
return offset.textFile;
}
}
if (options.console)
{
std::cout << "NOT FOUND ON CACHE: " << name << std::endl;
}
return nullptr;
}
// Obtiene un mapa de tiles
std::vector<int> *Resource::getTileMap(std::string name)
{
for (auto tileMap : tile_maps_)
{
// if (tileMap.name.find(name) != std::string::npos)
if (tileMap.name == name)
{
return tileMap.tileMap;
}
}
if (options.console)
{
std::cout << "NOT FOUND ON CACHE: " << name << std::endl;
}
return nullptr;
}
// Obtiene una habitacion
room_t *Resource::getRoom(std::string name)
{
for (auto room : rooms_)
{
// if (room.name.find(name) != std::string::npos)
if (room.name == name)
{
return room.room;
}
}
if (options.console)
{
std::cout << "NOT FOUND ON CACHE: " << name << std::endl;
}
return nullptr;
}
// Obtiene todas las habitaciones
std::vector<res_room_t> *Resource::getAllRooms()
{
return &rooms_;
}

142
source/resource_old.h Normal file
View File

@@ -0,0 +1,142 @@
#pragma once
#include <SDL2/SDL_render.h> // Para SDL_Renderer
#include <string> // Para string, basic_string
#include <vector> // Para vector
#include <memory> // Para shared_ptr
class Asset;
class Texture;
struct animatedSprite_t;
struct Options;
struct room_t;
struct textFile_t;
struct res_texture_t
{
std::string name; // Nombre de la textura
std::shared_ptr<Texture> texture; // La textura
};
struct res_animation_t
{
std::string name; // Nombre de la textura
std::shared_ptr<animatedSprite_t> animation; // La animación
};
struct res_textOffset_t
{
std::string name; // Nombre del offset
std::shared_ptr<textFile_t> textFile; // Los offsets de la fuente
};
struct res_tileMap_t
{
std::string name; // Nombre del mapa de tiles
std::vector<int> *tileMap; // Vector con los indices del mapa de tiles
};
struct res_room_t
{
std::string name; // Nombre de la habitación
std::shared_ptr<room_t> room; // Vector con las habitaciones
};
// Clase Resource. Almacena recursos de disco en memoria
class Resource
{
private:
// [SINGLETON] Objeto privado
static Resource *resource_;
// Variables
std::vector<res_texture_t> textures_;
std::vector<res_animation_t> animations_;
std::vector<res_textOffset_t> offsets_;
std::vector<res_tileMap_t> tile_maps_;
std::vector<res_room_t> rooms_;
// Constructor
Resource() = default;
// Destructor
~Resource() = default;
public:
// [SINGLETON] Crearemos el objeto con esta función estática
static void init();
// [SINGLETON] Destruiremos el objeto con esta función estática
static void destroy();
// [SINGLETON] Con este método obtenemos el objeto y podemos trabajar con él
static Resource *get();
// Carga las texturas de una lista
void loadTextures(std::vector<std::string> list);
// Vuelve a cargar las texturas
void reLoadTextures();
// Carga las animaciones desde una lista
void loadAnimations(std::vector<std::string> list);
// Vuelve a cargar las animaciones
void reLoadAnimations();
// Carga los offsets desde una lista
void loadOffsets(std::vector<std::string> list);
// Vuelve a cargar los offsets
void reLoadOffsets();
// Carga los mapas de tiles desde una lista
void loadTileMaps(std::vector<std::string> list);
// Vuelve a cargar los mapas de tiles
void reLoadTileMaps();
// Carga las habitaciones desde una lista
void loadRooms(std::vector<std::string> list);
// Vuelve a cargar las habitaciones
void reLoadRooms();
// Vuelve a cargar todos los recursos
void reLoad();
// Libera las texturas
void freeTextures();
// Libera las animaciones
void freeAnimations();
// Libera los offsets
void freeOffsets();
// Libera los mapas de tiles
void freeTileMaps();
// Libera las habitaciones
void freeRooms();
// Libera todos los recursos
void free();
// Obtiene una textura
std::shared_ptr<Texture> getTexture(std::string name);
// Obtiene una animación
std::shared_ptr<animatedSprite_t> getAnimation(std::string name);
// Obtiene un offset
textFile_t *getOffset(std::string name);
// Obtiene un mapa de tiles
std::vector<int> *getTileMap(std::string name);
// Obtiene una habitacion
room_t *getRoom(std::string name);
// Obtiene todas las habitaciones
std::vector<res_room_t> *getAllRooms();
};

View File

@@ -1,7 +1,7 @@
#include "scoreboard.h" #include "scoreboard.h"
#include <SDL2/SDL_rect.h> // Para SDL_Rect #include <SDL2/SDL_rect.h> // Para SDL_Rect
#include <SDL2/SDL_timer.h> // Para SDL_GetTicks #include <SDL2/SDL_timer.h> // Para SDL_GetTicks
#include "animatedsprite.h" // Para AnimatedSprite #include "animated_sprite.h" // Para AnimatedSprite
#include "const.h" // Para BLOCK, PLAY_AREA_HEIGHT, PLAY_AREA_WIDTH #include "const.h" // Para BLOCK, PLAY_AREA_HEIGHT, PLAY_AREA_WIDTH
#include "resource.h" // Para Resource #include "resource.h" // Para Resource
#include "text.h" // Para Text #include "text.h" // Para Text

View File

@@ -1,50 +1,56 @@
#include "text.h" #include "text.h"
#include <fstream> // Para char_traits, basic_ostream, basic_ifstream, ope... #include <SDL2/SDL_blendmode.h> // Para SDL_BLENDMODE_BLEND
#include <iostream> // Para cout #include <SDL2/SDL_pixels.h> // Para SDL_PIXELFORMAT_RGBA8888
#include <SDL2/SDL_rect.h> // Para SDL_Rect
#include <SDL2/SDL_render.h> // Para SDL_TEXTUREACCESS_TARGET
#include <stddef.h> // Para size_t
#include <fstream> // Para basic_ifstream, basic_istream, basic...
#include <iostream> // Para cerr
#include <stdexcept> // Para runtime_error
#include "screen.h" // Para Screen
#include "sprite.h" // Para Sprite #include "sprite.h" // Para Sprite
#include "texture.h" // Para Texture #include "texture.h" // Para Texture
#include "utils.h" // Para color_t #include "utils.h" // Para Color, getFileName, printWithDots
// Llena una estructuta textFile_t desde un fichero // Llena una estructuta TextFile desde un fichero
textFile_t LoadTextFile(std::string file, bool verbose) std::shared_ptr<TextFile> loadTextFile(const std::string &file_path)
{ {
textFile_t tf; auto tf = std::make_shared<TextFile>();
// Inicializa a cero el vector con las coordenadas // Inicializa a cero el vector con las coordenadas
for (int i = 0; i < 128; ++i) for (int i = 0; i < 128; ++i)
{ {
tf.offset[i].x = 0; tf->offset[i].x = 0;
tf.offset[i].y = 0; tf->offset[i].y = 0;
tf.offset[i].w = 0; tf->offset[i].w = 0;
tf->box_width = 0;
tf->box_height = 0;
} }
// Abre el fichero para leer los valores // Abre el fichero para leer los valores
const std::string filename = file.substr(file.find_last_of("\\/") + 1).c_str(); std::ifstream file(file_path);
std::ifstream rfile(file);
if (rfile.is_open() && rfile.good()) if (file.is_open() && file.good())
{ {
std::string buffer; std::string buffer;
// Lee los dos primeros valores del fichero // Lee los dos primeros valores del fichero
std::getline(rfile, buffer); std::getline(file, buffer);
std::getline(rfile, buffer); std::getline(file, buffer);
tf.boxWidth = std::stoi(buffer); tf->box_width = std::stoi(buffer);
std::getline(rfile, buffer); std::getline(file, buffer);
std::getline(rfile, buffer); std::getline(file, buffer);
tf.boxHeight = std::stoi(buffer); tf->box_height = std::stoi(buffer);
// lee el resto de datos del fichero // lee el resto de datos del fichero
int index = 32; auto index = 32;
int line_read = 0; auto line_read = 0;
while (std::getline(rfile, buffer)) while (std::getline(file, buffer))
{ {
// Almacena solo las lineas impares // Almacena solo las lineas impares
if (line_read % 2 == 1) if (line_read % 2 == 1)
{ tf->offset[index++].w = std::stoi(buffer);
tf.offset[index++].w = std::stoi(buffer);
}
// Limpia el buffer // Limpia el buffer
buffer.clear(); buffer.clear();
@@ -52,131 +58,171 @@ textFile_t LoadTextFile(std::string file, bool verbose)
}; };
// Cierra el fichero // Cierra el fichero
if (verbose) printWithDots("Text File : ", getFileName(file_path), "[ LOADED ]");
{ file.close();
std::cout << "Text loaded: " << filename.c_str() << std::endl;
}
rfile.close();
} }
// El fichero no se puede abrir // El fichero no se puede abrir
else else
{ {
if (verbose) std::cerr << "Error: Fichero no encontrado " << getFileName(file_path) << std::endl;
{ throw std::runtime_error("Fichero no encontrado: " + getFileName(file_path));
std::cout << "Warning: Unable to open " << filename.c_str() << " file" << std::endl;
}
} }
// Establece las coordenadas para cada caracter ascii de la cadena y su ancho // Establece las coordenadas para cada caracter ascii de la cadena y su ancho
for (int i = 32; i < 128; ++i) for (int i = 32; i < 128; ++i)
{ {
tf.offset[i].x = ((i - 32) % 15) * tf.boxWidth; tf->offset[i].x = ((i - 32) % 15) * tf->box_width;
tf.offset[i].y = ((i - 32) / 15) * tf.boxHeight; tf->offset[i].y = ((i - 32) / 15) * tf->box_height;
} }
return tf; return tf;
} }
// Constructor // Constructor
Text::Text(std::string textFile, Texture *texture, SDL_Renderer *renderer) Text::Text(std::shared_ptr<Texture> texture, const std::string &text_file)
{ {
// Carga los offsets desde el fichero // Carga los offsets desde el fichero
textFile_t tf = LoadTextFile(textFile); auto tf = loadTextFile(text_file);
// Inicializa variables desde la estructura // Inicializa variables desde la estructura
boxHeight = tf.boxHeight; box_height_ = tf->box_height;
boxWidth = tf.boxWidth; box_width_ = tf->box_width;
for (int i = 0; i < 128; ++i) for (int i = 0; i < 128; ++i)
{ {
offset[i].x = tf.offset[i].x; offset_[i].x = tf->offset[i].x;
offset[i].y = tf.offset[i].y; offset_[i].y = tf->offset[i].y;
offset[i].w = tf.offset[i].w; offset_[i].w = tf->offset[i].w;
} }
// Crea los objetos // Crea los objetos
sprite = new Sprite({0, 0, boxWidth, boxHeight}, texture, renderer); sprite_ = std::make_unique<Sprite>(texture, (SDL_Rect){0, 0, box_width_, box_height_});
// Inicializa variables // Inicializa variables
fixedWidth = false; fixed_width_ = false;
} }
// Constructor // Constructor
Text::Text(textFile_t *textFile, Texture *texture, SDL_Renderer *renderer) Text::Text(std::shared_ptr<Texture> texture, std::shared_ptr<TextFile> text_file)
{ {
// Inicializa variables desde la estructura // Inicializa variables desde la estructura
boxHeight = textFile->boxHeight; box_height_ = text_file->box_height;
boxWidth = textFile->boxWidth; box_width_ = text_file->box_width;
for (int i = 0; i < 128; ++i) for (int i = 0; i < 128; ++i)
{ {
offset[i].x = textFile->offset[i].x; offset_[i].x = text_file->offset[i].x;
offset[i].y = textFile->offset[i].y; offset_[i].y = text_file->offset[i].y;
offset[i].w = textFile->offset[i].w; offset_[i].w = text_file->offset[i].w;
} }
// Crea los objetos // Crea los objetos
sprite = new Sprite({0, 0, boxWidth, boxHeight}, texture, renderer); sprite_ = std::make_unique<Sprite>(texture, (SDL_Rect){0, 0, box_width_, box_height_});
// Inicializa variables // Inicializa variables
fixedWidth = false; fixed_width_ = false;
}
// Destructor
Text::~Text()
{
delete sprite;
} }
// Escribe texto en pantalla // Escribe texto en pantalla
void Text::write(int x, int y, std::string text, int kerning, int lenght) void Text::write(int x, int y, const std::string &text, int kerning, int lenght)
{ {
int shift = 0; int shift = 0;
if (lenght == -1) if (lenght == -1)
lenght = text.length(); lenght = text.length();
sprite_->setY(y);
for (int i = 0; i < lenght; ++i) for (int i = 0; i < lenght; ++i)
{ {
sprite->setClip(offset[int(text[i])].x, offset[int(text[i])].y, sprite->getWidth(), sprite->getHeight()); auto index = static_cast<int>(text[i]);
sprite->setPosX(x + shift); sprite_->setClip(offset_[index].x, offset_[index].y, box_width_, box_height_);
sprite->setPosY(y); sprite_->setX(x + shift);
sprite->render(); sprite_->render();
// shift += (offset[int(text[i])].w + kerning); shift += offset_[static_cast<int>(text[i])].w + kerning;
shift += fixedWidth ? boxWidth : (offset[int(text[i])].w + kerning);
} }
} }
// Escribe el texto con colores // Escribe texto en pantalla
void Text::writeColored(int x, int y, std::string text, Color color, int kerning, int lenght) void Text::write2X(int x, int y, const std::string &text, int kerning)
{ {
sprite->getTexture()->setColor(color.r, color.g, color.b); int shift = 0;
for (size_t i = 0; i < text.length(); ++i)
{
auto index = static_cast<size_t>(text[i]);
SDL_Rect rect = {offset_[index].x, offset_[index].y, box_width_, box_height_};
sprite_->getTexture()->render(x + shift, y, &rect, 2.0f, 2.0f);
shift += (offset_[index].w + kerning) * 2;
}
}
// Escribe el texto en una textura
std::shared_ptr<Texture> Text::writeToTexture(const std::string &text, int zoom, int kerning)
{
auto renderer = Screen::get()->getRenderer();
auto texture = std::make_shared<Texture>(renderer);
auto width = lenght(text, kerning) * zoom;
auto height = box_height_ * zoom;
auto temp = SDL_GetRenderTarget(renderer);
texture->createBlank(width, height, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET);
texture->setBlendMode(SDL_BLENDMODE_BLEND);
texture->setAsRenderTarget(renderer);
SDL_SetRenderDrawColor(renderer, 0, 0, 0, 0);
SDL_RenderClear(renderer);
zoom == 1 ? write(0, 0, text, kerning) : write2X(0, 0, text, kerning);
SDL_SetRenderTarget(renderer, temp);
return texture;
}
// Escribe el texto con extras en una textura
std::shared_ptr<Texture> Text::writeDXToTexture(Uint8 flags, const std::string &text, int kerning, Color textColor, Uint8 shadow_distance, Color shadow_color, int lenght)
{
auto renderer = Screen::get()->getRenderer();
auto texture = std::make_shared<Texture>(renderer);
auto width = Text::lenght(text, kerning) + shadow_distance;
auto height = box_height_ + shadow_distance;
auto temp = SDL_GetRenderTarget(renderer);
texture->createBlank(width, height, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET);
texture->setBlendMode(SDL_BLENDMODE_BLEND);
texture->setAsRenderTarget(renderer);
SDL_SetRenderDrawColor(renderer, 0, 0, 0, 0);
SDL_RenderClear(renderer);
writeDX(flags, 0, 0, text, kerning, textColor, shadow_distance, shadow_color, lenght);
SDL_SetRenderTarget(renderer, temp);
return texture;
}
// Escribe el texto con colores
void Text::writeColored(int x, int y, const std::string &text, Color color, int kerning, int lenght)
{
sprite_->getTexture()->setColor(color.r, color.g, color.b);
write(x, y, text, kerning, lenght); write(x, y, text, kerning, lenght);
sprite->getTexture()->setColor(255, 255, 255); sprite_->getTexture()->setColor(255, 255, 255);
} }
// Escribe el texto con sombra // Escribe el texto con sombra
void Text::writeShadowed(int x, int y, std::string text, Color color, Uint8 shadowDistance, int kerning, int lenght) void Text::writeShadowed(int x, int y, const std::string &text, Color color, Uint8 shadow_distance, int kerning, int lenght)
{ {
sprite->getTexture()->setColor(color.r, color.g, color.b); sprite_->getTexture()->setColor(color.r, color.g, color.b);
write(x + shadowDistance, y + shadowDistance, text, kerning, lenght); write(x + shadow_distance, y + shadow_distance, text, kerning, lenght);
sprite->getTexture()->setColor(255, 255, 255); sprite_->getTexture()->setColor(255, 255, 255);
write(x, y, text, kerning, lenght); write(x, y, text, kerning, lenght);
} }
// Escribe el texto centrado en un punto x // Escribe el texto centrado en un punto x
void Text::writeCentered(int x, int y, std::string text, int kerning, int lenght) void Text::writeCentered(int x, int y, const std::string &text, int kerning, int lenght)
{ {
x -= (Text::lenght(text, kerning) / 2); x -= (Text::lenght(text, kerning) / 2);
write(x, y, text, kerning, lenght); write(x, y, text, kerning, lenght);
} }
// Escribe texto con extras // Escribe texto con extras
void Text::writeDX(Uint8 flags, int x, int y, std::string text, int kerning, Color textColor, Uint8 shadowDistance, Color shadowColor, int lenght) void Text::writeDX(Uint8 flags, int x, int y, const std::string &text, int kerning, Color textColor, Uint8 shadow_distance, Color shadow_color, int lenght)
{ {
const bool centered = ((flags & TXT_CENTER) == TXT_CENTER); const auto centered = ((flags & TEXT_CENTER) == TEXT_CENTER);
const bool shadowed = ((flags & TXT_SHADOW) == TXT_SHADOW); const auto shadowed = ((flags & TEXT_SHADOW) == TEXT_SHADOW);
const bool colored = ((flags & TXT_COLOR) == TXT_COLOR); const auto colored = ((flags & TEXT_COLOR) == TEXT_COLOR);
const bool stroked = ((flags & TXT_STROKE) == TXT_STROKE); const auto stroked = ((flags & TEXT_STROKE) == TEXT_STROKE);
if (centered) if (centered)
{ {
@@ -185,18 +231,18 @@ void Text::writeDX(Uint8 flags, int x, int y, std::string text, int kerning, Col
if (shadowed) if (shadowed)
{ {
writeColored(x + shadowDistance, y + shadowDistance, text, shadowColor, kerning, lenght); writeColored(x + shadow_distance, y + shadow_distance, text, shadow_color, kerning, lenght);
} }
if (stroked) if (stroked)
{ {
for (int dist = 1; dist <= shadowDistance; ++dist) for (int dist = 1; dist <= shadow_distance; ++dist)
{ {
for (int dy = -dist; dy <= dist; ++dy) for (int dy = -dist; dy <= dist; ++dy)
{ {
for (int dx = -dist; dx <= dist; ++dx) for (int dx = -dist; dx <= dist; ++dx)
{ {
writeColored(x + dx, y + dy, text, shadowColor, kerning, lenght); writeColored(x + dx, y + dy, text, shadow_color, kerning, lenght);
} }
} }
} }
@@ -213,31 +259,39 @@ void Text::writeDX(Uint8 flags, int x, int y, std::string text, int kerning, Col
} }
// Obtiene la longitud en pixels de una cadena // Obtiene la longitud en pixels de una cadena
int Text::lenght(std::string text, int kerning) int Text::lenght(const std::string &text, int kerning) const
{ {
int shift = 0; int shift = 0;
for (size_t i = 0; i < text.length(); ++i)
for (int i = 0; i < (int)text.length(); ++i) shift += (offset_[static_cast<int>(text[i])].w + kerning);
shift += (offset[int(text[i])].w + kerning);
// Descuenta el kerning del último caracter // Descuenta el kerning del último caracter
return shift - kerning; return shift - kerning;
} }
// Devuelve el valor de la variable // Devuelve el valor de la variable
int Text::getCharacterSize() int Text::getCharacterSize() const
{ {
return boxWidth; return box_width_;
} }
// Recarga la textura // Recarga la textura
void Text::reLoadTexture() void Text::reLoadTexture()
{ {
sprite->getTexture()->reLoad(); sprite_->getTexture()->reLoad();
} }
// Establece si se usa un tamaño fijo de letra // Establece si se usa un tamaño fijo de letra
void Text::setFixedWidth(bool value) void Text::setFixedWidth(bool value)
{ {
fixedWidth = value; fixed_width_ = value;
}
// Establece una paleta
void Text::setPalette(int number)
{
auto temp = SDL_GetRenderTarget(Screen::get()->getRenderer());
SDL_SetRenderTarget(Screen::get()->getRenderer(), nullptr);
sprite_->getTexture()->setPalette(number);
SDL_SetRenderTarget(Screen::get()->getRenderer(), temp);
} }

View File

@@ -1,79 +1,87 @@
#pragma once #pragma once
#include <SDL2/SDL_render.h> // Para SDL_Renderer
#include <SDL2/SDL_stdinc.h> // Para Uint8 #include <SDL2/SDL_stdinc.h> // Para Uint8
#include <memory> // Para unique_ptr, shared_ptr
#include <string> // Para string #include <string> // Para string
class Sprite; #include "sprite.h" // Para Sprite
class Texture; #include "utils.h" // Para Color
#include "utils.h" class Texture; // lines 9-9
constexpr int TXT_COLOR = 1; constexpr int TEXT_COLOR = 1;
constexpr int TXT_SHADOW = 2; constexpr int TEXT_SHADOW = 2;
constexpr int TXT_CENTER = 4; constexpr int TEXT_CENTER = 4;
constexpr int TXT_STROKE = 8; constexpr int TEXT_STROKE = 8;
struct offset_t struct TextOffset
{ {
int x; int x, y, w;
int y;
int w;
}; };
struct textFile_t struct TextFile
{ {
int boxWidth; // Anchura de la caja de cada caracter en el png int box_width; // Anchura de la caja de cada caracter en el png
int boxHeight; // Altura de la caja de cada caracter en el png int box_height; // Altura de la caja de cada caracter en el png
offset_t offset[128]; // Vector con las posiciones y ancho de cada letra TextOffset offset[128]; // Vector con las posiciones y ancho de cada letra
}; };
// Llena una estructuta textFile_t desde un fichero // Llena una estructuta TextFile desde un fichero
textFile_t LoadTextFile(std::string file, bool verbose = false); std::shared_ptr<TextFile> loadTextFile(const std::string &file_path);
// Clase texto. Pinta texto en pantalla a partir de un bitmap // Clase texto. Pinta texto en pantalla a partir de un bitmap
class Text class Text
{ {
private: private:
// Objetos y punteros // Objetos y punteros
Sprite *sprite; // Objeto con los graficos para el texto std::unique_ptr<Sprite> sprite_ = nullptr; // Objeto con los graficos para el texto
// Variables // Variables
int boxWidth; // Anchura de la caja de cada caracter en el png int box_width_ = 0; // Anchura de la caja de cada caracter en el png
int boxHeight; // Altura de la caja de cada caracter en el png int box_height_ = 0; // Altura de la caja de cada caracter en el png
bool fixedWidth; // Indica si el texto se ha de escribir con longitud fija en todas las letras bool fixed_width_ = false; // Indica si el texto se ha de escribir con longitud fija en todas las letras
offset_t offset[128]; // Vector con las posiciones y ancho de cada letra TextOffset offset_[128] = {}; // Vector con las posiciones y ancho de cada letra
public: public:
// Constructor // Constructor
Text(std::string textFile, Texture *texture, SDL_Renderer *renderer); Text(std::shared_ptr<Texture> texture, const std::string &text_file);
Text(textFile_t *textFile, Texture *texture, SDL_Renderer *renderer); Text(std::shared_ptr<Texture> texture, std::shared_ptr<TextFile> text_file);
// Destructor // Destructor
~Text(); ~Text() = default;
// Escribe el texto en pantalla // Escribe el texto en pantalla
void write(int x, int y, std::string text, int kerning = 1, int lenght = -1); void write(int x, int y, const std::string &text, int kerning = 1, int lenght = -1);
void write2X(int x, int y, const std::string &text, int kerning = 1);
// Escribe el texto en una textura
std::shared_ptr<Texture> writeToTexture(const std::string &text, int zoom = 1, int kerning = 1);
// Escribe el texto con extras en una textura
std::shared_ptr<Texture> writeDXToTexture(Uint8 flags, const std::string &text, int kerning = 1, Color textColor = Color(), Uint8 shadow_distance = 1, Color shadow_color = Color(), int lenght = -1);
// Escribe el texto con colores // Escribe el texto con colores
void writeColored(int x, int y, std::string text, Color color, int kerning = 1, int lenght = -1); void writeColored(int x, int y, const std::string &text, Color color, int kerning = 1, int lenght = -1);
// Escribe el texto con sombra // Escribe el texto con sombra
void writeShadowed(int x, int y, std::string text, Color color, Uint8 shadowDistance = 1, int kerning = 1, int lenght = -1); void writeShadowed(int x, int y, const std::string &text, Color color, Uint8 shadow_distance = 1, int kerning = 1, int lenght = -1);
// Escribe el texto centrado en un punto x // Escribe el texto centrado en un punto x
void writeCentered(int x, int y, std::string text, int kerning = 1, int lenght = -1); void writeCentered(int x, int y, const std::string &text, int kerning = 1, int lenght = -1);
// Escribe texto con extras // Escribe texto con extras
void writeDX(Uint8 flags, int x, int y, std::string text, int kerning = 1, Color textColor = Color(255, 255, 255), Uint8 shadowDistance = 1, Color shadowColor = Color(0, 0, 0), int lenght = -1); void writeDX(Uint8 flags, int x, int y, const std::string &text, int kerning = 1, Color textColor = Color(), Uint8 shadow_distance = 1, Color shadow_color = Color(), int lenght = -1);
// Obtiene la longitud en pixels de una cadena // Obtiene la longitud en pixels de una cadena
int lenght(std::string text, int kerning = 1); int lenght(const std::string &text, int kerning = 1) const;
// Devuelve el valor de la variable // Devuelve el valor de la variable
int getCharacterSize(); int getCharacterSize() const;
// Recarga la textura // Recarga la textura
void reLoadTexture(); void reLoadTexture();
// Establece si se usa un tamaño fijo de letra // Establece si se usa un tamaño fijo de letra
void setFixedWidth(bool value); void setFixedWidth(bool value);
// Establece una paleta
void setPalette(int number);
}; };

View File

@@ -78,10 +78,18 @@ bool Texture::loadFromFile(const std::string &file_path)
int depth, pitch; int depth, pitch;
Uint32 pixel_format; Uint32 pixel_format;
// STBI_rgb_alpha (RGBA) /*if (req_format == STBI_rgb)
{
depth = 24;
pitch = 3 * width; // 3 bytes por pixel * pixels por linea
pixel_format = SDL_PIXELFORMAT_RGB24;
}
else*/
{ // STBI_rgb_alpha (RGBA)
depth = 32; depth = 32;
pitch = 4 * width; pitch = 4 * width;
pixel_format = SDL_PIXELFORMAT_RGBA32; pixel_format = SDL_PIXELFORMAT_RGBA32;
}
// Limpia // Limpia
unloadTexture(); unloadTexture();

View File

@@ -62,7 +62,7 @@ public:
bool loadFromFile(const std::string &path); bool loadFromFile(const std::string &path);
// Crea una textura en blanco // Crea una textura en blanco
bool createBlank(int width, int height, SDL_PixelFormatEnum format = SDL_PIXELFORMAT_RGBA8888, SDL_TextureAccess = SDL_TEXTUREACCESS_STREAMING); bool createBlank(int width, int height, SDL_PixelFormatEnum format = SDL_PIXELFORMAT_RGBA8888, SDL_TextureAccess = SDL_TEXTUREACCESS_TARGET);
// Establece el color para la modulacion // Establece el color para la modulacion
void setColor(Uint8 red, Uint8 green, Uint8 blue); void setColor(Uint8 red, Uint8 green, Uint8 blue);

View File

@@ -35,9 +35,9 @@ Title::Title()
{ {
texture_ = resource_->getTexture("title_logo.png"); texture_ = resource_->getTexture("title_logo.png");
} }
sprite_ = new Sprite(0, 0, texture_->getWidth(), texture_->getHeight(), texture_, renderer_); sprite_ = std::make_shared<Sprite>(0, 0, texture_->getWidth(), texture_->getHeight(), texture_, renderer_);
text_ = new Text(resource_->getOffset("smb2.txt"), resource_->getTexture("smb2.png"), renderer_); text_ = resource_->getText("smb2.txt");
info_text_ = new Text(resource_->getOffset("subatomic.txt"), resource_->getTexture("subatomic.png"), renderer_); info_text_ = resource_->getText("subatomic.txt");
// Crea la textura para los graficos que aparecen en el fondo de la pantalla de titulo // Crea la textura para los graficos que aparecen en el fondo de la pantalla de titulo
bg_texture_ = SDL_CreateTexture(renderer_, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, GAMECANVAS_WIDTH, GAMECANVAS_HEIGHT); bg_texture_ = SDL_CreateTexture(renderer_, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, GAMECANVAS_WIDTH, GAMECANVAS_HEIGHT);
@@ -75,11 +75,6 @@ Title::Title()
// Destructor // Destructor
Title::~Title() Title::~Title()
{ {
delete sprite_;
delete cheevos_sprite_;
delete cheevos_texture_;
delete text_;
delete info_text_;
pDeleteSurface(loading_screen_); pDeleteSurface(loading_screen_);
SDL_DestroyTexture(bg_texture_); SDL_DestroyTexture(bg_texture_);
} }
@@ -387,10 +382,10 @@ void Title::fillTexture()
// Escribe el texto en la textura // Escribe el texto en la textura
const Color textColor = stringToColor(options.video.palette, "green"); const Color textColor = stringToColor(options.video.palette, "green");
const int textSize = text_->getCharacterSize(); const int textSize = text_->getCharacterSize();
text_->writeDX(TXT_CENTER | TXT_COLOR, PLAY_AREA_CENTER_X, 11 * textSize, "1.PLAY", 1, textColor); text_->writeDX(TEXT_CENTER | TEXT_COLOR, PLAY_AREA_CENTER_X, 11 * textSize, "1.PLAY", 1, textColor);
text_->writeDX(TXT_CENTER | TXT_COLOR, PLAY_AREA_CENTER_X, 13 * textSize, "2.ACHIEVEMENTS", 1, textColor); text_->writeDX(TEXT_CENTER | TEXT_COLOR, PLAY_AREA_CENTER_X, 13 * textSize, "2.ACHIEVEMENTS", 1, textColor);
text_->writeDX(TXT_CENTER | TXT_COLOR, PLAY_AREA_CENTER_X, 15 * textSize, "3.REDEFINE KEYS", 1, textColor); text_->writeDX(TEXT_CENTER | TEXT_COLOR, PLAY_AREA_CENTER_X, 15 * textSize, "3.REDEFINE KEYS", 1, textColor);
text_->writeDX(TXT_CENTER | TXT_COLOR, PLAY_AREA_CENTER_X, 20 * textSize, "ESC.EXIT GAME", 1, textColor); text_->writeDX(TEXT_CENTER | TEXT_COLOR, PLAY_AREA_CENTER_X, 20 * textSize, "ESC.EXIT GAME", 1, textColor);
// Devuelve el puntero del renderizador a su sitio // Devuelve el puntero del renderizador a su sitio
SDL_SetRenderTarget(renderer_, nullptr); SDL_SetRenderTarget(renderer_, nullptr);
@@ -407,8 +402,8 @@ void Title::createCheevosTexture()
const int cheevosPadding = 10; const int cheevosPadding = 10;
const int cheevoHeight = cheevosPadding + (info_text_->getCharacterSize() * 2) + 1; const int cheevoHeight = cheevosPadding + (info_text_->getCharacterSize() * 2) + 1;
const int cheevosTextureHeight = (cheevoHeight * cheevosList.size()) + 2 + info_text_->getCharacterSize() + 8; const int cheevosTextureHeight = (cheevoHeight * cheevosList.size()) + 2 + info_text_->getCharacterSize() + 8;
cheevos_texture_ = new Texture(renderer_); cheevos_texture_ = std::make_shared<Texture>(renderer_);
cheevos_texture_->createBlank(renderer_, cheevosTextureWidth, cheevosTextureHeight, SDL_TEXTUREACCESS_TARGET); cheevos_texture_->createBlank(cheevosTextureWidth, cheevosTextureHeight, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET);
cheevos_texture_->setAsRenderTarget(renderer_); cheevos_texture_->setAsRenderTarget(renderer_);
cheevos_texture_->setBlendMode(SDL_BLENDMODE_BLEND); cheevos_texture_->setBlendMode(SDL_BLENDMODE_BLEND);
@@ -421,7 +416,7 @@ void Title::createCheevosTexture()
const std::string cheevosOwner = "ACHIEVEMENTS"; const std::string cheevosOwner = "ACHIEVEMENTS";
const std::string cheevosListCaption = cheevosOwner + " (" + std::to_string(Cheevos::get()->unlocked()) + " / " + std::to_string(Cheevos::get()->count()) + ")"; const std::string cheevosListCaption = cheevosOwner + " (" + std::to_string(Cheevos::get()->unlocked()) + " / " + std::to_string(Cheevos::get()->count()) + ")";
int pos = 2; int pos = 2;
info_text_->writeDX(TXT_CENTER | TXT_COLOR, cheevos_texture_->getWidth() / 2, pos, cheevosListCaption, 1, stringToColor(options.video.palette, "bright_green")); info_text_->writeDX(TEXT_CENTER | TEXT_COLOR, cheevos_texture_->getWidth() / 2, pos, cheevosListCaption, 1, stringToColor(options.video.palette, "bright_green"));
pos += info_text_->getCharacterSize(); pos += info_text_->getCharacterSize();
const Color cheevoLockedColor = stringToColor(options.video.palette, "white"); const Color cheevoLockedColor = stringToColor(options.video.palette, "white");
const Color cheevoUnlockedColor = stringToColor(options.video.palette, "bright_green"); const Color cheevoUnlockedColor = stringToColor(options.video.palette, "bright_green");
@@ -436,14 +431,14 @@ void Title::createCheevosTexture()
pos += cheevosPadding; pos += cheevosPadding;
int half = cheevosPadding / 2; int half = cheevosPadding / 2;
SDL_RenderDrawLine(renderer_, lineX1, pos - half - 1, lineX2, pos - half - 1); SDL_RenderDrawLine(renderer_, lineX1, pos - half - 1, lineX2, pos - half - 1);
info_text_->writeDX(TXT_CENTER | TXT_COLOR, cheevosTextureWidth / 2, pos, cheevo.caption, 1, cheevoColor); info_text_->writeDX(TEXT_CENTER | TEXT_COLOR, cheevosTextureWidth / 2, pos, cheevo.caption, 1, cheevoColor);
pos += info_text_->getCharacterSize() + 1; pos += info_text_->getCharacterSize() + 1;
info_text_->writeDX(TXT_CENTER | TXT_COLOR, cheevosTextureWidth / 2, pos, cheevo.description, 1, cheevoColor); info_text_->writeDX(TEXT_CENTER | TEXT_COLOR, cheevosTextureWidth / 2, pos, cheevo.description, 1, cheevoColor);
pos += info_text_->getCharacterSize(); pos += info_text_->getCharacterSize();
} }
// Crea el sprite para el listado de logros // Crea el sprite para el listado de logros
cheevos_sprite_ = new Sprite((GAMECANVAS_WIDTH - cheevos_texture_->getWidth()) / 2, cheevosTexturePosY, cheevos_texture_->getWidth(), cheevos_texture_->getHeight(), cheevos_texture_, renderer_); cheevos_sprite_ = std::make_shared<Sprite>((GAMECANVAS_WIDTH - cheevos_texture_->getWidth()) / 2, cheevosTexturePosY, cheevos_texture_->getWidth(), cheevos_texture_->getHeight(), cheevos_texture_, renderer_);
cheevos_texture_view_ = {0, 0, cheevos_texture_->getWidth(), cheevosTextureViewHeight}; cheevos_texture_view_ = {0, 0, cheevos_texture_->getWidth(), cheevosTextureViewHeight};
cheevos_sprite_->setClip(cheevos_texture_view_); cheevos_sprite_->setClip(cheevos_texture_view_);
} }

View File

@@ -41,13 +41,13 @@ private:
SDL_Renderer *renderer_; // El renderizador de la ventana SDL_Renderer *renderer_; // El renderizador de la ventana
Resource *resource_; // Objeto con los recursos Resource *resource_; // Objeto con los recursos
Input *input_; // Objeto pata gestionar la entrada Input *input_; // Objeto pata gestionar la entrada
Texture *texture_; // Textura con los graficos std::shared_ptr<Texture> texture_; // Textura con los graficos
Sprite *sprite_; // Sprite para manejar la textura std::shared_ptr<Sprite> sprite_; // Sprite para manejar la textura
SDL_Texture *bg_texture_; // Textura para dibujar el fondo de la pantalla SDL_Texture *bg_texture_; // Textura para dibujar el fondo de la pantalla
Text *text_; // Objeto para escribir texto en pantalla std::shared_ptr<Text> text_; // Objeto para escribir texto en pantalla
Text *info_text_; // Objeto para escribir texto en pantalla std::shared_ptr<Text> info_text_; // Objeto para escribir texto en pantalla
Texture *cheevos_texture_; // Textura con la lista de logros std::shared_ptr<Texture> cheevos_texture_; // Textura con la lista de logros
Sprite *cheevos_sprite_; // Sprite para manejar la textura con la lista de logros std::shared_ptr<Sprite> cheevos_sprite_; // Sprite para manejar la textura con la lista de logros
// Variables // Variables
int counter_ = 0; // Contador int counter_ = 0; // Contador

View File

@@ -3,6 +3,7 @@
#include <stdlib.h> // Para free, malloc, abs #include <stdlib.h> // Para free, malloc, abs
#include <cmath> // Para round, abs #include <cmath> // Para round, abs
#include <algorithm> #include <algorithm>
#include <iostream>
#include <cctype> #include <cctype>
// Calcula el cuadrado de la distancia entre dos puntos // Calcula el cuadrado de la distancia entre dos puntos
@@ -604,3 +605,16 @@ std::string getPath(const std::string &full_path)
std::filesystem::path path(full_path); std::filesystem::path path(full_path);
return path.parent_path().string(); return path.parent_path().string();
} }
// Imprime por pantalla una linea de texto de tamaño fijo rellena con puntos
void printWithDots(const std::string &text1, const std::string &text2, const std::string &text3)
{
std::cout.setf(std::ios::left, std::ios::adjustfield);
std::cout << text1;
std::cout.width(50 - text1.length() - text3.length());
std::cout.fill('.');
std::cout << text2;
std::cout << text3 << std::endl;
}

View File

@@ -121,3 +121,6 @@ std::string getFileName(const std::string &path);
// Obtiene la ruta eliminando el nombre del fichero // Obtiene la ruta eliminando el nombre del fichero
std::string getPath(const std::string &full_path); std::string getPath(const std::string &full_path);
// Imprime por pantalla una linea de texto de tamaño fijo rellena con puntos
void printWithDots(const std::string &text1, const std::string &text2, const std::string &text3);