From 85ab5ea03fcb1a3d3704d842141e938be2d04bc1 Mon Sep 17 00:00:00 2001 From: Sergio Valor Date: Wed, 26 Feb 2025 13:07:41 +0100 Subject: [PATCH] Singleton de ItemTracker Arreglos menors --- source/demo.cpp | 36 ++-- source/demo.h | 30 +-- source/director.cpp | 4 +- source/game.cpp | 12 +- source/game.h | 3 +- source/item_tracker.cpp | 49 ++--- source/item_tracker.h | 34 +++- source/resource.cpp | 4 +- source/resource.h | 8 +- source/room.cpp | 405 ++++++++++++++++++++-------------------- source/room.h | 145 +++++++------- source/scoreboard.cpp | 138 +++++++------- source/scoreboard.h | 40 ++-- 13 files changed, 466 insertions(+), 442 deletions(-) diff --git a/source/demo.cpp b/source/demo.cpp index 119b2a6..4c42b10 100644 --- a/source/demo.cpp +++ b/source/demo.cpp @@ -1,21 +1,21 @@ #include "demo.h" -#include // for SDL_PollEvent, SDL_Event -#include // for SDL_Rect -#include // for SDL_GetTicks -#include // for basic_ostream, operator<<, cout, endl -#include "asset.h" // for Asset -#include "debug.h" // for Debug -#include "defines.h" // for BLOCK, PLAY_AREA_WIDTH, GAMECANVAS_CENT... -#include "global_events.h" // for check -#include "global_inputs.h" // for check -#include "input.h" // for Input -#include "item_tracker.h" // for ItemTracker -#include "options.h" // for Options, options, OptionsVideo, Section... -#include "resource.h" // for Resource -#include "room.h" // for Room -#include "screen.h" // for Screen -#include "text.h" // for Text, TEXT_CENTER, TEXT_COLOR -#include "utils.h" // for Color, stringToColor, colorAreEqual +#include // for SDL_PollEvent, SDL_Event +#include // for SDL_Rect +#include // for SDL_GetTicks +#include // for basic_ostream, operator<<, cout, endl +#include "asset.h" // for Asset +#include "debug.h" // for Debug +#include "defines.h" // for BLOCK, PLAY_AREA_WIDTH, GAMECANVAS_CENT... +#include "global_events.h" // for check +#include "global_inputs.h" // for check +#include "input.h" // for Input +#include "item_tracker.h" // for ItemTracker +#include "options.h" // for Options, options, OptionsVideo, Section... +#include "resource.h" // for Resource +#include "room.h" // for Room +#include "screen.h" // for Screen +#include "text.h" // for Text, TEXT_CENTER, TEXT_COLOR +#include "utils.h" // for Color, stringToColor, colorAreEqual // Constructor Demo::Demo() @@ -27,7 +27,7 @@ Demo::Demo() debug(Debug::get()) { // Inicia algunas variables - board.iniClock = SDL_GetTicks(); + board.ini_clock = SDL_GetTicks(); rooms.push_back("04.room"); rooms.push_back("54.room"); rooms.push_back("20.room"); diff --git a/source/demo.h b/source/demo.h index ee393ce..d074b6a 100644 --- a/source/demo.h +++ b/source/demo.h @@ -1,19 +1,19 @@ #pragma once -#include // for SDL_Renderer -#include // for Uint32 -#include // for shared_ptr -#include // for string -#include // for vector -#include "scoreboard.h" // for board_t -class Asset; // lines 11-11 -class Debug; // lines 12-12 -class Input; // lines 13-13 -class ItemTracker; // lines 14-14 -class Resource; // lines 15-15 -class Room; // lines 16-16 -class Screen; // lines 17-17 -class Text; // lines 18-18 +#include // for SDL_Renderer +#include // for Uint32 +#include // for shared_ptr +#include // for string +#include // for vector +#include "scoreboard.h" // for board_t +class Asset; // lines 11-11 +class Debug; // lines 12-12 +class Input; // lines 13-13 +class ItemTracker; // lines 14-14 +class Resource; // lines 15-15 +class Room; // lines 16-16 +class Screen; // lines 17-17 +class Text; // lines 18-18 class Demo { @@ -34,7 +34,7 @@ private: Uint32 ticks; // Contador de ticks para ajustar la velocidad del programa Uint32 ticksSpeed; // Velocidad a la que se repiten los bucles del programa std::string currentRoom; // Fichero de la habitación actual - board_t board; // Estructura con los datos del marcador + ScoreboardData board; // Estructura con los datos del marcador int counter; // Contador para el modo demo int roomTime; // Tiempo que se muestra cada habitacion int roomIndex; // Indice para el vector de habitaciones diff --git a/source/director.cpp b/source/director.cpp index 7d21097..1db9697 100644 --- a/source/director.cpp +++ b/source/director.cpp @@ -83,7 +83,7 @@ Director::Director(int argc, const char *argv[]) Input::init(Asset::get()->get("gamecontrollerdb.txt")); initInput(); Debug::init(); - title_music_ = JA_LoadMusic(Asset::get()->get("title.ogg").c_str()); + title_music_ = Resource::get()->getMusic("title.ogg"); Cheevos::init(Asset::get()->get("cheevos.bin")); } @@ -101,8 +101,6 @@ Director::~Director() Resource::destroy(); Cheevos::destroy(); - JA_DeleteMusic(title_music_); - SDL_DestroyRenderer(renderer_); SDL_DestroyWindow(window_); SDL_Quit(); diff --git a/source/game.cpp b/source/game.cpp index 1d5e1d0..3ad36a0 100644 --- a/source/game.cpp +++ b/source/game.cpp @@ -36,7 +36,7 @@ Game::Game() cheevos_(Cheevos::get()) { // Inicia algunas variables - board_.iniClock = SDL_GetTicks(); + board_.ini_clock = SDL_GetTicks(); #ifdef DEBUG current_room_ = "03.room"; const int x = 25; @@ -51,10 +51,10 @@ Game::Game() #endif // Crea los objetos + ItemTracker::init(); scoreboard_ = std::make_shared(&board_); - item_tracker_ = std::make_shared(); room_tracker_ = std::make_shared(); - room_ = std::make_shared(resource_->getRoom(current_room_), item_tracker_, &board_.items, false); + 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 player_t player = {spawn_point_, playerPNG, playerANI, room_}; @@ -110,7 +110,7 @@ Game::Game() Game::~Game() { - // Libera la memoria de los objetos + ItemTracker::destroy(); SDL_DestroyTexture(room_name_texture_); } @@ -336,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), item_tracker_, &board_.items, board_.jail_is_open); + room_ = std::make_shared(resource_->getRoom(file), &board_.items, board_.jail_is_open); // Pone el nombre de la habitación en la textura fillRoomNameTexture(); @@ -440,7 +440,7 @@ void Game::killPlayer() setBlackScreen(); // Crea la nueva habitación y el nuevo jugador - room_ = std::make_shared(resource_->getRoom(current_room_), item_tracker_, &board_.items, board_.jail_is_open); + 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 player_t player = {spawn_point_, playerPNG, playerANI, room_}; diff --git a/source/game.h b/source/game.h index 7f4aa9a..7f9bfaa 100644 --- a/source/game.h +++ b/source/game.h @@ -37,7 +37,6 @@ private: Cheevos *cheevos_; // Objeto encargado de gestionar los logros del juego std::shared_ptr room_; // Objeto encargado de gestionar cada habitación del juego std::shared_ptr player_; // Objeto con el jugador - std::shared_ptr item_tracker_; // Lleva el control de los objetos recogidos std::shared_ptr room_tracker_; // Lleva el control de las habitaciones visitadas std::shared_ptr text_; // Objeto para los textos del juego std::shared_ptr scoreboard_; // Objeto encargado de gestionar el marcador @@ -51,7 +50,7 @@ private: std::string current_room_; // Fichero de la habitación actual playerSpawn_t spawn_point_; // Lugar de la habitación donde aparece el jugador JA_Sound_t *death_sound_; // Sonido a reproducir cuando muere el jugador - board_t board_; // Estructura con los datos del marcador + 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 diff --git a/source/item_tracker.cpp b/source/item_tracker.cpp index 073fa8d..66376c6 100644 --- a/source/item_tracker.cpp +++ b/source/item_tracker.cpp @@ -1,50 +1,57 @@ #include "item_tracker.h" -// Destructor -ItemTracker::~ItemTracker() +// [SINGLETON] +ItemTracker *ItemTracker::item_tracker_ = nullptr; + +// [SINGLETON] Crearemos el objeto con esta función estática +void ItemTracker::init() { - list.clear(); + ItemTracker::item_tracker_ = new ItemTracker(); +} + +// [SINGLETON] Destruiremos el objeto con esta función estática +void ItemTracker::destroy() +{ + delete ItemTracker::item_tracker_; +} + +// [SINGLETON] Con este método obtenemos el objeto y podemos trabajar con él +ItemTracker *ItemTracker::get() +{ + return ItemTracker::item_tracker_; } // Comprueba si el objeto ya ha sido cogido -bool ItemTracker::hasBeenPicked(std::string name, SDL_Point pos) +bool ItemTracker::hasBeenPicked(const std::string &name, SDL_Point pos) { - bool success = false; - // Primero busca si ya hay una entrada con ese nombre - const int index = findByName(name); - if (index != -1) + if (const int index = findByName(name); index != -1) { // Luego busca si existe ya una entrada con esa posición if (findByPos(index, pos) != -1) { - success = true; + return true; } } - return success; + return false; } // Añade el objeto a la lista de objetos cogidos -void ItemTracker::addItem(std::string name, SDL_Point pos) +void ItemTracker::addItem(const std::string &name, SDL_Point pos) { // Comprueba si el objeto no ha sido recogido con anterioridad if (!hasBeenPicked(name, pos)) { // Primero busca si ya hay una entrada con ese nombre - const int index = findByName(name); - if (index != -1) + if (const int index = findByName(name); index != -1) { - list[index].pos.push_back(pos); + list.at(index).pos.push_back(pos); } - // En caso contrario crea la entrada else { - item_tracker_t item; - item.name = name; - item.pos.push_back(pos); - list.push_back(item); + list.emplace_back(name, pos); } } } @@ -54,7 +61,7 @@ int ItemTracker::findByName(std::string name) { int i = 0; - for (auto l : list) + for (const auto &l : list) { if (l.name == name) { @@ -71,7 +78,7 @@ int ItemTracker::findByPos(int index, SDL_Point pos) { int i = 0; - for (auto l : list[index].pos) + for (const auto &l : list[index].pos) { if ((l.x == pos.x) && (l.y == pos.y)) { diff --git a/source/item_tracker.h b/source/item_tracker.h index 8d24da0..e84bac3 100644 --- a/source/item_tracker.h +++ b/source/item_tracker.h @@ -4,17 +4,27 @@ #include // Para string, basic_string #include // Para vector -struct item_tracker_t +struct ItemData { std::string name; // Nombre de la habitación donde se encuentra el objeto std::vector pos; // Lista de objetos cogidos de la habitación + + // Constructor + ItemData(const std::string& name, const SDL_Point& position) + : name(name) + { + pos.push_back(position); + } }; class ItemTracker { private: + // [SINGLETON] Objeto privado + static ItemTracker *item_tracker_; + // Variables - std::vector list; // Lista con todos los objetos recogidos + std::vector list; // Lista con todos los objetos recogidos // Busca una entrada en la lista por nombre int findByName(std::string name); @@ -22,13 +32,25 @@ private: // Busca una entrada en la lista por posición int findByPos(int index, SDL_Point pos); -public: + // Constructor + ItemTracker() = default; + // Destructor - ~ItemTracker(); + ~ItemTracker() = 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 ItemTracker *get(); // Comprueba si el objeto ya ha sido cogido - bool hasBeenPicked(std::string name, SDL_Point pos); + bool hasBeenPicked(const std::string &name, SDL_Point pos); // Añade el objeto a la lista de objetos cogidos - void addItem(std::string name, SDL_Point pos); + void addItem(const std::string &name, SDL_Point pos); }; \ No newline at end of file diff --git a/source/resource.cpp b/source/resource.cpp index c60a0b0..2ad57eb 100644 --- a/source/resource.cpp +++ b/source/resource.cpp @@ -181,7 +181,7 @@ std::vector &Resource::getTileMap(const std::string &name) } // Obtiene la habitación a partir de un nombre -std::shared_ptr Resource::getRoom(const std::string &name) +std::shared_ptr Resource::getRoom(const std::string &name) { auto it = std::find_if(rooms_.begin(), rooms_.end(), [&name](const auto &r) { return r.name == name; }); @@ -304,7 +304,7 @@ void Resource::loadRooms() for (const auto &l : list) { auto name = getFileName(l); - rooms_.emplace_back(ResourceRoom(name, std::make_shared(loadRoomFile(l)))); + rooms_.emplace_back(ResourceRoom(name, std::make_shared(loadRoomFile(l)))); printWithDots("Room : ", name, "[ LOADED ]"); updateLoadingProgress(); } diff --git a/source/resource.h b/source/resource.h index 8ab83d7..3b847d1 100644 --- a/source/resource.h +++ b/source/resource.h @@ -90,11 +90,11 @@ struct ResourceTileMap // Estructura para almacenar habitaciones y su nombre struct ResourceRoom { - std::string name; // Nombre de la habitación - std::shared_ptr room; // Habitación + std::string name; // Nombre de la habitación + std::shared_ptr room; // Habitación // Constructor - ResourceRoom(const std::string &name, std::shared_ptr room) + ResourceRoom(const std::string &name, std::shared_ptr room) : name(name), room(room) {} }; @@ -238,7 +238,7 @@ public: std::vector &getTileMap(const std::string &name); // Obtiene la habitación a partir de un nombre - std::shared_ptr getRoom(const std::string &name); + std::shared_ptr getRoom(const std::string &name); // Obtiene todas las habitaciones std::vector &getRooms(); diff --git a/source/room.cpp b/source/room.cpp index 7064450..f279184 100644 --- a/source/room.cpp +++ b/source/room.cpp @@ -69,12 +69,12 @@ std::vector loadRoomTileFile(std::string file_path, bool verbose) } // Carga las variables desde un fichero de mapa -room_t loadRoomFile(std::string file_path, bool verbose) +RoomData loadRoomFile(std::string file_path, bool verbose) { - room_t room; - room.itemColor1 = "yellow"; - room.itemColor2 = "magenta"; - room.autoSurfaceDirection = 1; + RoomData room; + room.item_color1 = "yellow"; + room.item_color2 = "magenta"; + room.auto_surface_direction = 1; const std::string fileName = file_path.substr(file_path.find_last_of("\\/") + 1); room.number = fileName.substr(0, fileName.find_last_of(".")); @@ -182,14 +182,14 @@ room_t loadRoomFile(std::string file_path, bool verbose) } // Asigna variables a partir de dos cadenas -bool setVars(room_t *room, std::string var, std::string value) +bool setVars(RoomData *room, std::string var, std::string value) { // Indicador de éxito en la asignación bool success = true; if (var == "tileMapFile") { - room->tileMapFile = value; + room->tile_map_file = value; } else if (var == "name") @@ -199,58 +199,58 @@ bool setVars(room_t *room, std::string var, std::string value) else if (var == "bgColor") { - room->bgColor = value; + room->bg_color = value; } else if (var == "border") { - room->borderColor = value; + room->border_color = value; } else if (var == "itemColor1") { - room->itemColor1 = value; + room->item_color1 = value; } else if (var == "itemColor2") { - room->itemColor2 = value; + room->item_color2 = value; } else if (var == "tileSetFile") { - room->tileSetFile = value; + room->tile_set_file = value; } else if (var == "roomUp") { - room->roomUp = value; + room->room_top = value; } else if (var == "roomDown") { - room->roomDown = value; + room->room_bottom = value; } else if (var == "roomLeft") { - room->roomLeft = value; + room->room_left = value; } else if (var == "roomRight") { - room->roomRight = value; + room->room_right = value; } else if (var == "autoSurface") { if (value == "right") { - room->autoSurfaceDirection = 1; + room->auto_surface_direction = 1; } else { - room->autoSurfaceDirection = -1; + room->auto_surface_direction = -1; } } @@ -408,45 +408,44 @@ bool setItem(item_t *item, std::string var, std::string value) } // Constructor -Room::Room(std::shared_ptr room, std::shared_ptr itemTracker, int *itemsPicked, bool jailEnabled) - : screen(Screen::get()), - renderer(Screen::get()->getRenderer()), - asset(Asset::get()), - debug(Debug::get()), - itemTracker(itemTracker), - itemsPicked(itemsPicked) +Room::Room(std::shared_ptr room, int *itemsPicked, bool jailEnabled) + : screen_(Screen::get()), + renderer_(Screen::get()->getRenderer()), + asset_(Asset::get()), + debug_(Debug::get()), + items_picked_(itemsPicked) { - number = room->number; - name = room->name; - bgColor = room->bgColor; - borderColor = room->borderColor; - itemColor1 = room->itemColor1 == "" ? "yellow" : room->itemColor1; - itemColor2 = room->itemColor2 == "" ? "magenta" : room->itemColor2; - roomUp = room->roomUp; - roomDown = room->roomDown; - roomLeft = room->roomLeft; - roomRight = room->roomRight; - tileSetFile = room->tileSetFile; - tileMapFile = room->tileMapFile; - autoSurfaceDirection = room->autoSurfaceDirection; - textureA = room->textureA; - textureB = room->textureB; - tileMap = room->tileMap; - texture = (options.video.palette == Palette::ZXSPECTRUM) ? textureA : textureB; - this->jailEnabled = jailEnabled; + number_ = room->number; + name_ = room->name; + bg_color_ = room->bg_color; + border_color_ = room->border_color; + item_color1_ = room->item_color1 == "" ? "yellow" : room->item_color1; + item_color2_ = room->item_color2 == "" ? "magenta" : room->item_color2; + room_top_ = room->room_top; + room_bottom_ = room->room_bottom; + room_left_ = room->room_left; + room_right_ = room->room_right; + tile_set_file_ = room->tile_set_file; + tile_map_file_ = room->tile_map_file; + auto_surface_direction_ = room->auto_surface_direction; + textureA_ = room->textureA; + textureB_ = room->textureB; + tile_map_ = room->tile_map; + texture_ = (options.video.palette == Palette::ZXSPECTRUM) ? textureA_ : textureB_; + jail_is_open_ = jailEnabled; // Inicializa variables - tileSize = 8; - tileSetWidth = texture->getWidth() / tileSize; - mapWidth = 32; - mapHeight = 16; - paused = false; - counter = 0; + tile_size_ = 8; + tile_set_width_ = texture_->getWidth() / tile_size_; + map_width_ = 32; + map_height_ = 16; + paused_ = false; + counter_ = 0; // Crea los enemigos for (auto &enemy_data : room->enemies) { - enemies.emplace_back(std::make_shared(enemy_data)); + enemies_.emplace_back(std::make_shared(enemy_data)); } // Crea los items @@ -454,17 +453,17 @@ Room::Room(std::shared_ptr room, std::shared_ptr itemTracke { const SDL_Point itemPos = {item.x, item.y}; - if (!itemTracker->hasBeenPicked(room->name, itemPos)) + if (!ItemTracker::get()->hasBeenPicked(room->name, itemPos)) { - item.renderer = renderer; - item.color1 = stringToColor(options.video.palette, itemColor1); - item.color2 = stringToColor(options.video.palette, itemColor2); - items.emplace_back(std::make_shared(item)); + item.renderer = renderer_; + item.color1 = stringToColor(options.video.palette, item_color1_); + item.color2 = stringToColor(options.video.palette, item_color2_); + items_.emplace_back(std::make_shared(item)); } } // Carga los sonidos - itemSound = JA_LoadSound(asset->get("item.wav").c_str()); + item_sound_ = JA_LoadSound(asset_->get("item.wav").c_str()); // Abre la jail para poder entrar if (jailEnabled) @@ -485,74 +484,74 @@ Room::Room(std::shared_ptr room, std::shared_ptr itemTracke setAnimatedTiles(); // Crea la textura para el mapa de tiles de la habitación - mapTexture = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, PLAY_AREA_WIDTH, PLAY_AREA_HEIGHT); - if (mapTexture == nullptr) + map_texture_ = SDL_CreateTexture(renderer_, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, PLAY_AREA_WIDTH, PLAY_AREA_HEIGHT); + if (map_texture_ == nullptr) { if (options.console) { std::cout << "Error: mapTexture could not be created!\nSDL Error: " << SDL_GetError() << std::endl; } } - SDL_SetTextureBlendMode(mapTexture, SDL_BLENDMODE_BLEND); + SDL_SetTextureBlendMode(map_texture_, SDL_BLENDMODE_BLEND); // Pinta el mapa de la habitación en la textura fillMapTexture(); // Establece el color del borde - screen->setBorderColor(stringToColor(options.video.palette, room->borderColor)); + screen_->setBorderColor(stringToColor(options.video.palette, room->border_color)); } // Destructor Room::~Room() { // Reclama la memoria utilizada por los objetos - SDL_DestroyTexture(mapTexture); + SDL_DestroyTexture(map_texture_); } // Devuelve el nombre de la habitación std::string Room::getName() { - return name; + return name_; } // Devuelve el color de la habitación Color Room::getBGColor() { - return stringToColor(options.video.palette, bgColor); + return stringToColor(options.video.palette, bg_color_); } // Devuelve el color del borde Color Room::getBorderColor() { - return stringToColor(options.video.palette, borderColor); + return stringToColor(options.video.palette, border_color_); } // Crea la textura con el mapeado de la habitación void Room::fillMapTexture() { - const Color color = stringToColor(options.video.palette, bgColor); - SDL_SetRenderTarget(renderer, mapTexture); - SDL_SetRenderDrawColor(renderer, color.r, color.g, color.b, 0xFF); - SDL_RenderClear(renderer); + const Color color = stringToColor(options.video.palette, bg_color_); + SDL_SetRenderTarget(renderer_, map_texture_); + SDL_SetRenderDrawColor(renderer_, color.r, color.g, color.b, 0xFF); + SDL_RenderClear(renderer_); // Los tileSetFiles son de 20x20 tiles. El primer tile es el 0. Cuentan hacia la derecha y hacia abajo - SDL_Rect clip = {0, 0, tileSize, tileSize}; - for (int y = 0; y < mapHeight; ++y) - for (int x = 0; x < mapWidth; ++x) + SDL_Rect clip = {0, 0, tile_size_, tile_size_}; + for (int y = 0; y < map_height_; ++y) + for (int x = 0; x < map_width_; ++x) { // Tiled pone los tiles vacios del mapa como cero y empieza a contar de 1 a n. // Al cargar el mapa en memoria, se resta uno, por tanto los tiles vacios son -1 // Tampoco hay que dibujar los tiles animados que estan en la fila 19 (indices) - const int index = (y * mapWidth) + x; - const bool a = (tileMap[index] >= 18 * tileSetWidth) && (tileMap[index] < 19 * tileSetWidth); - const bool b = tileMap[index] > -1; + const int index = (y * map_width_) + x; + const bool a = (tile_map_[index] >= 18 * tile_set_width_) && (tile_map_[index] < 19 * tile_set_width_); + const bool b = tile_map_[index] > -1; if (b && !a) { - clip.x = (tileMap[index] % tileSetWidth) * tileSize; - clip.y = (tileMap[index] / tileSetWidth) * tileSize; - texture->render(x * tileSize, y * tileSize, &clip); + clip.x = (tile_map_[index] % tile_set_width_) * tile_size_; + clip.y = (tile_map_[index] / tile_set_width_) * tile_size_; + texture_->render(x * tile_size_, y * tile_size_, &clip); #ifdef DEBUG // **** @@ -654,7 +653,7 @@ void Room::fillMapTexture() // **** #endif - SDL_SetRenderTarget(renderer, nullptr); + SDL_SetRenderTarget(renderer_, nullptr); } // Dibuja el mapa en pantalla @@ -662,7 +661,7 @@ void Room::renderMap() { // Dibuja la textura con el mapa en pantalla SDL_Rect dest = {0, 0, PLAY_AREA_WIDTH, PLAY_AREA_HEIGHT}; - SDL_RenderCopy(renderer, mapTexture, nullptr, &dest); + SDL_RenderCopy(renderer_, map_texture_, nullptr, &dest); // Dibuja los tiles animados #ifdef DEBUG @@ -678,7 +677,7 @@ void Room::renderMap() // Dibuja los enemigos en pantalla void Room::renderEnemies() { - for (auto enemy : enemies) + for (auto enemy : enemies_) { enemy->render(); } @@ -687,7 +686,7 @@ void Room::renderEnemies() // Dibuja los objetos en pantalla void Room::renderItems() { - for (auto item : items) + for (auto item : items_) { item->render(); } @@ -696,23 +695,23 @@ void Room::renderItems() // Actualiza las variables y objetos de la habitación void Room::update() { - if (paused) + if (paused_) { // Si está en modo pausa no se actualiza nada return; } // Actualiza el contador - counter++; + counter_++; // Actualiza los tiles animados updateAnimatedTiles(); - for (auto enemy : enemies) + for (auto enemy : enemies_) { // Actualiza los enemigos enemy->update(); } - for (auto item : items) + for (auto item : items_) { // Actualiza los items item->update(); } @@ -724,19 +723,19 @@ std::string Room::getRoom(int border) switch (border) { case BORDER_TOP: - return roomUp; + return room_top_; break; case BORDER_BOTTOM: - return roomDown; + return room_bottom_; break; case BORDER_RIGHT: - return roomRight; + return room_right_; break; case BORDER_LEFT: - return roomLeft; + return room_left_; break; default: @@ -748,7 +747,7 @@ std::string Room::getRoom(int border) // Devuelve el tipo de tile que hay en ese pixel tile_e Room::getTile(SDL_Point point) { - const int pos = ((point.y / tileSize) * mapWidth) + (point.x / tileSize); + const int pos = ((point.y / tile_size_) * map_width_) + (point.x / tile_size_); return getTile(pos); } @@ -756,42 +755,42 @@ tile_e Room::getTile(SDL_Point point) tile_e Room::getTile(int index) { // const bool onRange = (index > -1) && (index < mapWidth * mapHeight); - const bool onRange = (index > -1) && (index < (int)tileMap.size()); + const bool onRange = (index > -1) && (index < (int)tile_map_.size()); if (onRange) { // Las filas 0-8 son de tiles t_wall - if ((tileMap[index] >= 0) && (tileMap[index] < 9 * tileSetWidth)) + if ((tile_map_[index] >= 0) && (tile_map_[index] < 9 * tile_set_width_)) { return t_wall; } // Las filas 9-17 son de tiles t_passable - else if ((tileMap[index] >= 9 * tileSetWidth) && (tileMap[index] < 18 * tileSetWidth)) + else if ((tile_map_[index] >= 9 * tile_set_width_) && (tile_map_[index] < 18 * tile_set_width_)) { return t_passable; } // Las filas 18-20 es de tiles t_animated - else if ((tileMap[index] >= 18 * tileSetWidth) && (tileMap[index] < 21 * tileSetWidth)) + else if ((tile_map_[index] >= 18 * tile_set_width_) && (tile_map_[index] < 21 * tile_set_width_)) { return t_animated; } // La fila 21 es de tiles t_slope_r - else if ((tileMap[index] >= 21 * tileSetWidth) && (tileMap[index] < 22 * tileSetWidth)) + else if ((tile_map_[index] >= 21 * tile_set_width_) && (tile_map_[index] < 22 * tile_set_width_)) { return t_slope_r; } // La fila 22 es de tiles t_slope_l - else if ((tileMap[index] >= 22 * tileSetWidth) && (tileMap[index] < 23 * tileSetWidth)) + else if ((tile_map_[index] >= 22 * tile_set_width_) && (tile_map_[index] < 23 * tile_set_width_)) { return t_slope_l; } // La fila 23 es de tiles t_kill - else if ((tileMap[index] >= 23 * tileSetWidth) && (tileMap[index] < 24 * tileSetWidth)) + else if ((tile_map_[index] >= 23 * tile_set_width_) && (tile_map_[index] < 24 * tile_set_width_)) { return t_kill; } @@ -805,7 +804,7 @@ bool Room::enemyCollision(SDL_Rect &rect) { bool collision = false; - for (auto enemy : enemies) + for (auto enemy : enemies_) { collision |= checkCollision(rect, enemy->getCollider()); } @@ -816,15 +815,15 @@ bool Room::enemyCollision(SDL_Rect &rect) // Indica si hay colision con un objeto a partir de un rectangulo bool Room::itemCollision(SDL_Rect &rect) { - for (int i = 0; i < (int)items.size(); ++i) + for (int i = 0; i < (int)items_.size(); ++i) { - if (checkCollision(rect, items[i]->getCollider())) + if (checkCollision(rect, items_[i]->getCollider())) { - itemTracker->addItem(name, items[i]->getPos()); - items.erase(items.begin() + i); - JA_PlaySound(itemSound); - *itemsPicked = *itemsPicked + 1; - options.stats.items = *itemsPicked; + 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_; return true; } } @@ -835,15 +834,15 @@ bool Room::itemCollision(SDL_Rect &rect) // Recarga la textura void Room::reLoadTexture() { - texture->reLoad(); + texture_->reLoad(); fillMapTexture(); - for (auto enemy : enemies) + for (auto enemy : enemies_) { enemy->reLoadTexture(); } - for (auto item : items) + for (auto item : items_) { item->reLoadTexture(); } @@ -853,27 +852,27 @@ void Room::reLoadTexture() void Room::reLoadPalette() { // Cambia el color de los items - for (auto item : items) + for (auto item : items_) { - item->setColors(stringToColor(options.video.palette, itemColor1), stringToColor(options.video.palette, itemColor2)); + item->setColors(stringToColor(options.video.palette, item_color1_), stringToColor(options.video.palette, item_color2_)); } // Cambia el color de los enemigos - for (auto enemy : enemies) + for (auto enemy : enemies_) { enemy->setPalette(options.video.palette); } // Establece el color del borde - screen->setBorderColor(stringToColor(options.video.palette, borderColor)); + screen_->setBorderColor(stringToColor(options.video.palette, border_color_)); // Cambia la textura - texture = (options.video.palette == Palette::ZXSPECTRUM) ? textureA : textureB; + texture_ = (options.video.palette == Palette::ZXSPECTRUM) ? textureA_ : textureB_; // Pone la nueva textura a los tiles animados - for (auto tile : aTile) + for (auto tile : animated_tiles_) { - tile.sprite->setTexture(texture); + tile.sprite->setTexture(texture_); } // Recarga las texturas @@ -883,20 +882,20 @@ void Room::reLoadPalette() // Obten el tamaño del tile int Room::getTileSize() { - return tileSize; + return tile_size_; } // Obten la coordenada de la cuesta a partir de un punto perteneciente a ese tile int Room::getSlopeHeight(SDL_Point p, tile_e slope) { // Calcula la base del tile - int base = ((p.y / tileSize) * tileSize) + tileSize; + int base = ((p.y / tile_size_) * tile_size_) + tile_size_; #ifdef DEBUG debug->add("BASE = " + std::to_string(base)); #endif // Calcula cuanto se ha entrado en el tile horizontalmente - const int pos = (p.x % tileSize); // Esto da un valor entre 0 y 7 + const int pos = (p.x % tile_size_); // Esto da un valor entre 0 y 7 #ifdef DEBUG debug->add("POS = " + std::to_string(pos)); #endif @@ -911,7 +910,7 @@ int Room::getSlopeHeight(SDL_Point p, tile_e slope) } else { - base -= (tileSize - pos); + base -= (tile_size_ - pos); #ifdef DEBUG debug->add("BASE_L = " + std::to_string(base)); #endif @@ -927,14 +926,14 @@ void Room::setBottomSurfaces() // Busca todos los tiles de tipo muro que no tengan debajo otro muro // Hay que recorrer la habitación por filas (excepto los de la última fila) - for (int i = 0; i < (int)tileMap.size() - mapWidth; ++i) + for (int i = 0; i < (int)tile_map_.size() - map_width_; ++i) { - if (getTile(i) == t_wall && getTile(i + mapWidth) != t_wall) + if (getTile(i) == t_wall && getTile(i + map_width_) != t_wall) { tile.push_back(i); // Si llega al final de la fila, introduce un separador - if (i % mapWidth == mapWidth - 1) + if (i % map_width_ == map_width_ - 1) { tile.push_back(-1); } @@ -952,8 +951,8 @@ void Room::setBottomSurfaces() do { h_line_t line; - line.x1 = (tile[i] % mapWidth) * tileSize; - line.y = ((tile[i] / mapWidth) * tileSize) + tileSize - 1; + line.x1 = (tile[i] % map_width_) * tile_size_; + line.y = ((tile[i] / map_width_) * tile_size_) + tile_size_ - 1; lastOne = i; i++; @@ -970,8 +969,8 @@ void Room::setBottomSurfaces() } } - line.x2 = ((tile[lastOne] % mapWidth) * tileSize) + tileSize - 1; - bottomSurfaces.push_back(line); + line.x2 = ((tile[lastOne] % map_width_) * tile_size_) + tile_size_ - 1; + bottom_surfaces_.push_back(line); if (i <= (int)tile.size() - 1) { if (tile[i] == -1) @@ -990,14 +989,14 @@ void Room::setTopSurfaces() // Busca todos los tiles de tipo muro o pasable que no tengan encima un muro // Hay que recorrer la habitación por filas (excepto los de la primera fila) - for (int i = mapWidth; i < (int)tileMap.size(); ++i) + for (int i = map_width_; i < (int)tile_map_.size(); ++i) { - if ((getTile(i) == t_wall || getTile(i) == t_passable) && getTile(i - mapWidth) != t_wall) + if ((getTile(i) == t_wall || getTile(i) == t_passable) && getTile(i - map_width_) != t_wall) { tile.push_back(i); // Si llega al final de la fila, introduce un separador - if (i % mapWidth == mapWidth - 1) + if (i % map_width_ == map_width_ - 1) { tile.push_back(-1); } @@ -1015,8 +1014,8 @@ void Room::setTopSurfaces() do { h_line_t line; - line.x1 = (tile[i] % mapWidth) * tileSize; - line.y = (tile[i] / mapWidth) * tileSize; + line.x1 = (tile[i] % map_width_) * tile_size_; + line.y = (tile[i] / map_width_) * tile_size_; lastOne = i; i++; @@ -1033,8 +1032,8 @@ void Room::setTopSurfaces() } } - line.x2 = ((tile[lastOne] % mapWidth) * tileSize) + tileSize - 1; - topSurfaces.push_back(line); + line.x2 = ((tile[lastOne] % map_width_) * tile_size_) + tile_size_ - 1; + top_surfaces_.push_back(line); if (i <= (int)tile.size() - 1) { if (tile[i] == -1) @@ -1053,11 +1052,11 @@ void Room::setLeftSurfaces() // Busca todos los tiles de tipo muro que no tienen a su izquierda un tile de tipo muro // Hay que recorrer la habitación por columnas (excepto los de la primera columna) - for (int i = 1; i < mapWidth; ++i) + for (int i = 1; i < map_width_; ++i) { - for (int j = 0; j < mapHeight; ++j) + for (int j = 0; j < map_height_; ++j) { - const int pos = (j * mapWidth + i); + const int pos = (j * map_width_ + i); if (getTile(pos) == t_wall && getTile(pos - 1) != t_wall) { tile.push_back(pos); @@ -1077,9 +1076,9 @@ void Room::setLeftSurfaces() do { v_line_t line; - line.x = (tile[i] % mapWidth) * tileSize; - line.y1 = ((tile[i] / mapWidth) * tileSize); - while (tile[i] + mapWidth == tile[i + 1]) + line.x = (tile[i] % map_width_) * tile_size_; + line.y1 = ((tile[i] / map_width_) * tile_size_); + while (tile[i] + map_width_ == tile[i + 1]) { if (i == (int)tile.size() - 1) { @@ -1087,8 +1086,8 @@ void Room::setLeftSurfaces() } i++; } - line.y2 = ((tile[i] / mapWidth) * tileSize) + tileSize - 1; - leftSurfaces.push_back(line); + line.y2 = ((tile[i] / map_width_) * tile_size_) + tile_size_ - 1; + left_surfaces_.push_back(line); i++; } while (i < (int)tile.size() - 1); } @@ -1101,11 +1100,11 @@ void Room::setRightSurfaces() // Busca todos los tiles de tipo muro que no tienen a su derecha un tile de tipo muro // Hay que recorrer la habitación por columnas (excepto los de la última columna) - for (int i = 0; i < mapWidth - 1; ++i) + for (int i = 0; i < map_width_ - 1; ++i) { - for (int j = 0; j < mapHeight; ++j) + for (int j = 0; j < map_height_; ++j) { - const int pos = (j * mapWidth + i); + const int pos = (j * map_width_ + i); if (getTile(pos) == t_wall && getTile(pos + 1) != t_wall) { tile.push_back(pos); @@ -1125,9 +1124,9 @@ void Room::setRightSurfaces() do { v_line_t line; - line.x = ((tile[i] % mapWidth) * tileSize) + tileSize - 1; - line.y1 = ((tile[i] / mapWidth) * tileSize); - while (tile[i] + mapWidth == tile[i + 1]) + line.x = ((tile[i] % map_width_) * tile_size_) + tile_size_ - 1; + line.y1 = ((tile[i] / map_width_) * tile_size_); + while (tile[i] + map_width_ == tile[i + 1]) { if (i == (int)tile.size() - 1) { @@ -1135,8 +1134,8 @@ void Room::setRightSurfaces() } i++; } - line.y2 = ((tile[i] / mapWidth) * tileSize) + tileSize - 1; - rightSurfaces.push_back(line); + line.y2 = ((tile[i] / map_width_) * tile_size_) + tile_size_ - 1; + right_surfaces_.push_back(line); i++; } while (i < (int)tile.size() - 1); } @@ -1147,7 +1146,7 @@ void Room::setLeftSlopes() { // Recorre la habitación entera por filas buscando tiles de tipo t_slope_l std::vector found; - for (int i = 0; i < (int)tileMap.size(); ++i) + for (int i = 0; i < (int)tile_map_.size(); ++i) { if (getTile(i) == t_slope_l) { @@ -1162,9 +1161,9 @@ void Room::setLeftSlopes() while (found.size() > 0) { d_line_t line; - line.x1 = (found[0] % mapWidth) * tileSize; - line.y1 = (found[0] / mapWidth) * tileSize; - int lookingFor = found[0] + mapWidth + 1; + line.x1 = (found[0] % map_width_) * tile_size_; + line.y1 = (found[0] / map_width_) * tile_size_; + int lookingFor = found[0] + map_width_ + 1; int lastOneFound = found[0]; found.erase(found.begin()); for (int i = 0; i < (int)found.size(); ++i) @@ -1172,14 +1171,14 @@ void Room::setLeftSlopes() if (found[i] == lookingFor) { lastOneFound = lookingFor; - lookingFor += mapWidth + 1; + lookingFor += map_width_ + 1; found.erase(found.begin() + i); i--; } } - line.x2 = ((lastOneFound % mapWidth) * tileSize) + tileSize - 1; - line.y2 = ((lastOneFound / mapWidth) * tileSize) + tileSize - 1; - leftSlopes.push_back(line); + line.x2 = ((lastOneFound % map_width_) * tile_size_) + tile_size_ - 1; + line.y2 = ((lastOneFound / map_width_) * tile_size_) + tile_size_ - 1; + left_slopes_.push_back(line); } } @@ -1188,7 +1187,7 @@ void Room::setRightSlopes() { // Recorre la habitación entera por filas buscando tiles de tipo t_slope_r std::vector found; - for (int i = 0; i < (int)tileMap.size(); ++i) + for (int i = 0; i < (int)tile_map_.size(); ++i) { if (getTile(i) == t_slope_r) { @@ -1203,9 +1202,9 @@ void Room::setRightSlopes() while (found.size() > 0) { d_line_t line; - line.x1 = ((found[0] % mapWidth) * tileSize) + tileSize - 1; - line.y1 = (found[0] / mapWidth) * tileSize; - int lookingFor = found[0] + mapWidth - 1; + line.x1 = ((found[0] % map_width_) * tile_size_) + tile_size_ - 1; + line.y1 = (found[0] / map_width_) * tile_size_; + int lookingFor = found[0] + map_width_ - 1; int lastOneFound = found[0]; found.erase(found.begin()); for (int i = 0; i < (int)found.size(); ++i) @@ -1213,14 +1212,14 @@ void Room::setRightSlopes() if (found[i] == lookingFor) { lastOneFound = lookingFor; - lookingFor += mapWidth - 1; + lookingFor += map_width_ - 1; found.erase(found.begin() + i); i--; } } - line.x2 = (lastOneFound % mapWidth) * tileSize; - line.y2 = ((lastOneFound / mapWidth) * tileSize) + tileSize - 1; - rightSlopes.push_back(line); + line.x2 = (lastOneFound % map_width_) * tile_size_; + line.y2 = ((lastOneFound / map_width_) * tile_size_) + tile_size_ - 1; + right_slopes_.push_back(line); } } @@ -1231,14 +1230,14 @@ void Room::setAutoSurfaces() // Busca todos los tiles de tipo animado // Hay que recorrer la habitación por filas (excepto los de la primera fila) - for (int i = mapWidth; i < (int)tileMap.size(); ++i) + for (int i = map_width_; i < (int)tile_map_.size(); ++i) { if (getTile(i) == t_animated) { tile.push_back(i); // Si llega al final de la fila, introduce un separador - if (i % mapWidth == mapWidth - 1) + if (i % map_width_ == map_width_ - 1) { tile.push_back(-1); } @@ -1253,8 +1252,8 @@ void Room::setAutoSurfaces() do { h_line_t line; - line.x1 = (tile[i] % mapWidth) * tileSize; - line.y = (tile[i] / mapWidth) * tileSize; + line.x1 = (tile[i] % map_width_) * tile_size_; + line.y = (tile[i] / map_width_) * tile_size_; lastOne = i; i++; @@ -1271,8 +1270,8 @@ void Room::setAutoSurfaces() } } - line.x2 = ((tile[lastOne] % mapWidth) * tileSize) + tileSize - 1; - autoSurfaces.push_back(line); + line.x2 = ((tile[lastOne] % map_width_) * tile_size_) + tile_size_ - 1; + auto_surfaces_.push_back(line); if (i <= (int)tile.size() - 1) { if (tile[i] == -1) @@ -1288,23 +1287,23 @@ void Room::setAutoSurfaces() void Room::setAnimatedTiles() { // Recorre la habitación entera por filas buscando tiles de tipo t_animated - for (int i = 0; i < (int)tileMap.size(); ++i) + for (int i = 0; i < (int)tile_map_.size(); ++i) { if (getTile(i) == t_animated) { // La i es la ubicación - const int x = (i % mapWidth) * tileSize; - const int y = (i / mapWidth) * tileSize; + const int x = (i % map_width_) * tile_size_; + const int y = (i / map_width_) * tile_size_; // TileMap[i] es el tile a poner - const int xc = (tileMap[i] % tileSetWidth) * tileSize; - const int yc = (tileMap[i] / tileSetWidth) * tileSize; + const int xc = (tile_map_[i] % tile_set_width_) * tile_size_; + const int yc = (tile_map_[i] / tile_set_width_) * tile_size_; aTile_t at; - at.sprite = std::make_shared(texture, x, y, 8, 8); + at.sprite = std::make_shared(texture_, x, y, 8, 8); at.sprite->setClip(xc, yc, 8, 8); - at.xcOrig = xc; - aTile.push_back(at); + at.x_orig = xc; + animated_tiles_.push_back(at); } } } @@ -1314,19 +1313,19 @@ void Room::updateAnimatedTiles() { const int numFrames = 4; int offset = 0; - if (autoSurfaceDirection == -1) + if (auto_surface_direction_ == -1) { - offset = ((counter / 3) % numFrames * tileSize); + offset = ((counter_ / 3) % numFrames * tile_size_); } else { - offset = ((numFrames - 1 - ((counter / 3) % numFrames)) * tileSize); + offset = ((numFrames - 1 - ((counter_ / 3) % numFrames)) * tile_size_); } - for (auto &a : aTile) + for (auto &a : animated_tiles_) { SDL_Rect rect = a.sprite->getClip(); - rect.x = a.xcOrig + offset; + rect.x = a.x_orig + offset; a.sprite->setClip(rect); } } @@ -1334,7 +1333,7 @@ void Room::updateAnimatedTiles() // Pinta los tiles animados en pantalla void Room::renderAnimatedTiles() { - for (auto a : aTile) + for (auto a : animated_tiles_) { a.sprite->render(); } @@ -1343,7 +1342,7 @@ void Room::renderAnimatedTiles() // Comprueba las colisiones int Room::checkRightSurfaces(SDL_Rect *rect) { - for (auto s : rightSurfaces) + for (auto s : right_surfaces_) { if (checkCollision(s, *rect)) { @@ -1357,7 +1356,7 @@ int Room::checkRightSurfaces(SDL_Rect *rect) // Comprueba las colisiones int Room::checkLeftSurfaces(SDL_Rect *rect) { - for (auto s : leftSurfaces) + for (auto s : left_surfaces_) { if (checkCollision(s, *rect)) { @@ -1371,7 +1370,7 @@ int Room::checkLeftSurfaces(SDL_Rect *rect) // Comprueba las colisiones int Room::checkTopSurfaces(SDL_Rect *rect) { - for (auto s : topSurfaces) + for (auto s : top_surfaces_) { if (checkCollision(s, *rect)) { @@ -1385,7 +1384,7 @@ int Room::checkTopSurfaces(SDL_Rect *rect) // Comprueba las colisiones int Room::checkBottomSurfaces(SDL_Rect *rect) { - for (auto s : bottomSurfaces) + for (auto s : bottom_surfaces_) { if (checkCollision(s, *rect)) { @@ -1399,7 +1398,7 @@ int Room::checkBottomSurfaces(SDL_Rect *rect) // Comprueba las colisiones int Room::checkAutoSurfaces(SDL_Rect *rect) { - for (auto s : autoSurfaces) + for (auto s : auto_surfaces_) { if (checkCollision(s, *rect)) { @@ -1413,7 +1412,7 @@ int Room::checkAutoSurfaces(SDL_Rect *rect) // Comprueba las colisiones bool Room::checkTopSurfaces(SDL_Point *p) { - for (auto s : topSurfaces) + for (auto s : top_surfaces_) { if (checkCollision(s, *p)) { @@ -1427,7 +1426,7 @@ bool Room::checkTopSurfaces(SDL_Point *p) // Comprueba las colisiones bool Room::checkAutoSurfaces(SDL_Point *p) { - for (auto s : autoSurfaces) + for (auto s : auto_surfaces_) { if (checkCollision(s, *p)) { @@ -1441,7 +1440,7 @@ bool Room::checkAutoSurfaces(SDL_Point *p) // Comprueba las colisiones int Room::checkLeftSlopes(v_line_t *line) { - for (auto s : leftSlopes) + for (auto s : left_slopes_) { const SDL_Point p = checkCollision(s, *line); if (p.x != -1) @@ -1456,7 +1455,7 @@ int Room::checkLeftSlopes(v_line_t *line) // Comprueba las colisiones bool Room::checkLeftSlopes(SDL_Point *p) { - for (auto s : leftSlopes) + for (auto s : left_slopes_) { if (checkCollision(*p, s)) { @@ -1470,7 +1469,7 @@ bool Room::checkLeftSlopes(SDL_Point *p) // Comprueba las colisiones int Room::checkRightSlopes(v_line_t *line) { - for (auto s : rightSlopes) + for (auto s : right_slopes_) { const SDL_Point p = checkCollision(s, *line); if (p.x != -1) @@ -1485,7 +1484,7 @@ int Room::checkRightSlopes(v_line_t *line) // Comprueba las colisiones bool Room::checkRightSlopes(SDL_Point *p) { - for (auto s : rightSlopes) + for (auto s : right_slopes_) { if (checkCollision(*p, s)) { @@ -1499,33 +1498,33 @@ bool Room::checkRightSlopes(SDL_Point *p) // Pone el mapa en modo pausa void Room::pause() { - paused = true; + paused_ = true; } // Quita el modo pausa del mapa void Room::resume() { - paused = false; + paused_ = false; } // Obten la direccion de las superficies automaticas int Room::getAutoSurfaceDirection() { - return autoSurfaceDirection; + return auto_surface_direction_; } // Abre la jail para poder entrar void Room::openTheJail() { - if (name == "THE JAIL") + if (name_ == "THE JAIL") { // Elimina el último enemigo (Bry debe ser el ultimo enemigo definido en el fichero) - enemies.pop_back(); + enemies_.pop_back(); // Abre las puertas const int tileA = 16 + (13 * 32); const int tileB = 16 + (14 * 32); - tileMap[tileA] = -1; - tileMap[tileB] = -1; + tile_map_[tileA] = -1; + tile_map_[tileB] = -1; } } \ No newline at end of file diff --git a/source/room.h b/source/room.h index 98b53b7..eebcccb 100644 --- a/source/room.h +++ b/source/room.h @@ -1,20 +1,20 @@ #pragma once -#include // for SDL_Rect, SDL_Point -#include // for SDL_Renderer, SDL_Texture -#include // for shared_ptr -#include // for string -#include // for vector -#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 // for SDL_Rect, SDL_Point +#include // for SDL_Renderer, SDL_Texture +#include // for shared_ptr +#include // for string +#include // for vector +#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 class ItemTracker; -class Screen; // lines 14-14 -class Sprite; // lines 15-15 -class Texture; // lines 16-16 -struct JA_Sound_t; // lines 17-17 +class Screen; // lines 14-14 +class Sprite; // lines 15-15 +class Texture; // lines 16-16 +struct JA_Sound_t; // lines 17-17 enum tile_e { @@ -30,25 +30,25 @@ enum tile_e struct aTile_t { std::shared_ptr sprite; // Sprite para dibujar el tile - int xcOrig; // Poicion X donde se encuentra el primer tile de la animacion en la tilesheet + int x_orig; // Poicion X donde se encuentra el primer tile de la animacion en la tilesheet }; -struct room_t +struct RoomData { std::string number; // Numero de la habitación std::string name; // Nombre de la habitación - std::string bgColor; // Color de fondo de la habitación - std::string borderColor; // Color del borde de la pantalla - std::string itemColor1; // Color 1 para los items de la habitación - std::string itemColor2; // Color 2 para los items de la habitación - std::string roomUp; // Identificador de la habitación que se encuentra arriba - std::string roomDown; // Identificador de la habitación que se encuentra abajp - std::string roomLeft; // Identificador de la habitación que se encuentra a la izquierda - std::string roomRight; // Identificador de la habitación que se encuentra a la derecha - std::string tileSetFile; // Imagen con los graficos para la habitación - std::string tileMapFile; // Fichero con el mapa de indices de tile - std::vector tileMap; // Indice de los tiles a dibujar en la habitación - int autoSurfaceDirection; // Sentido en el que arrastran las superficies automáticas 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::shared_ptr textureA; // Textura con los graficos de la habitación @@ -56,13 +56,13 @@ struct room_t }; // Carga las variables desde un fichero de mapa -room_t loadRoomFile(std::string file, bool verbose = false); +RoomData loadRoomFile(std::string file, bool verbose = false); // Carga las variables y texturas desde un fichero de mapa de tiles std::vector loadRoomTileFile(std::string file_path, bool verbose = false); // Asigna variables a partir de dos cadenas -bool setVars(room_t *room, std::string var, std::string value); +bool setVars(RoomData *room, std::string var, std::string value); // Asigna variables a una estructura enemy_t bool setEnemy(EnemyData *enemy, std::string var, std::string value); @@ -74,50 +74,49 @@ class Room { private: // Objetos y punteros - Screen *screen; // Objeto encargado de dibujar en pantalla - SDL_Renderer *renderer; // El renderizador de la ventana - Asset *asset; // Objeto con la ruta a todos los ficheros de recursos - Debug *debug; // Objeto para gestionar la información de debug - 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::shared_ptr texture; // Textura con los graficos de la habitación - std::shared_ptr textureA; // Textura con los graficos de la habitación - std::shared_ptr textureB; // Textura con los graficos de la habitación - std::shared_ptr itemTracker; // Lleva el control de los objetos recogidos - SDL_Texture *mapTexture; // Textura para dibujar el mapa de la habitación - int *itemsPicked; // Puntero a la cantidad de items recogidos que lleva el juego + Screen *screen_; // Objeto encargado de dibujar en pantalla + SDL_Renderer *renderer_; // El renderizador de la ventana + Asset *asset_; // Objeto con la ruta a todos los ficheros de recursos + Debug *debug_; // Objeto para gestionar la información de debug + 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::shared_ptr texture_; // Textura con los graficos de la habitación + std::shared_ptr textureA_; // Textura con los graficos de la habitación + std::shared_ptr textureB_; // 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 // Variables - std::string number; // Numero de la habitación - std::string name; // Nombre de la habitación - std::string bgColor; // Color de fondo de la habitación - std::string borderColor; // Color del borde de la pantalla - std::string itemColor1; // Color 1 para los items de la habitación - std::string itemColor2; // Color 2 para los items de la habitación - std::string roomUp; // Identificador de la habitación que se encuentra arriba - std::string roomDown; // Identificador de la habitación que se encuentra abajp - std::string roomLeft; // Identificador de la habitación que se encuentra a la izquierda - std::string roomRight; // Identificador de la habitación que se encuentra a la derecha - std::string tileSetFile; // Imagen con los graficos para la habitación - std::string tileMapFile; // Fichero con el mapa de indices de tile - std::vector tileMap; // Indice de los tiles a dibujar en la habitación - int autoSurfaceDirection; // Sentido en el que arrastran las superficies automáticas de la habitación - JA_Sound_t *itemSound; // Sonido producido al coger un objeto - std::vector bottomSurfaces; // Lista con las superficies inferiores de la habitación - std::vector topSurfaces; // Lista con las superficies superiores de la habitación - std::vector leftSurfaces; // Lista con las superficies laterales de la parte izquierda de la habitación - std::vector rightSurfaces; // Lista con las superficies laterales de la parte derecha de la habitación - std::vector leftSlopes; // Lista con todas las rampas que suben hacia la izquierda - std::vector rightSlopes; // Lista con todas las rampas que suben hacia la derecha - int counter; // Contador para lo que haga falta - bool paused; // Indica si el mapa esta en modo pausa - std::vector aTile; // Vector con los indices de tiles animados - std::vector autoSurfaces; // Lista con las superficies automaticas de la habitación - int tileSize; // Ancho del tile en pixels - int mapWidth; // Ancho del mapa en tiles - int mapHeight; // Alto del mapa en tiles - int tileSetWidth; // Ancho del tileset en tiles - bool jailEnabled; // Indica si hay acceso a la Jail + 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 + JA_Sound_t *item_sound_; // Sonido producido al coger un objeto + std::vector bottom_surfaces_; // Lista con las superficies inferiores de la habitación + std::vector top_surfaces_; // Lista con las superficies superiores de la habitación + std::vector left_surfaces_; // Lista con las superficies laterales de la parte izquierda de la habitación + std::vector right_surfaces_; // Lista con las superficies laterales de la parte derecha de la habitación + std::vector left_slopes_; // Lista con todas las rampas que suben hacia la izquierda + std::vector right_slopes_; // Lista con todas las rampas que suben hacia la derecha + int counter_; // Contador para lo que haga falta + bool paused_; // Indica si el mapa esta en modo pausa + 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_size_; // Ancho del tile en pixels + int map_width_; // Ancho del mapa en tiles + int map_height_; // Alto del mapa en tiles + 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(); @@ -160,7 +159,7 @@ private: public: // Constructor - Room(std::shared_ptr room, std::shared_ptr itemTracker, int *itemsPicked, bool jailEnabled); + Room(std::shared_ptr room, int *itemsPicked, bool jailEnabled); // Destructor ~Room(); diff --git a/source/scoreboard.cpp b/source/scoreboard.cpp index 3f0819f..9233a00 100644 --- a/source/scoreboard.cpp +++ b/source/scoreboard.cpp @@ -1,43 +1,43 @@ #include "scoreboard.h" -#include // for SDL_Rect -#include // for SDL_GetTicks -#include "animated_sprite.h" // for AnimatedSprite -#include "asset.h" // for Asset -#include "defines.h" // for BLOCK, GAMECANVAS_HEIGHT, PLAY_AREA_HEIGHT -#include "options.h" // for Options, options, OptionsVideo, Cheat -#include "resource.h" // for Resource -#include "screen.h" // for Screen -#include "text.h" // for Text -#include "texture.h" // for Texture +#include // for SDL_Rect +#include // for SDL_GetTicks +#include "animated_sprite.h" // for AnimatedSprite +#include "asset.h" // for Asset +#include "defines.h" // for BLOCK, GAMECANVAS_HEIGHT, PLAY_AREA_HEIGHT +#include "options.h" // for Options, options, OptionsVideo, Cheat +#include "resource.h" // for Resource +#include "screen.h" // for Screen +#include "text.h" // for Text +#include "texture.h" // for Texture // Constructor -Scoreboard::Scoreboard(board_t *board) - : renderer(Screen::get()->getRenderer()), - resource(Resource::get()), - asset(Asset::get()), - board(board) +Scoreboard::Scoreboard(ScoreboardData *board) + : renderer_(Screen::get()->getRenderer()), + resource_(Resource::get()), + asset_(Asset::get()), + board_(board) { // Reserva memoria para los objetos - itemTexture = resource->getTexture("items.png"); + 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"; - sprite = std::make_shared(resource->getTexture(playerPNG), resource->getAnimation(playerANI)); - sprite->setCurrentAnimation("walk_menu"); - text = resource->getText("smb2"); + player_sprite_ = std::make_shared(resource_->getTexture(playerPNG), resource_->getAnimation(playerANI)); + player_sprite_->setCurrentAnimation("walk_menu"); + text_ = resource_->getText("smb2"); // Inicializa las variables - counter = 0; - colorChangeSpeed = 4; - paused = false; - timePaused = 0; - totalTimePaused = 0; - itemsColor = stringToColor(options.video.palette, "white"); + counter_ = 0; + change_color_speed_ = 4; + is_paused_ = false; + paused_time_ = 0; + paused_time_elapsed_ = 0; + items_color_ = stringToColor(options.video.palette, "white"); // Inicializa el vector de colores const std::vector vColors = {"blue", "magenta", "green", "cyan", "yellow", "white", "bright_blue", "bright_magenta", "bright_green", "bright_cyan", "bright_yellow", "bright_white"}; for (auto v : vColors) { - color.push_back(stringToColor(options.video.palette, v)); + color_.push_back(stringToColor(options.video.palette, v)); } } @@ -50,66 +50,66 @@ void Scoreboard::render() // Dibuja el fondo del marcador const SDL_Rect rect = {0, 18 * BLOCK, PLAY_AREA_WIDTH, GAMECANVAS_HEIGHT - PLAY_AREA_HEIGHT}; - SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255); - SDL_RenderFillRect(renderer, &rect); + SDL_SetRenderDrawColor(renderer_, 0, 0, 0, 255); + SDL_RenderFillRect(renderer_, &rect); // Dibuja las vidas - const int desp = (counter / 40) % 8; + const int desp = (counter_ / 40) % 8; const int frame = desp % 4; - sprite->setCurrentAnimationFrame(frame); - sprite->setPosY(line2); - for (int i = 0; i < board->lives; ++i) + player_sprite_->setCurrentAnimationFrame(frame); + player_sprite_->setPosY(line2); + for (int i = 0; i < board_->lives; ++i) { - sprite->setPosX(8 + (16 * i) + desp); - const int index = i % color.size(); - sprite->getTexture()->setColor(color[index].r, color[index].g, color[index].b); - sprite->render(); + player_sprite_->setPosX(8 + (16 * i) + desp); + const int index = i % color_.size(); + player_sprite_->getTexture()->setColor(color_[index].r, color_[index].g, color_[index].b); + player_sprite_->render(); } // Muestra si suena la música - if (board->music) + if (board_->music) { - const Color c = board->color; + const Color c = board_->color; SDL_Rect clip = {0, 8, 8, 8}; - itemTexture->setColor(c.r, c.g, c.b); - itemTexture->render(20 * BLOCK, line2, &clip); + item_texture_->setColor(c.r, c.g, c.b); + item_texture_->render(20 * BLOCK, line2, &clip); } // 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); - this->text->writeColored(17 * BLOCK, line1, itemsTxt, itemsColor); - this->text->writeColored(20 * BLOCK, line1, " Time ", board->color); - this->text->writeColored(26 * BLOCK, line1, timeTxt, stringToColor(options.video.palette, "white")); + 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); + this->text_->writeColored(17 * BLOCK, line1, itemsTxt, items_color_); + this->text_->writeColored(20 * BLOCK, line1, " Time ", board_->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); - this->text->writeColored(22 * BLOCK, line2, "Rooms", stringToColor(options.video.palette, "white")); - this->text->writeColored(28 * BLOCK, line2, roomsTxt, 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); + this->text_->writeColored(22 * BLOCK, line2, "Rooms", stringToColor(options.video.palette, "white")); + this->text_->writeColored(28 * BLOCK, line2, roomsTxt, stringToColor(options.video.palette, "white")); } // Actualiza las variables del objeto void Scoreboard::update() { - counter++; - sprite->update(); + counter_++; + player_sprite_->update(); // Actualiza el color de la cantidad de items recogidos updateItemsColor(); - if (!paused) + if (!is_paused_) { // Si está en pausa no se actualiza el reloj - clock = getTime(); + clock_ = getTime(); } } // Obtiene el tiempo transcurrido de partida -Scoreboard::clock_t Scoreboard::getTime() +Scoreboard::ClockData Scoreboard::getTime() { - const Uint32 timeElapsed = SDL_GetTicks() - board->iniClock - totalTimePaused; + const Uint32 timeElapsed = SDL_GetTicks() - board_->ini_clock - paused_time_elapsed_; - clock_t time; + ClockData time; time.hours = timeElapsed / 3600000; time.minutes = timeElapsed / 60000; time.seconds = timeElapsed / 1000; @@ -121,10 +121,10 @@ Scoreboard::clock_t Scoreboard::getTime() // Recarga la textura void Scoreboard::reLoadTexture() { - sprite->getTexture()->reLoad(); + player_sprite_->getTexture()->reLoad(); // playerTexture->reLoad(); - itemTexture->reLoad(); - text->reLoadTexture(); + item_texture_->reLoad(); + text_->reLoadTexture(); } // Recarga la paleta @@ -132,42 +132,42 @@ void Scoreboard::reLoadPalette() { // Reinicia el vector de colores const std::vector vColors = {"blue", "magenta", "green", "cyan", "yellow", "white", "bright_blue", "bright_magenta", "bright_green", "bright_cyan", "bright_yellow", "bright_white"}; - color.clear(); + color_.clear(); for (auto v : vColors) { - color.push_back(stringToColor(options.video.palette, v)); + color_.push_back(stringToColor(options.video.palette, v)); } } // Pone el marcador en modo pausa void Scoreboard::pause() { - paused = true; - timePaused = SDL_GetTicks(); + is_paused_ = true; + paused_time_ = SDL_GetTicks(); } // Quita el modo pausa del marcador void Scoreboard::resume() { - paused = false; - totalTimePaused += SDL_GetTicks() - timePaused; + is_paused_ = false; + paused_time_elapsed_ += SDL_GetTicks() - paused_time_; } // Actualiza el color de la cantidad de items recogidos void Scoreboard::updateItemsColor() { - if (!board->jail_is_open) + if (!board_->jail_is_open) { return; } - if (counter % 20 < 10) + if (counter_ % 20 < 10) { - itemsColor = stringToColor(options.video.palette, "white"); + items_color_ = stringToColor(options.video.palette, "white"); } else { - itemsColor = stringToColor(options.video.palette, "magenta"); + items_color_ = stringToColor(options.video.palette, "magenta"); } } diff --git a/source/scoreboard.h b/source/scoreboard.h index a1b8942..6639327 100644 --- a/source/scoreboard.h +++ b/source/scoreboard.h @@ -12,21 +12,21 @@ class Resource; class Text; class Texture; -struct board_t +struct ScoreboardData { int items; // Lleva la cuenta de los objetos recogidos int lives; // Lleva la cuenta de ls vidas restantes del jugador int rooms; // Lleva la cuenta de las habitaciones visitadas bool music; // Indica si ha de sonar la musica durante el juego Color color; // Color para escribir el texto del marcador - Uint32 iniClock; // Tiempo inicial para calcular el tiempo transcurrido + Uint32 ini_clock; // Tiempo inicial para calcular el tiempo transcurrido bool jail_is_open; // Indica si se puede entrar a la Jail }; class Scoreboard { private: - struct clock_t + struct ClockData { int hours; int minutes; @@ -35,33 +35,33 @@ private: }; // Objetos y punteros - SDL_Renderer *renderer; // El renderizador de la ventana - Resource *resource; // Objeto con los recursos - Asset *asset; // Objeto con la ruta a todos los ficheros de recursos - std::shared_ptr text; // Objeto para escribir texto - std::shared_ptr sprite; // Sprite para mostrar las vidas en el marcador - std::shared_ptr itemTexture; // Textura con los graficos para las vidas - std::shared_ptr board; // Contiene las variables a mostrar en el marcador + SDL_Renderer *renderer_; // El renderizador de la ventana + Resource *resource_; // Objeto con los recursos + Asset *asset_; // Objeto con la ruta a todos los ficheros de recursos + 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 // Variables - std::vector color; // Vector con los colores del objeto - int counter; // Contador interno - int colorChangeSpeed; // Cuanto mas alto, mas tarda en cambiar de color - bool paused; // Indica si el marcador esta en modo pausa - Uint32 timePaused; // Milisegundos que ha estado el marcador en pausa - Uint32 totalTimePaused; // Tiempo acumulado en pausa - clock_t clock; // Contiene las horas, minutos y segundos transcurridos desde el inicio de la partida - Color itemsColor; // Color de la cantidad de items recogidos + std::vector color_; // Vector con los colores del objeto + int counter_; // Contador interno + int change_color_speed_; // Cuanto mas alto, mas tarda en cambiar de color + bool is_paused_; // Indica si el marcador esta en modo pausa + Uint32 paused_time_; // Milisegundos que ha estado el marcador en pausa + Uint32 paused_time_elapsed_; // Tiempo acumulado en pausa + ClockData clock_; // Contiene las horas, minutos y segundos transcurridos desde el inicio de la partida + Color items_color_; // Color de la cantidad de items recogidos // Obtiene el tiempo transcurrido de partida - clock_t getTime(); + ClockData getTime(); // Actualiza el color de la cantidad de items recogidos void updateItemsColor(); public: // Constructor - Scoreboard(board_t *board); + Scoreboard(ScoreboardData *board); // Destructor ~Scoreboard() = default;