From e6f101ece6d112ebaa590112557387008c1783f5 Mon Sep 17 00:00:00 2001 From: Sergio Valor Date: Mon, 24 Feb 2025 14:09:29 +0100 Subject: [PATCH] Afegint smart pointers Actualitzat Resources Actualitzades les classes Sprite i derivades Afegida nova tipografia Actualitzat Asset Actualitzat Text --- data/font/8bithud.png | Bin 0 -> 1094 bytes data/font/8bithud.txt | 194 ++++++ source/animated_sprite.cpp | 250 ++++++++ source/animated_sprite.h | 66 ++ source/animatedsprite.cpp | 538 ---------------- source/animatedsprite.h | 98 --- source/asset.cpp | 167 ++--- source/asset.h | 65 +- source/credits.cpp | 12 +- source/credits.h | 19 +- source/director.cpp | 1233 +++++++++--------------------------- source/director.h | 3 - source/ending.cpp | 73 +-- source/ending.h | 27 +- source/ending2.cpp | 101 +-- source/ending2.h | 30 +- source/enemy.cpp | 8 +- source/game.cpp | 4 +- source/game_over.cpp | 54 +- source/game_over.h | 18 +- source/loading_screen.cpp | 30 +- source/loading_screen.h | 21 +- source/logo.cpp | 35 +- source/logo.h | 21 +- source/moving_sprite.cpp | 230 +++++++ source/moving_sprite.h | 122 ++++ source/movingsprite.cpp | 416 ------------ source/movingsprite.h | 185 ------ source/player.cpp | 24 +- source/resource.cpp | 613 +++++++++--------- source/resource.h | 262 +++++--- source/resource_old.cpp | 360 +++++++++++ source/resource_old.h | 142 +++++ source/scoreboard.cpp | 14 +- source/text.cpp | 238 ++++--- source/text.h | 74 ++- source/texture.cpp | 16 +- source/texture.h | 2 +- source/title.cpp | 31 +- source/title.h | 12 +- source/utils.cpp | 14 + source/utils.h | 5 +- 42 files changed, 2669 insertions(+), 3158 deletions(-) create mode 100644 data/font/8bithud.png create mode 100644 data/font/8bithud.txt create mode 100644 source/animated_sprite.cpp create mode 100644 source/animated_sprite.h delete mode 100644 source/animatedsprite.cpp delete mode 100644 source/animatedsprite.h create mode 100644 source/moving_sprite.cpp create mode 100644 source/moving_sprite.h delete mode 100644 source/movingsprite.cpp delete mode 100644 source/movingsprite.h create mode 100644 source/resource_old.cpp create mode 100644 source/resource_old.h diff --git a/data/font/8bithud.png b/data/font/8bithud.png new file mode 100644 index 0000000000000000000000000000000000000000..2ac5e4c8d74520242b2fb7a2bcf709bd8fc9a0e7 GIT binary patch literal 1094 zcmV-M1iAZ(P)Px(07*naRCt{2o7t9PF$hJ~<^TWk?H5xE5jcmCsMlscl|l#^7*f@Jxd4s_NXPow zvfhpT_qdRiy5p+oojAhM0dTk`RJWapbNLHU3$m*>sV z8)eDlcgJxYTF3hA9fUjpZOij%CFp`j-@k+M0Y`_+vMPctdpi$T+qdRIrHPS!bB1_w zFmhIYZ>3o&i!MZVBbd#LbgB_tJv=lXMsU>ul%lIxDLUgXss(-(ua zvAff1^8voP&YYN+#zaStx9O3d*YH^5SvmS#wZB{LWhEr9a%UBz1x1mEE)092SpTx} z?1i3{SDC#C_sZZw)Yvc!UZIn{IN7yk=V#|({D{uS%bWu`f~!OeiBkHi3{Z_QZ~Tf3 zG`fFJX3gWxuet560slLwc|;e2dB#O^&=Fj%E#A#vZMUkI9lxUHGHHAqqSo!eY?@z& z3h&j84SFXt_M;TP@*U33uk|zbCEA|#+49Y^cSj1=1bP9?FCn}QKytPT%-BccCDkT0 zyN-yc+xECe1zbDCbc4fQ_W9slhE*W@)%jO6Tgd*5U-!!;?$YE0Ll-$>eV<9ovx|wC zjbM$p4{RXJ;sp-kCLM|fUmq}zWE?mftJjyg4C9b9_F)ayj_f)>FGb4iBK4yZfKsrh zW8uxuqQ`kn8EcO%fkVFJu(F+E(=>~?>eR+Ob-cHj*0W?P?z?CRwoQoEMQur?PGbx&vIiRfX)zY%;e>TYU zI8$So#=^o%&9n1+{*TYm#q(;c_GvaqPzgF?=4zS-g1SzoGp%&4om%z+n=Di_Dh-6R zftnZTk0-O_NC%C#)*g+|`lxHPSHnHq);v-N{ylg%nF};NGtG`SKJtUHkH#bav&j9~ z{!H>5uzsGk;ek?lbtBpNcOB%eQbqs4e-_X2>^$fRg(9%ZYy@kV43zN;trte{S(+d( zg5>3u-?8JhJkqhS=FcFYa zH?6qa;aRNc(#&KKFLGBQQ!NT2YyWi$&d&exPj);bhafviL}mlf_?b=6>#EEjMVV*Y z^8cGMNYgY;vkkLmbq)AYb~I7VXL +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 \ No newline at end of file diff --git a/source/animated_sprite.cpp b/source/animated_sprite.cpp new file mode 100644 index 0000000..065a468 --- /dev/null +++ b/source/animated_sprite.cpp @@ -0,0 +1,250 @@ +#include "animated_sprite.h" +#include // Para size_t +#include // Para basic_ostream, basic_istream, operator<<, basic... +#include // Para cout, cerr +#include // Para basic_stringstream +#include // 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 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, 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, 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); +} \ No newline at end of file diff --git a/source/animated_sprite.h b/source/animated_sprite.h new file mode 100644 index 0000000..e2cc6f5 --- /dev/null +++ b/source/animated_sprite.h @@ -0,0 +1,66 @@ +#pragma once + +#include // Para SDL_Rect +#include // Para shared_ptr +#include // Para string +#include // Para vector +#include "moving_sprite.h" // Para MovingSprite +class Texture; // lines 9-9 + +struct Animation +{ + std::string name; // Nombre de la animacion + std::vector 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; + +// 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 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, const std::string &file_path); + AnimatedSprite(std::shared_ptr texture, const AnimationsFileBuffer &animations); + explicit AnimatedSprite(std::shared_ptr 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(); +}; \ No newline at end of file diff --git a/source/animatedsprite.cpp b/source/animatedsprite.cpp deleted file mode 100644 index 7cfbe32..0000000 --- a/source/animatedsprite.cpp +++ /dev/null @@ -1,538 +0,0 @@ -#include "animatedsprite.h" -#include // Para basic_ostream, operator<<, basic_istream, basic... -#include // Para cout -#include // 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 *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 *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; -} \ No newline at end of file diff --git a/source/animatedsprite.h b/source/animatedsprite.h deleted file mode 100644 index c8b5e79..0000000 --- a/source/animatedsprite.h +++ /dev/null @@ -1,98 +0,0 @@ -#pragma once - -#include // Para SDL_Rect -#include // Para SDL_Renderer -#include // Para Uint8 -#include // Para string -#include // Para vector -#include "movingsprite.h" // Para MovingSprite -class Texture; - -struct animation_t -{ - std::string name; // Nombre de la animacion - std::vector 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 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; // Vector con las diferentes animaciones - int currentAnimation; // Animacion activa - -public: - // Constructor - AnimatedSprite(Texture *texture = nullptr, SDL_Renderer *renderer = nullptr, std::string file = "", std::vector *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 *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(); -}; \ No newline at end of file diff --git a/source/asset.cpp b/source/asset.cpp index ce5a11e..68704bc 100644 --- a/source/asset.cpp +++ b/source/asset.cpp @@ -1,86 +1,77 @@ #include "asset.h" -#include // Para SDL_RWFromFile, SDL_RWclose, SDL_RWops -#include // Para SDL_max -#include // Para size_t -#include // Para basic_ostream, operator<<, cout, endl +#include // Para find_if, max +#include // Para basic_ostream, operator<<, basic_ifstream, endl +#include // Para cout +#include // 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 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) { 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() { 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() { return Asset::asset_; } // 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; - temp.file = absolute ? file : executable_path_ + file; - 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()); + file_list_.emplace_back(absolute ? file : executable_path_ + file, type, required); + longest_name_ = std::max(longest_name_, static_cast(file_list_.back().file.size())); } -// Devuelve el fichero de un elemento de la lista a partir de una cadena -std::string Asset::get(std::string text) +// Devuelve la ruta completa a un fichero a partir de una cadena +std::string Asset::get(const std::string &text) const { - for (auto f : fileList) - { - const size_t lastIndex = f.file.find_last_of("/") + 1; - const std::string file = f.file.substr(lastIndex, std::string::npos); + auto it = std::find_if(file_list_.begin(), file_list_.end(), + [&text](const auto &f) + { + return getFileName(f.file) == text; + }); - if (file == text) - { - return f.file; - } - } - - if (verbose_) + if (it != file_list_.end()) { - std::cout << "Warning: file " << text.c_str() << " not found" << std::endl; + return it->file; + } + else + { + std::cout << "Warning: file " << text << " not found" << std::endl; + return ""; } - return ""; } // Comprueba que existen todos los elementos -bool Asset::check() +bool Asset::check() const { 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 << "Sample filepath: " << fileList.back().file << std::endl; - } + // std::cout << "Executable path is: " << executable_path_ << std::endl; + // std::cout << "Sample filepath: " << file_list_.back().file << std::endl; // Comprueba la lista de ficheros clasificandolos por tipo - for (int type = 0; type < t_maxAssetType; ++type) + for (int type = 0; type < static_cast(AssetType::MAX_ASSET_TYPE); ++type) { // Comprueba si hay ficheros de ese tipo 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(type)) { any = true; } @@ -89,107 +80,77 @@ bool Asset::check() // Si hay ficheros de ese tipo, comprueba si existen if (any) { - if (verbose_) - { - std::cout << "\n>> " << getTypeName(type).c_str() << " FILES" << std::endl; - } + std::cout << "\n>> " << getTypeName(static_cast(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(type)) { success &= checkFile(f.file); } } + if (success) + std::cout << " All files are OK." << std::endl; } } // Resultado - if (verbose_) - { - if (success) - { - std::cout << "\n** All files OK.\n" - << std::endl; - } - else - { - std::cout << "\n** A file is missing. Exiting.\n" - << std::endl; - } - } + std::cout << (success ? "\n** CHECKING FILES COMPLETED.\n" : "\n** CHECKING FILES FAILED.\n") << std::endl; return success; } // Comprueba que existe un fichero -bool Asset::checkFile(std::string path) +bool Asset::checkFile(const std::string &path) const { - bool success = false; - std::string result = "ERROR"; + std::ifstream file(path); + bool success = file.good(); + file.close(); - // Comprueba si existe el fichero - const std::string filename = path.substr(path.find_last_of("\\/") + 1); - 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; - } + if (!success) + printWithDots("Checking file : ", getFileName(path), "[ ERROR ]"); return success; } // Devuelve el nombre del tipo de recurso -std::string Asset::getTypeName(int type) +std::string Asset::getTypeName(AssetType type) const { switch (type) { - case t_bitmap: + case AssetType::BITMAP: return "BITMAP"; break; - case t_music: + case AssetType::MUSIC: return "MUSIC"; break; - case t_sound: + case AssetType::SOUND: return "SOUND"; break; - case t_font: + case AssetType::FONT: return "FONT"; break; - case t_lang: + case AssetType::LANG: return "LANG"; break; - case t_data: + case AssetType::DATA: return "DATA"; break; - case t_room: - return "ROOM"; + case AssetType::ANIMATION: + return "ANIMATION"; break; - case t_enemy: - return "ENEMY"; + case AssetType::PALETTE: + return "PALETTE"; break; - case t_item: + case AssetType::ITEM: return "ITEM"; break; @@ -199,8 +160,18 @@ std::string Asset::getTypeName(int type) } } -// Establece si ha de mostrar texto por pantalla -void Asset::setVerbose(bool value) +// Devuelve la lista de recursos de un tipo +std::vector Asset::getListByType(AssetType type) const { - verbose_ = value; + std::vector list; + + for (auto f : file_list_) + { + if (f.type == type) + { + list.push_back(f.file); + } + } + + return list; } \ No newline at end of file diff --git a/source/asset.h b/source/asset.h index 72f6f00..89e618c 100644 --- a/source/asset.h +++ b/source/asset.h @@ -1,49 +1,52 @@ #pragma once -#include // Para string -#include // Para vector +#include // para string, basic_string +#include // para vector #include "utils.h" -enum assetType +enum class AssetType : int { - t_bitmap, - t_music, - t_sound, - t_font, - t_lang, - t_data, - t_room, - t_enemy, - t_item, - t_maxAssetType + BITMAP, + MUSIC, + SOUND, + FONT, + LANG, + DATA, + ROOM, + ENEMY, + ITEM, + MAX_ASSET_TYPE }; // Clase Asset class Asset { private: - // [SINGLETON] Objeto asset privado + // [SINGLETON] Objeto asset privado para Don Melitón static Asset *asset_; // Estructura para definir un item - struct item_t + struct AssetItem { - std::string file; // Ruta del fichero desde la raiz del directorio - enum assetType type; // Indica el tipo de recurso - bool required; // Indica si es un fichero que debe de existir + std::string file; // Ruta del fichero desde la raíz del directorio + AssetType type; // Indica el tipo de recurso + bool required; // Indica si es un fichero que debe de existir + + // Constructor + AssetItem(const std::string &filePath, AssetType assetType, bool isRequired) + : file(filePath), type(assetType), required(isRequired) {} }; // Variables - int longest_name_ = 0; // Contiene la longitud del nombre de fichero mas largo - std::vector fileList; // Listado con todas las rutas a los ficheros - std::string executable_path_; // Ruta al ejecutable - bool verbose_ = true; // Indica si ha de mostrar información por pantalla + int longest_name_ = 0; // Contiene la longitud del nombre de fichero mas largo + std::vector file_list_; // Listado con todas las rutas a los ficheros + std::string executable_path_; // Ruta al ejecutable // Comprueba que existe un fichero - bool checkFile(std::string executablePath); + bool checkFile(const std::string &path) const; // Devuelve el nombre del tipo de recurso - std::string getTypeName(int type); + std::string getTypeName(AssetType type) const; // Constructor explicit Asset(const std::string &executable_path) @@ -63,14 +66,14 @@ public: static Asset *get(); // 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 - std::string get(std::string text); + // Devuelve la ruta completa a un fichero a partir de una cadena + std::string get(const std::string &text) const; // Comprueba que existen todos los elementos - bool check(); + bool check() const; - // Establece si ha de mostrar texto por pantalla - void setVerbose(bool value); -}; + // Devuelve la lista de recursos de un tipo + std::vector getListByType(AssetType type) const; +}; \ No newline at end of file diff --git a/source/credits.cpp b/source/credits.cpp index 182a129..33e6fe9 100644 --- a/source/credits.cpp +++ b/source/credits.cpp @@ -6,7 +6,7 @@ #include // Para SDL_GetTicks #include // Para min #include // 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 "input.h" // Para Input, REPEAT_FALSE, inputs_e #include "resource.h" // Para Resource @@ -27,13 +27,13 @@ Credits::Credits() input_(Input::get()) { // Reserva memoria para los punteros - text_ = new Text(resource_->getOffset("smb2.txt"), resource_->getTexture("smb2.png"), renderer_); - sprite_ = new AnimatedSprite(renderer_, resource_->getAnimation("shine.ani")); + text_ = resource_->getText("smb2.txt"); + sprite_ = std::make_shared(resource_->getTexture("shine.png"), resource_->getAnimation("shine.ani")); // Inicializa variables options.section.section = Section::CREDITS; options.section.subsection = Subsection::NONE; - sprite_->setRect({194, 174, 8, 8}); + sprite_->setPosition({194, 174, 8, 8}); // Cambia el color del borde screen_->setBorderColor(stringToColor(options.video.palette, "black")); @@ -67,8 +67,6 @@ Credits::Credits() // Destructor Credits::~Credits() { - delete text_; - delete sprite_; SDL_DestroyTexture(text_texture_); SDL_DestroyTexture(cover_texture_); } @@ -185,7 +183,7 @@ void Credits::fillTexture() 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++; } diff --git a/source/credits.h b/source/credits.h index 5d5f6d5..f4c4933 100644 --- a/source/credits.h +++ b/source/credits.h @@ -5,6 +5,7 @@ #include // Para Uint32 #include // Para basic_string, string #include // Para vector +#include // Para shared_ptr #include "utils.h" // Para color_t class AnimatedSprite; class Asset; @@ -23,15 +24,15 @@ private: }; // Objetos y punteros - Screen *screen_; // Objeto encargado de dibujar en pantalla - SDL_Renderer *renderer_; // El renderizador de la ventana - Resource *resource_; // Objeto con los recursos - Asset *asset_; // Objeto con los ficheros de recursos - Input *input_; // Objeto pata gestionar la entrada - Text *text_; // Objeto para escribir texto en pantalla - SDL_Texture *text_texture_; // Textura para dibujar el texto - SDL_Texture *cover_texture_; // Textura para cubrir el texto - AnimatedSprite *sprite_; // Sprite para el brillo del corazón + Screen *screen_; // Objeto encargado de dibujar en pantalla + SDL_Renderer *renderer_; // El renderizador de la ventana + Resource *resource_; // Objeto con los recursos + Asset *asset_; // Objeto con los ficheros de recursos + Input *input_; // Objeto pata gestionar la entrada + std::shared_ptr text_; // Objeto para escribir texto en pantalla + SDL_Texture *text_texture_; // Textura para dibujar el texto + SDL_Texture *cover_texture_; // Textura para cubrir el texto + std::shared_ptr sprite_; // Sprite para el brillo del corazón // Variables int counter_ = 0; // Contador diff --git a/source/director.cpp b/source/director.cpp index 9cefb79..f6a0c59 100644 --- a/source/director.cpp +++ b/source/director.cpp @@ -57,7 +57,6 @@ Director::Director(int argc, const char *argv[]) // Crea el objeto que controla los ficheros de recursos Asset::init(executable_path_); - Asset::get()->setVerbose(options.console); // Crea la carpeta del sistema donde guardar datos createSystemFolder("jailgames"); @@ -211,554 +210,6 @@ void Director::createSystemFolder(const std::string &folder) } } -// Carga los recursos -void Director::loadResources(SectionState section) -{ - if (options.console) - { - std::cout << "** LOAD RESOURCES" << std::endl; - } - - if (options.section.section == Section::LOGO) - { - std::vector textureList; - textureList.push_back("jailgames.png"); - textureList.push_back("since_1998.png"); - - Resource::get()->loadTextures(textureList); - } - - else if (options.section.section == Section::LOADING_SCREEN) - { - std::vector textureList; - textureList.push_back("loading_screen_bn.png"); - textureList.push_back("loading_screen_color.png"); - textureList.push_back("loading_screen_bn_zxarne.png"); - textureList.push_back("loading_screen_color_zxarne.png"); - - Resource::get()->loadTextures(textureList); - } - - else if (options.section.section == Section::TITLE) - { - std::vector textureList; - textureList.push_back("loading_screen_color.png"); - textureList.push_back("loading_screen_color_zxarne.png"); - textureList.push_back("smb2.png"); - textureList.push_back("subatomic.png"); - textureList.push_back("notify.png"); - textureList.push_back("title_logo.png"); - - Resource::get()->loadTextures(textureList); - - // Offsets - std::vector offsetsList; - offsetsList.push_back("smb2.txt"); - offsetsList.push_back("subatomic.txt"); - - Resource::get()->loadOffsets(offsetsList); - } - - else if (options.section.section == Section::CREDITS) - { - // Texturas - std::vector textureList; - textureList.push_back("shine.png"); - textureList.push_back("smb2.png"); - - Resource::get()->loadTextures(textureList); - - // Animaciones - std::vector animationList; - animationList.push_back("shine.ani"); - - Resource::get()->loadAnimations(animationList); - - // Offsets - std::vector offsetsList; - offsetsList.push_back("smb2.txt"); - - Resource::get()->loadOffsets(offsetsList); - } - - else if (options.section.section == Section::ENDING) - { - // Texturas - std::vector textureList; - textureList.push_back("ending1.png"); - textureList.push_back("ending1_zxarne.png"); - textureList.push_back("ending2.png"); - textureList.push_back("ending2_zxarne.png"); - textureList.push_back("ending3.png"); - textureList.push_back("ending3_zxarne.png"); - textureList.push_back("ending4.png"); - textureList.push_back("ending4_zxarne.png"); - textureList.push_back("ending5.png"); - textureList.push_back("ending5_zxarne.png"); - textureList.push_back("smb2.png"); - - Resource::get()->loadTextures(textureList); - - // Offsets - std::vector offsetsList; - offsetsList.push_back("smb2.txt"); - - Resource::get()->loadOffsets(offsetsList); - } - - else if (options.section.section == Section::ENDING2) - { - // Texturas - std::vector textureList; - - // Texto - textureList.push_back("smb2.png"); - - // Enemigos - textureList.push_back("abad.png"); - textureList.push_back("abad_bell.png"); - textureList.push_back("amstrad_cs.png"); - textureList.push_back("flying_arounder.png"); - textureList.push_back("stopped_arounder.png"); - textureList.push_back("walking_arounder.png"); - textureList.push_back("arounders_door.png"); - textureList.push_back("arounders_machine.png"); - textureList.push_back("bat.png"); - textureList.push_back("batman_bell.png"); - textureList.push_back("batman_fire.png"); - textureList.push_back("batman.png"); - textureList.push_back("bell.png"); - textureList.push_back("bin.png"); - textureList.push_back("bird.png"); - textureList.push_back("breakout.png"); - textureList.push_back("bry.png"); - textureList.push_back("chip.png"); - textureList.push_back("code.png"); - textureList.push_back("congo.png"); - textureList.push_back("crosshair.png"); - textureList.push_back("demon.png"); - textureList.push_back("heavy.png"); - textureList.push_back("dimallas.png"); - textureList.push_back("floppy.png"); - textureList.push_back("dong.png"); - textureList.push_back("guitar.png"); - textureList.push_back("jailbattle_alien.png"); - textureList.push_back("jailbattle_human.png"); - textureList.push_back("jailer_#1.png"); - textureList.push_back("jailer_#2.png"); - textureList.push_back("jailer_#3.png"); - textureList.push_back("jeannine.png"); - textureList.push_back("lamp.png"); - textureList.push_back("lord_abad.png"); - textureList.push_back("robot.png"); - textureList.push_back("matatunos.png"); - textureList.push_back("mummy.png"); - textureList.push_back("paco.png"); - textureList.push_back("elsa.png"); - textureList.push_back("qvoid.png"); - textureList.push_back("sam.png"); - textureList.push_back("sigmasua.png"); - textureList.push_back("spider.png"); - textureList.push_back("spark.png"); - textureList.push_back("tree_thing.png"); - textureList.push_back("tuno.png"); - textureList.push_back("tv_panel.png"); - textureList.push_back("tv.png"); - textureList.push_back("shock.png"); - textureList.push_back("upv_student.png"); - textureList.push_back("wave.png"); - textureList.push_back("z80.png"); - - // Player - textureList.push_back("player.png"); - - Resource::get()->loadTextures(textureList); - - // Animaciones - std::vector animationList; - - // Enemigos - animationList.push_back("abad.ani"); - animationList.push_back("abad_bell.ani"); - animationList.push_back("amstrad_cs.ani"); - animationList.push_back("flying_arounder.ani"); - animationList.push_back("stopped_arounder.ani"); - animationList.push_back("walking_arounder.ani"); - animationList.push_back("arounders_door.ani"); - animationList.push_back("arounders_machine.ani"); - animationList.push_back("bat.ani"); - animationList.push_back("batman_bell.ani"); - animationList.push_back("batman_fire.ani"); - animationList.push_back("batman.ani"); - animationList.push_back("bell.ani"); - animationList.push_back("bin.ani"); - animationList.push_back("bird.ani"); - animationList.push_back("breakout.ani"); - animationList.push_back("bry.ani"); - animationList.push_back("chip.ani"); - animationList.push_back("code.ani"); - animationList.push_back("congo.ani"); - animationList.push_back("crosshair.ani"); - animationList.push_back("demon.ani"); - animationList.push_back("heavy.ani"); - animationList.push_back("dimallas.ani"); - animationList.push_back("floppy.ani"); - animationList.push_back("dong.ani"); - animationList.push_back("guitar.ani"); - animationList.push_back("jailbattle_alien.ani"); - animationList.push_back("jailbattle_human.ani"); - animationList.push_back("jailer_#1.ani"); - animationList.push_back("jailer_#2.ani"); - animationList.push_back("jailer_#3.ani"); - animationList.push_back("jeannine.ani"); - animationList.push_back("lamp.ani"); - animationList.push_back("lord_abad.ani"); - animationList.push_back("robot.ani"); - animationList.push_back("matatunos.ani"); - animationList.push_back("mummy.ani"); - animationList.push_back("paco.ani"); - animationList.push_back("elsa.ani"); - animationList.push_back("qvoid.ani"); - animationList.push_back("sam.ani"); - animationList.push_back("sigmasua.ani"); - animationList.push_back("spider.ani"); - animationList.push_back("spark.ani"); - animationList.push_back("tree_thing.ani"); - animationList.push_back("tuno.ani"); - animationList.push_back("tv_panel.ani"); - animationList.push_back("tv.ani"); - animationList.push_back("shock.ani"); - animationList.push_back("upv_student.ani"); - animationList.push_back("wave.ani"); - animationList.push_back("z80.ani"); - - // Player - animationList.push_back("player.ani"); - - Resource::get()->loadAnimations(animationList); - - // Offsets - std::vector offsetsList; - offsetsList.push_back("smb2.txt"); - - Resource::get()->loadOffsets(offsetsList); - } - - else if (options.section.section == Section::GAME_OVER) - { - // Texturas - std::vector textureList; - textureList.push_back("smb2.png"); - textureList.push_back("player_game_over.png"); - textureList.push_back("tv.png"); - - Resource::get()->loadTextures(textureList); - - // Animaciones - std::vector animationList; - animationList.push_back("player_game_over.ani"); - animationList.push_back("tv.ani"); - - Resource::get()->loadAnimations(animationList); - - // Offsets - std::vector offsetsList; - offsetsList.push_back("smb2.txt"); - - Resource::get()->loadOffsets(offsetsList); - } - - else if (options.section.section == Section::GAME || options.section.section == Section::DEMO) - { - // Texturas - std::vector textureList; - - // Jugador - textureList.push_back(options.cheats.alternate_skin == Cheat::CheatState::ENABLED ? "player2.png" : "player.png"); - - // Tilesets - textureList.push_back("standard.png"); - textureList.push_back("standard_zxarne.png"); - - // Enemigos - textureList.push_back("abad_bell.png"); - textureList.push_back("abad.png"); - textureList.push_back("aerojailer.png"); - textureList.push_back("amstrad_cs.png"); - textureList.push_back("flying_arounder.png"); - textureList.push_back("stopped_arounder.png"); - textureList.push_back("walking_arounder.png"); - textureList.push_back("arounder.png"); - textureList.push_back("arounders_door.png"); - textureList.push_back("arounders_machine.png"); - textureList.push_back("bat.png"); - textureList.push_back("batman_bell.png"); - textureList.push_back("batman_fire.png"); - textureList.push_back("batman.png"); - textureList.push_back("bell.png"); - textureList.push_back("bin.png"); - textureList.push_back("bird.png"); - textureList.push_back("breakout.png"); - textureList.push_back("bry.png"); - textureList.push_back("chip.png"); - textureList.push_back("code.png"); - textureList.push_back("congo.png"); - textureList.push_back("crosshair.png"); - textureList.push_back("demon.png"); - textureList.push_back("dimallas.png"); - textureList.push_back("floppy.png"); - textureList.push_back("dong.png"); - textureList.push_back("guitar.png"); - textureList.push_back("heavy.png"); - textureList.push_back("jailer_#1.png"); - textureList.push_back("jailer_#2.png"); - textureList.push_back("jailer_#3.png"); - textureList.push_back("jailbattle_alien.png"); - textureList.push_back("jailbattle_human.png"); - textureList.push_back("jeannine.png"); - textureList.push_back("lamp.png"); - textureList.push_back("lord_abad.png"); - textureList.push_back("matatunos.png"); - textureList.push_back("mummy.png"); - textureList.push_back("paco.png"); - textureList.push_back("pepe_rosita_job.png"); - textureList.push_back("elsa.png"); - textureList.push_back("qvoid.png"); - textureList.push_back("robot.png"); - textureList.push_back("sam.png"); - textureList.push_back("shock.png"); - textureList.push_back("shooting_star.png"); - textureList.push_back("sigmasua.png"); - textureList.push_back("spark.png"); - textureList.push_back("spider.png"); - textureList.push_back("tree_thing.png"); - textureList.push_back("tuno.png"); - textureList.push_back("tv_panel.png"); - textureList.push_back("tv.png"); - textureList.push_back("upv_student.png"); - textureList.push_back("wave.png"); - textureList.push_back("z80.png"); - - // Items - textureList.push_back("items.png"); - - // Texto - textureList.push_back("smb2.png"); - textureList.push_back("debug.png"); - - Resource::get()->loadTextures(textureList); - - // Animaciones - std::vector animationList; - - // Jugador - animationList.push_back(options.cheats.alternate_skin == Cheat::CheatState::ENABLED ? "player2.ani" : "player.ani"); - - // Enemigos - animationList.push_back("abad_bell.ani"); - animationList.push_back("abad.ani"); - animationList.push_back("aerojailer.ani"); - animationList.push_back("amstrad_cs.ani"); - animationList.push_back("flying_arounder.ani"); - animationList.push_back("stopped_arounder.ani"); - animationList.push_back("walking_arounder.ani"); - animationList.push_back("arounder.ani"); - animationList.push_back("arounders_door.ani"); - animationList.push_back("arounders_machine.ani"); - animationList.push_back("bat.ani"); - animationList.push_back("batman_bell.ani"); - animationList.push_back("batman_fire.ani"); - animationList.push_back("batman.ani"); - animationList.push_back("bell.ani"); - animationList.push_back("bin.ani"); - animationList.push_back("bird.ani"); - animationList.push_back("breakout.ani"); - animationList.push_back("bry.ani"); - animationList.push_back("chip.ani"); - animationList.push_back("code.ani"); - animationList.push_back("congo.ani"); - animationList.push_back("crosshair.ani"); - animationList.push_back("demon.ani"); - animationList.push_back("dimallas.ani"); - animationList.push_back("floppy.ani"); - animationList.push_back("dong.ani"); - animationList.push_back("guitar.ani"); - animationList.push_back("heavy.ani"); - animationList.push_back("jailer_#1.ani"); - animationList.push_back("jailer_#2.ani"); - animationList.push_back("jailer_#3.ani"); - animationList.push_back("jailbattle_alien.ani"); - animationList.push_back("jailbattle_human.ani"); - animationList.push_back("jeannine.ani"); - animationList.push_back("lamp.ani"); - animationList.push_back("lord_abad.ani"); - animationList.push_back("matatunos.ani"); - animationList.push_back("mummy.ani"); - animationList.push_back("paco.ani"); - animationList.push_back("pepe_rosita_job.ani"); - animationList.push_back("elsa.ani"); - animationList.push_back("qvoid.ani"); - animationList.push_back("robot.ani"); - animationList.push_back("sam.ani"); - animationList.push_back("shock.ani"); - animationList.push_back("shooting_star.ani"); - animationList.push_back("sigmasua.ani"); - animationList.push_back("spark.ani"); - animationList.push_back("spider.ani"); - animationList.push_back("tree_thing.ani"); - animationList.push_back("tuno.ani"); - animationList.push_back("tv_panel.ani"); - animationList.push_back("tv.ani"); - animationList.push_back("upv_student.ani"); - animationList.push_back("wave.ani"); - animationList.push_back("z80.ani"); - - Resource::get()->loadAnimations(animationList); - - // Offsets - std::vector offsetsList; - offsetsList.push_back("smb2.txt"); - offsetsList.push_back("debug.txt"); - - Resource::get()->loadOffsets(offsetsList); - - // TileMaps - std::vector tileMapList; - tileMapList.push_back("01.tmx"); - tileMapList.push_back("02.tmx"); - tileMapList.push_back("03.tmx"); - tileMapList.push_back("04.tmx"); - tileMapList.push_back("05.tmx"); - tileMapList.push_back("06.tmx"); - tileMapList.push_back("07.tmx"); - tileMapList.push_back("08.tmx"); - tileMapList.push_back("09.tmx"); - tileMapList.push_back("10.tmx"); - tileMapList.push_back("11.tmx"); - tileMapList.push_back("12.tmx"); - tileMapList.push_back("13.tmx"); - tileMapList.push_back("14.tmx"); - tileMapList.push_back("15.tmx"); - tileMapList.push_back("16.tmx"); - tileMapList.push_back("17.tmx"); - tileMapList.push_back("18.tmx"); - tileMapList.push_back("19.tmx"); - tileMapList.push_back("20.tmx"); - tileMapList.push_back("21.tmx"); - tileMapList.push_back("22.tmx"); - tileMapList.push_back("23.tmx"); - tileMapList.push_back("24.tmx"); - tileMapList.push_back("25.tmx"); - tileMapList.push_back("26.tmx"); - tileMapList.push_back("27.tmx"); - tileMapList.push_back("28.tmx"); - tileMapList.push_back("29.tmx"); - tileMapList.push_back("30.tmx"); - tileMapList.push_back("31.tmx"); - tileMapList.push_back("32.tmx"); - tileMapList.push_back("33.tmx"); - tileMapList.push_back("34.tmx"); - tileMapList.push_back("35.tmx"); - tileMapList.push_back("36.tmx"); - tileMapList.push_back("37.tmx"); - tileMapList.push_back("38.tmx"); - tileMapList.push_back("39.tmx"); - tileMapList.push_back("40.tmx"); - tileMapList.push_back("41.tmx"); - tileMapList.push_back("42.tmx"); - tileMapList.push_back("43.tmx"); - tileMapList.push_back("44.tmx"); - tileMapList.push_back("45.tmx"); - tileMapList.push_back("46.tmx"); - tileMapList.push_back("47.tmx"); - tileMapList.push_back("48.tmx"); - tileMapList.push_back("49.tmx"); - tileMapList.push_back("50.tmx"); - tileMapList.push_back("51.tmx"); - tileMapList.push_back("52.tmx"); - tileMapList.push_back("53.tmx"); - tileMapList.push_back("54.tmx"); - tileMapList.push_back("55.tmx"); - tileMapList.push_back("56.tmx"); - tileMapList.push_back("57.tmx"); - tileMapList.push_back("58.tmx"); - tileMapList.push_back("59.tmx"); - tileMapList.push_back("60.tmx"); - - Resource::get()->loadTileMaps(tileMapList); - - // Habitaciones - std::vector roomList; - roomList.push_back("01.room"); - roomList.push_back("02.room"); - roomList.push_back("03.room"); - roomList.push_back("04.room"); - roomList.push_back("05.room"); - roomList.push_back("06.room"); - roomList.push_back("07.room"); - roomList.push_back("08.room"); - roomList.push_back("09.room"); - roomList.push_back("10.room"); - roomList.push_back("11.room"); - roomList.push_back("12.room"); - roomList.push_back("13.room"); - roomList.push_back("14.room"); - roomList.push_back("15.room"); - roomList.push_back("16.room"); - roomList.push_back("17.room"); - roomList.push_back("18.room"); - roomList.push_back("19.room"); - roomList.push_back("20.room"); - roomList.push_back("21.room"); - roomList.push_back("22.room"); - roomList.push_back("23.room"); - roomList.push_back("24.room"); - roomList.push_back("25.room"); - roomList.push_back("26.room"); - roomList.push_back("27.room"); - roomList.push_back("28.room"); - roomList.push_back("29.room"); - roomList.push_back("30.room"); - roomList.push_back("31.room"); - roomList.push_back("32.room"); - roomList.push_back("33.room"); - roomList.push_back("34.room"); - roomList.push_back("35.room"); - roomList.push_back("36.room"); - roomList.push_back("37.room"); - roomList.push_back("38.room"); - roomList.push_back("39.room"); - roomList.push_back("40.room"); - roomList.push_back("41.room"); - roomList.push_back("42.room"); - roomList.push_back("43.room"); - roomList.push_back("44.room"); - roomList.push_back("45.room"); - roomList.push_back("46.room"); - roomList.push_back("47.room"); - roomList.push_back("48.room"); - roomList.push_back("49.room"); - roomList.push_back("50.room"); - roomList.push_back("51.room"); - roomList.push_back("52.room"); - roomList.push_back("53.room"); - roomList.push_back("54.room"); - roomList.push_back("55.room"); - roomList.push_back("56.room"); - roomList.push_back("57.room"); - roomList.push_back("58.room"); - roomList.push_back("59.room"); - roomList.push_back("60.room"); - - Resource::get()->loadRooms(roomList); - } - - if (options.console) - { - std::cout << "** RESOURCES LOADED" << std::endl; - } -} - // Inicia las variables necesarias para arrancar el programa void Director::initInput() { @@ -930,352 +381,354 @@ bool Director::setFileList() #endif // Texto - Asset::get()->add(prefix + "/data/font/smb2.png", t_font); - Asset::get()->add(prefix + "/data/font/smb2.txt", t_font); - Asset::get()->add(prefix + "/data/font/debug.png", t_font); - Asset::get()->add(prefix + "/data/font/debug.txt", t_font); - Asset::get()->add(prefix + "/data/font/gauntlet.png", t_font); - Asset::get()->add(prefix + "/data/font/gauntlet.txt", t_font); - Asset::get()->add(prefix + "/data/font/subatomic.png", t_font); - Asset::get()->add(prefix + "/data/font/subatomic.txt", t_font); + Asset::get()->add(prefix + "/data/font/smb2.png", AssetType::FONT); + Asset::get()->add(prefix + "/data/font/smb2.txt", AssetType::FONT); + Asset::get()->add(prefix + "/data/font/debug.png", AssetType::FONT); + Asset::get()->add(prefix + "/data/font/debug.txt", AssetType::FONT); + Asset::get()->add(prefix + "/data/font/gauntlet.png", AssetType::FONT); + Asset::get()->add(prefix + "/data/font/gauntlet.txt", AssetType::FONT); + Asset::get()->add(prefix + "/data/font/subatomic.png", AssetType::FONT); + Asset::get()->add(prefix + "/data/font/subatomic.txt", AssetType::FONT); + Asset::get()->add(prefix + "/data/font/8bithud.png", AssetType::FONT); + Asset::get()->add(prefix + "/data/font/8bithud.txt", AssetType::FONT); // Shaders - Asset::get()->add(prefix + "/data/shaders/crtpi_192.glsl", t_data); - Asset::get()->add(prefix + "/data/shaders/crtpi_240.glsl", t_data); + Asset::get()->add(prefix + "/data/shaders/crtpi_192.glsl", AssetType::DATA); + Asset::get()->add(prefix + "/data/shaders/crtpi_240.glsl", AssetType::DATA); // Datos - Asset::get()->add(prefix + "/data/input/gamecontrollerdb.txt", t_data); + Asset::get()->add(prefix + "/data/input/gamecontrollerdb.txt", AssetType::DATA); // Ficheros de sistema - Asset::get()->add(system_folder_ + "/config.txt", t_data, false, true); - Asset::get()->add(system_folder_ + "/stats_buffer.csv", t_data, false, true); - Asset::get()->add(system_folder_ + "/stats.csv", t_data, false, true); - Asset::get()->add(system_folder_ + "/cheevos.bin", t_data, false, true); + Asset::get()->add(system_folder_ + "/config.txt", AssetType::DATA, false, true); + Asset::get()->add(system_folder_ + "/stats_buffer.csv", AssetType::DATA, false, true); + Asset::get()->add(system_folder_ + "/stats.csv", AssetType::DATA, false, true); + Asset::get()->add(system_folder_ + "/cheevos.bin", AssetType::DATA, false, true); // Notificaciones - Asset::get()->add(prefix + "/data/notifications/notify.png", t_bitmap); + Asset::get()->add(prefix + "/data/notifications/notify.png", AssetType::BITMAP); // Habitaciones - Asset::get()->add(prefix + "/data/room/01.room", t_room); - Asset::get()->add(prefix + "/data/room/02.room", t_room); - Asset::get()->add(prefix + "/data/room/03.room", t_room); - Asset::get()->add(prefix + "/data/room/04.room", t_room); - Asset::get()->add(prefix + "/data/room/05.room", t_room); - Asset::get()->add(prefix + "/data/room/06.room", t_room); - Asset::get()->add(prefix + "/data/room/07.room", t_room); - Asset::get()->add(prefix + "/data/room/08.room", t_room); - Asset::get()->add(prefix + "/data/room/09.room", t_room); - Asset::get()->add(prefix + "/data/room/10.room", t_room); - Asset::get()->add(prefix + "/data/room/11.room", t_room); - Asset::get()->add(prefix + "/data/room/12.room", t_room); - Asset::get()->add(prefix + "/data/room/13.room", t_room); - Asset::get()->add(prefix + "/data/room/14.room", t_room); - Asset::get()->add(prefix + "/data/room/15.room", t_room); - Asset::get()->add(prefix + "/data/room/16.room", t_room); - Asset::get()->add(prefix + "/data/room/17.room", t_room); - Asset::get()->add(prefix + "/data/room/18.room", t_room); - Asset::get()->add(prefix + "/data/room/19.room", t_room); - Asset::get()->add(prefix + "/data/room/20.room", t_room); - Asset::get()->add(prefix + "/data/room/21.room", t_room); - Asset::get()->add(prefix + "/data/room/22.room", t_room); - Asset::get()->add(prefix + "/data/room/23.room", t_room); - Asset::get()->add(prefix + "/data/room/24.room", t_room); - Asset::get()->add(prefix + "/data/room/25.room", t_room); - Asset::get()->add(prefix + "/data/room/26.room", t_room); - Asset::get()->add(prefix + "/data/room/27.room", t_room); - Asset::get()->add(prefix + "/data/room/28.room", t_room); - Asset::get()->add(prefix + "/data/room/29.room", t_room); - Asset::get()->add(prefix + "/data/room/30.room", t_room); - Asset::get()->add(prefix + "/data/room/31.room", t_room); - Asset::get()->add(prefix + "/data/room/32.room", t_room); - Asset::get()->add(prefix + "/data/room/33.room", t_room); - Asset::get()->add(prefix + "/data/room/34.room", t_room); - Asset::get()->add(prefix + "/data/room/35.room", t_room); - Asset::get()->add(prefix + "/data/room/36.room", t_room); - Asset::get()->add(prefix + "/data/room/37.room", t_room); - Asset::get()->add(prefix + "/data/room/38.room", t_room); - Asset::get()->add(prefix + "/data/room/39.room", t_room); - Asset::get()->add(prefix + "/data/room/40.room", t_room); - Asset::get()->add(prefix + "/data/room/41.room", t_room); - Asset::get()->add(prefix + "/data/room/42.room", t_room); - Asset::get()->add(prefix + "/data/room/43.room", t_room); - Asset::get()->add(prefix + "/data/room/44.room", t_room); - Asset::get()->add(prefix + "/data/room/45.room", t_room); - Asset::get()->add(prefix + "/data/room/46.room", t_room); - Asset::get()->add(prefix + "/data/room/47.room", t_room); - Asset::get()->add(prefix + "/data/room/48.room", t_room); - Asset::get()->add(prefix + "/data/room/49.room", t_room); - Asset::get()->add(prefix + "/data/room/50.room", t_room); - Asset::get()->add(prefix + "/data/room/51.room", t_room); - Asset::get()->add(prefix + "/data/room/52.room", t_room); - Asset::get()->add(prefix + "/data/room/53.room", t_room); - Asset::get()->add(prefix + "/data/room/54.room", t_room); - Asset::get()->add(prefix + "/data/room/55.room", t_room); - Asset::get()->add(prefix + "/data/room/56.room", t_room); - Asset::get()->add(prefix + "/data/room/57.room", t_room); - Asset::get()->add(prefix + "/data/room/58.room", t_room); - Asset::get()->add(prefix + "/data/room/59.room", t_room); - Asset::get()->add(prefix + "/data/room/60.room", t_room); + Asset::get()->add(prefix + "/data/room/01.room", AssetType::ROOM); + Asset::get()->add(prefix + "/data/room/02.room", AssetType::ROOM); + Asset::get()->add(prefix + "/data/room/03.room", AssetType::ROOM); + Asset::get()->add(prefix + "/data/room/04.room", AssetType::ROOM); + Asset::get()->add(prefix + "/data/room/05.room", AssetType::ROOM); + Asset::get()->add(prefix + "/data/room/06.room", AssetType::ROOM); + Asset::get()->add(prefix + "/data/room/07.room", AssetType::ROOM); + Asset::get()->add(prefix + "/data/room/08.room", AssetType::ROOM); + Asset::get()->add(prefix + "/data/room/09.room", AssetType::ROOM); + Asset::get()->add(prefix + "/data/room/10.room", AssetType::ROOM); + Asset::get()->add(prefix + "/data/room/11.room", AssetType::ROOM); + Asset::get()->add(prefix + "/data/room/12.room", AssetType::ROOM); + Asset::get()->add(prefix + "/data/room/13.room", AssetType::ROOM); + Asset::get()->add(prefix + "/data/room/14.room", AssetType::ROOM); + Asset::get()->add(prefix + "/data/room/15.room", AssetType::ROOM); + Asset::get()->add(prefix + "/data/room/16.room", AssetType::ROOM); + Asset::get()->add(prefix + "/data/room/17.room", AssetType::ROOM); + Asset::get()->add(prefix + "/data/room/18.room", AssetType::ROOM); + Asset::get()->add(prefix + "/data/room/19.room", AssetType::ROOM); + Asset::get()->add(prefix + "/data/room/20.room", AssetType::ROOM); + Asset::get()->add(prefix + "/data/room/21.room", AssetType::ROOM); + Asset::get()->add(prefix + "/data/room/22.room", AssetType::ROOM); + Asset::get()->add(prefix + "/data/room/23.room", AssetType::ROOM); + Asset::get()->add(prefix + "/data/room/24.room", AssetType::ROOM); + Asset::get()->add(prefix + "/data/room/25.room", AssetType::ROOM); + Asset::get()->add(prefix + "/data/room/26.room", AssetType::ROOM); + Asset::get()->add(prefix + "/data/room/27.room", AssetType::ROOM); + Asset::get()->add(prefix + "/data/room/28.room", AssetType::ROOM); + Asset::get()->add(prefix + "/data/room/29.room", AssetType::ROOM); + Asset::get()->add(prefix + "/data/room/30.room", AssetType::ROOM); + Asset::get()->add(prefix + "/data/room/31.room", AssetType::ROOM); + Asset::get()->add(prefix + "/data/room/32.room", AssetType::ROOM); + Asset::get()->add(prefix + "/data/room/33.room", AssetType::ROOM); + Asset::get()->add(prefix + "/data/room/34.room", AssetType::ROOM); + Asset::get()->add(prefix + "/data/room/35.room", AssetType::ROOM); + Asset::get()->add(prefix + "/data/room/36.room", AssetType::ROOM); + Asset::get()->add(prefix + "/data/room/37.room", AssetType::ROOM); + Asset::get()->add(prefix + "/data/room/38.room", AssetType::ROOM); + Asset::get()->add(prefix + "/data/room/39.room", AssetType::ROOM); + Asset::get()->add(prefix + "/data/room/40.room", AssetType::ROOM); + Asset::get()->add(prefix + "/data/room/41.room", AssetType::ROOM); + Asset::get()->add(prefix + "/data/room/42.room", AssetType::ROOM); + Asset::get()->add(prefix + "/data/room/43.room", AssetType::ROOM); + Asset::get()->add(prefix + "/data/room/44.room", AssetType::ROOM); + Asset::get()->add(prefix + "/data/room/45.room", AssetType::ROOM); + Asset::get()->add(prefix + "/data/room/46.room", AssetType::ROOM); + Asset::get()->add(prefix + "/data/room/47.room", AssetType::ROOM); + Asset::get()->add(prefix + "/data/room/48.room", AssetType::ROOM); + Asset::get()->add(prefix + "/data/room/49.room", AssetType::ROOM); + Asset::get()->add(prefix + "/data/room/50.room", AssetType::ROOM); + Asset::get()->add(prefix + "/data/room/51.room", AssetType::ROOM); + Asset::get()->add(prefix + "/data/room/52.room", AssetType::ROOM); + Asset::get()->add(prefix + "/data/room/53.room", AssetType::ROOM); + Asset::get()->add(prefix + "/data/room/54.room", AssetType::ROOM); + Asset::get()->add(prefix + "/data/room/55.room", AssetType::ROOM); + Asset::get()->add(prefix + "/data/room/56.room", AssetType::ROOM); + Asset::get()->add(prefix + "/data/room/57.room", AssetType::ROOM); + Asset::get()->add(prefix + "/data/room/58.room", AssetType::ROOM); + Asset::get()->add(prefix + "/data/room/59.room", AssetType::ROOM); + Asset::get()->add(prefix + "/data/room/60.room", AssetType::ROOM); // Tilemaps - Asset::get()->add(prefix + "/data/room/01.tmx", t_room); - Asset::get()->add(prefix + "/data/room/02.tmx", t_room); - Asset::get()->add(prefix + "/data/room/03.tmx", t_room); - Asset::get()->add(prefix + "/data/room/04.tmx", t_room); - Asset::get()->add(prefix + "/data/room/05.tmx", t_room); - Asset::get()->add(prefix + "/data/room/06.tmx", t_room); - Asset::get()->add(prefix + "/data/room/07.tmx", t_room); - Asset::get()->add(prefix + "/data/room/08.tmx", t_room); - Asset::get()->add(prefix + "/data/room/09.tmx", t_room); - Asset::get()->add(prefix + "/data/room/10.tmx", t_room); - Asset::get()->add(prefix + "/data/room/11.tmx", t_room); - Asset::get()->add(prefix + "/data/room/12.tmx", t_room); - Asset::get()->add(prefix + "/data/room/13.tmx", t_room); - Asset::get()->add(prefix + "/data/room/14.tmx", t_room); - Asset::get()->add(prefix + "/data/room/15.tmx", t_room); - Asset::get()->add(prefix + "/data/room/16.tmx", t_room); - Asset::get()->add(prefix + "/data/room/17.tmx", t_room); - Asset::get()->add(prefix + "/data/room/18.tmx", t_room); - Asset::get()->add(prefix + "/data/room/19.tmx", t_room); - Asset::get()->add(prefix + "/data/room/20.tmx", t_room); - Asset::get()->add(prefix + "/data/room/21.tmx", t_room); - Asset::get()->add(prefix + "/data/room/22.tmx", t_room); - Asset::get()->add(prefix + "/data/room/23.tmx", t_room); - Asset::get()->add(prefix + "/data/room/24.tmx", t_room); - Asset::get()->add(prefix + "/data/room/25.tmx", t_room); - Asset::get()->add(prefix + "/data/room/26.tmx", t_room); - Asset::get()->add(prefix + "/data/room/27.tmx", t_room); - Asset::get()->add(prefix + "/data/room/28.tmx", t_room); - Asset::get()->add(prefix + "/data/room/29.tmx", t_room); - Asset::get()->add(prefix + "/data/room/30.tmx", t_room); - Asset::get()->add(prefix + "/data/room/31.tmx", t_room); - Asset::get()->add(prefix + "/data/room/32.tmx", t_room); - Asset::get()->add(prefix + "/data/room/33.tmx", t_room); - Asset::get()->add(prefix + "/data/room/34.tmx", t_room); - Asset::get()->add(prefix + "/data/room/35.tmx", t_room); - Asset::get()->add(prefix + "/data/room/36.tmx", t_room); - Asset::get()->add(prefix + "/data/room/37.tmx", t_room); - Asset::get()->add(prefix + "/data/room/38.tmx", t_room); - Asset::get()->add(prefix + "/data/room/39.tmx", t_room); - Asset::get()->add(prefix + "/data/room/40.tmx", t_room); - Asset::get()->add(prefix + "/data/room/41.tmx", t_room); - Asset::get()->add(prefix + "/data/room/42.tmx", t_room); - Asset::get()->add(prefix + "/data/room/43.tmx", t_room); - Asset::get()->add(prefix + "/data/room/44.tmx", t_room); - Asset::get()->add(prefix + "/data/room/45.tmx", t_room); - Asset::get()->add(prefix + "/data/room/46.tmx", t_room); - Asset::get()->add(prefix + "/data/room/47.tmx", t_room); - Asset::get()->add(prefix + "/data/room/48.tmx", t_room); - Asset::get()->add(prefix + "/data/room/49.tmx", t_room); - Asset::get()->add(prefix + "/data/room/50.tmx", t_room); - Asset::get()->add(prefix + "/data/room/51.tmx", t_room); - Asset::get()->add(prefix + "/data/room/52.tmx", t_room); - Asset::get()->add(prefix + "/data/room/53.tmx", t_room); - Asset::get()->add(prefix + "/data/room/54.tmx", t_room); - Asset::get()->add(prefix + "/data/room/55.tmx", t_room); - Asset::get()->add(prefix + "/data/room/56.tmx", t_room); - Asset::get()->add(prefix + "/data/room/57.tmx", t_room); - Asset::get()->add(prefix + "/data/room/58.tmx", t_room); - Asset::get()->add(prefix + "/data/room/59.tmx", t_room); - Asset::get()->add(prefix + "/data/room/60.tmx", t_room); + Asset::get()->add(prefix + "/data/room/01.tmx", AssetType::ROOM); + Asset::get()->add(prefix + "/data/room/02.tmx", AssetType::ROOM); + Asset::get()->add(prefix + "/data/room/03.tmx", AssetType::ROOM); + Asset::get()->add(prefix + "/data/room/04.tmx", AssetType::ROOM); + Asset::get()->add(prefix + "/data/room/05.tmx", AssetType::ROOM); + Asset::get()->add(prefix + "/data/room/06.tmx", AssetType::ROOM); + Asset::get()->add(prefix + "/data/room/07.tmx", AssetType::ROOM); + Asset::get()->add(prefix + "/data/room/08.tmx", AssetType::ROOM); + Asset::get()->add(prefix + "/data/room/09.tmx", AssetType::ROOM); + Asset::get()->add(prefix + "/data/room/10.tmx", AssetType::ROOM); + Asset::get()->add(prefix + "/data/room/11.tmx", AssetType::ROOM); + Asset::get()->add(prefix + "/data/room/12.tmx", AssetType::ROOM); + Asset::get()->add(prefix + "/data/room/13.tmx", AssetType::ROOM); + Asset::get()->add(prefix + "/data/room/14.tmx", AssetType::ROOM); + Asset::get()->add(prefix + "/data/room/15.tmx", AssetType::ROOM); + Asset::get()->add(prefix + "/data/room/16.tmx", AssetType::ROOM); + Asset::get()->add(prefix + "/data/room/17.tmx", AssetType::ROOM); + Asset::get()->add(prefix + "/data/room/18.tmx", AssetType::ROOM); + Asset::get()->add(prefix + "/data/room/19.tmx", AssetType::ROOM); + Asset::get()->add(prefix + "/data/room/20.tmx", AssetType::ROOM); + Asset::get()->add(prefix + "/data/room/21.tmx", AssetType::ROOM); + Asset::get()->add(prefix + "/data/room/22.tmx", AssetType::ROOM); + Asset::get()->add(prefix + "/data/room/23.tmx", AssetType::ROOM); + Asset::get()->add(prefix + "/data/room/24.tmx", AssetType::ROOM); + Asset::get()->add(prefix + "/data/room/25.tmx", AssetType::ROOM); + Asset::get()->add(prefix + "/data/room/26.tmx", AssetType::ROOM); + Asset::get()->add(prefix + "/data/room/27.tmx", AssetType::ROOM); + Asset::get()->add(prefix + "/data/room/28.tmx", AssetType::ROOM); + Asset::get()->add(prefix + "/data/room/29.tmx", AssetType::ROOM); + Asset::get()->add(prefix + "/data/room/30.tmx", AssetType::ROOM); + Asset::get()->add(prefix + "/data/room/31.tmx", AssetType::ROOM); + Asset::get()->add(prefix + "/data/room/32.tmx", AssetType::ROOM); + Asset::get()->add(prefix + "/data/room/33.tmx", AssetType::ROOM); + Asset::get()->add(prefix + "/data/room/34.tmx", AssetType::ROOM); + Asset::get()->add(prefix + "/data/room/35.tmx", AssetType::ROOM); + Asset::get()->add(prefix + "/data/room/36.tmx", AssetType::ROOM); + Asset::get()->add(prefix + "/data/room/37.tmx", AssetType::ROOM); + Asset::get()->add(prefix + "/data/room/38.tmx", AssetType::ROOM); + Asset::get()->add(prefix + "/data/room/39.tmx", AssetType::ROOM); + Asset::get()->add(prefix + "/data/room/40.tmx", AssetType::ROOM); + Asset::get()->add(prefix + "/data/room/41.tmx", AssetType::ROOM); + Asset::get()->add(prefix + "/data/room/42.tmx", AssetType::ROOM); + Asset::get()->add(prefix + "/data/room/43.tmx", AssetType::ROOM); + Asset::get()->add(prefix + "/data/room/44.tmx", AssetType::ROOM); + Asset::get()->add(prefix + "/data/room/45.tmx", AssetType::ROOM); + Asset::get()->add(prefix + "/data/room/46.tmx", AssetType::ROOM); + Asset::get()->add(prefix + "/data/room/47.tmx", AssetType::ROOM); + Asset::get()->add(prefix + "/data/room/48.tmx", AssetType::ROOM); + Asset::get()->add(prefix + "/data/room/49.tmx", AssetType::ROOM); + Asset::get()->add(prefix + "/data/room/50.tmx", AssetType::ROOM); + Asset::get()->add(prefix + "/data/room/51.tmx", AssetType::ROOM); + Asset::get()->add(prefix + "/data/room/52.tmx", AssetType::ROOM); + Asset::get()->add(prefix + "/data/room/53.tmx", AssetType::ROOM); + Asset::get()->add(prefix + "/data/room/54.tmx", AssetType::ROOM); + Asset::get()->add(prefix + "/data/room/55.tmx", AssetType::ROOM); + Asset::get()->add(prefix + "/data/room/56.tmx", AssetType::ROOM); + Asset::get()->add(prefix + "/data/room/57.tmx", AssetType::ROOM); + Asset::get()->add(prefix + "/data/room/58.tmx", AssetType::ROOM); + Asset::get()->add(prefix + "/data/room/59.tmx", AssetType::ROOM); + Asset::get()->add(prefix + "/data/room/60.tmx", AssetType::ROOM); // Tilesets - Asset::get()->add(prefix + "/data/tilesets/standard.png", t_bitmap); - Asset::get()->add(prefix + "/data/tilesets/standard_zxarne.png", t_bitmap); + Asset::get()->add(prefix + "/data/tilesets/standard.png", AssetType::BITMAP); + Asset::get()->add(prefix + "/data/tilesets/standard_zxarne.png", AssetType::BITMAP); // Enemigos - Asset::get()->add(prefix + "/data/enemies/abad_bell.ani", t_data); - Asset::get()->add(prefix + "/data/enemies/abad_bell.png", t_bitmap); - Asset::get()->add(prefix + "/data/enemies/abad.ani", t_data); - Asset::get()->add(prefix + "/data/enemies/abad.png", t_bitmap); - Asset::get()->add(prefix + "/data/enemies/amstrad_cs.ani", t_data); - Asset::get()->add(prefix + "/data/enemies/amstrad_cs.png", t_bitmap); - Asset::get()->add(prefix + "/data/enemies/flying_arounder.ani", t_data); - Asset::get()->add(prefix + "/data/enemies/flying_arounder.png", t_bitmap); - Asset::get()->add(prefix + "/data/enemies/stopped_arounder.ani", t_data); - Asset::get()->add(prefix + "/data/enemies/stopped_arounder.png", t_bitmap); - Asset::get()->add(prefix + "/data/enemies/walking_arounder.ani", t_data); - Asset::get()->add(prefix + "/data/enemies/walking_arounder.png", t_bitmap); - Asset::get()->add(prefix + "/data/enemies/arounders_door.ani", t_data); - Asset::get()->add(prefix + "/data/enemies/arounders_door.png", t_bitmap); - Asset::get()->add(prefix + "/data/enemies/arounders_machine.ani", t_data); - Asset::get()->add(prefix + "/data/enemies/arounders_machine.png", t_bitmap); - Asset::get()->add(prefix + "/data/enemies/bat.ani", t_data); - Asset::get()->add(prefix + "/data/enemies/bat.png", t_bitmap); - Asset::get()->add(prefix + "/data/enemies/batman_bell.ani", t_data); - Asset::get()->add(prefix + "/data/enemies/batman_bell.png", t_bitmap); - Asset::get()->add(prefix + "/data/enemies/batman_fire.ani", t_data); - Asset::get()->add(prefix + "/data/enemies/batman_fire.png", t_bitmap); - Asset::get()->add(prefix + "/data/enemies/batman.ani", t_data); - Asset::get()->add(prefix + "/data/enemies/batman.png", t_bitmap); - Asset::get()->add(prefix + "/data/enemies/bell.ani", t_data); - Asset::get()->add(prefix + "/data/enemies/bell.png", t_bitmap); - Asset::get()->add(prefix + "/data/enemies/bin.ani", t_data); - Asset::get()->add(prefix + "/data/enemies/bin.png", t_bitmap); - Asset::get()->add(prefix + "/data/enemies/bird.ani", t_data); - Asset::get()->add(prefix + "/data/enemies/bird.png", t_bitmap); - Asset::get()->add(prefix + "/data/enemies/breakout.ani", t_data); - Asset::get()->add(prefix + "/data/enemies/breakout.png", t_bitmap); - Asset::get()->add(prefix + "/data/enemies/bry.ani", t_data); - Asset::get()->add(prefix + "/data/enemies/bry.png", t_bitmap); - Asset::get()->add(prefix + "/data/enemies/chip.ani", t_data); - Asset::get()->add(prefix + "/data/enemies/chip.png", t_bitmap); - Asset::get()->add(prefix + "/data/enemies/code.ani", t_data); - Asset::get()->add(prefix + "/data/enemies/code.png", t_bitmap); - Asset::get()->add(prefix + "/data/enemies/congo.ani", t_data); - Asset::get()->add(prefix + "/data/enemies/congo.png", t_bitmap); - Asset::get()->add(prefix + "/data/enemies/crosshair.ani", t_data); - Asset::get()->add(prefix + "/data/enemies/crosshair.png", t_bitmap); - Asset::get()->add(prefix + "/data/enemies/demon.ani", t_data); - Asset::get()->add(prefix + "/data/enemies/demon.png", t_bitmap); - Asset::get()->add(prefix + "/data/enemies/dimallas.ani", t_data); - Asset::get()->add(prefix + "/data/enemies/dimallas.png", t_bitmap); - Asset::get()->add(prefix + "/data/enemies/floppy.ani", t_data); - Asset::get()->add(prefix + "/data/enemies/floppy.png", t_bitmap); - Asset::get()->add(prefix + "/data/enemies/dong.ani", t_data); - Asset::get()->add(prefix + "/data/enemies/dong.png", t_bitmap); - Asset::get()->add(prefix + "/data/enemies/guitar.ani", t_data); - Asset::get()->add(prefix + "/data/enemies/guitar.png", t_bitmap); - Asset::get()->add(prefix + "/data/enemies/heavy.ani", t_data); - Asset::get()->add(prefix + "/data/enemies/heavy.png", t_bitmap); - Asset::get()->add(prefix + "/data/enemies/jailer_#1.ani", t_data); - Asset::get()->add(prefix + "/data/enemies/jailer_#1.png", t_bitmap); - Asset::get()->add(prefix + "/data/enemies/jailer_#2.ani", t_data); - Asset::get()->add(prefix + "/data/enemies/jailer_#2.png", t_bitmap); - Asset::get()->add(prefix + "/data/enemies/jailer_#3.ani", t_data); - Asset::get()->add(prefix + "/data/enemies/jailer_#3.png", t_bitmap); - Asset::get()->add(prefix + "/data/enemies/jailbattle_alien.ani", t_data); - Asset::get()->add(prefix + "/data/enemies/jailbattle_alien.png", t_bitmap); - Asset::get()->add(prefix + "/data/enemies/jailbattle_human.ani", t_data); - Asset::get()->add(prefix + "/data/enemies/jailbattle_human.png", t_bitmap); - Asset::get()->add(prefix + "/data/enemies/jeannine.ani", t_data); - Asset::get()->add(prefix + "/data/enemies/jeannine.png", t_bitmap); - Asset::get()->add(prefix + "/data/enemies/lamp.ani", t_data); - Asset::get()->add(prefix + "/data/enemies/lamp.png", t_bitmap); - Asset::get()->add(prefix + "/data/enemies/lord_abad.ani", t_data); - Asset::get()->add(prefix + "/data/enemies/lord_abad.png", t_bitmap); - Asset::get()->add(prefix + "/data/enemies/matatunos.ani", t_data); - Asset::get()->add(prefix + "/data/enemies/matatunos.png", t_bitmap); - Asset::get()->add(prefix + "/data/enemies/mummy.ani", t_data); - Asset::get()->add(prefix + "/data/enemies/mummy.png", t_bitmap); - Asset::get()->add(prefix + "/data/enemies/paco.ani", t_data); - Asset::get()->add(prefix + "/data/enemies/paco.png", t_bitmap); - Asset::get()->add(prefix + "/data/enemies/elsa.ani", t_data); - Asset::get()->add(prefix + "/data/enemies/elsa.png", t_bitmap); - Asset::get()->add(prefix + "/data/enemies/qvoid.ani", t_data); - Asset::get()->add(prefix + "/data/enemies/qvoid.png", t_bitmap); - Asset::get()->add(prefix + "/data/enemies/robot.ani", t_data); - Asset::get()->add(prefix + "/data/enemies/robot.png", t_bitmap); - Asset::get()->add(prefix + "/data/enemies/sam.ani", t_data); - Asset::get()->add(prefix + "/data/enemies/sam.png", t_bitmap); - Asset::get()->add(prefix + "/data/enemies/shock.ani", t_data); - Asset::get()->add(prefix + "/data/enemies/shock.png", t_bitmap); - Asset::get()->add(prefix + "/data/enemies/sigmasua.ani", t_data); - Asset::get()->add(prefix + "/data/enemies/sigmasua.png", t_bitmap); - Asset::get()->add(prefix + "/data/enemies/spark.ani", t_data); - Asset::get()->add(prefix + "/data/enemies/spark.png", t_bitmap); - Asset::get()->add(prefix + "/data/enemies/special/aerojailer.ani", t_data); - Asset::get()->add(prefix + "/data/enemies/special/aerojailer.png", t_bitmap); - Asset::get()->add(prefix + "/data/enemies/special/arounder.ani", t_data); - Asset::get()->add(prefix + "/data/enemies/special/arounder.png", t_bitmap); - Asset::get()->add(prefix + "/data/enemies/special/pepe_rosita_job.ani", t_data); - Asset::get()->add(prefix + "/data/enemies/special/pepe_rosita_job.png", t_bitmap); - Asset::get()->add(prefix + "/data/enemies/special/shooting_star.ani", t_data); - Asset::get()->add(prefix + "/data/enemies/special/shooting_star.png", t_bitmap); - Asset::get()->add(prefix + "/data/enemies/spider.ani", t_data); - Asset::get()->add(prefix + "/data/enemies/spider.png", t_bitmap); - Asset::get()->add(prefix + "/data/enemies/tree_thing.ani", t_data); - Asset::get()->add(prefix + "/data/enemies/tree_thing.png", t_bitmap); - Asset::get()->add(prefix + "/data/enemies/tuno.ani", t_data); - Asset::get()->add(prefix + "/data/enemies/tuno.png", t_bitmap); - Asset::get()->add(prefix + "/data/enemies/tv_panel.ani", t_data); - Asset::get()->add(prefix + "/data/enemies/tv_panel.png", t_bitmap); - Asset::get()->add(prefix + "/data/enemies/tv.ani", t_data); - Asset::get()->add(prefix + "/data/enemies/tv.png", t_bitmap); - Asset::get()->add(prefix + "/data/enemies/upv_student.ani", t_data); - Asset::get()->add(prefix + "/data/enemies/upv_student.png", t_bitmap); - Asset::get()->add(prefix + "/data/enemies/wave.ani", t_data); - Asset::get()->add(prefix + "/data/enemies/wave.png", t_bitmap); - Asset::get()->add(prefix + "/data/enemies/z80.ani", t_data); - Asset::get()->add(prefix + "/data/enemies/z80.png", t_bitmap); + Asset::get()->add(prefix + "/data/enemies/abad_bell.ani", AssetType::DATA); + Asset::get()->add(prefix + "/data/enemies/abad_bell.png", AssetType::BITMAP); + Asset::get()->add(prefix + "/data/enemies/abad.ani", AssetType::DATA); + Asset::get()->add(prefix + "/data/enemies/abad.png", AssetType::BITMAP); + Asset::get()->add(prefix + "/data/enemies/amstrad_cs.ani", AssetType::DATA); + Asset::get()->add(prefix + "/data/enemies/amstrad_cs.png", AssetType::BITMAP); + Asset::get()->add(prefix + "/data/enemies/flying_arounder.ani", AssetType::DATA); + Asset::get()->add(prefix + "/data/enemies/flying_arounder.png", AssetType::BITMAP); + Asset::get()->add(prefix + "/data/enemies/stopped_arounder.ani", AssetType::DATA); + Asset::get()->add(prefix + "/data/enemies/stopped_arounder.png", AssetType::BITMAP); + Asset::get()->add(prefix + "/data/enemies/walking_arounder.ani", AssetType::DATA); + Asset::get()->add(prefix + "/data/enemies/walking_arounder.png", AssetType::BITMAP); + Asset::get()->add(prefix + "/data/enemies/arounders_door.ani", AssetType::DATA); + Asset::get()->add(prefix + "/data/enemies/arounders_door.png", AssetType::BITMAP); + Asset::get()->add(prefix + "/data/enemies/arounders_machine.ani", AssetType::DATA); + Asset::get()->add(prefix + "/data/enemies/arounders_machine.png", AssetType::BITMAP); + Asset::get()->add(prefix + "/data/enemies/bat.ani", AssetType::DATA); + Asset::get()->add(prefix + "/data/enemies/bat.png", AssetType::BITMAP); + Asset::get()->add(prefix + "/data/enemies/batman_bell.ani", AssetType::DATA); + Asset::get()->add(prefix + "/data/enemies/batman_bell.png", AssetType::BITMAP); + Asset::get()->add(prefix + "/data/enemies/batman_fire.ani", AssetType::DATA); + Asset::get()->add(prefix + "/data/enemies/batman_fire.png", AssetType::BITMAP); + Asset::get()->add(prefix + "/data/enemies/batman.ani", AssetType::DATA); + Asset::get()->add(prefix + "/data/enemies/batman.png", AssetType::BITMAP); + Asset::get()->add(prefix + "/data/enemies/bell.ani", AssetType::DATA); + Asset::get()->add(prefix + "/data/enemies/bell.png", AssetType::BITMAP); + Asset::get()->add(prefix + "/data/enemies/bin.ani", AssetType::DATA); + Asset::get()->add(prefix + "/data/enemies/bin.png", AssetType::BITMAP); + Asset::get()->add(prefix + "/data/enemies/bird.ani", AssetType::DATA); + Asset::get()->add(prefix + "/data/enemies/bird.png", AssetType::BITMAP); + Asset::get()->add(prefix + "/data/enemies/breakout.ani", AssetType::DATA); + Asset::get()->add(prefix + "/data/enemies/breakout.png", AssetType::BITMAP); + Asset::get()->add(prefix + "/data/enemies/bry.ani", AssetType::DATA); + Asset::get()->add(prefix + "/data/enemies/bry.png", AssetType::BITMAP); + Asset::get()->add(prefix + "/data/enemies/chip.ani", AssetType::DATA); + Asset::get()->add(prefix + "/data/enemies/chip.png", AssetType::BITMAP); + Asset::get()->add(prefix + "/data/enemies/code.ani", AssetType::DATA); + Asset::get()->add(prefix + "/data/enemies/code.png", AssetType::BITMAP); + Asset::get()->add(prefix + "/data/enemies/congo.ani", AssetType::DATA); + Asset::get()->add(prefix + "/data/enemies/congo.png", AssetType::BITMAP); + Asset::get()->add(prefix + "/data/enemies/crosshair.ani", AssetType::DATA); + Asset::get()->add(prefix + "/data/enemies/crosshair.png", AssetType::BITMAP); + Asset::get()->add(prefix + "/data/enemies/demon.ani", AssetType::DATA); + Asset::get()->add(prefix + "/data/enemies/demon.png", AssetType::BITMAP); + Asset::get()->add(prefix + "/data/enemies/dimallas.ani", AssetType::DATA); + Asset::get()->add(prefix + "/data/enemies/dimallas.png", AssetType::BITMAP); + Asset::get()->add(prefix + "/data/enemies/floppy.ani", AssetType::DATA); + Asset::get()->add(prefix + "/data/enemies/floppy.png", AssetType::BITMAP); + Asset::get()->add(prefix + "/data/enemies/dong.ani", AssetType::DATA); + Asset::get()->add(prefix + "/data/enemies/dong.png", AssetType::BITMAP); + Asset::get()->add(prefix + "/data/enemies/guitar.ani", AssetType::DATA); + Asset::get()->add(prefix + "/data/enemies/guitar.png", AssetType::BITMAP); + Asset::get()->add(prefix + "/data/enemies/heavy.ani", AssetType::DATA); + Asset::get()->add(prefix + "/data/enemies/heavy.png", AssetType::BITMAP); + Asset::get()->add(prefix + "/data/enemies/jailer_#1.ani", AssetType::DATA); + Asset::get()->add(prefix + "/data/enemies/jailer_#1.png", AssetType::BITMAP); + Asset::get()->add(prefix + "/data/enemies/jailer_#2.ani", AssetType::DATA); + Asset::get()->add(prefix + "/data/enemies/jailer_#2.png", AssetType::BITMAP); + Asset::get()->add(prefix + "/data/enemies/jailer_#3.ani", AssetType::DATA); + Asset::get()->add(prefix + "/data/enemies/jailer_#3.png", AssetType::BITMAP); + Asset::get()->add(prefix + "/data/enemies/jailbattle_alien.ani", AssetType::DATA); + Asset::get()->add(prefix + "/data/enemies/jailbattle_alien.png", AssetType::BITMAP); + Asset::get()->add(prefix + "/data/enemies/jailbattle_human.ani", AssetType::DATA); + Asset::get()->add(prefix + "/data/enemies/jailbattle_human.png", AssetType::BITMAP); + Asset::get()->add(prefix + "/data/enemies/jeannine.ani", AssetType::DATA); + Asset::get()->add(prefix + "/data/enemies/jeannine.png", AssetType::BITMAP); + Asset::get()->add(prefix + "/data/enemies/lamp.ani", AssetType::DATA); + Asset::get()->add(prefix + "/data/enemies/lamp.png", AssetType::BITMAP); + Asset::get()->add(prefix + "/data/enemies/lord_abad.ani", AssetType::DATA); + Asset::get()->add(prefix + "/data/enemies/lord_abad.png", AssetType::BITMAP); + Asset::get()->add(prefix + "/data/enemies/matatunos.ani", AssetType::DATA); + Asset::get()->add(prefix + "/data/enemies/matatunos.png", AssetType::BITMAP); + Asset::get()->add(prefix + "/data/enemies/mummy.ani", AssetType::DATA); + Asset::get()->add(prefix + "/data/enemies/mummy.png", AssetType::BITMAP); + Asset::get()->add(prefix + "/data/enemies/paco.ani", AssetType::DATA); + Asset::get()->add(prefix + "/data/enemies/paco.png", AssetType::BITMAP); + Asset::get()->add(prefix + "/data/enemies/elsa.ani", AssetType::DATA); + Asset::get()->add(prefix + "/data/enemies/elsa.png", AssetType::BITMAP); + Asset::get()->add(prefix + "/data/enemies/qvoid.ani", AssetType::DATA); + Asset::get()->add(prefix + "/data/enemies/qvoid.png", AssetType::BITMAP); + Asset::get()->add(prefix + "/data/enemies/robot.ani", AssetType::DATA); + Asset::get()->add(prefix + "/data/enemies/robot.png", AssetType::BITMAP); + Asset::get()->add(prefix + "/data/enemies/sam.ani", AssetType::DATA); + Asset::get()->add(prefix + "/data/enemies/sam.png", AssetType::BITMAP); + Asset::get()->add(prefix + "/data/enemies/shock.ani", AssetType::DATA); + Asset::get()->add(prefix + "/data/enemies/shock.png", AssetType::BITMAP); + Asset::get()->add(prefix + "/data/enemies/sigmasua.ani", AssetType::DATA); + Asset::get()->add(prefix + "/data/enemies/sigmasua.png", AssetType::BITMAP); + Asset::get()->add(prefix + "/data/enemies/spark.ani", AssetType::DATA); + Asset::get()->add(prefix + "/data/enemies/spark.png", AssetType::BITMAP); + Asset::get()->add(prefix + "/data/enemies/special/aerojailer.ani", AssetType::DATA); + Asset::get()->add(prefix + "/data/enemies/special/aerojailer.png", AssetType::BITMAP); + Asset::get()->add(prefix + "/data/enemies/special/arounder.ani", AssetType::DATA); + Asset::get()->add(prefix + "/data/enemies/special/arounder.png", AssetType::BITMAP); + Asset::get()->add(prefix + "/data/enemies/special/pepe_rosita_job.ani", AssetType::DATA); + Asset::get()->add(prefix + "/data/enemies/special/pepe_rosita_job.png", AssetType::BITMAP); + Asset::get()->add(prefix + "/data/enemies/special/shooting_star.ani", AssetType::DATA); + Asset::get()->add(prefix + "/data/enemies/special/shooting_star.png", AssetType::BITMAP); + Asset::get()->add(prefix + "/data/enemies/spider.ani", AssetType::DATA); + Asset::get()->add(prefix + "/data/enemies/spider.png", AssetType::BITMAP); + Asset::get()->add(prefix + "/data/enemies/tree_thing.ani", AssetType::DATA); + Asset::get()->add(prefix + "/data/enemies/tree_thing.png", AssetType::BITMAP); + Asset::get()->add(prefix + "/data/enemies/tuno.ani", AssetType::DATA); + Asset::get()->add(prefix + "/data/enemies/tuno.png", AssetType::BITMAP); + Asset::get()->add(prefix + "/data/enemies/tv_panel.ani", AssetType::DATA); + Asset::get()->add(prefix + "/data/enemies/tv_panel.png", AssetType::BITMAP); + Asset::get()->add(prefix + "/data/enemies/tv.ani", AssetType::DATA); + Asset::get()->add(prefix + "/data/enemies/tv.png", AssetType::BITMAP); + Asset::get()->add(prefix + "/data/enemies/upv_student.ani", AssetType::DATA); + Asset::get()->add(prefix + "/data/enemies/upv_student.png", AssetType::BITMAP); + Asset::get()->add(prefix + "/data/enemies/wave.ani", AssetType::DATA); + Asset::get()->add(prefix + "/data/enemies/wave.png", AssetType::BITMAP); + Asset::get()->add(prefix + "/data/enemies/z80.ani", AssetType::DATA); + Asset::get()->add(prefix + "/data/enemies/z80.png", AssetType::BITMAP); // Jugador - Asset::get()->add(prefix + "/data/player/player.png", t_bitmap); - Asset::get()->add(prefix + "/data/player/player.ani", t_data); - Asset::get()->add(prefix + "/data/player/player2.png", t_bitmap); - Asset::get()->add(prefix + "/data/player/player2.ani", t_data); - Asset::get()->add(prefix + "/data/player/player_game_over.png", t_bitmap); - Asset::get()->add(prefix + "/data/player/player_game_over.ani", t_data); + Asset::get()->add(prefix + "/data/player/player.png", AssetType::BITMAP); + Asset::get()->add(prefix + "/data/player/player.ani", AssetType::DATA); + Asset::get()->add(prefix + "/data/player/player2.png", AssetType::BITMAP); + Asset::get()->add(prefix + "/data/player/player2.ani", AssetType::DATA); + Asset::get()->add(prefix + "/data/player/player_game_over.png", AssetType::BITMAP); + Asset::get()->add(prefix + "/data/player/player_game_over.ani", AssetType::DATA); // Items - Asset::get()->add(prefix + "/data/items/items.png", t_bitmap); + Asset::get()->add(prefix + "/data/items/items.png", AssetType::BITMAP); // Musicas - Asset::get()->add(prefix + "/data/music/title.ogg", t_music); - Asset::get()->add(prefix + "/data/music/game.ogg", t_music); - Asset::get()->add(prefix + "/data/music/loading_sound1.ogg", t_music); - Asset::get()->add(prefix + "/data/music/loading_sound2.ogg", t_music); - Asset::get()->add(prefix + "/data/music/loading_sound3.ogg", t_music); - Asset::get()->add(prefix + "/data/music/ending1.ogg", t_music); - Asset::get()->add(prefix + "/data/music/ending2.ogg", t_music); - Asset::get()->add(prefix + "/data/music/game_over.ogg", t_music); + Asset::get()->add(prefix + "/data/music/title.ogg", AssetType::MUSIC); + Asset::get()->add(prefix + "/data/music/game.ogg", AssetType::MUSIC); + Asset::get()->add(prefix + "/data/music/loading_sound1.ogg", AssetType::MUSIC); + Asset::get()->add(prefix + "/data/music/loading_sound2.ogg", AssetType::MUSIC); + Asset::get()->add(prefix + "/data/music/loading_sound3.ogg", AssetType::MUSIC); + Asset::get()->add(prefix + "/data/music/ending1.ogg", AssetType::MUSIC); + Asset::get()->add(prefix + "/data/music/ending2.ogg", AssetType::MUSIC); + Asset::get()->add(prefix + "/data/music/game_over.ogg", AssetType::MUSIC); // Efectos de sonido - Asset::get()->add(prefix + "/data/sound/item.wav", t_sound); - Asset::get()->add(prefix + "/data/sound/death.wav", t_sound); - Asset::get()->add(prefix + "/data/sound/jump1.wav", t_sound); - Asset::get()->add(prefix + "/data/sound/jump2.wav", t_sound); - Asset::get()->add(prefix + "/data/sound/jump3.wav", t_sound); - Asset::get()->add(prefix + "/data/sound/jump4.wav", t_sound); - Asset::get()->add(prefix + "/data/sound/jump5.wav", t_sound); - Asset::get()->add(prefix + "/data/sound/jump6.wav", t_sound); - Asset::get()->add(prefix + "/data/sound/jump7.wav", t_sound); - Asset::get()->add(prefix + "/data/sound/jump8.wav", t_sound); - Asset::get()->add(prefix + "/data/sound/jump9.wav", t_sound); - Asset::get()->add(prefix + "/data/sound/jump10.wav", t_sound); - Asset::get()->add(prefix + "/data/sound/jump11.wav", t_sound); - Asset::get()->add(prefix + "/data/sound/jump12.wav", t_sound); - Asset::get()->add(prefix + "/data/sound/jump13.wav", t_sound); - Asset::get()->add(prefix + "/data/sound/jump14.wav", t_sound); - Asset::get()->add(prefix + "/data/sound/jump15.wav", t_sound); - Asset::get()->add(prefix + "/data/sound/jump16.wav", t_sound); - Asset::get()->add(prefix + "/data/sound/jump17.wav", t_sound); - Asset::get()->add(prefix + "/data/sound/jump18.wav", t_sound); - Asset::get()->add(prefix + "/data/sound/jump19.wav", t_sound); - Asset::get()->add(prefix + "/data/sound/jump20.wav", t_sound); - Asset::get()->add(prefix + "/data/sound/jump21.wav", t_sound); - Asset::get()->add(prefix + "/data/sound/jump22.wav", t_sound); - Asset::get()->add(prefix + "/data/sound/jump23.wav", t_sound); - Asset::get()->add(prefix + "/data/sound/jump24.wav", t_sound); - Asset::get()->add(prefix + "/data/sound/notify.wav", t_sound); + Asset::get()->add(prefix + "/data/sound/item.wav", AssetType::SOUND); + Asset::get()->add(prefix + "/data/sound/death.wav", AssetType::SOUND); + Asset::get()->add(prefix + "/data/sound/jump1.wav", AssetType::SOUND); + Asset::get()->add(prefix + "/data/sound/jump2.wav", AssetType::SOUND); + Asset::get()->add(prefix + "/data/sound/jump3.wav", AssetType::SOUND); + Asset::get()->add(prefix + "/data/sound/jump4.wav", AssetType::SOUND); + Asset::get()->add(prefix + "/data/sound/jump5.wav", AssetType::SOUND); + Asset::get()->add(prefix + "/data/sound/jump6.wav", AssetType::SOUND); + Asset::get()->add(prefix + "/data/sound/jump7.wav", AssetType::SOUND); + Asset::get()->add(prefix + "/data/sound/jump8.wav", AssetType::SOUND); + Asset::get()->add(prefix + "/data/sound/jump9.wav", AssetType::SOUND); + Asset::get()->add(prefix + "/data/sound/jump10.wav", AssetType::SOUND); + Asset::get()->add(prefix + "/data/sound/jump11.wav", AssetType::SOUND); + Asset::get()->add(prefix + "/data/sound/jump12.wav", AssetType::SOUND); + Asset::get()->add(prefix + "/data/sound/jump13.wav", AssetType::SOUND); + Asset::get()->add(prefix + "/data/sound/jump14.wav", AssetType::SOUND); + Asset::get()->add(prefix + "/data/sound/jump15.wav", AssetType::SOUND); + Asset::get()->add(prefix + "/data/sound/jump16.wav", AssetType::SOUND); + Asset::get()->add(prefix + "/data/sound/jump17.wav", AssetType::SOUND); + Asset::get()->add(prefix + "/data/sound/jump18.wav", AssetType::SOUND); + Asset::get()->add(prefix + "/data/sound/jump19.wav", AssetType::SOUND); + Asset::get()->add(prefix + "/data/sound/jump20.wav", AssetType::SOUND); + Asset::get()->add(prefix + "/data/sound/jump21.wav", AssetType::SOUND); + Asset::get()->add(prefix + "/data/sound/jump22.wav", AssetType::SOUND); + Asset::get()->add(prefix + "/data/sound/jump23.wav", AssetType::SOUND); + Asset::get()->add(prefix + "/data/sound/jump24.wav", AssetType::SOUND); + Asset::get()->add(prefix + "/data/sound/notify.wav", AssetType::SOUND); // Logo - Asset::get()->add(prefix + "/data/logo/jailgames.png", t_bitmap); - Asset::get()->add(prefix + "/data/logo/since_1998.png", t_bitmap); + Asset::get()->add(prefix + "/data/logo/jailgames.png", AssetType::BITMAP); + Asset::get()->add(prefix + "/data/logo/since_1998.png", AssetType::BITMAP); // Intro - Asset::get()->add(prefix + "/data/title/loading_screen_bn.png", t_bitmap); - Asset::get()->add(prefix + "/data/title/loading_screen_color.png", t_bitmap); - Asset::get()->add(prefix + "/data/title/loading_screen_bn_zxarne.png", t_bitmap); - Asset::get()->add(prefix + "/data/title/loading_screen_color_zxarne.png", t_bitmap); - Asset::get()->add(prefix + "/data/title/loading_screen_color.gif", t_bitmap); - Asset::get()->add(prefix + "/data/title/title_logo.png", t_bitmap); + Asset::get()->add(prefix + "/data/title/loading_screen_bn.png", AssetType::BITMAP); + Asset::get()->add(prefix + "/data/title/loading_screen_color.png", AssetType::BITMAP); + Asset::get()->add(prefix + "/data/title/loading_screen_bn_zxarne.png", AssetType::BITMAP); + Asset::get()->add(prefix + "/data/title/loading_screen_color_zxarne.png", AssetType::BITMAP); + Asset::get()->add(prefix + "/data/title/loading_screen_color.gif", AssetType::BITMAP); + Asset::get()->add(prefix + "/data/title/title_logo.png", AssetType::BITMAP); // Ending - Asset::get()->add(prefix + "/data/ending/ending1.png", t_bitmap); - Asset::get()->add(prefix + "/data/ending/ending1_zxarne.png", t_bitmap); - Asset::get()->add(prefix + "/data/ending/ending2.png", t_bitmap); - Asset::get()->add(prefix + "/data/ending/ending2_zxarne.png", t_bitmap); - Asset::get()->add(prefix + "/data/ending/ending3.png", t_bitmap); - Asset::get()->add(prefix + "/data/ending/ending3_zxarne.png", t_bitmap); - Asset::get()->add(prefix + "/data/ending/ending4.png", t_bitmap); - Asset::get()->add(prefix + "/data/ending/ending4_zxarne.png", t_bitmap); - Asset::get()->add(prefix + "/data/ending/ending5.png", t_bitmap); - Asset::get()->add(prefix + "/data/ending/ending5_zxarne.png", t_bitmap); + Asset::get()->add(prefix + "/data/ending/ending1.png", AssetType::BITMAP); + Asset::get()->add(prefix + "/data/ending/ending1_zxarne.png", AssetType::BITMAP); + Asset::get()->add(prefix + "/data/ending/ending2.png", AssetType::BITMAP); + Asset::get()->add(prefix + "/data/ending/ending2_zxarne.png", AssetType::BITMAP); + Asset::get()->add(prefix + "/data/ending/ending3.png", AssetType::BITMAP); + Asset::get()->add(prefix + "/data/ending/ending3_zxarne.png", AssetType::BITMAP); + Asset::get()->add(prefix + "/data/ending/ending4.png", AssetType::BITMAP); + Asset::get()->add(prefix + "/data/ending/ending4_zxarne.png", AssetType::BITMAP); + Asset::get()->add(prefix + "/data/ending/ending5.png", AssetType::BITMAP); + Asset::get()->add(prefix + "/data/ending/ending5_zxarne.png", AssetType::BITMAP); // Credits - Asset::get()->add(prefix + "/data/credits/shine.png", t_bitmap); - Asset::get()->add(prefix + "/data/credits/shine.ani", t_bitmap); + Asset::get()->add(prefix + "/data/credits/shine.png", AssetType::BITMAP); + Asset::get()->add(prefix + "/data/credits/shine.ani", AssetType::BITMAP); return Asset::get()->check(); } @@ -1283,123 +736,69 @@ bool Director::setFileList() // Ejecuta la seccion de juego con el logo void Director::runLogo() { - if (options.console) - { - std::cout << "\n* SECTION: LOGO" << std::endl; - } - loadResources(options.section); auto logo = std::make_unique(); logo->run(); - Resource::get()->free(); } // Ejecuta la seccion de juego de la pantalla de carga void Director::runLoadingScreen() { - if (options.console) - { - std::cout << "\n* SECTION: INTRO" << std::endl; - } - loadResources(options.section); auto loadingScreen = std::make_unique(); loadingScreen->run(); - Resource::get()->free(); } // Ejecuta la seccion de juego con el titulo y los menus void Director::runTitle() { - if (options.console) - { - std::cout << "\n* SECTION: TITLE" << std::endl; - } if ((JA_GetMusicState() == JA_MUSIC_INVALID) || (JA_GetMusicState() == JA_MUSIC_STOPPED)) { JA_PlayMusic(title_music_); } - loadResources(options.section); auto title = std::make_unique(); title->run(); - Resource::get()->free(); } // Ejecuta la seccion de los creditos del juego void Director::runCredits() { - if (options.console) - { - std::cout << "\n* SECTION: CREDITS" << std::endl; - } - loadResources(options.section); auto credits = std::make_unique<Credits>(); credits->run(); - Resource::get()->free(); } // Ejecuta la seccion de la demo, donde se ven pantallas del juego void Director::runDemo() { - if (options.console) - { - std::cout << "\n* SECTION: DEMO" << std::endl; - } - loadResources(options.section); auto demo = std::make_unique<Demo>(); demo->run(); - Resource::get()->free(); } // Ejecuta la seccion del final del juego void Director::runEnding() { - if (options.console) - { - std::cout << "\n* SECTION: ENDING" << std::endl; - } - loadResources(options.section); auto ending = std::make_unique<Ending>(); ending->run(); - Resource::get()->free(); } // Ejecuta la seccion del final del juego void Director::runEnding2() { - if (options.console) - { - std::cout << "\n* SECTION: ENDING2" << std::endl; - } - loadResources(options.section); auto ending2 = std::make_unique<Ending2>(); ending2->run(); - Resource::get()->free(); } // Ejecuta la seccion del final de la partida void Director::runGameOver() { - if (options.console) - { - std::cout << "\n* SECTION: GAME OVER" << std::endl; - } - loadResources(options.section); auto gameOver = std::make_unique<GameOver>(); gameOver->run(); - Resource::get()->free(); } // Ejecuta la seccion de juego donde se juega void Director::runGame() { - if (options.console) - { - std::cout << "\n* SECTION: GAME" << std::endl; - } JA_StopMusic(); - loadResources(options.section); auto game = std::make_unique<Game>(); game->run(); - Resource::get()->free(); } int Director::run() diff --git a/source/director.h b/source/director.h index 58c55bb..dbc4e9b 100644 --- a/source/director.h +++ b/source/director.h @@ -30,9 +30,6 @@ private: // Crea la carpeta del sistema donde guardar datos void createSystemFolder(const std::string &folder); - // Carga los recursos - void loadResources(SectionState section); - // Inicializa jail_audio void initJailAudio(); diff --git a/source/ending.cpp b/source/ending.cpp index 0bbbfe2..18ac84d 100644 --- a/source/ending.cpp +++ b/source/ending.cpp @@ -13,7 +13,7 @@ #include "resource.h" // Para Resource #include "screen.h" // Para Screen #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 "utils.h" // Para color_t, stringToColor, options_t #include "options.h" @@ -29,8 +29,8 @@ Ending::Ending() input(Input::get()) { // Reserva memoria para los punteros a objetos - text = new Text(resource->getOffset("smb2.txt"), resource->getTexture("smb2.png"), renderer); - music = JA_LoadMusic(asset->get("ending1.ogg").c_str()); + text = resource->getText("smb2.txt"); + music = resource->getMusic("ending1.ogg"); // Inicializa variables counter = -1; @@ -73,27 +73,7 @@ Ending::Ending() Ending::~Ending() { // Libera la memoria de los objetos - delete text; 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 @@ -206,13 +186,6 @@ void Ending::iniTexts() texts.push_back({"WERE BORN...", 158}); // Crea los sprites - for (auto st : spriteTexts) - { - delete st.sprite; - delete st.texture; - delete st.coverSprite; - delete st.coverTexture; - } spriteTexts.clear(); for (auto t : texts) @@ -223,19 +196,19 @@ void Ending::iniTexts() Color c = stringToColor(options.video.palette, "black"); // Crea la texture - st.texture = new Texture(renderer); - st.texture->createBlank(renderer, width, height, SDL_TEXTUREACCESS_TARGET); + st.texture = std::make_shared<Texture>(renderer); + st.texture->createBlank(width, height); st.texture->setAsRenderTarget(renderer); 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 - st.sprite = new Sprite({0, 0, st.texture->getWidth(), st.texture->getHeight()}, st.texture, renderer); - st.sprite->setPos({(GAMECANVAS_WIDTH - st.texture->getWidth()) / 2, t.pos}); + st.sprite = std::make_shared<Sprite>(st.texture, 0, 0, st.texture->getWidth(), st.texture->getHeight()); + st.sprite->setPosition((GAMECANVAS_WIDTH - st.texture->getWidth()) / 2, t.pos); // Crea la coverTexture - st.coverTexture = new Texture(renderer); - st.coverTexture->createBlank(renderer, width, height + 8, SDL_TEXTUREACCESS_TARGET); + st.coverTexture = std::make_shared<Texture>(renderer); + st.coverTexture->createBlank(width, height + 8); st.coverTexture->setAsRenderTarget(renderer); st.coverTexture->setBlendMode(SDL_BLENDMODE_BLEND); @@ -264,8 +237,8 @@ void Ending::iniTexts() SDL_RenderFillRect(renderer, &rect); // Crea el sprite - st.coverSprite = new Sprite({0, 0, st.coverTexture->getWidth(), st.coverTexture->getHeight() - 8}, st.coverTexture, renderer); - st.coverSprite->setPos({(GAMECANVAS_WIDTH - st.coverTexture->getWidth()) / 2, t.pos}); + st.coverSprite = std::make_shared<Sprite>(st.coverTexture, 0, 0, st.coverTexture->getWidth(), st.coverTexture->getHeight() - 8); + st.coverSprite->setPosition((GAMECANVAS_WIDTH - st.coverTexture->getWidth()) / 2, t.pos); st.coverSprite->setClip(0, 8, -1, -1); // Inicializa variables @@ -300,12 +273,6 @@ void Ending::iniPics() } // Crea los sprites - for (auto sp : spritePics) - { - delete sp.sprite; - delete sp.coverSprite; - delete sp.coverTexture; - } spritePics.clear(); for (auto p : pics) @@ -318,12 +285,12 @@ void Ending::iniPics() const int height = sp.texture->getHeight(); // Crea el sprite - sp.sprite = new Sprite({0, 0, width, height}, sp.texture, renderer); - sp.sprite->setPos({(GAMECANVAS_WIDTH - width) / 2, p.pos}); + sp.sprite = std::make_shared<Sprite>(sp.texture, 0, 0, width, height); + sp.sprite->setPosition((GAMECANVAS_WIDTH - width) / 2, p.pos); // Crea la coverTexture - sp.coverTexture = new Texture(renderer); - sp.coverTexture->createBlank(renderer, width, height + 8, SDL_TEXTUREACCESS_TARGET); + sp.coverTexture = std::make_shared<Texture>(renderer); + sp.coverTexture->createBlank(width, height + 8); sp.coverTexture->setAsRenderTarget(renderer); sp.coverTexture->setBlendMode(SDL_BLENDMODE_BLEND); @@ -352,8 +319,8 @@ void Ending::iniPics() SDL_RenderFillRect(renderer, &rect); // Crea el sprite - sp.coverSprite = new Sprite({0, 0, sp.coverTexture->getWidth(), sp.coverTexture->getHeight() - 8}, sp.coverTexture, renderer); - sp.coverSprite->setPos({(GAMECANVAS_WIDTH - sp.coverTexture->getWidth()) / 2, p.pos}); + sp.coverSprite = std::make_shared<Sprite>(sp.coverTexture, 0, 0, sp.coverTexture->getWidth(), sp.coverTexture->getHeight() - 8); + sp.coverSprite->setPosition((GAMECANVAS_WIDTH - sp.coverTexture->getWidth()) / 2, p.pos); sp.coverSprite->setClip(0, 8, -1, -1); // Inicializa variables @@ -498,7 +465,7 @@ void Ending::updateSpriteCovers() else if (spriteTexts[ti.index].clipHeight > 0) { 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); } @@ -519,7 +486,7 @@ void Ending::updateSpriteCovers() { 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); } diff --git a/source/ending.h b/source/ending.h index d80e283..70d6f0f 100644 --- a/source/ending.h +++ b/source/ending.h @@ -5,6 +5,7 @@ #include <SDL2/SDL_stdinc.h> // Para Uint32 #include <string> // Para basic_string, string #include <vector> // Para vector +#include <memory> // Para shared_ptr class Asset; class Input; class Resource; @@ -22,12 +23,12 @@ private: // Estructuras struct endingTexture_t // Estructura con dos texturas y sprites, uno para mostrar y el otro hace de cortinilla { - Texture *texture; // Textura a mostrar - Sprite *sprite; // Sprite para mostrar la textura - Texture *coverTexture; // Textura que cubre a la otra textura - Sprite *coverSprite; // Sprite para mostrar la textura que cubre a la otra textura - int clipDesp; // Desplazamiento del spriteClip de la textura de cobertura - int clipHeight; // Altura del spriteClip de la textura de cobertura + std::shared_ptr<Texture> texture; // Textura a mostrar + std::shared_ptr<Sprite> sprite; // Sprite para mostrar la textura + std::shared_ptr<Texture> coverTexture; // 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 clipHeight; // Altura del spriteClip de la textura de cobertura }; struct textAndPos_t // Estructura con un texto y su posición en el eje Y @@ -50,13 +51,13 @@ private: }; // Objetos y punteros - Screen *screen; // Objeto encargado de dibujar en pantalla - SDL_Renderer *renderer; // El renderizador de la ventana - Resource *resource; // Objeto con los recursos - Asset *asset; // Objeto con los ficheros de recursos - Input *input; // Objeto pata gestionar la entrada - Text *text; // Objeto para escribir texto en pantalla - SDL_Texture *coverTexture; // Textura para cubrir el texto + Screen *screen; // Objeto encargado de dibujar en pantalla + SDL_Renderer *renderer; // El renderizador de la ventana + Resource *resource; // Objeto con los recursos + Asset *asset; // Objeto con los ficheros de recursos + Input *input; // Objeto pata gestionar la entrada + std::shared_ptr<Text> text; // Objeto para escribir texto en pantalla + SDL_Texture *coverTexture; // Textura para cubrir el texto // Variables int counter; // Contador diff --git a/source/ending2.cpp b/source/ending2.cpp index 9ec4e50..00066ef 100644 --- a/source/ending2.cpp +++ b/source/ending2.cpp @@ -2,12 +2,12 @@ #include <SDL2/SDL_blendmode.h> // for SDL_BLENDMODE_BLEND #include <SDL2/SDL_timer.h> // for SDL_GetTicks #include <algorithm> // for max, min, replace -#include "animatedsprite.h" // for AnimatedSprite +#include "animated_sprite.h" // for AnimatedSprite #include "asset.h" // for Asset #include "const.h" // for GAMECANVAS_HEIGHT, GAMECANVAS_CENTER_X #include "input.h" // for Input, REPEAT_FALSE, inputs_e #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 "screen.h" // for Screen #include "text.h" // for Text @@ -26,8 +26,8 @@ Ending2::Ending2() input(Input::get()) { // Reserva memoria para los punteros a objetos - text = new Text(resource->getOffset("smb2.txt"), resource->getTexture("smb2.png"), renderer); - music = JA_LoadMusic(asset->get("ending2.ogg").c_str()); + text = resource->getText("smb2.txt"); + music = resource->getMusic("ending2.ogg"); // Inicializa variables counterEnabled = false; @@ -70,18 +70,6 @@ Ending2::Ending2() createTexts(); } -// Destructor -Ending2::~Ending2() -{ - // Libera la memoria de los objetos - delete text; - JA_DeleteMusic(music); - - deleteSprites(); - deleteSpriteTexts(); - deleteTexts(); -} - // Actualiza el objeto void Ending2::update() { @@ -324,9 +312,6 @@ void Ending2::iniSpriteList() // Carga todos los sprites desde una lista void Ending2::loadSprites() { - // Borra la memoria ocupada por los sprites - deleteSprites(); - // Inicializa variables maxSpriteWidth = 0; maxSpriteHeight = 0; @@ -334,9 +319,9 @@ void Ending2::loadSprites() // Carga los sprites for (auto sl : spriteList) { - sprites.push_back(new AnimatedSprite(renderer, resource->getAnimation(sl + ".ani"))); - maxSpriteWidth = std::max(sprites.back()->getAnimationClip(0, 0).w, maxSpriteWidth); - maxSpriteHeight = std::max(sprites.back()->getAnimationClip(0, 0).h, maxSpriteHeight); + sprites.emplace_back(std::make_shared<AnimatedSprite>(renderer, resource->getAnimation(sl + ".ani"))); + maxSpriteWidth = std::max(sprites.back()->getWidth(), maxSpriteWidth); + maxSpriteHeight = std::max(sprites.back()->getHeight(), maxSpriteHeight); } } @@ -432,17 +417,17 @@ void Ending2::placeSprites() { const int x = i % 2 == 0 ? firstCol : secondCol; const int y = (i / 1) * (maxSpriteHeight + distSpriteText + text->getCharacterSize() + distSpriteSprite) + GAMECANVAS_HEIGHT + 40; - const int w = sprites[i]->getAnimationClip(0, 0).w; - const int h = sprites[i]->getAnimationClip(0, 0).h; + const int w = sprites[i]->getWidth(); + const int h = sprites[i]->getHeight(); const int dx = -(w / 2); 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); } // 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 y = sprites.back()->getPosY() + maxSpriteHeight * 2; sprites.back()->setPosX(x); @@ -453,9 +438,6 @@ void Ending2::placeSprites() // Crea los sprites con las texturas con los textos 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 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; // Crea la textura - Texture *texture = new Texture(renderer); - texture->createBlank(renderer, w, h, SDL_TEXTUREACCESS_TARGET); + auto texture = std::make_shared<Texture>(renderer); + texture->createBlank(w, h); texture->setAsRenderTarget(renderer); texture->setBlendMode(SDL_BLENDMODE_BLEND); text->write(0, 0, txt); // Crea el sprite - MovingSprite *sprite = new MovingSprite(X, y, w, h, 0.0f, despSpeed, 0.0f, 0.0f, texture, renderer); - spriteTexts.push_back(sprite); + SDL_Rect pos = {X, y, w, h}; + spriteTexts.emplace_back(std::make_shared<MovingSprite>(texture, pos)); + spriteTexts.back()->setVelY(despSpeed); } } // Crea los sprites con las texturas con los textos del final void Ending2::createTexts() { - // Borra la memoria ocupada por los sprites con las texturas de los textos del final - deleteTexts(); - // Crea los primeros textos std::vector<std::string> list; list.push_back("STARRING"); @@ -506,15 +486,16 @@ void Ending2::createTexts() const int y = GAMECANVAS_HEIGHT + (text->getCharacterSize() * (i * 2)); // Crea la textura - Texture *texture = new Texture(renderer); - texture->createBlank(renderer, w, h, SDL_TEXTUREACCESS_TARGET); + auto texture = std::make_shared<Texture>(renderer); + texture->createBlank(w, h); texture->setAsRenderTarget(renderer); texture->setBlendMode(SDL_BLENDMODE_BLEND); text->write(0, 0, list[i]); // Crea el sprite - MovingSprite *sprite = new MovingSprite(x + dx, y, w, h, 0.0f, despSpeed, 0.0f, 0.0f, texture, renderer); - texts.push_back(sprite); + SDL_Rect pos = {x + dx, y, w, h}; + texts.emplace_back(std::make_shared<MovingSprite>(texture, pos)); + texts.back()->setVelY(despSpeed); } // Crea los últimos textos @@ -535,49 +516,19 @@ void Ending2::createTexts() const int y = start + (text->getCharacterSize() * (i * 2)); // Crea la textura - Texture *texture = new Texture(renderer); - texture->createBlank(renderer, w, h, SDL_TEXTUREACCESS_TARGET); + auto texture = std::make_shared<Texture>(renderer); + texture->createBlank(w, h); texture->setAsRenderTarget(renderer); texture->setBlendMode(SDL_BLENDMODE_BLEND); text->write(0, 0, list[i]); // Crea el sprite - MovingSprite *sprite = new MovingSprite(x + dx, y, w, h, 0.0f, despSpeed, 0.0f, 0.0f, texture, renderer); - texts.push_back(sprite); + SDL_Rect pos = {x + dx, y, w, h}; + 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 void Ending2::updateFinalFade() { diff --git a/source/ending2.h b/source/ending2.h index b68dd79..7216b11 100644 --- a/source/ending2.h +++ b/source/ending2.h @@ -5,6 +5,7 @@ #include <SDL2/SDL_stdinc.h> // for Uint32 #include <string> // for string #include <vector> // for vector +#include <memory> // for shared_ptr class AnimatedSprite; // lines 9-9 class Asset; // lines 10-10 class Input; // lines 11-11 @@ -21,15 +22,15 @@ class Ending2 { private: // Objetos y punteros - Screen *screen; // Objeto encargado de dibujar en pantalla - SDL_Renderer *renderer; // El renderizador de la ventana - Resource *resource; // Objeto con los recursos - Asset *asset; // Objeto con los ficheros de recursos - Input *input; // Objeto pata gestionar la entrada - Text *text; // Objeto para escribir texto en pantalla - std::vector<AnimatedSprite *> sprites; // Vector con todos los sprites a dibujar - std::vector<MovingSprite *> spriteTexts; // Vector con los sprites de texto de los sprites - std::vector<MovingSprite *> texts; // Vector con los sprites de texto + Screen *screen; // Objeto encargado de dibujar en pantalla + SDL_Renderer *renderer; // El renderizador de la ventana + Resource *resource; // Objeto con los recursos + Asset *asset; // Objeto con los ficheros de recursos + Input *input; // Objeto pata gestionar la entrada + std::shared_ptr<Text> text; // Objeto para escribir texto en pantalla + std::vector<std::shared_ptr<AnimatedSprite>> sprites; // Vector con todos los sprites a dibujar + std::vector<std::shared_ptr<MovingSprite>> spriteTexts; // Vector con los sprites de texto de los sprites + std::vector<std::shared_ptr<MovingSprite>> texts; // Vector con los sprites de texto // Variables bool counterEnabled; // Indica si está el contador habilitado @@ -97,15 +98,6 @@ private: // Crea los sprites con las texturas con los textos del final 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 void updateFinalFade(); @@ -117,7 +109,7 @@ public: Ending2(); // Destructor - ~Ending2(); + ~Ending2() = default; // Bucle principal void run(); diff --git a/source/enemy.cpp b/source/enemy.cpp index 84f1051..25c717b 100644 --- a/source/enemy.cpp +++ b/source/enemy.cpp @@ -1,8 +1,8 @@ #include "enemy.h" -#include <stdlib.h> // Para rand -#include <algorithm> // Para min -#include "animatedsprite.h" // Para AnimatedSprite -#include "texture.h" // Para Texture +#include <stdlib.h> // Para rand +#include <algorithm> // Para min +#include "animated_sprite.h" // Para AnimatedSprite +#include "texture.h" // Para Texture // Constructor Enemy::Enemy(enemy_t enemy) diff --git a/source/game.cpp b/source/game.cpp index 75da5f9..d044528 100644 --- a/source/game.cpp +++ b/source/game.cpp @@ -533,9 +533,9 @@ void Game::setScoreBoardColor() // Comprueba si ha finalizado el juego bool Game::checkEndGame() { - const bool isOnTheRoom = room_->getName() == "THE JAIL"; // Estar en la habitación que toca + const bool isOnTheRoom = room_->getName() == "THE JAIL"; // Estar en la habitación que toca const bool haveTheItems = board_.items >= int(total_items_ * 0.9f) || options.cheats.jail_is_open == Cheat::CheatState::ENABLED; // Con mas del 90% de los items recogidos - const bool isOnTheDoor = player_->getRect().x <= 128; // Y en la ubicación que toca (En la puerta) + const bool isOnTheDoor = player_->getRect().x <= 128; // Y en la ubicación que toca (En la puerta) if (haveTheItems) { diff --git a/source/game_over.cpp b/source/game_over.cpp index 41f17f5..9604566 100644 --- a/source/game_over.cpp +++ b/source/game_over.cpp @@ -1,16 +1,16 @@ #include "game_over.h" -#include <SDL2/SDL_timer.h> // Para SDL_GetTicks -#include <algorithm> // Para min, max -#include <string> // Para basic_string, operator+, to_string, char... -#include "animatedsprite.h" // Para AnimatedSprite -#include "asset.h" // Para Asset -#include "const.h" // Para GAMECANVAS_CENTER_X, SECTION_GAME_OVER -#include "input.h" // Para Input, REPEAT_FALSE, inputs_e -#include "jail_audio.h" // Para JA_DeleteMusic, JA_LoadMusic, JA_PlayMusic -#include "resource.h" // Para Resource -#include "screen.h" // Para Screen -#include "text.h" // Para Text, TXT_CENTER, TXT_COLOR -#include "texture.h" // Para Texture +#include <SDL2/SDL_timer.h> // Para SDL_GetTicks +#include <algorithm> // Para min, max +#include <string> // Para basic_string, operator+, to_string, char... +#include "animated_sprite.h" // Para AnimatedSprite +#include "asset.h" // Para Asset +#include "const.h" // Para GAMECANVAS_CENTER_X, SECTION_GAME_OVER +#include "input.h" // Para Input, REPEAT_FALSE, inputs_e +#include "jail_audio.h" // Para JA_DeleteMusic, JA_LoadMusic, JA_PlayMusic +#include "resource.h" // Para Resource +#include "screen.h" // Para Screen +#include "text.h" // Para Text, TEXT_CENTER, TEXT_COLOR +#include "texture.h" // Para Texture #include "options.h" #include "global_inputs.h" #include "global_events.h" @@ -24,10 +24,10 @@ GameOver::GameOver() input(Input::get()) { // Reserva memoria para los punteros a objetos - text = new Text(resource->getOffset("smb2.txt"), resource->getTexture("smb2.png"), renderer); - playerSprite = new AnimatedSprite(renderer, resource->getAnimation("player_game_over.ani")); - tvSprite = new AnimatedSprite(renderer, resource->getAnimation("tv.ani")); - music = JA_LoadMusic(asset->get("game_over.ogg").c_str()); + text = resource->getText("smb2.txt"); + playerSprite = std::make_shared<AnimatedSprite>(resource->getTexture("player_game_over.png"), resource->getAnimation("player_game_over.ani")); + tvSprite = std::make_shared<AnimatedSprite>(resource->getTexture("tv.png"), resource->getAnimation("tv.ani")); + music = resource->getMusic("game_over.ogg"); // Inicializa variables preCounter = 0; @@ -41,7 +41,7 @@ GameOver::GameOver() fadeLenght = 20; playerSprite->setPosX(GAMECANVAS_CENTER_X + 10); 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); // Inicializa el vector de colores @@ -53,16 +53,6 @@ GameOver::GameOver() color = colors.back(); } -// Destructor -GameOver::~GameOver() -{ - // Libera la memoria de los objetos - delete text; - delete playerSprite; - delete tvSprite; - JA_DeleteMusic(music); -} - // Actualiza el objeto void GameOver::update() { @@ -101,7 +91,7 @@ void GameOver::render() screen->clean(); // 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 playerSprite->setPosY(y + 30); @@ -111,12 +101,12 @@ void GameOver::render() // 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 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(TXT_CENTER | TXT_COLOR, GAMECANVAS_CENTER_X, y + 90, "ROOMS: " + roomsTxt, 1, color); + text->writeDX(TEXT_CENTER | TEXT_COLOR, GAMECANVAS_CENTER_X, y + 80, "ITEMS: " + itemsTxt, 1, color); + text->writeDX(TEXT_CENTER | TEXT_COLOR, GAMECANVAS_CENTER_X, y + 90, "ROOMS: " + roomsTxt, 1, color); // 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(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 + 110, "YOUR WORST NIGHTMARE IS", 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 screen->render(); diff --git a/source/game_over.h b/source/game_over.h index 1d76429..a6f37e2 100644 --- a/source/game_over.h +++ b/source/game_over.h @@ -17,14 +17,14 @@ class GameOver { private: // Objetos y punteros - Screen *screen; // Objeto encargado de dibujar en pantalla - SDL_Renderer *renderer; // El renderizador de la ventana - Resource *resource; // Objeto con los recursos - Asset *asset; // Objeto con los ficheros de recursos - Input *input; // Objeto pata gestionar la entrada - Text *text; // Objeto para escribir texto en pantalla - AnimatedSprite *playerSprite; // Sprite con el jugador - AnimatedSprite *tvSprite; // Sprite con el televisor + Screen *screen; // Objeto encargado de dibujar en pantalla + SDL_Renderer *renderer; // El renderizador de la ventana + Resource *resource; // Objeto con los recursos + Asset *asset; // Objeto con los ficheros de recursos + Input *input; // Objeto pata gestionar la entrada + std::shared_ptr<Text> text; // Objeto para escribir texto en pantalla + std::shared_ptr<AnimatedSprite> playerSprite; // Sprite con el jugador + std::shared_ptr<AnimatedSprite> tvSprite; // Sprite con el televisor // Variables int preCounter; // Contador previo @@ -64,7 +64,7 @@ public: GameOver(); // Destructor - ~GameOver(); + ~GameOver() = default; // Bucle principal void run(); diff --git a/source/loading_screen.cpp b/source/loading_screen.cpp index dbba6e9..1a963c4 100644 --- a/source/loading_screen.cpp +++ b/source/loading_screen.cpp @@ -33,11 +33,11 @@ LoadingScreen::LoadingScreen() mono_loading_screen_texture_ = resource_->getTexture("loading_screen_bn_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_); - color_loading_screen_sprite_ = new 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_sound2_ = JA_LoadMusic(asset_->get("loading_sound2.ogg").c_str()); - loading_sound3_ = JA_LoadMusic(asset_->get("loading_sound3.ogg").c_str()); + 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_ = std::make_shared<Sprite>(0, 0, color_loading_screen_texture_->getWidth(), color_loading_screen_texture_->getHeight(), color_loading_screen_texture_, renderer_); + loading_sound1_ = resource_->getMusic("loading_sound1.ogg"); + loading_sound2_ = resource_->getMusic("loading_sound2.ogg"); + loading_sound3_ = resource_->getMusic("loading_sound3.ogg"); // Inicializa variables options.section.section = Section::LOADING_SCREEN; @@ -66,16 +66,6 @@ LoadingScreen::LoadingScreen() 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 void LoadingScreen::checkEvents() { @@ -108,7 +98,7 @@ void LoadingScreen::updateLoad() load_rect_.x = step * (counter_ % numSteps); load_rect_.y = line_index_[load_counter_]; 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 else if (load_counter_ == 192) @@ -116,8 +106,8 @@ void LoadingScreen::updateLoad() loading_first_part_ = false; load_counter_ = 0; load_rect_ = {0, 0, 16, 8}; - color_loading_screen_sprite_->setRect(load_rect_); color_loading_screen_sprite_->setClip(load_rect_); + color_loading_screen_sprite_->setPosition(load_rect_); JA_PlayMusic(loading_sound3_); } } @@ -128,7 +118,7 @@ void LoadingScreen::updateLoad() load_rect_.x = (load_counter_ * 8) % 256; load_rect_.y = (load_counter_ / 32) * 8; 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 if (load_counter_ >= 768) @@ -270,7 +260,7 @@ void LoadingScreen::recreateLoadingScreen() load_rect_.x = step * (i % numSteps); load_rect_.y = line_index_[load_counter_]; 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(); } } @@ -282,7 +272,7 @@ void LoadingScreen::recreateLoadingScreen() load_rect_.x = (i * 8) % 256; load_rect_.y = (i / 32) * 8; 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(); } } diff --git a/source/loading_screen.h b/source/loading_screen.h index fb503c5..da82997 100644 --- a/source/loading_screen.h +++ b/source/loading_screen.h @@ -4,6 +4,7 @@ #include <SDL2/SDL_rect.h> // Para SDL_Rect #include <SDL2/SDL_render.h> // Para SDL_Renderer #include <SDL2/SDL_stdinc.h> // Para Uint32 +#include <memory> // Para shared_ptr class Asset; class Input; class Resource; @@ -18,15 +19,15 @@ class LoadingScreen { private: // Objetos y punteros - Screen *screen_; // Objeto encargado de dibujar en pantalla - SDL_Renderer *renderer_; // El renderizador de la ventana - Resource *resource_; // Objeto con los recursos - Asset *asset_; // Objeto con los ficheros de recursos - Input *input_; // Objeto pata gestionar la entrada - 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 - Sprite *mono_loading_screen_sprite_; // Sprite para manejar la textura loadingScreenTexture1 - Sprite *color_loading_screen_sprite_; // Sprite para manejar la textura loadingScreenTexture2 + Screen *screen_; // Objeto encargado de dibujar en pantalla + SDL_Renderer *renderer_; // El renderizador de la ventana + Resource *resource_; // Objeto con los recursos + Asset *asset_; // Objeto con los ficheros de recursos + Input *input_; // Objeto pata gestionar la entrada + std::shared_ptr<Texture> mono_loading_screen_texture_; // Textura con la pantalla de carga en blanco y negro + std::shared_ptr<Texture> color_loading_screen_texture_; // Textura con la pantalla de carga en color + std::shared_ptr<Sprite> mono_loading_screen_sprite_; // Sprite para manejar la textura loadingScreenTexture1 + std::shared_ptr<Sprite> color_loading_screen_sprite_; // Sprite para manejar la textura loadingScreenTexture2 // Variables int pre_counter_ = 0; // Contador previo para realizar una pausa inicial @@ -73,7 +74,7 @@ public: LoadingScreen(); // Destructor - ~LoadingScreen(); + ~LoadingScreen() = default; // Bucle principal void run(); diff --git a/source/logo.cpp b/source/logo.cpp index f1eb457..8db5eca 100644 --- a/source/logo.cpp +++ b/source/logo.cpp @@ -26,24 +26,24 @@ Logo::Logo() // Reserva memoria para los punteros jailgames_texture_ = resource_->getTexture("jailgames.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_texture_->setColor(0, 0, 0); // Crea los sprites de cada linea 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); if (i % 2 == 0) { - jailgames_sprite_[i]->setPosX(256 + (i * 3)); + jailgames_sprite_[i]->setX(256 + (i * 3)); } 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 @@ -60,17 +60,6 @@ Logo::Logo() 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 void Logo::checkEvents() { @@ -96,22 +85,22 @@ void Logo::updateJAILGAMES() { const int speed = 8; const int dest = 37; - if (jailgames_sprite_[i]->getPosX() != 37) + if (jailgames_sprite_[i]->getX() != 37) { if (i % 2 == 0) { - jailgames_sprite_[i]->incPosX(-speed); - if (jailgames_sprite_[i]->getPosX() < dest) + jailgames_sprite_[i]->incX(-speed); + if (jailgames_sprite_[i]->getX() < dest) { - jailgames_sprite_[i]->setPosX(dest); + jailgames_sprite_[i]->setX(dest); } } else { - jailgames_sprite_[i]->incPosX(speed); - if (jailgames_sprite_[i]->getPosX() > dest) + jailgames_sprite_[i]->incX(speed); + if (jailgames_sprite_[i]->getX() > dest) { - jailgames_sprite_[i]->setPosX(dest); + jailgames_sprite_[i]->setX(dest); } } } diff --git a/source/logo.h b/source/logo.h index a389718..2a91bdd 100644 --- a/source/logo.h +++ b/source/logo.h @@ -4,6 +4,7 @@ #include <SDL2/SDL_render.h> // for SDL_Renderer #include <SDL2/SDL_stdinc.h> // for Uint32 #include <vector> // for vector +#include <memory> // for shared_ptr class Asset; // lines 8-8 class Input; // lines 9-9 class Resource; // lines 10-10 @@ -18,15 +19,15 @@ class Logo { private: // Objetos y punteros - Screen *screen_; // Objeto encargado de dibujar en pantalla - SDL_Renderer *renderer_; // El renderizador de la ventana - Resource *resource_; // Objeto con los recursos - Asset *asset_; // Objeto con los ficheros de recursos - Input *input_; // Objeto pata gestionar la entrada - Texture *jailgames_texture_; // Textura con los graficos "JAILGAMES" - 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 - Sprite *since_1998_sprite_; // Sprite para manejar la textura2 + Screen *screen_; // Objeto encargado de dibujar en pantalla + SDL_Renderer *renderer_; // El renderizador de la ventana + Resource *resource_; // Objeto con los recursos + Asset *asset_; // Objeto con los ficheros de recursos + Input *input_; // Objeto pata gestionar la entrada + std::shared_ptr<Texture> jailgames_texture_; // Textura con los graficos "JAILGAMES" + std::shared_ptr<Texture> since_1998_texture_; // Textura con los graficos "Since 1998" + std::vector<std::shared_ptr<Sprite>> jailgames_sprite_; // Vector con los sprites de cada linea que forman el bitmap JAILGAMES + std::shared_ptr<Sprite> since_1998_sprite_; // Sprite para manejar la textura2 // Variables std::vector<Color> color_; // Vector con los colores para el fade @@ -63,7 +64,7 @@ public: Logo(); // Destructor - ~Logo(); + ~Logo() = default; // Bucle principal void run(); diff --git a/source/moving_sprite.cpp b/source/moving_sprite.cpp new file mode 100644 index 0000000..3e4493e --- /dev/null +++ b/source/moving_sprite.cpp @@ -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; +} \ No newline at end of file diff --git a/source/moving_sprite.h b/source/moving_sprite.h new file mode 100644 index 0000000..90ca717 --- /dev/null +++ b/source/moving_sprite.h @@ -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); +}; \ No newline at end of file diff --git a/source/movingsprite.cpp b/source/movingsprite.cpp deleted file mode 100644 index aa5e13b..0000000 --- a/source/movingsprite.cpp +++ /dev/null @@ -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; -} \ No newline at end of file diff --git a/source/movingsprite.h b/source/movingsprite.h deleted file mode 100644 index 0179767..0000000 --- a/source/movingsprite.h +++ /dev/null @@ -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(); -}; \ No newline at end of file diff --git a/source/player.cpp b/source/player.cpp index a678cf0..6406757 100644 --- a/source/player.cpp +++ b/source/player.cpp @@ -1,17 +1,17 @@ // IWYU pragma: no_include <bits/std_abs.h> #include "player.h" -#include <stdlib.h> // Para rand -#include <algorithm> // Para max, min -#include <cmath> // Para ceil, abs -#include "animatedsprite.h" // Para AnimatedSprite -#include "asset.h" // Para Asset -#include "const.h" // Para BORDER_TOP, BLOCK, BORDER_BOTTOM, BORDER... -#include "debug.h" // Para Debug -#include "input.h" // Para Input, inputs_e -#include "jail_audio.h" // Para JA_LoadSound, JA_Sound_t, JA_PlaySound -#include "resource.h" // Para Resource -#include "room.h" // Para Room, tile_e -#include "texture.h" // Para Texture +#include <stdlib.h> // Para rand +#include <algorithm> // Para max, min +#include <cmath> // Para ceil, abs +#include "animated_sprite.h" // Para AnimatedSprite +#include "asset.h" // Para Asset +#include "const.h" // Para BORDER_TOP, BLOCK, BORDER_BOTTOM, BORDER... +#include "debug.h" // Para Debug +#include "input.h" // Para Input, inputs_e +#include "jail_audio.h" // Para JA_LoadSound, JA_Sound_t, JA_PlaySound +#include "resource.h" // Para Resource +#include "room.h" // Para Room, tile_e +#include "texture.h" // Para Texture #include "options.h" #include "screen.h" diff --git a/source/resource.cpp b/source/resource.cpp index 849e956..c236a76 100644 --- a/source/resource.cpp +++ b/source/resource.cpp @@ -1,360 +1,355 @@ #include "resource.h" -#include <iostream> // Para basic_ostream, operator<<, cout, endl -#include "animatedsprite.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" +#include <algorithm> // Para find_if +#include <iostream> // Para basic_ostream, operator<<, endl, cout, cerr +#include <stdexcept> // Para runtime_error +#include <utility> // Para pair +#include "asset.h" // Para Asset, AssetType +#include "jail_audio.h" // Para JA_LoadMusic, JA_LoadSound +#include "lang.h" // Para getText +#include "screen.h" // Para Screen +#include "text.h" // Para Text, loadTextFile +struct JA_Music_t; // lines 10-10 +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; -// [SINGLETON] Crearemos el objeto con esta función estática +// [SINGLETON] Crearemos el objeto screen con esta función estática void Resource::init() { 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() { 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() { return Resource::resource_; } -// Carga las texturas de una lista -void Resource::loadTextures(std::vector<std::string> list) +// Constructor +Resource::Resource() { - 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 = new Texture(Screen::get()->getRenderer(), Asset::get()->get(t.name), options.console); - textures_.push_back(t); - } + load(); } -// Vuelve a cargar las texturas -void Resource::reLoadTextures() +// Vacia todos los vectores de recursos +void Resource::clear() { - 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 = 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; - } + clearSounds(); + clearMusics(); textures_.clear(); -} - -// Libera las animaciones -void Resource::freeAnimations() -{ - for (auto a : animations_) - { - delete a.animation; - } + text_files_.clear(); + texts_.clear(); animations_.clear(); + demos_.clear(); } -// Libera los offsets -void Resource::freeOffsets() +// Carga todos los recursos +void Resource::load() { - for (auto o : offsets_) - { - delete o.textFile; - } - offsets_.clear(); + std::cout << "** LOADING RESOURCES" << std::endl; + loadSounds(); + loadMusics(); + loadTextures(); + loadTextFiles(); + loadAnimations(); + loadDemoData(); + addPalettes(); + createText(); + createTextures(); + std::cout << "\n** RESOURCES LOADED" << std::endl; } -// Libera los mapas de tiles -void Resource::freeTileMaps() +// Recarga todos los recursos +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(); + + 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 -void Resource::freeRooms() +// Carga las habitaciones +void Resource::loadRooms() { - for (auto r : rooms_) - { - delete r.room; - } + std::cout << "\n>> ROOMS" << std::endl; + auto list = Asset::get()->getListByType(AssetType::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_) + for (const auto &l : list) { - // 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; + auto name = getFileName(l); + rooms_.emplace_back(ResourceRoom(name, std::make_shared<room_t>(loadRoomFile(l)))); + } +} - return texture.texture; +void Resource::createText() +{ + struct ResourceInfo + { + std::string key; // Identificador del recurso + std::string textureFile; // Nombre del archivo de textura + 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 ]"); + } +} + +// Vacía el vector de sonidos +void Resource::clearSounds() +{ + // Itera sobre el vector y libera los recursos asociados a cada JA_Sound_t + for (auto &sound : sounds_) + { + if (sound.sound) + { + JA_DeleteSound(sound.sound); + sound.sound = nullptr; } } - - if (options.console) - { - std::cout << "NOT FOUND ON CACHE: " << name << std::endl; - } - return nullptr; + sounds_.clear(); // Limpia el vector después de liberar todos los recursos } -// Obtiene una animación -animatedSprite_t *Resource::getAnimation(std::string name) +// Vacía el vector de musicas +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 (animation.name == name) + if (music.music) { - // std::cout << "\nANIMATION REQUESTED: " << name << std::endl; - // std::cout << "served: " << animation.name << std::endl; - return animation.animation; + JA_DeleteMusic(music.music); + music.music = nullptr; } } - - 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_; + musics_.clear(); // Limpia el vector después de liberar todos los recursos } \ No newline at end of file diff --git a/source/resource.h b/source/resource.h index e7f7624..b3524c5 100644 --- a/source/resource.h +++ b/source/resource.h @@ -1,141 +1,197 @@ #pragma once -#include <SDL2/SDL_render.h> // Para SDL_Renderer -#include <string> // Para string, basic_string -#include <vector> // Para vector -class Asset; -class Texture; -struct animatedSprite_t; -struct Options; -struct room_t; -struct textFile_t; +#include <memory> // Para shared_ptr +#include <string> // Para string +#include <vector> // Para vector +#include "animated_sprite.h" // Para AnimationsFileBuffer +#include "text.h" // Para TextFile +#include "texture.h" // Para Texture +#include "utils.h" // Para DemoData +#include "room.h" +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 de la textura - Texture *texture; // La textura + 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) {} }; -struct res_animation_t +// Estructura para almacenar ficheros musicales y su nombre +struct ResourceMusic { - std::string name; // Nombre de la textura - animatedSprite_t *animation; // La animación + 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) {} }; -struct res_textOffset_t +// Estructura para almacenar objetos Texture y su nombre +struct ResourceTexture { - std::string name; // Nombre del offset - textFile_t *textFile; // Los offsets de la fuente + std::string name; // Nombre de 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_tileMap_t +// Estructura para almacenar ficheros TextFile y su nombre +struct ResourceTextFile { - std::string name; // Nombre del mapa de tiles - std::vector<int> *tileMap; // Vector con los indices del mapa de tiles + std::string name; // Nombre del fichero + 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_room_t +// Estructura para almacenar objetos Text y su nombre +struct ResourceText { - std::string name; // Nombre de la habitación - room_t *room; // Vector con las habitaciones + std::string name; // Nombre del objeto + std::shared_ptr<Text> text; // Objeto + + // Constructor + ResourceText(const std::string &name, std::shared_ptr<Text> text) + : name(name), text(text) {} +}; + +// 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::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) {} +}; + +// Estructura para almacenar habitaciones y su nombre +struct ResourceRoom +{ + std::string name; // Nombre de la habitación + 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 { private: - // [SINGLETON] Objeto privado - static Resource *resource_; + // [SINGLETON] Objeto resource privado para Don Melitón + 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_; + std::vector<ResourceSound> sounds_; // Vector con los sonidos + std::vector<ResourceMusic> musics_; // Vector con las musicas + std::vector<ResourceTexture> textures_; // Vector con las musicas + std::vector<ResourceTextFile> text_files_; // Vector con los ficheros de texto + std::vector<ResourceText> texts_; // Vector con los objetos de texto + 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 - // Constructor - Resource() = default; + // Carga los sonidos + void loadSounds(); - // Destructor - ~Resource() = default; + // 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 + Resource(); + + // Destructor + ~Resource() = default; public: - // [SINGLETON] Crearemos el objeto con esta función estática - static void init(); + // [SINGLETON] Crearemos el objeto resource con esta función estática + static void init(); - // [SINGLETON] Destruiremos el objeto con esta función estática - static void destroy(); + // [SINGLETON] Destruiremos el objeto resource 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(); + // [SINGLETON] Con este método obtenemos el objeto resource y podemos trabajar con él + static Resource *get(); - // Carga las texturas de una lista - void loadTextures(std::vector<std::string> list); + // Obtiene el sonido a partir de un nombre + JA_Sound_t *getSound(const std::string &name); - // Vuelve a cargar las texturas - void reLoadTextures(); + // Obtiene la música a partir de un nombre + JA_Music_t *getMusic(const std::string &name); - // Carga las animaciones desde una lista - void loadAnimations(std::vector<std::string> list); + // Obtiene la textura a partir de un nombre + std::shared_ptr<Texture> getTexture(const std::string &name); - // Vuelve a cargar las animaciones - void reLoadAnimations(); + // Obtiene el fichero de texto a partir de un nombre + std::shared_ptr<TextFile> getTextFile(const std::string &name); - // Carga los offsets desde una lista - void loadOffsets(std::vector<std::string> list); + // Obtiene el objeto de texto a partir de un nombre + std::shared_ptr<Text> getText(const std::string &name); - // Vuelve a cargar los offsets - void reLoadOffsets(); + // Obtiene la animación a partir de un nombre + AnimationsFileBuffer &getAnimation(const std::string &name); - // Carga los mapas de tiles desde una lista - void loadTileMaps(std::vector<std::string> list); + // Obtiene el mapa de tiles a partir de un nombre + std::vector<int> &getTileMap(const std::string &name); - // Vuelve a cargar los mapas de tiles - void reLoadTileMaps(); + // Obtiene la habitación a partir de un nombre + std::shared_ptr<room_t> getRoom(const std::string &name); - // 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 - 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(); + // Recarga todos los recursos + void reload(); }; \ No newline at end of file diff --git a/source/resource_old.cpp b/source/resource_old.cpp new file mode 100644 index 0000000..8e51a04 --- /dev/null +++ b/source/resource_old.cpp @@ -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_; +} \ No newline at end of file diff --git a/source/resource_old.h b/source/resource_old.h new file mode 100644 index 0000000..1f9fa00 --- /dev/null +++ b/source/resource_old.h @@ -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(); +}; \ No newline at end of file diff --git a/source/scoreboard.cpp b/source/scoreboard.cpp index b69c093..86bbe9c 100644 --- a/source/scoreboard.cpp +++ b/source/scoreboard.cpp @@ -1,11 +1,11 @@ #include "scoreboard.h" -#include <SDL2/SDL_rect.h> // Para SDL_Rect -#include <SDL2/SDL_timer.h> // Para SDL_GetTicks -#include "animatedsprite.h" // Para AnimatedSprite -#include "const.h" // Para BLOCK, PLAY_AREA_HEIGHT, PLAY_AREA_WIDTH -#include "resource.h" // Para Resource -#include "text.h" // Para Text -#include "texture.h" // Para Texture +#include <SDL2/SDL_rect.h> // Para SDL_Rect +#include <SDL2/SDL_timer.h> // Para SDL_GetTicks +#include "animated_sprite.h" // Para AnimatedSprite +#include "const.h" // Para BLOCK, PLAY_AREA_HEIGHT, PLAY_AREA_WIDTH +#include "resource.h" // Para Resource +#include "text.h" // Para Text +#include "texture.h" // Para Texture #include "options.h" #include "screen.h" #include "asset.h" diff --git a/source/text.cpp b/source/text.cpp index 6a70bff..86a7a6d 100644 --- a/source/text.cpp +++ b/source/text.cpp @@ -1,50 +1,56 @@ #include "text.h" -#include <fstream> // Para char_traits, basic_ostream, basic_ifstream, ope... -#include <iostream> // Para cout -#include "sprite.h" // Para Sprite -#include "texture.h" // Para Texture -#include "utils.h" // Para color_t +#include <SDL2/SDL_blendmode.h> // Para SDL_BLENDMODE_BLEND +#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 "texture.h" // Para Texture +#include "utils.h" // Para Color, getFileName, printWithDots -// Llena una estructuta textFile_t desde un fichero -textFile_t LoadTextFile(std::string file, bool verbose) +// Llena una estructuta TextFile desde un fichero +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 for (int i = 0; i < 128; ++i) { - tf.offset[i].x = 0; - tf.offset[i].y = 0; - tf.offset[i].w = 0; + tf->offset[i].x = 0; + tf->offset[i].y = 0; + tf->offset[i].w = 0; + tf->box_width = 0; + tf->box_height = 0; } // Abre el fichero para leer los valores - const std::string filename = file.substr(file.find_last_of("\\/") + 1).c_str(); - std::ifstream rfile(file); + std::ifstream file(file_path); - if (rfile.is_open() && rfile.good()) + if (file.is_open() && file.good()) { std::string buffer; // Lee los dos primeros valores del fichero - std::getline(rfile, buffer); - std::getline(rfile, buffer); - tf.boxWidth = std::stoi(buffer); + std::getline(file, buffer); + std::getline(file, buffer); + tf->box_width = std::stoi(buffer); - std::getline(rfile, buffer); - std::getline(rfile, buffer); - tf.boxHeight = std::stoi(buffer); + std::getline(file, buffer); + std::getline(file, buffer); + tf->box_height = std::stoi(buffer); // lee el resto de datos del fichero - int index = 32; - int line_read = 0; - while (std::getline(rfile, buffer)) + auto index = 32; + auto line_read = 0; + while (std::getline(file, buffer)) { // Almacena solo las lineas impares if (line_read % 2 == 1) - { - tf.offset[index++].w = std::stoi(buffer); - } + tf->offset[index++].w = std::stoi(buffer); // Limpia el buffer buffer.clear(); @@ -52,131 +58,171 @@ textFile_t LoadTextFile(std::string file, bool verbose) }; // Cierra el fichero - if (verbose) - { - std::cout << "Text loaded: " << filename.c_str() << std::endl; - } - rfile.close(); + printWithDots("Text File : ", getFileName(file_path), "[ LOADED ]"); + file.close(); } // El fichero no se puede abrir else { - if (verbose) - { - std::cout << "Warning: Unable to open " << filename.c_str() << " file" << std::endl; - } + std::cerr << "Error: Fichero no encontrado " << getFileName(file_path) << std::endl; + throw std::runtime_error("Fichero no encontrado: " + getFileName(file_path)); } // Establece las coordenadas para cada caracter ascii de la cadena y su ancho for (int i = 32; i < 128; ++i) { - tf.offset[i].x = ((i - 32) % 15) * tf.boxWidth; - tf.offset[i].y = ((i - 32) / 15) * tf.boxHeight; + tf->offset[i].x = ((i - 32) % 15) * tf->box_width; + tf->offset[i].y = ((i - 32) / 15) * tf->box_height; } return tf; } // 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 - textFile_t tf = LoadTextFile(textFile); + auto tf = loadTextFile(text_file); // Inicializa variables desde la estructura - boxHeight = tf.boxHeight; - boxWidth = tf.boxWidth; + box_height_ = tf->box_height; + box_width_ = tf->box_width; for (int i = 0; i < 128; ++i) { - offset[i].x = tf.offset[i].x; - offset[i].y = tf.offset[i].y; - offset[i].w = tf.offset[i].w; + offset_[i].x = tf->offset[i].x; + offset_[i].y = tf->offset[i].y; + offset_[i].w = tf->offset[i].w; } // 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 - fixedWidth = false; + fixed_width_ = false; } // 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 - boxHeight = textFile->boxHeight; - boxWidth = textFile->boxWidth; + box_height_ = text_file->box_height; + box_width_ = text_file->box_width; for (int i = 0; i < 128; ++i) { - offset[i].x = textFile->offset[i].x; - offset[i].y = textFile->offset[i].y; - offset[i].w = textFile->offset[i].w; + offset_[i].x = text_file->offset[i].x; + offset_[i].y = text_file->offset[i].y; + offset_[i].w = text_file->offset[i].w; } // 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 - fixedWidth = false; -} - -// Destructor -Text::~Text() -{ - delete sprite; + fixed_width_ = false; } // 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; if (lenght == -1) lenght = text.length(); + sprite_->setY(y); for (int i = 0; i < lenght; ++i) { - sprite->setClip(offset[int(text[i])].x, offset[int(text[i])].y, sprite->getWidth(), sprite->getHeight()); - sprite->setPosX(x + shift); - sprite->setPosY(y); - sprite->render(); - // shift += (offset[int(text[i])].w + kerning); - shift += fixedWidth ? boxWidth : (offset[int(text[i])].w + kerning); + auto index = static_cast<int>(text[i]); + sprite_->setClip(offset_[index].x, offset_[index].y, box_width_, box_height_); + sprite_->setX(x + shift); + sprite_->render(); + shift += offset_[static_cast<int>(text[i])].w + kerning; } } -// Escribe el texto con colores -void Text::writeColored(int x, int y, std::string text, Color color, int kerning, int lenght) +// Escribe texto en pantalla +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); - sprite->getTexture()->setColor(255, 255, 255); + sprite_->getTexture()->setColor(255, 255, 255); } // 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); - write(x + shadowDistance, y + shadowDistance, text, kerning, lenght); - sprite->getTexture()->setColor(255, 255, 255); + sprite_->getTexture()->setColor(color.r, color.g, color.b); + write(x + shadow_distance, y + shadow_distance, text, kerning, lenght); + sprite_->getTexture()->setColor(255, 255, 255); write(x, y, text, kerning, lenght); } // 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); write(x, y, text, kerning, lenght); } // 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 bool shadowed = ((flags & TXT_SHADOW) == TXT_SHADOW); - const bool colored = ((flags & TXT_COLOR) == TXT_COLOR); - const bool stroked = ((flags & TXT_STROKE) == TXT_STROKE); + const auto centered = ((flags & TEXT_CENTER) == TEXT_CENTER); + const auto shadowed = ((flags & TEXT_SHADOW) == TEXT_SHADOW); + const auto colored = ((flags & TEXT_COLOR) == TEXT_COLOR); + const auto stroked = ((flags & TEXT_STROKE) == TEXT_STROKE); if (centered) { @@ -185,18 +231,18 @@ void Text::writeDX(Uint8 flags, int x, int y, std::string text, int kerning, Col 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) { - for (int dist = 1; dist <= shadowDistance; ++dist) + for (int dist = 1; dist <= shadow_distance; ++dist) { for (int dy = -dist; dy <= dist; ++dy) { 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 -int Text::lenght(std::string text, int kerning) +int Text::lenght(const std::string &text, int kerning) const { int shift = 0; - - for (int i = 0; i < (int)text.length(); ++i) - shift += (offset[int(text[i])].w + kerning); + for (size_t i = 0; i < text.length(); ++i) + shift += (offset_[static_cast<int>(text[i])].w + kerning); // Descuenta el kerning del último caracter return shift - kerning; } // Devuelve el valor de la variable -int Text::getCharacterSize() +int Text::getCharacterSize() const { - return boxWidth; + return box_width_; } // Recarga la textura void Text::reLoadTexture() { - sprite->getTexture()->reLoad(); + sprite_->getTexture()->reLoad(); } // Establece si se usa un tamaño fijo de letra 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); } \ No newline at end of file diff --git a/source/text.h b/source/text.h index aca2550..3ec7b97 100644 --- a/source/text.h +++ b/source/text.h @@ -1,79 +1,87 @@ #pragma once -#include <SDL2/SDL_render.h> // Para SDL_Renderer #include <SDL2/SDL_stdinc.h> // Para Uint8 +#include <memory> // Para unique_ptr, shared_ptr #include <string> // Para string -class Sprite; -class Texture; -#include "utils.h" +#include "sprite.h" // Para Sprite +#include "utils.h" // Para Color +class Texture; // lines 9-9 -constexpr int TXT_COLOR = 1; -constexpr int TXT_SHADOW = 2; -constexpr int TXT_CENTER = 4; -constexpr int TXT_STROKE = 8; +constexpr int TEXT_COLOR = 1; +constexpr int TEXT_SHADOW = 2; +constexpr int TEXT_CENTER = 4; +constexpr int TEXT_STROKE = 8; -struct offset_t +struct TextOffset { - int x; - int y; - int w; + int x, y, w; }; -struct textFile_t +struct TextFile { - int boxWidth; // Anchura de la caja de cada caracter en el png - int boxHeight; // Altura de la caja de cada caracter en el png - offset_t offset[128]; // Vector con las posiciones y ancho de cada letra + int box_width; // Anchura de la caja de cada caracter en el png + int box_height; // Altura de la caja de cada caracter en el png + TextOffset offset[128]; // Vector con las posiciones y ancho de cada letra }; -// Llena una estructuta textFile_t desde un fichero -textFile_t LoadTextFile(std::string file, bool verbose = false); +// Llena una estructuta TextFile desde un fichero +std::shared_ptr<TextFile> loadTextFile(const std::string &file_path); // Clase texto. Pinta texto en pantalla a partir de un bitmap class Text { private: // 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 - int boxWidth; // Anchura de la caja de cada caracter en el png - int boxHeight; // 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 - offset_t offset[128]; // Vector con las posiciones y ancho de cada letra + int box_width_ = 0; // Anchura de la caja de cada caracter en el png + int box_height_ = 0; // Altura de la caja de cada caracter en el png + bool fixed_width_ = false; // Indica si el texto se ha de escribir con longitud fija en todas las letras + TextOffset offset_[128] = {}; // Vector con las posiciones y ancho de cada letra public: // Constructor - Text(std::string textFile, Texture *texture, SDL_Renderer *renderer); - Text(textFile_t *textFile, Texture *texture, SDL_Renderer *renderer); + Text(std::shared_ptr<Texture> texture, const std::string &text_file); + Text(std::shared_ptr<Texture> texture, std::shared_ptr<TextFile> text_file); // Destructor - ~Text(); + ~Text() = default; // 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 - 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 - 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 - 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 - 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 - int lenght(std::string text, int kerning = 1); + int lenght(const std::string &text, int kerning = 1) const; // Devuelve el valor de la variable - int getCharacterSize(); + int getCharacterSize() const; // Recarga la textura void reLoadTexture(); // Establece si se usa un tamaño fijo de letra void setFixedWidth(bool value); + + // Establece una paleta + void setPalette(int number); }; \ No newline at end of file diff --git a/source/texture.cpp b/source/texture.cpp index 4eaacea..20f7dd5 100644 --- a/source/texture.cpp +++ b/source/texture.cpp @@ -78,10 +78,18 @@ bool Texture::loadFromFile(const std::string &file_path) int depth, pitch; Uint32 pixel_format; - // STBI_rgb_alpha (RGBA) - depth = 32; - pitch = 4 * width; - pixel_format = SDL_PIXELFORMAT_RGBA32; + /*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; + pitch = 4 * width; + pixel_format = SDL_PIXELFORMAT_RGBA32; + } // Limpia unloadTexture(); diff --git a/source/texture.h b/source/texture.h index 16cc4e6..22f6790 100644 --- a/source/texture.h +++ b/source/texture.h @@ -62,7 +62,7 @@ public: bool loadFromFile(const std::string &path); // 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 void setColor(Uint8 red, Uint8 green, Uint8 blue); diff --git a/source/title.cpp b/source/title.cpp index 213b9f5..e6e92d7 100644 --- a/source/title.cpp +++ b/source/title.cpp @@ -35,9 +35,9 @@ Title::Title() { texture_ = resource_->getTexture("title_logo.png"); } - sprite_ = new Sprite(0, 0, texture_->getWidth(), texture_->getHeight(), texture_, renderer_); - text_ = new Text(resource_->getOffset("smb2.txt"), resource_->getTexture("smb2.png"), renderer_); - info_text_ = new Text(resource_->getOffset("subatomic.txt"), resource_->getTexture("subatomic.png"), renderer_); + sprite_ = std::make_shared<Sprite>(0, 0, texture_->getWidth(), texture_->getHeight(), texture_, renderer_); + text_ = resource_->getText("smb2.txt"); + info_text_ = resource_->getText("subatomic.txt"); // 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); @@ -75,11 +75,6 @@ Title::Title() // Destructor Title::~Title() { - delete sprite_; - delete cheevos_sprite_; - delete cheevos_texture_; - delete text_; - delete info_text_; pDeleteSurface(loading_screen_); SDL_DestroyTexture(bg_texture_); } @@ -387,10 +382,10 @@ void Title::fillTexture() // Escribe el texto en la textura const Color textColor = stringToColor(options.video.palette, "green"); const int textSize = text_->getCharacterSize(); - text_->writeDX(TXT_CENTER | TXT_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(TXT_CENTER | TXT_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, 11 * textSize, "1.PLAY", 1, textColor); + text_->writeDX(TEXT_CENTER | TEXT_COLOR, PLAY_AREA_CENTER_X, 13 * textSize, "2.ACHIEVEMENTS", 1, textColor); + text_->writeDX(TEXT_CENTER | TEXT_COLOR, PLAY_AREA_CENTER_X, 15 * textSize, "3.REDEFINE KEYS", 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 SDL_SetRenderTarget(renderer_, nullptr); @@ -407,8 +402,8 @@ void Title::createCheevosTexture() const int cheevosPadding = 10; const int cheevoHeight = cheevosPadding + (info_text_->getCharacterSize() * 2) + 1; const int cheevosTextureHeight = (cheevoHeight * cheevosList.size()) + 2 + info_text_->getCharacterSize() + 8; - cheevos_texture_ = new Texture(renderer_); - cheevos_texture_->createBlank(renderer_, cheevosTextureWidth, cheevosTextureHeight, SDL_TEXTUREACCESS_TARGET); + cheevos_texture_ = std::make_shared<Texture>(renderer_); + cheevos_texture_->createBlank(cheevosTextureWidth, cheevosTextureHeight, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET); cheevos_texture_->setAsRenderTarget(renderer_); cheevos_texture_->setBlendMode(SDL_BLENDMODE_BLEND); @@ -421,7 +416,7 @@ void Title::createCheevosTexture() const std::string cheevosOwner = "ACHIEVEMENTS"; const std::string cheevosListCaption = cheevosOwner + " (" + std::to_string(Cheevos::get()->unlocked()) + " / " + std::to_string(Cheevos::get()->count()) + ")"; 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(); const Color cheevoLockedColor = stringToColor(options.video.palette, "white"); const Color cheevoUnlockedColor = stringToColor(options.video.palette, "bright_green"); @@ -436,14 +431,14 @@ void Title::createCheevosTexture() pos += cheevosPadding; int half = cheevosPadding / 2; 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; - 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(); } // 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_sprite_->setClip(cheevos_texture_view_); } diff --git a/source/title.h b/source/title.h index 3496095..df5c7a9 100644 --- a/source/title.h +++ b/source/title.h @@ -41,13 +41,13 @@ private: SDL_Renderer *renderer_; // El renderizador de la ventana Resource *resource_; // Objeto con los recursos Input *input_; // Objeto pata gestionar la entrada - Texture *texture_; // Textura con los graficos - Sprite *sprite_; // Sprite para manejar la textura + std::shared_ptr<Texture> texture_; // Textura con los graficos + std::shared_ptr<Sprite> sprite_; // Sprite para manejar la textura SDL_Texture *bg_texture_; // Textura para dibujar el fondo de la pantalla - Text *text_; // Objeto para escribir texto en pantalla - Text *info_text_; // Objeto para escribir texto en pantalla - 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<Text> text_; // Objeto para escribir texto en pantalla + std::shared_ptr<Text> info_text_; // Objeto para escribir texto en pantalla + std::shared_ptr<Texture> cheevos_texture_; // Textura con la lista de logros + std::shared_ptr<Sprite> cheevos_sprite_; // Sprite para manejar la textura con la lista de logros // Variables int counter_ = 0; // Contador diff --git a/source/utils.cpp b/source/utils.cpp index ded51be..12ae67f 100644 --- a/source/utils.cpp +++ b/source/utils.cpp @@ -3,6 +3,7 @@ #include <stdlib.h> // Para free, malloc, abs #include <cmath> // Para round, abs #include <algorithm> +#include <iostream> #include <cctype> // Calcula el cuadrado de la distancia entre dos puntos @@ -603,4 +604,17 @@ std::string getPath(const std::string &full_path) { std::filesystem::path path(full_path); 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; } \ No newline at end of file diff --git a/source/utils.h b/source/utils.h index af49cc1..345f719 100644 --- a/source/utils.h +++ b/source/utils.h @@ -120,4 +120,7 @@ std::string toUpper(std::string str); std::string getFileName(const std::string &path); // Obtiene la ruta eliminando el nombre del fichero -std::string getPath(const std::string &full_path); \ No newline at end of file +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); \ No newline at end of file