diff --git a/source/animated_sprite.cpp b/source/animated_sprite.cpp index 4427180..2d45431 100644 --- a/source/animated_sprite.cpp +++ b/source/animated_sprite.cpp @@ -8,7 +8,7 @@ #include "utils.h" // Para printWithDots // Carga las animaciones en un vector(Animations) desde un fichero -AnimationsFileBuffer loadAnimationsFromFile(const std::string &file_path) +Animations loadAnimationsFromFile(const std::string &file_path) { std::ifstream file(file_path); if (!file) @@ -37,18 +37,18 @@ AnimatedSprite::AnimatedSprite(std::shared_ptr texture, const std::stri // Carga las animaciones if (!file_path.empty()) { - AnimationsFileBuffer v = loadAnimationsFromFile(file_path); - loadFromAnimationsFileBuffer(v); + Animations v = loadAnimationsFromFile(file_path); + setAnimations(v); } } // Constructor -AnimatedSprite::AnimatedSprite(std::shared_ptr texture, const AnimationsFileBuffer &animations) +AnimatedSprite::AnimatedSprite(std::shared_ptr texture, const Animations &animations) : MovingSprite(texture) { if (!animations.empty()) { - loadFromAnimationsFileBuffer(animations); + setAnimations(animations); } } @@ -122,6 +122,7 @@ void AnimatedSprite::setCurrentAnimation(const std::string &name) animations_[current_animation_].current_frame = 0; animations_[current_animation_].counter = 0; animations_[current_animation_].completed = false; + setClip(animations_[current_animation_].frames[animations_[current_animation_].current_frame]); } } @@ -135,6 +136,7 @@ void AnimatedSprite::setCurrentAnimation(int index) animations_[current_animation_].current_frame = 0; animations_[current_animation_].counter = 0; animations_[current_animation_].completed = false; + setClip(animations_[current_animation_].frames[animations_[current_animation_].current_frame]); } } @@ -154,7 +156,7 @@ void AnimatedSprite::resetAnimation() } // Carga la animación desde un vector de cadenas -void AnimatedSprite::loadFromAnimationsFileBuffer(const AnimationsFileBuffer &source) +void AnimatedSprite::setAnimations(const Animations &animations) { int frame_width = 1; int frame_height = 1; @@ -162,9 +164,9 @@ void AnimatedSprite::loadFromAnimationsFileBuffer(const AnimationsFileBuffer &so int max_tiles = 1; size_t index = 0; - while (index < source.size()) + while (index < animations.size()) { - std::string line = source.at(index); + std::string line = animations.at(index); // Parsea el fichero para buscar variables y valores if (line != "[animation]") @@ -194,11 +196,11 @@ void AnimatedSprite::loadFromAnimationsFileBuffer(const AnimationsFileBuffer &so // Si la linea contiene el texto [animation] se realiza el proceso de carga de una animación if (line == "[animation]") { - Animation animation; + AnimationData animation; do { index++; - line = source.at(index); + line = animations.at(index); size_t pos = line.find("="); if (pos != std::string::npos) diff --git a/source/animated_sprite.h b/source/animated_sprite.h index 52d9156..c669eb2 100644 --- a/source/animated_sprite.h +++ b/source/animated_sprite.h @@ -7,7 +7,7 @@ #include "moving_sprite.h" // Para MovingSprite class Texture; // lines 9-9 -struct Animation +struct AnimationData { std::string name; // Nombre de la animacion std::vector frames; // Cada uno de los frames que componen la animación @@ -17,31 +17,31 @@ struct Animation 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) {} + AnimationData() : name(std::string()), speed(5), loop(0), completed(false), current_frame(0), counter(0) {} }; -using AnimationsFileBuffer = std::vector; +using Animations = std::vector; // Carga las animaciones en un vector(Animations) desde un fichero -AnimationsFileBuffer loadAnimationsFromFile(const std::string &file_path); +Animations 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 + 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); + void setAnimations(const Animations &animations); public: // Constructor AnimatedSprite(std::shared_ptr texture, const std::string &file_path); - AnimatedSprite(std::shared_ptr texture, const AnimationsFileBuffer &animations); + AnimatedSprite(std::shared_ptr texture, const Animations &animations); explicit AnimatedSprite(std::shared_ptr texture) : MovingSprite(texture) {} diff --git a/source/credits.cpp b/source/credits.cpp index 1197b2a..7325b5e 100644 --- a/source/credits.cpp +++ b/source/credits.cpp @@ -1,22 +1,22 @@ #include "credits.h" -#include // for SDL_BLENDMODE_BLEND -#include // for SDL_GetError -#include // for SDL_PollEvent, SDL_Event -#include // for SDL_PIXELFORMAT_RGBA8888 -#include // for SDL_Rect -#include // for SDL_GetTicks -#include // for min -#include // for basic_ostream, operator<<, cout, endl -#include "animated_sprite.h" // for AnimatedSprite -#include "asset.h" // for Asset -#include "defines.h" // for GAMECANVAS_HEIGHT, GAMECANVAS_WIDTH -#include "global_events.h" // for check -#include "global_inputs.h" // for check -#include "input.h" // for Input -#include "options.h" // for Options, options, OptionsVideo, Sect... -#include "resource.h" // for Resource -#include "screen.h" // for Screen -#include "text.h" // for Text, TEXT_CENTER, TEXT_COLOR +#include // for SDL_BLENDMODE_BLEND +#include // for SDL_GetError +#include // for SDL_PollEvent, SDL_Event +#include // for SDL_PIXELFORMAT_RGBA8888 +#include // for SDL_Rect +#include // for SDL_GetTicks +#include // for min +#include // for basic_ostream, operator<<, cout, endl +#include "animated_sprite.h" // for AnimatedSprite +#include "asset.h" // for Asset +#include "defines.h" // for GAMECANVAS_HEIGHT, GAMECANVAS_WIDTH +#include "global_events.h" // for check +#include "global_inputs.h" // for check +#include "input.h" // for Input +#include "options.h" // for Options, options, OptionsVideo, Sect... +#include "resource.h" // for Resource +#include "screen.h" // for Screen +#include "text.h" // for Text, TEXT_CENTER, TEXT_COLOR // Constructor Credits::Credits() @@ -28,7 +28,7 @@ Credits::Credits() { // Reserva memoria para los punteros text_ = resource_->getText("smb2"); - sprite_ = std::make_shared(resource_->getTexture("shine.png"), resource_->getAnimation("shine.ani")); + sprite_ = std::make_shared(resource_->getTexture("shine.png"), resource_->getAnimations("shine.ani")); // Inicializa variables options.section.section = Section::CREDITS; diff --git a/source/demo.cpp b/source/demo.cpp index 53f605f..ddfcb48 100644 --- a/source/demo.cpp +++ b/source/demo.cpp @@ -27,7 +27,8 @@ Demo::Demo() debug_(Debug::get()) { // Inicia algunas variables - board_.ini_clock = SDL_GetTicks(); + board_ = std::make_shared(); + board_->ini_clock = SDL_GetTicks(); rooms_.push_back("04.room"); rooms_.push_back("54.room"); rooms_.push_back("20.room"); @@ -42,19 +43,19 @@ Demo::Demo() // Crea los objetos ItemTracker::init(); - scoreboard_ = std::make_shared(&board_); - room_ = std::make_shared(resource_->getRoom(current_room_), &board_.items, false); + scoreboard_ = std::make_shared(board_); + room_ = std::make_shared(resource_->getRoom(current_room_), board_); text_ = resource_->getText("smb2"); // Inicializa el resto de variables counter_ = 0; room_time_ = 400; ticks_ = 0; - board_.lives = 9; - board_.items = 0; - board_.rooms = 1; - board_.jail_is_open = false; - board_.music = true; + board_->lives = 9; + board_->items = 0; + board_->rooms = 1; + board_->jail_is_open = false; + board_->music = true; setScoreBoardColor(); options.section.section = Section::DEMO; @@ -188,7 +189,7 @@ bool Demo::changeRoom(std::string file) if (asset_->get(file) != "") { // Crea un objeto habitación a partir del fichero - room_ = std::make_shared(resource_->getRoom(file), &board_.items, false); + room_ = std::make_shared(resource_->getRoom(file), board_); // Pone el color del marcador en función del color del borde de la habitación setScoreBoardColor(); @@ -228,9 +229,9 @@ void Demo::setScoreBoardColor() // Si el color es negro lo cambia a blanco const Color black_color = stringToColor(options.video.palette, "black"); - board_.color = colorAreEqual(color, black_color) ? stringToColor(options.video.palette, "white") : color; + board_->color = colorAreEqual(color, black_color) ? stringToColor(options.video.palette, "white") : color; // Si el color es negro brillante lo cambia a blanco const Color bright_blac_color = stringToColor(options.video.palette, "bright_black"); - board_.color = colorAreEqual(color, bright_blac_color) ? stringToColor(options.video.palette, "white") : color; + board_->color = colorAreEqual(color, bright_blac_color) ? stringToColor(options.video.palette, "white") : color; } \ No newline at end of file diff --git a/source/demo.h b/source/demo.h index dd41983..b30a211 100644 --- a/source/demo.h +++ b/source/demo.h @@ -30,13 +30,13 @@ private: std::shared_ptr scoreboard_; // Objeto encargado de gestionar el marcador // Variables - Uint32 ticks_; // Contador de ticks para ajustar la velocidad del programa - std::string current_room_; // Fichero de la habitación actual - ScoreboardData board_; // Estructura con los datos del marcador - int counter_; // Contador para el modo demo - int room_time_; // Tiempo que se muestra cada habitacion - int room_index_; // Indice para el vector de habitaciones - std::vector rooms_; // Listado con los mapas de la demo + Uint32 ticks_; // Contador de ticks para ajustar la velocidad del programa + std::string current_room_; // Fichero de la habitación actual + std::shared_ptr board_; // Estructura con los datos del marcador + int counter_; // Contador para el modo demo + int room_time_; // Tiempo que se muestra cada habitacion + int room_index_; // Indice para el vector de habitaciones + std::vector rooms_; // Listado con los mapas de la demo // Actualiza el juego, las variables, comprueba la entrada, etc. void update(); diff --git a/source/ending2.cpp b/source/ending2.cpp index b6bb300..69a440b 100644 --- a/source/ending2.cpp +++ b/source/ending2.cpp @@ -318,7 +318,7 @@ void Ending2::loadSprites() // Carga los sprites for (auto sl : sprite_list_) { - sprites_.emplace_back(std::make_shared(resource_->getTexture(sl + ".png"), resource_->getAnimation(sl + ".ani"))); + sprites_.emplace_back(std::make_shared(resource_->getTexture(sl + ".png"), resource_->getAnimations(sl + ".ani"))); sprite_max_width_ = std::max(sprites_.back()->getWidth(), sprite_max_width_); sprite_max_height_ = std::max(sprites_.back()->getHeight(), sprite_max_height_); } diff --git a/source/enemy.cpp b/source/enemy.cpp index c7aa052..0eead01 100644 --- a/source/enemy.cpp +++ b/source/enemy.cpp @@ -1,16 +1,16 @@ #include "enemy.h" -#include // for SDL_RendererFlip, SDL_FLIP_NONE, SDL_FL... -#include // for rand -#include "animated_sprite.h" // for AnimatedSprite -#include "options.h" // for Options, OptionsVideo, options -#include "resource.h" // for Resource -#include "texture.h" // for Texture +#include // for SDL_RendererFlip, SDL_FLIP_NONE, SDL_FL... +#include // for rand +#include "animated_sprite.h" // for AnimatedSprite +#include "options.h" // for Options, OptionsVideo, options +#include "resource.h" // for Resource +#include "texture.h" // for Texture // Constructor Enemy::Enemy(EnemyData enemy) { // Crea objetos - sprite_ = std::make_shared(Resource::get()->getTexture(enemy.texture_path), Resource::get()->getAnimation(enemy.animation_path)); + sprite_ = std::make_shared(Resource::get()->getTexture(enemy.texture_path), Resource::get()->getAnimations(enemy.animation_path)); // Obten el resto de valores x1_ = enemy.x1; diff --git a/source/game.cpp b/source/game.cpp index d78b175..186db11 100644 --- a/source/game.cpp +++ b/source/game.cpp @@ -36,32 +36,33 @@ Game::Game() cheevos_(Cheevos::get()) { // Inicia algunas variables - board_.ini_clock = SDL_GetTicks(); + board_ = std::make_shared(); + board_->ini_clock = SDL_GetTicks(); #ifdef DEBUG current_room_ = "03.room"; - const int x = 25; - const int y = 13; - spawn_point_ = PlayerSpawn(x * 8, y * 8, 0, 0, 0, PlayerState::STANDING, SDL_FLIP_HORIZONTAL); + constexpr int X = 25; + constexpr int Y = 13; + spawn_point_ = PlayerSpawn(X * 8, Y * 8, 0, 0, 0, PlayerState::STANDING, SDL_FLIP_HORIZONTAL); debug_->setEnabled(false); #else current_room_ = "03.room"; - const int x = 25; - const int y = 13; - spawn_point_ = PlayerSpawn(x * 8, y * 8, 0, 0, 0, PlayerState::STANDING, SDL_FLIP_HORIZONTAL); + constexpr int X = 25; + constexpr int Y = 13; + spawn_point_ = PlayerSpawn(X * 8, Y * 8, 0, 0, 0, PlayerState::STANDING, SDL_FLIP_HORIZONTAL); #endif // Crea los objetos ItemTracker::init(); - scoreboard_ = std::make_shared(&board_); + scoreboard_ = std::make_shared(board_); room_tracker_ = std::make_shared(); - room_ = std::make_shared(resource_->getRoom(current_room_), &board_.items, false); - const std::string playerPNG = options.cheats.alternate_skin == Cheat::CheatState::ENABLED ? "player2.png" : "player.png"; - const std::string playerANI = options.cheats.alternate_skin == Cheat::CheatState::ENABLED ? "player2.ani" : "player.ani"; - const PlayerData player(spawn_point_, playerPNG, playerANI, room_); + room_ = std::make_shared(resource_->getRoom(current_room_), board_); + std::string player_texture = options.cheats.alternate_skin == Cheat::CheatState::ENABLED ? "player2.png" : "player.png"; + std::string player_animations = options.cheats.alternate_skin == Cheat::CheatState::ENABLED ? "player2.ani" : "player.ani"; + const PlayerData player(spawn_point_, player_texture, player_animations, room_); player_ = std::make_shared(player); text_ = resource_->getText("smb2"); music_ = resource_->getMusic("game.ogg"); - death_sound_ = JA_LoadSound(asset_->get("death.wav").c_str()); + death_sound_ = resource_->getSound("death.wav"); stats_ = std::make_shared(asset_->get("stats.csv"), asset_->get("stats_buffer.csv")); // Crea la textura para poner el nombre de la habitación @@ -85,14 +86,14 @@ Game::Game() // Inicializa el resto de variables ticks_ = 0; - board_.lives = 9; + board_->lives = 9; #ifdef DEBUG - board_.lives = 9; + board_->lives = 9; #endif - board_.items = 0; - board_.rooms = 1; - board_.music = true; - board_.jail_is_open = options.cheats.jail_is_open == Cheat::CheatState::ENABLED; + board_->items = 0; + board_->rooms = 1; + board_->music = true; + board_->jail_is_open = options.cheats.jail_is_open == Cheat::CheatState::ENABLED; setScoreBoardColor(); room_tracker_->addRoom(current_room_); paused_ = false; @@ -129,8 +130,8 @@ void Game::checkEvents() case SDL_SCANCODE_G: debug_->switchEnabled(); options.cheats.invincible = static_cast(debug_->getEnabled()); - board_.music = !debug_->getEnabled(); - board_.music ? JA_ResumeMusic() : JA_PauseMusic(); + board_->music = !debug_->getEnabled(); + board_->music ? JA_ResumeMusic() : JA_PauseMusic(); break; case SDL_SCANCODE_R: @@ -181,8 +182,8 @@ void Game::checkInput() { if (input_->checkInput(input_toggle_music, REPEAT_FALSE)) { - board_.music = !board_.music; - board_.music ? JA_ResumeMusic() : JA_PauseMusic(); + board_->music = !board_->music; + board_->music ? JA_ResumeMusic() : JA_PauseMusic(); } else if (input_->checkInput(input_pause, REPEAT_FALSE)) @@ -197,7 +198,7 @@ void Game::checkInput() void Game::run() { JA_PlayMusic(music_); - if (!board_.music) + if (!board_->music) { JA_PauseMusic(); } @@ -335,7 +336,7 @@ bool Game::changeRoom(std::string file) if (asset_->get(file) != "") { // Crea un objeto habitación nuevo a partir del fichero - room_ = std::make_shared(resource_->getRoom(file), &board_.items, board_.jail_is_open); + room_ = std::make_shared(resource_->getRoom(file), board_); // Pone el nombre de la habitación en la textura fillRoomNameTexture(); @@ -346,8 +347,8 @@ bool Game::changeRoom(std::string file) if (room_tracker_->addRoom(file)) { // Incrementa el contador de habitaciones visitadas - board_.rooms++; - options.stats.rooms = board_.rooms; + board_->rooms++; + options.stats.rooms = board_->rooms; // Actualiza las estadisticas stats_->addVisit(room_->getName()); @@ -406,7 +407,7 @@ void Game::checkIfPlayerIsAlive() // Comprueba si ha terminado la partida void Game::checkGameOver() { - if (board_.lives < 0 && black_screen_counter_ > 17) + if (board_->lives < 0 && black_screen_counter_ > 17) { options.section.section = Section::GAME_OVER; } @@ -423,7 +424,7 @@ void Game::killPlayer() // Resta una vida al jugador if (options.cheats.infinite_lives == Cheat::CheatState::DISABLED) { - --board_.lives; + --board_->lives; } // Actualiza las estadisticas @@ -439,10 +440,10 @@ void Game::killPlayer() setBlackScreen(); // Crea la nueva habitación y el nuevo jugador - room_ = std::make_shared(resource_->getRoom(current_room_), &board_.items, board_.jail_is_open); - const std::string playerPNG = options.cheats.alternate_skin == Cheat::CheatState::ENABLED ? "player2.png" : "player.png"; - const std::string playerANI = options.cheats.alternate_skin == Cheat::CheatState::ENABLED ? "player2.ani" : "player.ani"; - const PlayerData player(spawn_point_, playerPNG, playerANI, room_); + room_ = std::make_shared(resource_->getRoom(current_room_), board_); + std::string player_texture = options.cheats.alternate_skin == Cheat::CheatState::ENABLED ? "player2.png" : "player.png"; + std::string player_animations = options.cheats.alternate_skin == Cheat::CheatState::ENABLED ? "player2.ani" : "player.ani"; + const PlayerData player(spawn_point_, player_texture, player_animations, room_); player_ = std::make_shared(player); // Pone los objetos en pausa mientras esta la habitación en negro @@ -507,19 +508,19 @@ void Game::setScoreBoardColor() const bool isBrightBlack = colorAreEqual(colorBorder, stringToColor(options.video.palette, "bright_black")); // Si el color del borde es negro o negro brillante cambia el texto del marcador a blanco - board_.color = isBlack || isBrightBlack ? stringToColor(options.video.palette, "white") : colorBorder; + board_->color = isBlack || isBrightBlack ? stringToColor(options.video.palette, "white") : colorBorder; } // 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 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 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) if (haveTheItems) { - board_.jail_is_open = true; + board_->jail_is_open = true; } if (haveTheItems && isOnTheRoom && isOnTheDoor) @@ -580,7 +581,7 @@ void Game::switchPause() // Da vidas al jugador cuando está en la Jail void Game::checkRestoringJail() { - if (room_->getName() != "THE JAIL" || board_.lives == 9) + if (room_->getName() != "THE JAIL" || board_->lives == 9) { return; } @@ -596,11 +597,11 @@ void Game::checkRestoringJail() if (counter == 100) { counter = 0; - board_.lives++; + board_->lives++; JA_PlaySound(death_sound_); // Invalida el logro de completar el juego sin entrar a la jail - const bool haveTheItems = board_.items >= int(total_items_ * 0.9f); + const bool haveTheItems = board_->items >= int(total_items_ * 0.9f); if (!haveTheItems) { cheevos_->invalidate(9); @@ -643,42 +644,42 @@ void Game::fillRoomNameTexture() void Game::checkSomeCheevos() { // Logros sobre la cantidad de items - if (board_.items == total_items_) + if (board_->items == total_items_) { cheevos_->unlock(4); cheevos_->unlock(3); cheevos_->unlock(2); cheevos_->unlock(1); } - else if (board_.items >= total_items_ * 0.75f) + else if (board_->items >= total_items_ * 0.75f) { cheevos_->unlock(3); cheevos_->unlock(2); cheevos_->unlock(1); } - else if (board_.items >= total_items_ * 0.5f) + else if (board_->items >= total_items_ * 0.5f) { cheevos_->unlock(2); cheevos_->unlock(1); } - else if (board_.items >= total_items_ * 0.25f) + else if (board_->items >= total_items_ * 0.25f) { cheevos_->unlock(1); } // Logros sobre las habitaciones visitadas - if (board_.rooms >= 60) + if (board_->rooms >= 60) { cheevos_->unlock(7); cheevos_->unlock(6); cheevos_->unlock(5); } - else if (board_.rooms >= 40) + else if (board_->rooms >= 40) { cheevos_->unlock(6); cheevos_->unlock(5); } - else if (board_.rooms >= 20) + else if (board_->rooms >= 20) { cheevos_->unlock(5); } @@ -694,7 +695,7 @@ void Game::checkEndGameCheevos() cheevos_->unlock(9); // "Complete the game with all items" - if (board_.items == total_items_) + if (board_->items == total_items_) { cheevos_->unlock(10); } diff --git a/source/game.h b/source/game.h index 52ef70c..1d113cb 100644 --- a/source/game.h +++ b/source/game.h @@ -44,17 +44,17 @@ private: SDL_Texture *room_name_texture_; // Textura para escribir el nombre de la habitación // Variables - JA_Music_t *music_; // Musica que suena durante el juego - Uint32 ticks_; // Contador de ticks para ajustar la velocidad del programa - std::string current_room_; // Fichero de la habitación actual - PlayerSpawn spawn_point_; // Lugar de la habitación donde aparece el jugador - JA_Sound_t *death_sound_; // Sonido a reproducir cuando muere el jugador - ScoreboardData board_; // Estructura con los datos del marcador - bool paused_; // Indica si el juego se encuentra en pausa - bool black_screen_; // Indica si la pantalla está en negro. Se utiliza para la muerte del jugador - int black_screen_counter_; // Contador para temporizar la pantalla en negro - int total_items_; // Cantidad total de items que hay en el mapeado del juego - SDL_Rect room_name_rect_; // Rectangulo donde pintar la textura con el nombre de la habitación + JA_Music_t *music_; // Musica que suena durante el juego + Uint32 ticks_; // Contador de ticks para ajustar la velocidad del programa + std::string current_room_; // Fichero de la habitación actual + PlayerSpawn spawn_point_; // Lugar de la habitación donde aparece el jugador + JA_Sound_t *death_sound_; // Sonido a reproducir cuando muere el jugador + std::shared_ptr board_; // Estructura con los datos del marcador + bool paused_; // Indica si el juego se encuentra en pausa + bool black_screen_; // Indica si la pantalla está en negro. Se utiliza para la muerte del jugador + int black_screen_counter_; // Contador para temporizar la pantalla en negro + int total_items_; // Cantidad total de items que hay en el mapeado del juego + SDL_Rect room_name_rect_; // Rectangulo donde pintar la textura con el nombre de la habitación // Actualiza el juego, las variables, comprueba la entrada, etc. void update(); diff --git a/source/game_over.cpp b/source/game_over.cpp index dca5e85..bcfe861 100644 --- a/source/game_over.cpp +++ b/source/game_over.cpp @@ -26,8 +26,8 @@ GameOver::GameOver() { // Reserva memoria para los punteros a objetos text_ = resource_->getText("smb2"); - player_sprite_ = std::make_shared(resource_->getTexture("player_game_over.png"), resource_->getAnimation("player_game_over.ani")); - tv_sprite_ = std::make_shared(resource_->getTexture("tv.png"), resource_->getAnimation("tv.ani")); + player_sprite_ = std::make_shared(resource_->getTexture("player_game_over.png"), resource_->getAnimations("player_game_over.ani")); + tv_sprite_ = std::make_shared(resource_->getTexture("tv.png"), resource_->getAnimations("tv.ani")); music_ = resource_->getMusic("game_over.ogg"); // Inicializa variables diff --git a/source/player.cpp b/source/player.cpp index 25be12f..e523e71 100644 --- a/source/player.cpp +++ b/source/player.cpp @@ -24,7 +24,7 @@ Player::Player(PlayerData player) room_(player.room) { // Inicializa algunas variables - initSprite(player.texture, player.animation); + initSprite(player.texture_path, player.animations_path); setColor(); applySpawnValues(player.spawn); placeSprite(); @@ -48,38 +48,11 @@ Player::Player(PlayerData player) // Pinta el jugador en pantalla void Player::render() { + sprite_->getTexture()->setColor(color_.r, color_.g, color_.b); sprite_->render(); #ifdef DEBUG - if (debug_->getEnabled()) - { - // Pinta los underfeet - SDL_SetRenderDrawColor(renderer_, 255, 0, 255, 255); - SDL_RenderDrawPoint(renderer_, under_feet_[0].x, under_feet_[0].y); - SDL_RenderDrawPoint(renderer_, under_feet_[1].x, under_feet_[1].y); - - // Pinta rectangulo del jugador - SDL_SetRenderDrawColor(renderer_, debug_color_.r, debug_color_.g, debug_color_.b, 192); - SDL_Rect rect = getRect(); - SDL_RenderFillRect(renderer_, &rect); - SDL_SetRenderDrawColor(renderer_, 0, 255, 255, 255); - SDL_RenderDrawRect(renderer_, &rect); - - // Pinta el rectangulo de movimiento - SDL_SetRenderDrawColor(renderer_, 255, 0, 0, 255); - if (vx_ != 0.0f) - { - SDL_RenderFillRect(renderer_, &debug_rect_x_); - } - if (vy_ != 0.0f) - { - SDL_RenderFillRect(renderer_, &debug_rect_y_); - } - - // Pinta el punto de debug - SDL_SetRenderDrawColor(renderer_, rand() % 256, rand() % 256, rand() % 256, 255); - SDL_RenderDrawPoint(renderer_, debug_point_.x, debug_point_.y); - } + renderDebugInfo(); #endif } @@ -122,10 +95,12 @@ void Player::checkInput() } else - { // No se pulsa ninguna dirección + { + // No se pulsa ninguna dirección vx_ = 0.0f; if (isOnAutoSurface()) - { // Si deja de moverse sobre una superficie se engancha + { + // Si deja de moverse sobre una superficie se engancha auto_movement_ = true; } } @@ -679,8 +654,6 @@ void Player::setColor() { color_ = stringToColor(options.video.palette, "white"); } - - sprite_->getTexture()->setColor(color_.r, color_.g, color_.b); } // Actualiza los puntos de colisión @@ -756,11 +729,49 @@ void Player::applySpawnValues(const PlayerSpawn &spawn) } // Inicializa el sprite del jugador -void Player::initSprite(const std::string &png, const std::string &animation) +void Player::initSprite(const std::string &texture_path, const std::string &animations_path) { - sprite_ = std::make_shared(png, animation); + auto texture = Resource::get()->getTexture(texture_path); + auto animations = Resource::get()->getAnimations(animations_path); + + sprite_ = std::make_shared(texture, animations); sprite_->setWidth(WIDTH_); sprite_->setHeight(HEIGHT_); sprite_->setCurrentAnimation("walk"); - // sprite_->update(); -} \ No newline at end of file +} + +#ifdef DEBUG +// Pinta la información de debug del jugador +void Player::renderDebugInfo() +{ + if (debug_->getEnabled()) + { + // Pinta los underfeet + SDL_SetRenderDrawColor(renderer_, 255, 0, 255, 255); + SDL_RenderDrawPoint(renderer_, under_feet_[0].x, under_feet_[0].y); + SDL_RenderDrawPoint(renderer_, under_feet_[1].x, under_feet_[1].y); + + // Pinta rectangulo del jugador + SDL_SetRenderDrawColor(renderer_, debug_color_.r, debug_color_.g, debug_color_.b, 192); + SDL_Rect rect = getRect(); + SDL_RenderFillRect(renderer_, &rect); + SDL_SetRenderDrawColor(renderer_, 0, 255, 255, 255); + SDL_RenderDrawRect(renderer_, &rect); + + // Pinta el rectangulo de movimiento + SDL_SetRenderDrawColor(renderer_, 255, 0, 0, 255); + if (vx_ != 0.0f) + { + SDL_RenderFillRect(renderer_, &debug_rect_x_); + } + if (vy_ != 0.0f) + { + SDL_RenderFillRect(renderer_, &debug_rect_y_); + } + + // Pinta el punto de debug + SDL_SetRenderDrawColor(renderer_, rand() % 256, rand() % 256, rand() % 256, 255); + SDL_RenderDrawPoint(renderer_, debug_point_.x, debug_point_.y); + } +} +#endif \ No newline at end of file diff --git a/source/player.h b/source/player.h index 821e261..2ec4d79 100644 --- a/source/player.h +++ b/source/player.h @@ -44,13 +44,13 @@ struct PlayerSpawn struct PlayerData { PlayerSpawn spawn; - std::shared_ptr< texture; - std::string animation; + std::string texture_path; + std::string animations_path; std::shared_ptr room; // Constructor - PlayerData(PlayerSpawn spawn, std::string png, std::string animation, std::shared_ptr room) - : spawn(spawn), texture(png), animation(animation), room(room) {} + PlayerData(PlayerSpawn spawn, std::string texture_path, std::string animations_path, std::shared_ptr room) + : spawn(spawn), texture_path(texture_path), animations_path(animations_path), room(room) {} }; class Player @@ -159,7 +159,12 @@ public: void applySpawnValues(const PlayerSpawn &spawn); // Inicializa el sprite del jugador - void initSprite(const std::string &png, const std::string &animation); + void initSprite(const std::string &texture_path, const std::string &animations_path); + +#ifdef DEBUG + // Pinta la información de debug del jugador + void renderDebugInfo(); +#endif public: // Constructor diff --git a/source/resource.cpp b/source/resource.cpp index 2ad57eb..f8eb0ca 100644 --- a/source/resource.cpp +++ b/source/resource.cpp @@ -151,7 +151,7 @@ std::shared_ptr Resource::getText(const std::string &name) } // Obtiene la animación a partir de un nombre -AnimationsFileBuffer &Resource::getAnimation(const std::string &name) +Animations &Resource::getAnimations(const std::string &name) { auto it = std::find_if(animations_.begin(), animations_.end(), [&name](const auto &a) { return a.name == name; }); diff --git a/source/resource.h b/source/resource.h index 3b847d1..2e695c9 100644 --- a/source/resource.h +++ b/source/resource.h @@ -68,11 +68,11 @@ struct ResourceText // Estructura para almacenar ficheros animaciones y su nombre struct ResourceAnimation { - std::string name; // Nombre del fichero - AnimationsFileBuffer animation; // Objeto con las animaciones + std::string name; // Nombre del fichero + Animations animation; // Objeto con las animaciones // Constructor - ResourceAnimation(const std::string &name, const AnimationsFileBuffer &animation) + ResourceAnimation(const std::string &name, const Animations &animation) : name(name), animation(animation) {} }; @@ -232,7 +232,7 @@ public: std::shared_ptr getText(const std::string &name); // Obtiene la animación a partir de un nombre - AnimationsFileBuffer &getAnimation(const std::string &name); + Animations &getAnimations(const std::string &name); // Obtiene el mapa de tiles a partir de un nombre std::vector &getTileMap(const std::string &name); diff --git a/source/room.cpp b/source/room.cpp index 578e150..b58d34c 100644 --- a/source/room.cpp +++ b/source/room.cpp @@ -398,12 +398,12 @@ bool setItem(ItemData *item, const std::string &key, const std::string &value) } // Constructor -Room::Room(std::shared_ptr room, int *itemsPicked, bool jail_is_open) +Room::Room(std::shared_ptr room, std::shared_ptr data) : screen_(Screen::get()), renderer_(Screen::get()->getRenderer()), asset_(Asset::get()), debug_(Debug::get()), - items_picked_(itemsPicked) + data_(data) { number_ = room->number; name_ = room->name; @@ -420,7 +420,6 @@ Room::Room(std::shared_ptr room, int *itemsPicked, bool jail_is_open) auto_surface_direction_ = room->auto_surface_direction; tile_map_ = Resource::get()->getTileMap(room->tile_map_file); texture_ = (options.video.palette == Palette::ZXSPECTRUM) ? Resource::get()->getTexture(room->tile_set_file) : Resource::get()->getTexture(room->tile_set_file); - jail_is_open_ = jail_is_open; // Inicializa variables tile_set_width_ = texture_->getWidth() / TILE_SIZE_; @@ -447,10 +446,10 @@ Room::Room(std::shared_ptr room, int *itemsPicked, bool jail_is_open) } // Carga los sonidos - item_sound_ = JA_LoadSound(asset_->get("item.wav").c_str()); + item_sound_ = Resource::get()->getSound("item.wav"); // Abre la jail para poder entrar - if (jail_is_open) + if (data_->jail_is_open) { openTheJail(); } @@ -802,8 +801,8 @@ bool Room::itemCollision(SDL_Rect &rect) ItemTracker::get()->addItem(name_, items_[i]->getPos()); items_.erase(items_.begin() + i); JA_PlaySound(item_sound_); - *items_picked_ = *items_picked_ + 1; - options.stats.items = *items_picked_; + data_->items++; + options.stats.items = data_->items; return true; } } diff --git a/source/room.h b/source/room.h index fe9a5a8..e751745 100644 --- a/source/room.h +++ b/source/room.h @@ -8,8 +8,9 @@ #include "enemy.h" // for EnemyData #include "item.h" // for item_t #include "utils.h" // for Color -class Asset; // lines 12-12 -class Debug; // lines 13-13 +#include "scoreboard.h" +class Asset; // lines 12-12 +class Debug; // lines 13-13 class ItemTracker; class Screen; // lines 14-14 class Sprite; // lines 15-15 @@ -35,22 +36,22 @@ struct aTile_t struct RoomData { - std::string number; // Numero de la habitación - std::string name; // Nombre de la habitación - std::string bg_color; // Color de fondo de la habitación - std::string border_color; // Color del borde de la pantalla - std::string item_color1; // Color 1 para los items de la habitación - std::string item_color2; // Color 2 para los items de la habitación - std::string room_top; // Identificador de la habitación que se encuentra arriba - std::string room_bottom; // Identificador de la habitación que se encuentra abajp - std::string room_left; // Identificador de la habitación que se encuentra a la izquierda - std::string room_right; // Identificador de la habitación que se encuentra a la derecha - std::string tile_set_file; // Imagen con los graficos para la habitación - std::string tile_map_file; // Fichero con el mapa de indices de tile - std::vector tile_map; // Indice de los tiles a dibujar en la habitación - int auto_surface_direction; // Sentido en el que arrastran las superficies automáticas de la habitación - std::vector enemies; // Listado con los enemigos de la habitación - std::vector items; // Listado con los items que hay en la habitación + std::string number; // Numero de la habitación + std::string name; // Nombre de la habitación + std::string bg_color; // Color de fondo de la habitación + std::string border_color; // Color del borde de la pantalla + std::string item_color1; // Color 1 para los items de la habitación + std::string item_color2; // Color 2 para los items de la habitación + std::string room_top; // Identificador de la habitación que se encuentra arriba + std::string room_bottom; // Identificador de la habitación que se encuentra abajp + std::string room_left; // Identificador de la habitación que se encuentra a la izquierda + std::string room_right; // Identificador de la habitación que se encuentra a la derecha + std::string tile_set_file; // Imagen con los graficos para la habitación + std::string tile_map_file; // Fichero con el mapa de indices de tile + std::vector tile_map; // Indice de los tiles a dibujar en la habitación + int auto_surface_direction; // Sentido en el que arrastran las superficies automáticas de la habitación + std::vector enemies; // Listado con los enemigos de la habitación + std::vector items; // Listado con los items que hay en la habitación }; // Carga las variables desde un fichero de mapa @@ -85,7 +86,7 @@ private: std::vector> items_; // Listado con los items que hay en la habitación std::shared_ptr texture_; // Textura con los graficos de la habitación SDL_Texture *map_texture_; // Textura para dibujar el mapa de la habitación - int *items_picked_; // Puntero a la cantidad de items recogidos que lleva el juego + std::shared_ptr data_; // Puntero a los datos del marcador // Variables std::string number_; // Numero de la habitación @@ -114,7 +115,6 @@ private: std::vector animated_tiles_; // Vector con los indices de tiles animados std::vector auto_surfaces_; // Lista con las superficies automaticas de la habitación int tile_set_width_; // Ancho del tileset en tiles - bool jail_is_open_; // Indica si hay acceso a la Jail // Pinta el mapa de la habitación en la textura void fillMapTexture(); @@ -157,7 +157,7 @@ private: public: // Constructor - Room(std::shared_ptr room, int *itemsPicked, bool jailEnabled); + Room(std::shared_ptr room, std::shared_ptr data); // Destructor ~Room(); diff --git a/source/scoreboard.cpp b/source/scoreboard.cpp index 9233a00..f07cc72 100644 --- a/source/scoreboard.cpp +++ b/source/scoreboard.cpp @@ -11,17 +11,17 @@ #include "texture.h" // for Texture // Constructor -Scoreboard::Scoreboard(ScoreboardData *board) +Scoreboard::Scoreboard(std::shared_ptr data) : renderer_(Screen::get()->getRenderer()), resource_(Resource::get()), asset_(Asset::get()), - board_(board) + data_(data) { // Reserva memoria para los objetos item_texture_ = resource_->getTexture("items.png"); - const std::string playerPNG = options.cheats.alternate_skin == Cheat::CheatState::ENABLED ? "player2.png" : "player.png"; - const std::string playerANI = options.cheats.alternate_skin == Cheat::CheatState::ENABLED ? "player2.ani" : "player.ani"; - player_sprite_ = std::make_shared(resource_->getTexture(playerPNG), resource_->getAnimation(playerANI)); + auto player_texture = resource_->getTexture(options.cheats.alternate_skin == Cheat::CheatState::ENABLED ? "player2.png" : "player.png"); + auto player_animations = resource_->getAnimations(options.cheats.alternate_skin == Cheat::CheatState::ENABLED ? "player2.ani" : "player.ani"); + player_sprite_ = std::make_shared(player_texture, player_animations); player_sprite_->setCurrentAnimation("walk_menu"); text_ = resource_->getText("smb2"); @@ -58,7 +58,7 @@ void Scoreboard::render() const int frame = desp % 4; player_sprite_->setCurrentAnimationFrame(frame); player_sprite_->setPosY(line2); - for (int i = 0; i < board_->lives; ++i) + for (int i = 0; i < data_->lives; ++i) { player_sprite_->setPosX(8 + (16 * i) + desp); const int index = i % color_.size(); @@ -67,9 +67,9 @@ void Scoreboard::render() } // Muestra si suena la música - if (board_->music) + if (data_->music) { - const Color c = board_->color; + const Color c = data_->color; SDL_Rect clip = {0, 8, 8, 8}; item_texture_->setColor(c.r, c.g, c.b); item_texture_->render(20 * BLOCK, line2, &clip); @@ -77,13 +77,13 @@ void Scoreboard::render() // Escribe los textos const std::string timeTxt = std::to_string((clock_.minutes % 100) / 10) + std::to_string(clock_.minutes % 10) + clock_.separator + std::to_string((clock_.seconds % 60) / 10) + std::to_string(clock_.seconds % 10); - const std::string itemsTxt = std::to_string(board_->items / 100) + std::to_string((board_->items % 100) / 10) + std::to_string(board_->items % 10); - this->text_->writeColored(BLOCK, line1, "Items collected ", board_->color); + const std::string itemsTxt = std::to_string(data_->items / 100) + std::to_string((data_->items % 100) / 10) + std::to_string(data_->items % 10); + this->text_->writeColored(BLOCK, line1, "Items collected ", data_->color); this->text_->writeColored(17 * BLOCK, line1, itemsTxt, items_color_); - this->text_->writeColored(20 * BLOCK, line1, " Time ", board_->color); + this->text_->writeColored(20 * BLOCK, line1, " Time ", data_->color); this->text_->writeColored(26 * BLOCK, line1, timeTxt, stringToColor(options.video.palette, "white")); - const std::string roomsTxt = std::to_string(board_->rooms / 100) + std::to_string((board_->rooms % 100) / 10) + std::to_string(board_->rooms % 10); + const std::string roomsTxt = std::to_string(data_->rooms / 100) + std::to_string((data_->rooms % 100) / 10) + std::to_string(data_->rooms % 10); this->text_->writeColored(22 * BLOCK, line2, "Rooms", stringToColor(options.video.palette, "white")); this->text_->writeColored(28 * BLOCK, line2, roomsTxt, stringToColor(options.video.palette, "white")); } @@ -107,7 +107,7 @@ void Scoreboard::update() // Obtiene el tiempo transcurrido de partida Scoreboard::ClockData Scoreboard::getTime() { - const Uint32 timeElapsed = SDL_GetTicks() - board_->ini_clock - paused_time_elapsed_; + const Uint32 timeElapsed = SDL_GetTicks() - data_->ini_clock - paused_time_elapsed_; ClockData time; time.hours = timeElapsed / 3600000; @@ -156,7 +156,7 @@ void Scoreboard::resume() // Actualiza el color de la cantidad de items recogidos void Scoreboard::updateItemsColor() { - if (!board_->jail_is_open) + if (!data_->jail_is_open) { return; } diff --git a/source/scoreboard.h b/source/scoreboard.h index 6639327..593b147 100644 --- a/source/scoreboard.h +++ b/source/scoreboard.h @@ -21,6 +21,10 @@ struct ScoreboardData Color color; // Color para escribir el texto del marcador Uint32 ini_clock; // Tiempo inicial para calcular el tiempo transcurrido bool jail_is_open; // Indica si se puede entrar a la Jail + + // Constructor + ScoreboardData() + : items(0), lives(3), rooms(0), music(true), color({0, 0, 0}), ini_clock(0), jail_is_open(false) {} }; class Scoreboard @@ -41,7 +45,7 @@ private: std::shared_ptr text_; // Objeto para escribir texto std::shared_ptr player_sprite_; // Sprite para mostrar las vidas en el marcador std::shared_ptr item_texture_; // Textura con los graficos para las vidas - std::shared_ptr board_; // Contiene las variables a mostrar en el marcador + std::shared_ptr data_; // Contiene las variables a mostrar en el marcador // Variables std::vector color_; // Vector con los colores del objeto @@ -61,7 +65,7 @@ private: public: // Constructor - Scoreboard(ScoreboardData *board); + Scoreboard(std::shared_ptr data); // Destructor ~Scoreboard() = default; diff --git a/source/texture.cpp b/source/texture.cpp index 77491bf..7168e93 100644 --- a/source/texture.cpp +++ b/source/texture.cpp @@ -52,7 +52,7 @@ Texture::Texture(SDL_Renderer *renderer, const std::string &path) Texture::~Texture() { unloadTexture(); - //unloadSurface(); + // unloadSurface(); palettes_.clear(); } diff --git a/source/texture.h b/source/texture.h index 8a69d46..95ad5cb 100644 --- a/source/texture.h +++ b/source/texture.h @@ -37,19 +37,19 @@ private: int current_palette_ = 0; // Indice de la paleta en uso // Crea una surface desde un fichero .gif - //std::shared_ptr loadSurface(const std::string &file_name); + // std::shared_ptr loadSurface(const std::string &file_name); // Vuelca la surface en la textura - //void flipSurface(); + // void flipSurface(); // Carga una paleta desde un fichero - //std::vector loadPaletteFromFile(const std::string &file_name); + // std::vector loadPaletteFromFile(const std::string &file_name); // Libera la memoria de la textura void unloadTexture(); // Desencadenar la superficie actual - //void unloadSurface(); + // void unloadSurface(); public: // Constructor @@ -93,13 +93,13 @@ public: SDL_Texture *getSDLTexture(); // Añade una paleta a la lista - //void addPaletteFromFile(const std::string &path); + // void addPaletteFromFile(const std::string &path); // Establece un color de la paleta - //void setPaletteColor(int palette, int index, Uint32 color); + // void setPaletteColor(int palette, int index, Uint32 color); // Cambia la paleta de la textura - //void setPalette(int palette); + // void setPalette(int palette); // Obtiene el renderizador SDL_Renderer *getRenderer();