From fc01676df22e889b61b838eea7f1b7e86aed83a0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sergio=20Valor=20Mart=C3=ADnez?= Date: Sat, 22 Feb 2025 18:27:23 +0100 Subject: [PATCH] Singletonejant Borrat menu.cpp que no estava gastantse...mmm.. desde mai --- source/cheevos.cpp | 220 ++------- source/cheevos.h | 41 +- source/credits.cpp | 7 +- source/credits.h | 2 +- source/debug.cpp | 21 + source/debug.h | 20 +- source/demo.cpp | 27 +- source/demo.h | 6 +- source/director.cpp | 87 ++-- source/director.h | 3 - source/ending.cpp | 17 +- source/ending.h | 4 +- source/ending2.cpp | 17 +- source/ending2.h | 8 +- source/game.cpp | 36 +- source/game.h | 4 +- source/game_over.cpp | 17 +- source/game_over.h | 4 +- source/loading_screen.cpp | 15 +- source/loading_screen.h | 2 +- source/logo.cpp | 7 +- source/logo.h | 2 +- source/menu.cpp | 990 -------------------------------------- source/menu.h | 220 --------- source/notifier.cpp | 20 +- source/notifier.h | 6 +- source/player.cpp | 215 ++++----- source/player.h | 19 +- source/resource.cpp | 21 + source/resource.h | 14 +- source/room.cpp | 16 +- source/room.h | 10 +- source/scoreboard.cpp | 34 +- source/scoreboard.h | 6 +- source/screen.cpp | 23 +- source/screen.h | 9 +- source/title.cpp | 19 +- source/title.h | 2 +- 38 files changed, 440 insertions(+), 1751 deletions(-) delete mode 100644 source/menu.cpp delete mode 100644 source/menu.h diff --git a/source/cheevos.cpp b/source/cheevos.cpp index 87c83d3..b9a4ac8 100644 --- a/source/cheevos.cpp +++ b/source/cheevos.cpp @@ -3,113 +3,49 @@ #include // Para SDL_RWFromFile, SDL_RWclose, SDL_RWwrite #include // Para NULL #include // Para basic_ostream, operator<<, cout, endl -#include "screen.h" // Para Screen +#include "notifier.h" // Para Screen #include "utils.h" // Para options_t #include "options.h" +#include // Para fstream // Constructor -Cheevos::Cheevos(Screen *screen, std::string file) +Cheevos::Cheevos(const std::string &file) + : file_(file) { - // Copia la dirección de los objetos - this->screen = screen; - this->file = file; - - // Inicializa los logros init(); - - // Inicializa variables - enabled = true; - - // Carga el estado de los logros - load(); + loadFromFile(); } // Destructor Cheevos::~Cheevos() { - // Guarda el estado de los logros - save(); - - cheevos.clear(); + saveToFile(); } // Inicializa los logros void Cheevos::init() { - cheevos.clear(); - - cheevos_t c; - c.completed = false; - c.valid = true; - c.icon = 2; - - c.id = 1; - c.caption = "SHINY THINGS"; - c.description = "Get 25\% of the items"; - cheevos.push_back(c); - - c.id = 2; - c.caption = "HALF THE WORK"; - c.description = "Get 50\% of the items"; - cheevos.push_back(c); - - c.id = 3; - c.caption = "GETTING THERE"; - c.description = "Get 75\% of the items"; - cheevos.push_back(c); - - c.id = 4; - c.caption = "THE COLLECTOR"; - c.description = "Get 100\% of the items"; - cheevos.push_back(c); - - c.id = 5; - c.caption = "WANDERING AROUND"; - c.description = "Visit 20 rooms"; - cheevos.push_back(c); - - c.id = 6; - c.caption = "I GOT LOST"; - c.description = "Visit 40 rooms"; - cheevos.push_back(c); - - c.id = 7; - c.caption = "I LIKE TO EXPLORE"; - c.description = "Visit all rooms"; - cheevos.push_back(c); - - c.id = 8; - c.caption = "FINISH THE GAME"; - c.description = "Complete the game"; - cheevos.push_back(c); - - c.id = 9; - c.caption = "I WAS SUCKED BY A HOLE"; - c.description = "Complete the game without entering the jail"; - cheevos.push_back(c); - - c.id = 10; - c.caption = "MY LITTLE PROJECTS"; - c.description = "Complete the game with all items"; - cheevos.push_back(c); - - c.id = 11; - c.caption = "I LIKE MY MULTICOLOURED FRIENDS"; - c.description = "Complete the game without dying"; - cheevos.push_back(c); - - c.id = 12; - c.caption = "SHIT PROJECTS DONE FAST"; - c.description = "Complete the game in under 30 minutes"; - cheevos.push_back(c); + cheevos_.clear(); + cheevos_.emplace_back(1, "SHINY THINGS", "Get 25% of the items", 2); + cheevos_.emplace_back(2, "HALF THE WORK", "Get 50% of the items", 2); + cheevos_.emplace_back(3, "GETTING THERE", "Get 75% of the items", 2); + cheevos_.emplace_back(4, "THE COLLECTOR", "Get 100% of the items", 2); + cheevos_.emplace_back(5, "WANDERING AROUND", "Visit 20 rooms", 2); + cheevos_.emplace_back(6, "I GOT LOST", "Visit 40 rooms", 2); + cheevos_.emplace_back(7, "I LIKE TO EXPLORE", "Visit all rooms", 2); + cheevos_.emplace_back(8, "FINISH THE GAME", "Complete the game", 2); + cheevos_.emplace_back(9, "I WAS SUCKED BY A HOLE", "Complete the game without entering the jail", 2); + cheevos_.emplace_back(10, "MY LITTLE PROJECTS", "Complete the game with all items", 2); + cheevos_.emplace_back(11, "I LIKE MY MULTICOLOURED FRIENDS", "Complete the game without dying", 2); + cheevos_.emplace_back(12, "SHIT PROJECTS DONE FAST", "Complete the game in under 30 minutes", 2); } // Busca un logro por id y devuelve el indice int Cheevos::find(int id) { - for (int i = 0; i < (int)cheevos.size(); ++i) + for (int i = 0; i < (int)cheevos_.size(); ++i) { - if (cheevos[i].id == id) + if (cheevos_[i].id == id) { return i; } @@ -123,80 +59,49 @@ void Cheevos::unlock(int id) { const int index = find(id); - if (index == -1) + // Si el índice es inválido, el logro no es válido, ya está completado o el sistema de logros no está habilitado, no hacemos nada + if (index == -1 || !cheevos_.at(index).valid || cheevos_.at(index).completed || !enabled_) { return; } - if (!cheevos[index].valid) - { - return; - } - - if (cheevos[index].completed) - { - return; - } - - if (!enabled) - { - return; - } - - cheevos[index].completed = true; - screen->showNotification("ACHIEVEMENT UNLOCKED!", cheevos[index].caption, cheevos[index].icon); - save(); + // Marcar el logro como completado + cheevos_.at(index).completed = true; + // Mostrar notificación en la pantalla + Notifier::get()->show("ACHIEVEMENT UNLOCKED!", cheevos_.at(index).caption, cheevos_.at(index).icon); + // Guardar el estado de los logros + saveToFile(); } // Invalida un logro void Cheevos::invalidate(int id) { const int index = find(id); - if (index == -1) + + // Si el índice es válido, se invalida el logro + if (index != -1) { - return; + cheevos_.at(index).valid = false; } - cheevos[index].valid = false; -} - -// Habilita o deshabilita los logros -void Cheevos::enable(bool value) -{ - enabled = value; -} - -// Carga el estado de los logros -void Cheevos::load() -{ - // Carga el estado de los logros desde un fichero - loadFromFile(); -} - -// Guarda el estado de los logros -void Cheevos::save() -{ - // Guarda el estado de los logros en un fichero - saveToFile(); } // Carga el estado de los logros desde un fichero void Cheevos::loadFromFile() { - // Abre el fichero en modo lectura (binario) - SDL_RWops *file = SDL_RWFromFile(this->file.c_str(), "r+b"); + std::ifstream file(this->file_, std::ios::binary); // El fichero no existe - if (file == NULL) + if (!file) { if (options.console) { - std::cout << "Warning: Unable to open file! SDL Error: " << SDL_GetError() << std::endl; + std::cout << "Warning: Unable to open file! Creating new file..." << std::endl; } // Crea el fichero en modo escritura (binario) - file = SDL_RWFromFile(this->file.c_str(), "w+b"); + std::ofstream newFile(this->file_, std::ios::binary); - if (file != NULL) + if (newFile) { if (options.console) { @@ -204,37 +109,32 @@ void Cheevos::loadFromFile() } // Guarda la información - for (int i = 0; i < (int)cheevos.size(); ++i) + for (const auto &cheevo : cheevos_) { - SDL_RWwrite(file, &cheevos[i].completed, sizeof(bool), 1); + newFile.write(reinterpret_cast(&cheevo.completed), sizeof(bool)); } - - // Cierra el fichero - SDL_RWclose(file); } else { if (options.console) { - std::cout << "Error: Unable to create file! SDL Error: " << SDL_GetError() << std::endl; + std::cerr << "Error: Unable to create file!" << std::endl; } } } // El fichero existe else { - // Carga los datos if (options.console) { std::cout << "Reading file...!" << std::endl; } - for (int i = 0; i < (int)cheevos.size(); ++i) - { - SDL_RWread(file, &cheevos[i].completed, sizeof(bool), 1); - } - // Cierra el fichero - SDL_RWclose(file); + // Carga los datos + for (auto &cheevo : cheevos_) + { + file.read(reinterpret_cast(&cheevo.completed), sizeof(bool)); + } } } @@ -242,13 +142,13 @@ void Cheevos::loadFromFile() void Cheevos::saveToFile() { // Abre el fichero en modo escritura (binario) - SDL_RWops *file = SDL_RWFromFile(this->file.c_str(), "w+b"); + SDL_RWops *file = SDL_RWFromFile(this->file_.c_str(), "w+b"); if (file != NULL) { // Guarda la información - for (int i = 0; i < (int)cheevos.size(); ++i) + for (int i = 0; i < (int)cheevos_.size(); ++i) { - SDL_RWwrite(file, &cheevos[i].completed, sizeof(bool), 1); + SDL_RWwrite(file, &cheevos_[i].completed, sizeof(bool), 1); } // Cierra el fichero @@ -263,32 +163,16 @@ void Cheevos::saveToFile() } } -// Lista los logros -std::vector Cheevos::list() -{ - return cheevos; -} - // Devuelve el número total de logros desbloqueados int Cheevos::unlocked() { int count = 0; - for (auto cheevo : cheevos) + for (auto cheevo : cheevos_) { if (cheevo.completed) + { count++; + } } return count; -} - -// Devuelve el número total de logros -int Cheevos::count() -{ - return cheevos.size(); -} - -// Vuelve a cargar los logros desde el origen -void Cheevos::reload() -{ - load(); } \ No newline at end of file diff --git a/source/cheevos.h b/source/cheevos.h index 730f1c5..5aef832 100644 --- a/source/cheevos.h +++ b/source/cheevos.h @@ -1,11 +1,11 @@ #pragma once - #include // Para string #include // Para vector class Screen; struct options_t; -struct cheevos_t +// Struct para los logros +struct Achievement { int id; // Identificador del logro std::string caption; // Texto con el nombre del logro @@ -13,31 +13,29 @@ struct cheevos_t int icon; // Indice del icono a utilizar en la notificación bool completed; // Indica si se ha obtenido el logro bool valid; // Indica si se puede obtener el logro + + // Constructor vacío + Achievement() : id(0), icon(0), completed(false), valid(true) {} + + // Constructor parametrizado + Achievement(int id, const std::string &caption, const std::string &description, int icon, bool completed = false, bool valid = true) + : id(id), caption(caption), description(description), icon(icon), completed(completed), valid(valid) {} }; class Cheevos { private: - // Punteros y objetos - Screen *screen; // Objeto encargado de dibujar en pantalla - // Variables - std::vector cheevos; // Listado de logros - bool enabled; // Indica si los logros se pueden obtener - std::string file; // Fichero done leer/almacenar el estado de los logros + std::vector cheevos_; // Listado de logros + bool enabled_ = true; // Indica si los logros se pueden obtener + std::string file_; // Fichero donde leer/almacenar el estado de los logros // Inicializa los logros void init(); - // Busca un logro por id y devuelve el indice + // Busca un logro por id y devuelve el índice int find(int id); - // Carga el estado de los logros - void load(); - - // Guarda el estado de los logros - void save(); - // Carga el estado de los logros desde un fichero void loadFromFile(); @@ -46,7 +44,7 @@ private: public: // Constructor - Cheevos(Screen *screen, std::string file); + Cheevos(const std::string &file); // Destructor ~Cheevos(); @@ -58,17 +56,14 @@ public: void invalidate(int id); // Habilita o deshabilita los logros - void enable(bool value); + void enable(bool value) { enabled_ = value; } // Lista los logros - std::vector list(); + std::vector list() { return cheevos_; } // Devuelve el número total de logros desbloqueados int unlocked(); // Devuelve el número total de logros - int count(); - - // Vuelve a cargar los logros desde el origen - void reload(); -}; \ No newline at end of file + int count() { return cheevos_.size(); } +}; diff --git a/source/credits.cpp b/source/credits.cpp index 9d47a66..c939c1e 100644 --- a/source/credits.cpp +++ b/source/credits.cpp @@ -17,10 +17,10 @@ class Asset; // Constructor -Credits::Credits(Resource *resource) +Credits::Credits() : screen_(Screen::get()), renderer_(Screen::get()->getRenderer()), - resource_(resource), + resource_(Resource::get()), asset_(Asset::get()), input_(Input::get()) { @@ -308,8 +308,7 @@ void Credits::update() // Actualiza el contador updateCounter(); - // Actualiza las notificaciones - screen_->updateNotifier(); + screen_->update(); // Actualiza el sprite con el brillo if (counter_ > 770) diff --git a/source/credits.h b/source/credits.h index 6e1e08a..cd26b31 100644 --- a/source/credits.h +++ b/source/credits.h @@ -68,7 +68,7 @@ private: public: // Constructor - Credits(Resource *resource); + Credits(); // Destructor ~Credits(); diff --git a/source/debug.cpp b/source/debug.cpp index c9264e6..89b992f 100644 --- a/source/debug.cpp +++ b/source/debug.cpp @@ -7,6 +7,27 @@ #include "screen.h" #include "asset.h" +// [SINGLETON] +Debug *Debug::debug_ = nullptr; + +// [SINGLETON] Crearemos el objeto con esta función estática +void Debug::init() +{ + Debug::debug_ = new Debug(); +} + +// [SINGLETON] Destruiremos el objeto con esta función estática +void Debug::destroy() +{ + delete Debug::debug_; +} + +// [SINGLETON] Con este método obtenemos el objeto y podemos trabajar con él +Debug *Debug::get() +{ + return Debug::debug_; +} + // Constructor Debug::Debug() // Copia la dirección de los objetos diff --git a/source/debug.h b/source/debug.h index bb008d4..23b3fdd 100644 --- a/source/debug.h +++ b/source/debug.h @@ -13,6 +13,9 @@ class Texture; class Debug { private: + // [SINGLETON] Objeto privado + static Debug *debug_; + // Objetos y punteros Screen *screen_; // Objeto encargado de dibujar en pantalla SDL_Renderer *renderer_; // El renderizador de la ventana @@ -23,17 +26,26 @@ private: // Variables std::vector slot_; // Vector con los textos a escribir std::vector log_; // Vector con los textos a escribir - int x_ = 0; // Posicion donde escribir el texto de debug - int y_ = 0; // Posición donde escribir el texto de debug - bool enabled_ = false; // Indica si esta activo el modo debug + int x_ = 0; // Posicion donde escribir el texto de debug + int y_ = 0; // Posición donde escribir el texto de debug + bool enabled_ = false; // Indica si esta activo el modo debug -public: // Constructor Debug(); // Destructor ~Debug(); +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 Debug *get(); + // Actualiza las variables void update(); diff --git a/source/demo.cpp b/source/demo.cpp index 80ade83..5bfe9f4 100644 --- a/source/demo.cpp +++ b/source/demo.cpp @@ -12,10 +12,16 @@ #include "text.h" // Para Text, TXT_CENTER, TXT_COLOR #include "utils.h" // Para color_t, stringToColor, options_t, secti... #include "options.h" -class Debug; +#include "debug.h" // Constructor -Demo::Demo(Resource *resource, Debug *debug) +Demo::Demo() + : screen(Screen::get()), + renderer(Screen::get()->getRenderer()), + resource(Resource::get()), + asset(Asset::get()), + input(Input::get()), + debug(Debug::get()) { // Inicia algunas variables board.iniClock = SDL_GetTicks(); @@ -31,18 +37,10 @@ Demo::Demo(Resource *resource, Debug *debug) roomIndex = 0; currentRoom = rooms[roomIndex]; - // Copia los punteros - this->resource = resource; - this->screen = Screen::get(); - this->renderer = Screen::get()->getRenderer(); - this->asset = Asset::get(); - this->input = Input::get(); - this->debug = debug; - // Crea los objetos itemTracker = new ItemTracker(); - scoreboard = new ScoreBoard(renderer, resource, asset, &board); - room = new Room(resource->getRoom(currentRoom), renderer, screen, asset, itemTracker, &board.items, false, debug); + scoreboard = new Scoreboard(&board); + room = new Room(resource->getRoom(currentRoom), itemTracker, &board.items, false); eventHandler = new SDL_Event(); text = new Text(resource->getOffset("smb2.txt"), resource->getTexture("smb2.png"), renderer); @@ -162,8 +160,7 @@ void Demo::update() screen->updateFX(); checkRoomChange(); - // Actualiza las notificaciones - screen->updateNotifier(); + screen->update(); } } @@ -242,7 +239,7 @@ bool Demo::changeRoom(std::string file) room = nullptr; // Crea un objeto habitación nuevo a partir del fichero - room = new Room(resource->getRoom(file), renderer, screen, asset, itemTracker, &board.items, false, debug); + room = new Room(resource->getRoom(file), itemTracker, &board.items, false); // Pone el color del marcador en función del color del borde de la habitación setScoreBoardColor(); diff --git a/source/demo.h b/source/demo.h index 756019e..7ecd8b0 100644 --- a/source/demo.h +++ b/source/demo.h @@ -21,15 +21,15 @@ class Demo { private: // Objetos y punteros + Screen *screen; // Objeto encargado de manejar el renderizador SDL_Renderer *renderer; // El renderizador de la ventana SDL_Event *eventHandler; // Manejador de eventos - Screen *screen; // Objeto encargado de manejar el renderizador Room *room; // Objeto encargado de gestionar cada habitación del juego Resource *resource; // Objeto con los recursos Asset *asset; // Objeto con la ruta a todos los ficheros de recursos Input *input; // Objeto pata gestionar la entrada Text *text; // Objeto para los textos del juego - ScoreBoard *scoreboard; // Objeto encargado de gestionar el marcador + Scoreboard *scoreboard; // Objeto encargado de gestionar el marcador ItemTracker *itemTracker; // Lleva el control de los objetos recogidos Debug *debug; // Objeto para gestionar la información de debug @@ -75,7 +75,7 @@ private: public: // Constructor - Demo(Resource *resource, Debug *debug); + Demo(); // Destructor ~Demo(); diff --git a/source/director.cpp b/source/director.cpp index 1061f75..e150f73 100644 --- a/source/director.cpp +++ b/source/director.cpp @@ -84,11 +84,11 @@ Director::Director(int argc, const char *argv[]) // Crea los objetos Screen::init(window_, renderer_); Screen::get()->setBorderColor(borderColor); + Resource::init(); Notifier::init(Asset::get()->get("notify.png"), Asset::get()->get("smb2.png"), Asset::get()->get("smb2.txt"), Asset::get()->get("notify.wav")); - resource_ = new Resource(); Input::init(Asset::get()->get("gamecontrollerdb.txt")); initInput(); - debug_ = new Debug(); + Debug::init(); title_music_ = JA_LoadMusic(Asset::get()->get("title.ogg").c_str()); } @@ -97,13 +97,14 @@ Director::~Director() // Guarda las opciones a un fichero saveOptionsFromFile(Asset::get()->get("config.txt")); - // Libera la memoria + // Destruye los singletones Asset::destroy(); Input::destroy(); Screen::destroy(); Notifier::destroy(); - delete debug_; - delete resource_; + Debug::destroy(); + Resource::destroy(); + JA_DeleteMusic(title_music_); SDL_DestroyRenderer(renderer_); @@ -223,7 +224,7 @@ void Director::loadResources(section_t section) textureList.push_back("jailgames.png"); textureList.push_back("since_1998.png"); - resource_->loadTextures(textureList); + Resource::get()->loadTextures(textureList); } else if (options.section.name == SECTION_LOADING_SCREEN) @@ -234,7 +235,7 @@ void Director::loadResources(section_t section) textureList.push_back("loading_screen_bn_zxarne.png"); textureList.push_back("loading_screen_color_zxarne.png"); - resource_->loadTextures(textureList); + Resource::get()->loadTextures(textureList); } else if (options.section.name == SECTION_TITLE) @@ -247,14 +248,14 @@ void Director::loadResources(section_t section) textureList.push_back("notify.png"); textureList.push_back("title_logo.png"); - resource_->loadTextures(textureList); + Resource::get()->loadTextures(textureList); // Offsets std::vector offsetsList; offsetsList.push_back("smb2.txt"); offsetsList.push_back("subatomic.txt"); - resource_->loadOffsets(offsetsList); + Resource::get()->loadOffsets(offsetsList); } else if (options.section.name == SECTION_CREDITS) @@ -264,19 +265,19 @@ void Director::loadResources(section_t section) textureList.push_back("shine.png"); textureList.push_back("smb2.png"); - resource_->loadTextures(textureList); + Resource::get()->loadTextures(textureList); // Animaciones std::vector animationList; animationList.push_back("shine.ani"); - resource_->loadAnimations(animationList); + Resource::get()->loadAnimations(animationList); // Offsets std::vector offsetsList; offsetsList.push_back("smb2.txt"); - resource_->loadOffsets(offsetsList); + Resource::get()->loadOffsets(offsetsList); } else if (options.section.name == SECTION_ENDING) @@ -295,13 +296,13 @@ void Director::loadResources(section_t section) textureList.push_back("ending5_zxarne.png"); textureList.push_back("smb2.png"); - resource_->loadTextures(textureList); + Resource::get()->loadTextures(textureList); // Offsets std::vector offsetsList; offsetsList.push_back("smb2.txt"); - resource_->loadOffsets(offsetsList); + Resource::get()->loadOffsets(offsetsList); } else if (options.section.name == SECTION_ENDING2) @@ -370,7 +371,7 @@ void Director::loadResources(section_t section) // Player textureList.push_back("player.png"); - resource_->loadTextures(textureList); + Resource::get()->loadTextures(textureList); // Animaciones std::vector animationList; @@ -433,13 +434,13 @@ void Director::loadResources(section_t section) // Player animationList.push_back("player.ani"); - resource_->loadAnimations(animationList); + Resource::get()->loadAnimations(animationList); // Offsets std::vector offsetsList; offsetsList.push_back("smb2.txt"); - resource_->loadOffsets(offsetsList); + Resource::get()->loadOffsets(offsetsList); } else if (options.section.name == SECTION_GAME_OVER) @@ -450,20 +451,20 @@ void Director::loadResources(section_t section) textureList.push_back("player_game_over.png"); textureList.push_back("tv.png"); - resource_->loadTextures(textureList); + Resource::get()->loadTextures(textureList); // Animaciones std::vector animationList; animationList.push_back("player_game_over.ani"); animationList.push_back("tv.ani"); - resource_->loadAnimations(animationList); + Resource::get()->loadAnimations(animationList); // Offsets std::vector offsetsList; offsetsList.push_back("smb2.txt"); - resource_->loadOffsets(offsetsList); + Resource::get()->loadOffsets(offsetsList); } else if (options.section.name == SECTION_GAME || options.section.name == SECTION_DEMO) @@ -551,7 +552,7 @@ void Director::loadResources(section_t section) textureList.push_back("smb2.png"); textureList.push_back("debug.png"); - resource_->loadTextures(textureList); + Resource::get()->loadTextures(textureList); // Animaciones std::vector animationList; @@ -625,14 +626,14 @@ void Director::loadResources(section_t section) animationList.push_back("wave.ani"); animationList.push_back("z80.ani"); - resource_->loadAnimations(animationList); + Resource::get()->loadAnimations(animationList); // Offsets std::vector offsetsList; offsetsList.push_back("smb2.txt"); offsetsList.push_back("debug.txt"); - resource_->loadOffsets(offsetsList); + Resource::get()->loadOffsets(offsetsList); // TileMaps std::vector tileMapList; @@ -697,7 +698,7 @@ void Director::loadResources(section_t section) tileMapList.push_back("59.tmx"); tileMapList.push_back("60.tmx"); - resource_->loadTileMaps(tileMapList); + Resource::get()->loadTileMaps(tileMapList); // Habitaciones std::vector roomList; @@ -762,7 +763,7 @@ void Director::loadResources(section_t section) roomList.push_back("59.room"); roomList.push_back("60.room"); - resource_->loadRooms(roomList); + Resource::get()->loadRooms(roomList); } if (options.console) @@ -1305,9 +1306,9 @@ void Director::runLogo() std::cout << "\n* SECTION: LOGO" << std::endl; } loadResources(options.section); - auto logo = std::make_unique(resource_); + auto logo = std::make_unique(); logo->run(); - resource_->free(); + Resource::get()->free(); } // Ejecuta la seccion de juego de la pantalla de carga @@ -1318,9 +1319,9 @@ void Director::runLoadingScreen() std::cout << "\n* SECTION: INTRO" << std::endl; } loadResources(options.section); - auto loadingScreen = std::make_unique(resource_); + auto loadingScreen = std::make_unique(); loadingScreen->run(); - resource_->free(); + Resource::get()->free(); } // Ejecuta la seccion de juego con el titulo y los menus @@ -1335,9 +1336,9 @@ void Director::runTitle() JA_PlayMusic(title_music_); } loadResources(options.section); - auto title = std::make_unique(resource_); + auto title = std::make_unique<Title>(); title->run(); - resource_->free(); + Resource::get()->free(); } // Ejecuta la seccion de los creditos del juego @@ -1348,9 +1349,9 @@ void Director::runCredits() std::cout << "\n* SECTION: CREDITS" << std::endl; } loadResources(options.section); - auto credits = std::make_unique<Credits>(resource_); + auto credits = std::make_unique<Credits>(); credits->run(); - resource_->free(); + Resource::get()->free(); } // Ejecuta la seccion de la demo, donde se ven pantallas del juego @@ -1361,9 +1362,9 @@ void Director::runDemo() std::cout << "\n* SECTION: DEMO" << std::endl; } loadResources(options.section); - auto demo = std::make_unique<Demo>(resource_, debug_); + auto demo = std::make_unique<Demo>(); demo->run(); - resource_->free(); + Resource::get()->free(); } // Ejecuta la seccion del final del juego @@ -1374,9 +1375,9 @@ void Director::runEnding() std::cout << "\n* SECTION: ENDING" << std::endl; } loadResources(options.section); - auto ending = std::make_unique<Ending>(resource_); + auto ending = std::make_unique<Ending>(); ending->run(); - resource_->free(); + Resource::get()->free(); } // Ejecuta la seccion del final del juego @@ -1387,9 +1388,9 @@ void Director::runEnding2() std::cout << "\n* SECTION: ENDING2" << std::endl; } loadResources(options.section); - auto ending2 = std::make_unique<Ending2>(resource_); + auto ending2 = std::make_unique<Ending2>(); ending2->run(); - resource_->free(); + Resource::get()->free(); } // Ejecuta la seccion del final de la partida @@ -1400,9 +1401,9 @@ void Director::runGameOver() std::cout << "\n* SECTION: GAME OVER" << std::endl; } loadResources(options.section); - auto gameOver = std::make_unique<GameOver>(resource_); + auto gameOver = std::make_unique<GameOver>(); gameOver->run(); - resource_->free(); + Resource::get()->free(); } // Ejecuta la seccion de juego donde se juega @@ -1414,9 +1415,9 @@ void Director::runGame() } JA_StopMusic(); loadResources(options.section); - auto game = std::make_unique<Game>(resource_, debug_); + auto game = std::make_unique<Game>(); game->run(); - resource_->free(); + Resource::get()->free(); } int Director::run() diff --git a/source/director.h b/source/director.h index d60d736..da21cde 100644 --- a/source/director.h +++ b/source/director.h @@ -19,9 +19,6 @@ private: SDL_Window *window_; // La ventana donde dibujamos SDL_Renderer *renderer_; // El renderizador de la ventana - Resource *resource_; // Objeto con los recursos - Debug *debug_; // Objeto para gestionar la información de debug - // Variables JA_Music_t *title_music_; // Musica del titulo std::string executable_path_; // Path del ejecutable diff --git a/source/ending.cpp b/source/ending.cpp index edef810..bc07509 100644 --- a/source/ending.cpp +++ b/source/ending.cpp @@ -19,15 +19,13 @@ #include "options.h" // Constructor -Ending::Ending(Resource *resource) +Ending::Ending() + : screen(Screen::get()), + renderer(Screen::get()->getRenderer()), + resource(Resource::get()), + asset(Asset::get()), + input(Input::get()) { - // Copia los punteros - this->screen = Screen::get(); - this->renderer = Screen::get()->getRenderer(); - this->resource = resource; - this->asset = Asset::get(); - this->input = Input::get(); - // Reserva memoria para los punteros a objetos eventHandler = new SDL_Event(); text = new Text(resource->getOffset("smb2.txt"), resource->getTexture("smb2.png"), renderer); @@ -122,8 +120,7 @@ void Ending::update() // Actualiza el volumen de la musica updateMusicVolume(); - // Actualiza las notificaciones - screen->updateNotifier(); + screen->update(); } } diff --git a/source/ending.h b/source/ending.h index ad7a405..99a9ded 100644 --- a/source/ending.h +++ b/source/ending.h @@ -50,8 +50,8 @@ private: }; // Objetos y punteros - SDL_Renderer *renderer; // El renderizador de la ventana Screen *screen; // Objeto encargado de dibujar en pantalla + SDL_Renderer *renderer; // El renderizador de la ventana Resource *resource; // Objeto con los recursos Asset *asset; // Objeto con los ficheros de recursos Input *input; // Objeto pata gestionar la entrada @@ -115,7 +115,7 @@ private: public: // Constructor - Ending(Resource *resource); + Ending(); // Destructor ~Ending(); diff --git a/source/ending2.cpp b/source/ending2.cpp index 9ef74c2..5ee7636 100644 --- a/source/ending2.cpp +++ b/source/ending2.cpp @@ -16,15 +16,13 @@ #include "options.h" // Constructor -Ending2::Ending2(Resource *resource) +Ending2::Ending2() + : screen(Screen::get()), + renderer(Screen::get()->getRenderer()), + resource(Resource::get()), + asset(Asset::get()), + input(Input::get()) { - // Copia los punteros - this->screen = Screen::get(); - this->renderer = Screen::get()->getRenderer(); - this->resource = resource; - this->asset = Asset::get(); - this->input = Input::get(); - // Reserva memoria para los punteros a objetos eventHandler = new SDL_Event(); text = new Text(resource->getOffset("smb2.txt"), resource->getTexture("smb2.png"), renderer); @@ -117,8 +115,7 @@ void Ending2::update() // Actualiza el volumen de la musica updateMusicVolume(); - // Actualiza las notificaciones - screen->updateNotifier(); + screen->update(); } } diff --git a/source/ending2.h b/source/ending2.h index c0c82b0..70816a7 100644 --- a/source/ending2.h +++ b/source/ending2.h @@ -21,12 +21,12 @@ class Ending2 { private: // Objetos y punteros - Asset *asset; // Objeto con los ficheros de recursos - Resource *resource; // Objeto con los recursos Screen *screen; // Objeto encargado de dibujar en pantalla - SDL_Event *eventHandler; // Manejador de eventos SDL_Renderer *renderer; // El renderizador de la ventana + Resource *resource; // Objeto con los recursos + Asset *asset; // Objeto con los ficheros de recursos Input *input; // Objeto pata gestionar la entrada + SDL_Event *eventHandler; // Manejador de eventos Text *text; // Objeto para escribir texto en pantalla std::vector<AnimatedSprite *> sprites; // Vector con todos los sprites a dibujar std::vector<MovingSprite *> spriteTexts; // Vector con los sprites de texto de los sprites @@ -118,7 +118,7 @@ private: public: // Constructor - Ending2(Resource *resource); + Ending2(); // Destructor ~Ending2(); diff --git a/source/game.cpp b/source/game.cpp index b3ed848..e7ce002 100644 --- a/source/game.cpp +++ b/source/game.cpp @@ -21,15 +21,16 @@ #include "text.h" // for Text, TXT_CENTER, TXT_COLOR #include "utils.h" // for options_t, cheat_t, stringToColor #include "options.h" +#include "notifier.h" // Constructor -Game::Game(Resource *resource, Debug *debug) +Game::Game() : screen_(Screen::get()), renderer_(Screen::get()->getRenderer()), asset_(Asset::get()), input_(Input::get()), - resource_(resource), - debug_(debug) + resource_(Resource::get()), + debug_(Debug::get()) { // Inicia algunas variables board_.iniClock = SDL_GetTicks(); @@ -38,7 +39,7 @@ Game::Game(Resource *resource, Debug *debug) const int x = 25; const int y = 13; spawn_point_ = {x * 8, y * 8, 0, 0, 0, s_standing, SDL_FLIP_HORIZONTAL}; - debug->setEnabled(false); + debug_->setEnabled(false); #else current_room_ = "03.room"; const int x = 25; @@ -47,17 +48,17 @@ Game::Game(Resource *resource, Debug *debug) #endif // Crea los objetos - cheevos_ = new Cheevos(screen_, asset_->get("cheevos.bin")); - scoreboard_ = new ScoreBoard(renderer_, resource, asset_, &board_); + cheevos_ = new Cheevos(asset_->get("cheevos.bin")); + scoreboard_ = new Scoreboard(&board_); item_tracker_ = new ItemTracker(); room_tracker_ = new RoomTracker(); - room_ = new Room(resource->getRoom(current_room_), renderer_, screen_, asset_, item_tracker_, &board_.items, false, debug); + room_ = new Room(resource_->getRoom(current_room_), item_tracker_, &board_.items, false); const std::string playerPNG = options.cheat.altSkin ? "player2.png" : "player.png"; const std::string playerANI = options.cheat.altSkin ? "player2.ani" : "player.ani"; - const player_t player = {spawn_point_, playerPNG, playerANI, renderer_, resource, asset_, input_, room_, debug}; + const player_t player = {spawn_point_, playerPNG, playerANI, room_}; this->player_ = new Player(player); event_handler_ = new SDL_Event(); - text_ = new Text(resource->getOffset("smb2.txt"), resource->getTexture("smb2.png"), renderer_); + text_ = new Text(resource_->getOffset("smb2.txt"), resource_->getTexture("smb2.png"), renderer_); music_ = JA_LoadMusic(asset_->get("game.ogg").c_str()); death_sound_ = JA_LoadSound(asset_->get("death.wav").c_str()); stats_ = new Stats(asset_->get("stats.csv"), asset_->get("stats_buffer.csv")); @@ -178,19 +179,19 @@ void Game::checkEvents() break; case SDL_SCANCODE_F6: - screen_->showNotification("ACHIEVEMENT UNLOCKED!", "I LIKE MY MULTICOLOURED FRIENDS", 2); + Notifier::get()->show("ACHIEVEMENT UNLOCKED!", "I LIKE MY MULTICOLOURED FRIENDS", 2); break; case SDL_SCANCODE_F7: - screen_->showNotification("ACHIEVEMENT UNLOCKED!", "I LIKE MY MULTICOLOURED FRIENDS", 3); + Notifier::get()->show("ACHIEVEMENT UNLOCKED!", "I LIKE MY MULTICOLOURED FRIENDS", 3); break; case SDL_SCANCODE_F8: - screen_->showNotification("JAILDESIGNER IS LOGGED IN", "", 4); + Notifier::get()->show("JAILDESIGNER IS LOGGED IN", "", 4); break; case SDL_SCANCODE_F9: - screen_->showNotification("JAILDESIGNER IS LOGGED IN", "", 5); + Notifier::get()->show("JAILDESIGNER IS LOGGED IN", "", 5); break; #endif default: @@ -305,8 +306,7 @@ void Game::update() updateBlackScreen(); - // Actualiza las notificaciones - screen_->updateNotifier(); + screen_->update(); #ifdef DEBUG updateDebugInfo(); @@ -401,7 +401,7 @@ bool Game::changeRoom(std::string file) room_ = nullptr; // Crea un objeto habitación nuevo a partir del fichero - room_ = new Room(resource_->getRoom(file), renderer_, screen_, asset_, item_tracker_, &board_.items, board_.jailEnabled, debug_); + room_ = new Room(resource_->getRoom(file), item_tracker_, &board_.items, board_.jailEnabled); // Pone el nombre de la habitación en la textura fillRoomNameTexture(); @@ -509,10 +509,10 @@ void Game::killPlayer() setBlackScreen(); // Crea la nueva habitación y el nuevo jugador - room_ = new Room(resource_->getRoom(current_room_), renderer_, screen_, asset_, item_tracker_, &board_.items, board_.jailEnabled, debug_); + room_ = new Room(resource_->getRoom(current_room_),item_tracker_, &board_.items, board_.jailEnabled); const std::string playerPNG = options.cheat.altSkin ? "player2.png" : "player.png"; const std::string playerANI = options.cheat.altSkin ? "player2.ani" : "player.ani"; - const player_t player = {spawn_point_, playerPNG, playerANI, renderer_, resource_, asset_, input_, room_, debug_}; + const player_t player = {spawn_point_, playerPNG, playerANI, room_}; this->player_ = new Player(player); // Pone los objetos en pausa mientras esta la habitación en negro diff --git a/source/game.h b/source/game.h index c47f7ff..84e5b67 100644 --- a/source/game.h +++ b/source/game.h @@ -37,7 +37,7 @@ private: Asset *asset_; // Objeto con la ruta a todos los ficheros de recursos Input *input_; // Objeto pata gestionar la entrada Text *text_; // Objeto para los textos del juego - ScoreBoard *scoreboard_; // Objeto encargado de gestionar el marcador + Scoreboard *scoreboard_; // Objeto encargado de gestionar el marcador Cheevos *cheevos_; // Objeto encargado de gestionar los logros del juego Resource *resource_; // Objeto con los recursos Debug *debug_; // Objeto para gestionar la información de debug @@ -149,7 +149,7 @@ private: public: // Constructor - Game(Resource *resource, Debug *debug); + Game(); // Destructor ~Game(); diff --git a/source/game_over.cpp b/source/game_over.cpp index 2a839bd..88ee0ee 100644 --- a/source/game_over.cpp +++ b/source/game_over.cpp @@ -14,15 +14,13 @@ #include "options.h" // Constructor -GameOver::GameOver(Resource *resource) +GameOver::GameOver() + : screen(Screen::get()), + renderer(Screen::get()->getRenderer()), + resource(Resource::get()), + asset(Asset::get()), + input(Input::get()) { - // Copia los punteros - this->screen = Screen::get(); - this->renderer = Screen::get()->getRenderer(); - this->resource = resource; - this->asset = Asset::get(); - this->input = Input::get(); - // Reserva memoria para los punteros a objetos eventHandler = new SDL_Event(); text = new Text(resource->getOffset("smb2.txt"), resource->getTexture("smb2.png"), renderer); @@ -87,8 +85,7 @@ void GameOver::update() playerSprite->update(); tvSprite->update(); - // Actualiza las notificaciones - screen->updateNotifier(); + screen->update(); } } diff --git a/source/game_over.h b/source/game_over.h index 96913fa..93f6d50 100644 --- a/source/game_over.h +++ b/source/game_over.h @@ -17,8 +17,8 @@ class GameOver { private: // Objetos y punteros - SDL_Renderer *renderer; // El renderizador de la ventana Screen *screen; // Objeto encargado de dibujar en pantalla + SDL_Renderer *renderer; // El renderizador de la ventana Resource *resource; // Objeto con los recursos Asset *asset; // Objeto con los ficheros de recursos Input *input; // Objeto pata gestionar la entrada @@ -65,7 +65,7 @@ private: public: // Constructor - GameOver(Resource *resource); + GameOver(); // Destructor ~GameOver(); diff --git a/source/loading_screen.cpp b/source/loading_screen.cpp index baa69b1..8aef1f9 100644 --- a/source/loading_screen.cpp +++ b/source/loading_screen.cpp @@ -13,10 +13,10 @@ #include "options.h" // Constructor -LoadingScreen::LoadingScreen(Resource *resource) +LoadingScreen::LoadingScreen() : screen_(Screen::get()), renderer_(Screen::get()->getRenderer()), - resource_(resource), + resource_(Resource::get()), asset_(Asset::get()), input_(Input::get()) { @@ -24,13 +24,13 @@ LoadingScreen::LoadingScreen(Resource *resource) eventHandler = new SDL_Event(); if (options.palette == p_zxspectrum) { - mono_loading_screen_texture_ = resource->getTexture("loading_screen_bn.png"); - color_loading_screen_texture_ = resource->getTexture("loading_screen_color.png"); + mono_loading_screen_texture_ = resource_->getTexture("loading_screen_bn.png"); + color_loading_screen_texture_ = resource_->getTexture("loading_screen_color.png"); } else if (options.palette == p_zxarne) { - mono_loading_screen_texture_ = resource->getTexture("loading_screen_bn_zxarne.png"); - color_loading_screen_texture_ = resource->getTexture("loading_screen_color_zxarne.png"); + mono_loading_screen_texture_ = resource_->getTexture("loading_screen_bn_zxarne.png"); + color_loading_screen_texture_ = resource_->getTexture("loading_screen_color_zxarne.png"); } mono_loading_screen_sprite_ = new Sprite(0, 0, mono_loading_screen_texture_->getWidth(), mono_loading_screen_texture_->getHeight(), mono_loading_screen_texture_, renderer_); color_loading_screen_sprite_ = new Sprite(0, 0, color_loading_screen_texture_->getWidth(), color_loading_screen_texture_->getHeight(), color_loading_screen_texture_, renderer_); @@ -251,8 +251,7 @@ void LoadingScreen::update() // Gestiona el contador de carga updateLoad(); - // Actualiza las notificaciones - screen_->updateNotifier(); + screen_->update(); } } diff --git a/source/loading_screen.h b/source/loading_screen.h index 44dcfbc..4f0d0d7 100644 --- a/source/loading_screen.h +++ b/source/loading_screen.h @@ -74,7 +74,7 @@ private: public: // Constructor - LoadingScreen(Resource *resource); + LoadingScreen(); // Destructor ~LoadingScreen(); diff --git a/source/logo.cpp b/source/logo.cpp index a64f166..935d46d 100644 --- a/source/logo.cpp +++ b/source/logo.cpp @@ -14,10 +14,10 @@ class Asset; // lines 11-11 // Constructor -Logo::Logo(Resource *resource) +Logo::Logo() : screen_(Screen::get()), renderer_(Screen::get()->getRenderer()), - resource_(resource), + resource_(Resource::get()), asset_(Asset::get()), input_(Input::get()) { @@ -268,8 +268,7 @@ void Logo::update() // Gestiona el color de las texturas updateTextureColors(); - // Actualiza las notificaciones - screen_->updateNotifier(); + screen_->update(); // Comprueba si ha terminado el logo if (counter_ == end_logo_ + post_logo_) diff --git a/source/logo.h b/source/logo.h index 2dae539..6c654e5 100644 --- a/source/logo.h +++ b/source/logo.h @@ -64,7 +64,7 @@ private: public: // Constructor - Logo(Resource *resource); + Logo(); // Destructor ~Logo(); diff --git a/source/menu.cpp b/source/menu.cpp deleted file mode 100644 index 757f6ae..0000000 --- a/source/menu.cpp +++ /dev/null @@ -1,990 +0,0 @@ -#include "menu.h" -#include <algorithm> // Para max -#include <fstream> // Para char_traits, basic_ostream, operator<<, basi... -#include <iostream> // Para cout -#include <sstream> // Para basic_stringstream -#include "asset.h" // Para Asset -#include "input.h" // Para Input, REPEAT_FALSE, inputs_e -#include "jail_audio.h" // Para JA_LoadSound, JA_PlaySound, JA_DeleteSound -#include "resource.h" // Para Resource -#include "text.h" // Para Text - -// Constructor -Menu::Menu(SDL_Renderer *renderer, Resource *resource, Asset *asset, Input *input, std::string file) -{ - // Copia punteros - this->renderer = renderer; - this->asset = asset; - this->input = input; - - // Inicializa punteros - soundMove = nullptr; - soundAccept = nullptr; - soundCancel = nullptr; - - // Inicializa variables - name = ""; - selector.index = 0; - itemSelected = MENU_NO_OPTION; - x = 0; - y = 0; - w = 0; - rectBG.rect = {0, 0, 0, 0}; - rectBG.color = {0, 0, 0}; - rectBG.a = 0; - backgroundType = MENU_BACKGROUND_SOLID; - isCenteredOnX = false; - isCenteredOnY = false; - areElementsCenteredOnX = false; - centerX = 0; - centerY = 0; - widestItem = 0; - colorGreyed = {128, 128, 128}; - defaultActionWhenCancel = 0; - font_png = ""; - font_txt = ""; - - // Selector - selector.originY = 0; - selector.targetY = 0; - selector.despY = 0; - selector.originH = 0; - selector.targetH = 0; - selector.incH = 0; - selector.y = 0.0f; - selector.h = 0.0f; - selector.numJumps = 8; - selector.moving = false; - selector.resizing = false; - selector.rect = {0, 0, 0, 0}; - selector.color = {0, 0, 0}; - selector.itemColor = {0, 0, 0}; - selector.a = 255; - - // Inicializa las variables desde un fichero - if (file != "") - { - load(file); - } - - // Deja el cursor en el primer elemento - reset(); -} - -Menu::~Menu() -{ - renderer = nullptr; - asset = nullptr; - input = nullptr; - - if (soundMove) - { - JA_DeleteSound(soundMove); - } - - if (soundAccept) - { - JA_DeleteSound(soundAccept); - } - - if (soundCancel) - { - JA_DeleteSound(soundCancel); - } - - if (text != nullptr) - { - delete text; - } -} - -// Carga la configuración del menu desde un archivo de texto -bool Menu::load(std::string file_path) -{ - // Indicador de éxito en la carga - bool success = true; - - // Indica si se ha creado ya el objeto de texto - bool textAllocated = false; - - const std::string filename = file_path.substr(file_path.find_last_of("\\/") + 1); - std::string line; - std::ifstream file(file_path); - - // El fichero se puede abrir - if (file.good()) - { - // Procesa el fichero linea a linea - std::cout << "Reading file " << filename.c_str() << std::endl; - while (std::getline(file, line)) - { - if (line == "[item]") - { - item_t item; - item.label = ""; - item.hPaddingDown = 1; - item.selectable = true; - item.greyed = false; - item.linkedDown = false; - - do - { - // Lee la siguiente linea - std::getline(file, line); - - // Encuentra la posición del caracter '=' - int pos = line.find("="); - - // Procesa las dos subcadenas - if (!setItem(&item, line.substr(0, pos), line.substr(pos + 1, line.length()))) - { - std::cout << "Warning: file " << filename.c_str() << "\n, unknown parameter \"" << line.substr(0, pos).c_str() << "\"" << std::endl; - success = false; - } - - } while (line != "[/item]"); - - addItem(item.label, item.hPaddingDown, item.selectable, item.greyed, item.linkedDown); - } - - // En caso contrario se parsea el fichero para buscar las variables y los valores - else - { - // Encuentra la posición del caracter '=' - int pos = line.find("="); - // Procesa las dos subcadenas - if (!setVars(line.substr(0, pos), line.substr(pos + 1, line.length()))) - { - std::cout << "Warning: file " << filename.c_str() << "\n, unknown parameter \"" << line.substr(0, pos).c_str() << "\"" << std::endl; - success = false; - } - - // Crea el objeto text tan pronto como se pueda. Necesario para añadir items - if (font_png != "" && font_txt != "" && !textAllocated) - { - text = new Text(resource->getOffset(font_txt), resource->getTexture(font_png), renderer); - textAllocated = true; - } - } - } - - // Cierra el fichero - std::cout << "Closing file " << filename.c_str() << std::endl; - file.close(); - } - // El fichero no se puede abrir - else - { - std::cout << "Warning: Unable to open " << filename.c_str() << " file" << std::endl; - success = false; - } - - return success; -} - -// Asigna variables a partir de dos cadenas -bool Menu::setItem(item_t *item, std::string var, std::string value) -{ - // Indicador de éxito en la asignación - bool success = true; - - if (var == "text") - { - item->label = value; - } - - else if (var == "hPaddingDown") - { - item->hPaddingDown = std::stoi(value); - } - - else if (var == "selectable") - { - item->selectable = value == "true" ? true : false; - } - - else if (var == "greyed") - { - item->greyed = value == "true" ? true : false; - } - - else if (var == "linkedDown") - { - item->linkedDown = value == "true" ? true : false; - } - - else if ((var == "") || (var == "[/item]")) - { - } - - else - { - success = false; - } - - return success; -} - -// Asigna variables a partir de dos cadenas -bool Menu::setVars(std::string var, std::string value) -{ - // Indicador de éxito en la asignación - bool success = true; - - if (var == "font_png") - { - font_png = value; - } - - else if (var == "font_txt") - { - font_txt = value; - } - - else if (var == "sound_cancel") - { - soundCancel = JA_LoadSound(asset->get(value).c_str()); - } - - else if (var == "sound_accept") - { - soundAccept = JA_LoadSound(asset->get(value).c_str()); - } - - else if (var == "sound_move") - { - soundMove = JA_LoadSound(asset->get(value).c_str()); - } - - else if (var == "name") - { - name = value; - } - - else if (var == "x") - { - x = std::stoi(value); - } - - else if (var == "centerX") - { - centerX = std::stoi(value); - } - - else if (var == "centerY") - { - centerY = std::stoi(value); - } - - else if (var == "y") - { - y = std::stoi(value); - } - - else if (var == "backgroundType") - { - backgroundType = std::stoi(value); - } - - else if (var == "backgroundColor") - { - // Se introducen los valores separados por comas en un vector - std::stringstream ss(value); - std::string tmp; - getline(ss, tmp, ','); - rectBG.color.r = std::stoi(tmp); - getline(ss, tmp, ','); - rectBG.color.g = std::stoi(tmp); - getline(ss, tmp, ','); - rectBG.color.b = std::stoi(tmp); - getline(ss, tmp, ','); - rectBG.a = std::stoi(tmp); - } - - else if (var == "selector_color") - { - // Se introducen los valores separados por comas en un vector - std::stringstream ss(value); - std::string tmp; - getline(ss, tmp, ','); - selector.color.r = std::stoi(tmp); - getline(ss, tmp, ','); - selector.color.g = std::stoi(tmp); - getline(ss, tmp, ','); - selector.color.b = std::stoi(tmp); - getline(ss, tmp, ','); - selector.a = std::stoi(tmp); - } - - else if (var == "selector_text_color") - { - // Se introducen los valores separados por comas en un vector - std::stringstream ss(value); - std::string tmp; - getline(ss, tmp, ','); - selector.itemColor.r = std::stoi(tmp); - getline(ss, tmp, ','); - selector.itemColor.g = std::stoi(tmp); - getline(ss, tmp, ','); - selector.itemColor.b = std::stoi(tmp); - } - - else if (var == "areElementsCenteredOnX") - { - areElementsCenteredOnX = value == "true" ? true : false; - } - - else if (var == "isCenteredOnX") - { - isCenteredOnX = value == "true" ? true : false; - } - - else if (var == "isCenteredOnY") - { - isCenteredOnY = value == "true" ? true : false; - } - - else if (var == "defaultActionWhenCancel") - { - defaultActionWhenCancel = std::stoi(value); - } - - else if (var == "") - { - } - - else - { - success = false; - } - - return success; -} - -// Carga los ficheros de audio -void Menu::loadAudioFile(std::string file, int sound) -{ - switch (sound) - { - case SOUND_ACCEPT: - soundAccept = JA_LoadSound(file.c_str()); - break; - - case SOUND_CANCEL: - soundCancel = JA_LoadSound(file.c_str()); - break; - - case SOUND_MOVE: - soundMove = JA_LoadSound(file.c_str()); - break; - - default: - break; - } -} - -// Obtiene el nombre del menu -std::string Menu::getName() -{ - return name; -} - -// Obtiene el valor de la variable -int Menu::getItemSelected() -{ - // Al llamar a esta funcion, se obtiene el valor y se borra - const int temp = itemSelected; - itemSelected = MENU_NO_OPTION; - return temp; -} - -// Actualiza la posicion y el estado del selector -void Menu::updateSelector() -{ - if (selector.moving) - { - // Calcula el desplazamiento en Y - selector.y += selector.despY; - if (selector.despY > 0) // Va hacia abajo - { - if (selector.y > selector.targetY) // Ha llegado al destino - { - selector.originY = selector.y = selector.targetY; - selector.moving = false; - } - } - - else if (selector.despY < 0) // Va hacia arriba - { - if (selector.y < selector.targetY) // Ha llegado al destino - { - selector.originY = selector.y = selector.targetY; - selector.moving = false; - } - } - selector.rect.y = int(selector.y); - } - else - { - selector.rect.y = int(selector.y); - } - - if (selector.resizing) - { - // Calcula el incremento en H - selector.h += selector.incH; - if (selector.incH > 0) // Crece - { - if (selector.h > selector.targetH) // Ha llegado al destino - { - // selector.originH = selector.targetH = selector.rect.h = getSelectorHeight(selector.index); - selector.originH = selector.h = selector.targetH; - selector.resizing = false; - } - } - - else if (selector.incH < 0) // Decrece - { - if (selector.h < selector.targetH) // Ha llegado al destino - { - // selector.originH = selector.targetH = selector.rect.h = getSelectorHeight(selector.index); - selector.originH = selector.h = selector.targetH; - selector.resizing = false; - } - } - selector.rect.h = int(selector.h); - } - else - { - selector.rect.h = getSelectorHeight(selector.index); - } -} - -// Coloca el selector en una posición específica -void Menu::setSelectorPos(int index) -{ - if (index < (int)item.size()) - { - selector.index = index; - selector.rect.y = selector.y = selector.originY = selector.targetY = item[selector.index].rect.y; - selector.rect.w = rectBG.rect.w; - selector.rect.x = rectBG.rect.x; - selector.originH = selector.targetH = selector.rect.h = getSelectorHeight(selector.index); - selector.moving = false; - selector.resizing = false; - } -} - -// Obtiene la anchura del elemento más ancho del menu -int Menu::getWidestItem() -{ - int result = 0; - - // Obtenemos la anchura del item mas ancho - for (auto &i : item) - { - result = std::max(result, i.rect.w); - } - - return result; -} - -// Deja el menu apuntando al primer elemento -void Menu::reset() -{ - itemSelected = MENU_NO_OPTION; - selector.index = 0; - selector.originY = selector.targetY = selector.y = item[0].rect.y; - selector.originH = selector.targetH = item[0].rect.h; - selector.moving = false; - selector.resizing = false; - - // Si el primer elemento no es seleccionable, incrementa el selector - if (!item[selector.index].selectable) - { - increaseSelectorIndex(); - setSelectorPos(selector.index); - } -} - -// Actualiza el menu para recolocarlo correctamente y establecer el tamaño -void Menu::reorganize() -{ - setRectSize(); - - if (isCenteredOnX) - { - centerMenuOnX(centerX); - } - - if (isCenteredOnY) - { - centerMenuOnY(centerY); - } - - if (areElementsCenteredOnX) - { - centerMenuElementsOnX(); - } -} - -// Deja el menu apuntando al siguiente elemento -bool Menu::increaseSelectorIndex() -{ - // Obten las coordenadas del elemento actual - selector.y = selector.originY = item[selector.index].rect.y; - selector.h = selector.originH = getSelectorHeight(selector.index); - - // Calcula cual es el siguiente elemento - ++selector.index %= item.size(); - while (!item[selector.index].selectable) - { - ++selector.index %= item.size(); - } - - // Establece las coordenadas y altura de destino - selector.targetY = item[selector.index].rect.y; - selector.despY = (selector.targetY - selector.originY) / selector.numJumps; - - selector.targetH = getSelectorHeight(selector.index); - selector.incH = (selector.targetH - selector.originH) / selector.numJumps; - - selector.moving = true; - if (selector.incH != 0) - { - selector.resizing = true; - } - - return true; -} - -// Deja el menu apuntando al elemento anterior -bool Menu::decreaseSelectorIndex() -{ - // Obten las coordenadas del elemento actual - selector.y = selector.originY = item[selector.index].rect.y; - selector.h = selector.originH = getSelectorHeight(selector.index); - - // Calcula cual es el siguiente elemento - if (selector.index == 0) - { - selector.index = item.size() - 1; - } - else - { - selector.index--; - } - - while (!item[selector.index].selectable) - { - if (selector.index == 0) - { - selector.index = item.size() - 1; - } - else - { - selector.index--; - } - } - - // Establece las coordenadas y altura de destino - selector.targetY = item[selector.index].rect.y; - selector.despY = (selector.targetY - selector.originY) / selector.numJumps; - - selector.targetH = getSelectorHeight(selector.index); - selector.incH = (selector.targetH - selector.originH) / selector.numJumps; - - selector.moving = true; - if (selector.incH != 0) - { - selector.resizing = true; - } - - return true; -} - -// Actualiza la logica del menu -void Menu::update() -{ - checkInput(); - updateSelector(); -} - -// Pinta el menu en pantalla -void Menu::render() -{ - // Rendereritza el fondo del menu - if (backgroundType == MENU_BACKGROUND_SOLID) - { - SDL_SetRenderDrawColor(renderer, rectBG.color.r, rectBG.color.g, rectBG.color.b, rectBG.a); - SDL_RenderFillRect(renderer, &rectBG.rect); - } - - // Renderiza el rectangulo del selector - const SDL_Rect temp = {selector.rect.x, selector.rect.y - 1, selector.rect.w, selector.rect.h + 1}; - SDL_SetRenderDrawColor(renderer, selector.color.r, selector.color.g, selector.color.b, selector.a); - SDL_RenderFillRect(renderer, &temp); - - // Renderiza el borde del fondo - if (backgroundType == MENU_BACKGROUND_SOLID) - { - SDL_SetRenderDrawColor(renderer, rectBG.color.r, rectBG.color.g, rectBG.color.b, 255); - SDL_RenderDrawRect(renderer, &rectBG.rect); - } - - // Renderiza el texto - for (int i = 0; i < (int)item.size(); ++i) - { - if (i == selector.index) - { - const color_t color = {selector.itemColor.r, selector.itemColor.g, selector.itemColor.b}; - text->writeColored(item[i].rect.x, item[i].rect.y, item[i].label, color); - } - - else if (item[i].selectable) - { - text->write(item[i].rect.x, item[i].rect.y, item[i].label); - } - - else if (item[i].greyed) - { - text->writeColored(item[i].rect.x, item[i].rect.y, item[i].label, colorGreyed); - } - - else - { // No seleccionable - if ((item[i].linkedUp) && (i == selector.index + 1)) - { - const color_t color = {selector.itemColor.r, selector.itemColor.g, selector.itemColor.b}; - text->writeColored(item[i].rect.x, item[i].rect.y, item[i].label, color); - } - else // No enlazado con el de arriba - { - text->write(item[i].rect.x, item[i].rect.y, item[i].label); - } - } - } -} - -// Establece el rectangulo de fondo del menu y el selector -void Menu::setRectSize(int w, int h) -{ - // Establece el ancho - if (w == 0) - { // Si no se pasa un valor, se busca si hay uno prefijado - if (this->w == 0) - { // Si no hay prefijado, coge el item mas ancho - rectBG.rect.w = findWidth() + text->getCharacterSize(); - } - else - { // Si hay prefijado, coge ese - rectBG.rect.w = this->w; - } - } - else - { // Si se pasa un valor, se usa y se prefija - rectBG.rect.w = w; - this->w = w; - } - - // Establece el alto - if (h == 0) - { // Si no se pasa un valor, se busca de manera automatica - rectBG.rect.h = findHeight() + text->getCharacterSize(); - } - else - { // Si se pasa un valor, se aplica - rectBG.rect.h = h; - } - - // La posición X es la del menú menos medio caracter - if (this->w != 0) - { // Si el ancho esta prefijado, la x coinccide - rectBG.rect.x = x; - } - else - { // Si el ancho es automatico, se le da un poco de margen - rectBG.rect.x = x - (text->getCharacterSize() / 2); - } - - // La posición Y es la del menu menos la altura de medio caracter - rectBG.rect.y = y - (text->getCharacterSize() / 2); - - // Establecemos los valores del rectangulo del selector a partir de los valores del rectangulo de fondo - setSelectorPos(selector.index); -} - -// Establece el color del rectangulo de fondo -void Menu::setBackgroundColor(color_t color, int alpha) -{ - rectBG.color = color; - rectBG.a = alpha; -} - -// Establece el color del rectangulo del selector -void Menu::setSelectorColor(color_t color, int alpha) -{ - selector.color = color; - selector.a = alpha; -} - -// Establece el color del texto del selector -void Menu::setSelectorTextColor(color_t color) -{ - selector.itemColor = color; -} - -// Centra el menu respecto un punto en el eje X -void Menu::centerMenuOnX(int value) -{ - isCenteredOnX = true; - if (value != 0) - { - centerX = value; - } - else if (centerX == 0) - { - return; - } - - // Establece la nueva posición centrada en funcion del elemento más ancho o del ancho fijo del menu - if (w != 0) - { // Si se ha definido un ancho fijo - x = (centerX) - (w / 2); - } - else - { // Si se actua en función del elemento más ancho - x = (centerX) - (findWidth() / 2); - } - - // Actualiza el rectangulo de fondo y del selector - rectBG.rect.x = x; - selector.rect.x = x; - - // Reposiciona los elementos del menu - for (auto &i : item) - { - i.rect.x = x; - } - - // Recalcula el rectangulo de fondo - setRectSize(); - - // Vuelve a centrar los elementos si fuera el caso - if (areElementsCenteredOnX) - { - centerMenuElementsOnX(); - } -} - -// Centra el menu respecto un punto en el eje Y -void Menu::centerMenuOnY(int value) -{ - isCenteredOnY = true; - centerY = value; - - // Establece la nueva posición centrada en funcion del elemento más ancho - y = (value) - (findHeight() / 2); - - // Reposiciona los elementos del menu - replaceElementsOnY(); - - // Recalcula el rectangulo de fondo - setRectSize(); -} - -// Centra los elementos del menu en el eje X -void Menu::centerMenuElementsOnX() -{ - areElementsCenteredOnX = true; - - for (auto &i : item) - { - i.rect.x = (centerX - (i.rect.w / 2)); - } -} - -// Añade un item al menu -void Menu::addItem(std::string text, int hPaddingDown, bool selectable, bool greyed, bool linkedDown) -{ - item_t temp; - - if (item.empty()) - { // Si es el primer item coge la posición en el eje Y del propio menu - temp.rect.y = y; - } - else - { // En caso contrario, coge la posición en el eje Y a partir del último elemento - temp.rect.y = item.back().rect.y + item.back().rect.h + item.back().hPaddingDown; - } - - temp.rect.x = x; - temp.hPaddingDown = hPaddingDown; - temp.selectable = selectable; - temp.greyed = greyed; - temp.linkedDown = linkedDown; - - item.push_back(temp); - - setItemCaption(item.size() - 1, text); - - if (item.size() > 1) - { - if (item[item.size() - 2].linkedDown) - { - item.back().linkedUp = true; - } - } - - centerX = x + (findWidth() / 2); - reorganize(); -} - -// Cambia el texto de un item -void Menu::setItemCaption(int index, std::string text) -{ - item[index].label = text; - item[index].rect.w = this->text->lenght(item[index].label); - item[index].rect.h = this->text->getCharacterSize(); - reorganize(); -} - -// Establece el indice del itemm que se usará por defecto al cancelar el menu -void Menu::setDefaultActionWhenCancel(int item) -{ - defaultActionWhenCancel = item; -} - -// Gestiona la entrada de teclado y mando durante el menu -void Menu::checkInput() -{ - if (input->checkInput(input_up, REPEAT_FALSE)) - { - if (decreaseSelectorIndex()) - { - if (soundMove) - { - JA_PlaySound(soundMove); - } - } - } - - if (input->checkInput(input_down, REPEAT_FALSE)) - { - if (increaseSelectorIndex()) - { - if (soundMove) - { - JA_PlaySound(soundMove); - } - } - } - - if (input->checkInput(input_accept, REPEAT_FALSE)) - { - itemSelected = selector.index; - if (soundAccept) - { - JA_PlaySound(soundAccept); - } - } - - if (input->checkInput(input_cancel, REPEAT_FALSE)) - { - itemSelected = defaultActionWhenCancel; - if (soundCancel) - { - JA_PlaySound(soundCancel); - } - } -} - -// Calcula el ancho del menu -int Menu::findWidth() -{ - return getWidestItem(); -} - -// Calcula el alto del menu -int Menu::findHeight() -{ - int height = 0; - - // Obtenemos la altura de la suma de alturas de los items - for (auto &i : item) - { - height += i.rect.h + i.hPaddingDown; - } - - return height - item.back().hPaddingDown; -} - -// Recoloca los elementos del menu en el eje Y -void Menu::replaceElementsOnY() -{ - item[0].rect.y = y; - - for (int i = 1; i < (int)item.size(); i++) - { - item[i].rect.y = item[i - 1].rect.y + item[i - 1].rect.h + item[i - 1].hPaddingDown; - } -} - -// Establece el estado seleccionable de un item -void Menu::setSelectable(int index, bool value) -{ - item[index].selectable = value; -} - -// Establece el estado agrisado de un item -void Menu::setGreyed(int index, bool value) -{ - item[index].greyed = value; -} - -// Establece el estado de enlace de un item -void Menu::setLinkedDown(int index, bool value) -{ - item[index].linkedDown = value; -} - -// Calcula la altura del selector -int Menu::getSelectorHeight(int value) -{ - if (item[value].linkedDown) - { - return item[value].rect.h + item[value].hPaddingDown + item[value + 1].rect.h; - } - else - { - return item[value].rect.h; - } -} - -// Establece el nombre del menu -void Menu::setName(std::string name) -{ - this->name = name; -} - -// Establece la posición del menu -void Menu::setPos(int x, int y) -{ - this->x = x; - this->y = y; -} - -// Establece el tipo de fondo del menu -void Menu::setBackgroundType(int value) -{ - backgroundType = value; -} - -// Establece la fuente de texto que se utilizará -void Menu::setText(std::string font_png, std::string font_txt) -{ - if (!text) - { - text = new Text(resource->getOffset(font_txt), resource->getTexture(font_png), renderer); - } -} \ No newline at end of file diff --git a/source/menu.h b/source/menu.h deleted file mode 100644 index f4fb308..0000000 --- a/source/menu.h +++ /dev/null @@ -1,220 +0,0 @@ -#pragma once - -#include <SDL2/SDL_rect.h> // Para SDL_Rect -#include <SDL2/SDL_render.h> // Para SDL_Renderer -#include <string> // Para string, basic_string -#include <vector> // Para vector -#include "utils.h" // Para color_t -class Asset; -class Input; -class Resource; -class Text; -struct JA_Sound_t; - -// Tipos de fondos para el menú -constexpr int MENU_BACKGROUND_TRANSPARENT = 0; -constexpr int MENU_BACKGROUND_SOLID = 1; - -// Tipos de archivos de audio -constexpr int SOUND_ACCEPT = 0; -constexpr int SOUND_MOVE = 1; -constexpr int SOUND_CANCEL = 2; - -// Opciones de menú -constexpr int MENU_NO_OPTION = -1; - -// Clase Menu -class Menu -{ -private: - struct rectangle_t - { - SDL_Rect rect; // Rectangulo - color_t color; // Color - int a; // Transparencia - }; - - struct item_t - { - std::string label; // Texto - SDL_Rect rect; // Rectangulo que delimita el elemento - int hPaddingDown; // Espaciado bajo el elemento - bool selectable; // Indica si se puede seleccionar - bool greyed; // Indica si ha de aparecer con otro color mas oscuro - bool linkedDown; // Indica si el elemento actual y el siguiente se tratan como uno solo. Afecta al selector - bool linkedUp; // Indica si el elemento actual y el anterior se tratan como uno solo. Afecta al selector - }; - - struct selector_t - { - float originY; // Coordenada de origen - float targetY; // Coordenada de destino - float despY; // Cantidad de pixeles que se desplaza el selector en cada salto: (target - origin) / numJumps - bool moving; // Indica si el selector está avanzando hacia el destino - float originH; // Altura de origen - float targetH; // Altura de destino - float incH; // Cantidad de pixels que debe incrementar o decrementar el selector en cada salto - bool resizing; // Indica si el selector está cambiando de tamaño - float y; // Coordenada actual, usado para el desplazamiento - float h; // Altura actual, usado para el cambio de tamaño - int numJumps; // Numero de pasos preestablecido para llegar al destino - int index; // Elemento del menu que tiene el foco - SDL_Rect rect; // Rectangulo del selector - color_t color; // Color del selector - color_t itemColor; // Color del item - int a; // Cantidad de transparencia para el rectangulo del selector - }; - - // Objetos y punteros - SDL_Renderer *renderer; // Puntero al renderizador de la ventana - Resource *resource; // Objeto con los recursos - Asset *asset; // Objeto para gestionar los ficheros de recursos - Text *text; // Texto para poder escribir los items del menu - Input *input; // Gestor de eventos de entrada de teclado o gamepad - - // Variables - std::string name; // Nombre del menu - int x; // Posición en el eje X de la primera letra del primer elemento - int y; // Posición en el eje Y de la primera letra del primer elemento - int h; // Altura del menu - int w; // Anchura del menu - int itemSelected; // Índice del item del menu que ha sido seleccionado - int defaultActionWhenCancel; // Indice del item del menu que se selecciona cuando se cancela el menu - int backgroundType; // Tipo de fondo para el menu - int centerX; // Centro del menu en el eje X - int centerY; // Centro del menu en el eje Y - bool isCenteredOnX; // Variable para saber si el menu debe estar centrado respecto a un punto en el eje X - bool isCenteredOnY; // Variable para saber si el menu debe estar centrado respecto a un punto en el eje Y - bool areElementsCenteredOnX; // Variable para saber si los elementos van centrados en el eje X - int widestItem; // Anchura del elemento más ancho - JA_Sound_t *soundAccept; // Sonido al aceptar o elegir una opción del menu - JA_Sound_t *soundCancel; // Sonido al cancelar el menu - JA_Sound_t *soundMove; // Sonido al mover el selector - color_t colorGreyed; // Color para los elementos agrisados - rectangle_t rectBG; // Rectangulo de fondo del menu - std::vector<item_t> item; // Estructura para cada elemento del menu - selector_t selector; // Variables para pintar el selector del menu - std::string font_png; - std::string font_txt; - - // Carga la configuración del menu desde un archivo de texto - bool load(std::string file_path); - - // Asigna variables a partir de dos cadenas - bool setVars(std::string var, std::string value); - - // Asigna variables a partir de dos cadenas - bool setItem(item_t *item, std::string var, std::string value); - - // Actualiza el menu para recolocarlo correctamente y establecer el tamaño - void reorganize(); - - // Deja el menu apuntando al siguiente elemento - bool increaseSelectorIndex(); - - // Deja el menu apuntando al elemento anterior - bool decreaseSelectorIndex(); - - // Actualiza la posicion y el estado del selector - void updateSelector(); - - // Obtiene la anchura del elemento más ancho del menu - int getWidestItem(); - - // Gestiona la entrada de teclado y mando durante el menu - void checkMenuInput(Menu *menu); - - // Calcula el ancho del menu - int findWidth(); - - // Calcula el alto del menu - int findHeight(); - - // Recoloca los elementos del menu en el eje Y - void replaceElementsOnY(); - - // Calcula la altura del selector - int getSelectorHeight(int value); - -public: - // Constructor - Menu(SDL_Renderer *renderer, Resource *resource, Asset *asset, Input *input, std::string file = ""); - - // Destructor - ~Menu(); - - // Carga los ficheros de audio - void loadAudioFile(std::string file, int sound); - - // Obtiene el nombre del menu - std::string getName(); - - // Obtiene el valor de la variable - int getItemSelected(); - - // Deja el menu apuntando al primer elemento - void reset(); - - // Gestiona la entrada de teclado y mando durante el menu - void checkInput(); - - // Actualiza la logica del menu - void update(); - - // Pinta el menu en pantalla - void render(); - - // Establece el color del rectangulo de fondo - void setBackgroundColor(color_t color, int alpha); - - // Establece el color del rectangulo del selector - void setSelectorColor(color_t color, int alpha); - - // Establece el color del texto del selector - void setSelectorTextColor(color_t color); - - // Centra el menu respecto a un punto en el eje X - void centerMenuOnX(int value = 0); - - // Centra el menu respecto a un punto en el eje Y - void centerMenuOnY(int value); - - // Centra los elementos del menu en el eje X - void centerMenuElementsOnX(); - - // Añade un item al menu - void addItem(std::string text, int hPaddingDown = 1, bool selectable = true, bool greyed = false, bool linkedDown = false); - - // Cambia el texto de un item - void setItemCaption(int index, std::string text); - - // Establece el indice del item que se usará por defecto al cancelar el menu - void setDefaultActionWhenCancel(int item); - - // Coloca el selector en una posición específica - void setSelectorPos(int index); - - // Establece el estado seleccionable de un item - void setSelectable(int index, bool value); - - // Establece el estado agrisado de un item - void setGreyed(int index, bool value); - - // Establece el estado de enlace de un item - void setLinkedDown(int index, bool value); - - // Establece el nombre del menu - void setName(std::string name); - - // Establece la posición del menu - void setPos(int x, int y); - - // Establece el tipo de fondo del menu - void setBackgroundType(int value); - - // Establece la fuente de texto que se utilizará - void setText(std::string font_png, std::string font_txt); - - // Establece el rectangulo de fondo del menu - void setRectSize(int w = 0, int h = 0); -}; \ No newline at end of file diff --git a/source/notifier.cpp b/source/notifier.cpp index e8aadaa..38474eb 100644 --- a/source/notifier.cpp +++ b/source/notifier.cpp @@ -63,9 +63,12 @@ Notifier::~Notifier() // Dibuja las notificaciones por pantalla void Notifier::render() { - for (int i = (int)notifications_.size() - 1; i >= 0; --i) + if (active()) { - notifications_[i].sprite->render(); + for (auto it = notifications_.rbegin(); it != notifications_.rend(); ++it) + { + it->sprite->render(); + } } } @@ -172,7 +175,7 @@ void Notifier::clearFinishedNotifications() } // Muestra una notificación de texto por pantalla; -void Notifier::showText(std::string text1, std::string text2, int icon) +void Notifier::show(std::string text1, std::string text2, int icon) { // Inicializa variables const int iconSize = 16; @@ -296,15 +299,4 @@ void Notifier::showText(std::string text1, std::string text2, int icon) // Añade la notificación a la lista notifications_.push_back(n); -} - -// Indica si hay notificaciones activas -bool Notifier::active() -{ - if ((int)notifications_.size() > 0) - { - return true; - } - - return false; } \ No newline at end of file diff --git a/source/notifier.h b/source/notifier.h index 82acb99..d9c6760 100644 --- a/source/notifier.h +++ b/source/notifier.h @@ -88,8 +88,8 @@ public: void update(); // Muestra una notificación de texto por pantalla; - void showText(std::string text1 = "", std::string text2 = "", int icon = -1); + void show(std::string text1 = "", std::string text2 = "", int icon = -1); - // Indica si hay notificaciones activas - bool active(); + // Getters + bool active() const { return !notifications_.empty(); } }; diff --git a/source/player.cpp b/source/player.cpp index 999985a..b3d5f02 100644 --- a/source/player.cpp +++ b/source/player.cpp @@ -13,20 +13,19 @@ #include "room.h" // Para Room, tile_e #include "texture.h" // Para Texture #include "options.h" +#include "screen.h" // Constructor Player::Player(player_t player) + : renderer_(Screen::get()->getRenderer()), + input_(Input::get()), + resource_(Resource::get()), + asset_(Asset::get()), + room_(player.room), + debug_(Debug::get()) { - // Obten punteros a objetos - this->resource = player.resource; - this->asset = player.asset; - this->renderer = player.renderer; - this->input = player.input; - this->room = player.room; - this->debug = player.debug; - // Crea objetos - sprite = new AnimatedSprite(renderer, resource->getAnimation(player.animation)); + sprite_ = new AnimatedSprite(renderer_, resource_->getAnimation(player.animation)); // Inicializa variables reLoadPalette(); @@ -49,14 +48,14 @@ Player::Player(player_t player) h = 16; maxVY = 1.2f; - sprite->setPosX(player.spawn.x); - sprite->setPosY(player.spawn.y); - sprite->setWidth(8); - sprite->setHeight(16); + sprite_->setPosX(player.spawn.x); + sprite_->setPosY(player.spawn.y); + sprite_->setWidth(8); + sprite_->setHeight(16); - sprite->setFlipH(player.spawn.flipH); - sprite->setCurrentAnimation("walk"); - sprite->animate(); + sprite_->setFlipH(player.spawn.flipH); + sprite_->setCurrentAnimation("walk"); + sprite_->animate(); lastPosition = getRect(); colliderBox = getRect(); @@ -64,45 +63,45 @@ Player::Player(player_t player) colliderPoints.insert(colliderPoints.end(), {p, p, p, p, p, p, p, p}); underFeet.insert(underFeet.end(), {p, p}); feet.insert(feet.end(), {p, p}); - jumpSound.push_back(JA_LoadSound(asset->get("jump1.wav").c_str())); - jumpSound.push_back(JA_LoadSound(asset->get("jump2.wav").c_str())); - jumpSound.push_back(JA_LoadSound(asset->get("jump3.wav").c_str())); - jumpSound.push_back(JA_LoadSound(asset->get("jump4.wav").c_str())); - jumpSound.push_back(JA_LoadSound(asset->get("jump5.wav").c_str())); - jumpSound.push_back(JA_LoadSound(asset->get("jump6.wav").c_str())); - jumpSound.push_back(JA_LoadSound(asset->get("jump7.wav").c_str())); - jumpSound.push_back(JA_LoadSound(asset->get("jump8.wav").c_str())); - jumpSound.push_back(JA_LoadSound(asset->get("jump9.wav").c_str())); - jumpSound.push_back(JA_LoadSound(asset->get("jump10.wav").c_str())); - jumpSound.push_back(JA_LoadSound(asset->get("jump11.wav").c_str())); - jumpSound.push_back(JA_LoadSound(asset->get("jump12.wav").c_str())); - jumpSound.push_back(JA_LoadSound(asset->get("jump13.wav").c_str())); - jumpSound.push_back(JA_LoadSound(asset->get("jump14.wav").c_str())); - jumpSound.push_back(JA_LoadSound(asset->get("jump15.wav").c_str())); - jumpSound.push_back(JA_LoadSound(asset->get("jump16.wav").c_str())); - jumpSound.push_back(JA_LoadSound(asset->get("jump17.wav").c_str())); - jumpSound.push_back(JA_LoadSound(asset->get("jump18.wav").c_str())); - jumpSound.push_back(JA_LoadSound(asset->get("jump19.wav").c_str())); - jumpSound.push_back(JA_LoadSound(asset->get("jump20.wav").c_str())); - jumpSound.push_back(JA_LoadSound(asset->get("jump21.wav").c_str())); - jumpSound.push_back(JA_LoadSound(asset->get("jump22.wav").c_str())); - jumpSound.push_back(JA_LoadSound(asset->get("jump23.wav").c_str())); - jumpSound.push_back(JA_LoadSound(asset->get("jump24.wav").c_str())); + jumpSound.push_back(JA_LoadSound(asset_->get("jump1.wav").c_str())); + jumpSound.push_back(JA_LoadSound(asset_->get("jump2.wav").c_str())); + jumpSound.push_back(JA_LoadSound(asset_->get("jump3.wav").c_str())); + jumpSound.push_back(JA_LoadSound(asset_->get("jump4.wav").c_str())); + jumpSound.push_back(JA_LoadSound(asset_->get("jump5.wav").c_str())); + jumpSound.push_back(JA_LoadSound(asset_->get("jump6.wav").c_str())); + jumpSound.push_back(JA_LoadSound(asset_->get("jump7.wav").c_str())); + jumpSound.push_back(JA_LoadSound(asset_->get("jump8.wav").c_str())); + jumpSound.push_back(JA_LoadSound(asset_->get("jump9.wav").c_str())); + jumpSound.push_back(JA_LoadSound(asset_->get("jump10.wav").c_str())); + jumpSound.push_back(JA_LoadSound(asset_->get("jump11.wav").c_str())); + jumpSound.push_back(JA_LoadSound(asset_->get("jump12.wav").c_str())); + jumpSound.push_back(JA_LoadSound(asset_->get("jump13.wav").c_str())); + jumpSound.push_back(JA_LoadSound(asset_->get("jump14.wav").c_str())); + jumpSound.push_back(JA_LoadSound(asset_->get("jump15.wav").c_str())); + jumpSound.push_back(JA_LoadSound(asset_->get("jump16.wav").c_str())); + jumpSound.push_back(JA_LoadSound(asset_->get("jump17.wav").c_str())); + jumpSound.push_back(JA_LoadSound(asset_->get("jump18.wav").c_str())); + jumpSound.push_back(JA_LoadSound(asset_->get("jump19.wav").c_str())); + jumpSound.push_back(JA_LoadSound(asset_->get("jump20.wav").c_str())); + jumpSound.push_back(JA_LoadSound(asset_->get("jump21.wav").c_str())); + jumpSound.push_back(JA_LoadSound(asset_->get("jump22.wav").c_str())); + jumpSound.push_back(JA_LoadSound(asset_->get("jump23.wav").c_str())); + jumpSound.push_back(JA_LoadSound(asset_->get("jump24.wav").c_str())); - fallSound.push_back(JA_LoadSound(asset->get("jump11.wav").c_str())); - fallSound.push_back(JA_LoadSound(asset->get("jump12.wav").c_str())); - fallSound.push_back(JA_LoadSound(asset->get("jump13.wav").c_str())); - fallSound.push_back(JA_LoadSound(asset->get("jump14.wav").c_str())); - fallSound.push_back(JA_LoadSound(asset->get("jump15.wav").c_str())); - fallSound.push_back(JA_LoadSound(asset->get("jump16.wav").c_str())); - fallSound.push_back(JA_LoadSound(asset->get("jump17.wav").c_str())); - fallSound.push_back(JA_LoadSound(asset->get("jump18.wav").c_str())); - fallSound.push_back(JA_LoadSound(asset->get("jump19.wav").c_str())); - fallSound.push_back(JA_LoadSound(asset->get("jump20.wav").c_str())); - fallSound.push_back(JA_LoadSound(asset->get("jump21.wav").c_str())); - fallSound.push_back(JA_LoadSound(asset->get("jump22.wav").c_str())); - fallSound.push_back(JA_LoadSound(asset->get("jump23.wav").c_str())); - fallSound.push_back(JA_LoadSound(asset->get("jump24.wav").c_str())); + fallSound.push_back(JA_LoadSound(asset_->get("jump11.wav").c_str())); + fallSound.push_back(JA_LoadSound(asset_->get("jump12.wav").c_str())); + fallSound.push_back(JA_LoadSound(asset_->get("jump13.wav").c_str())); + fallSound.push_back(JA_LoadSound(asset_->get("jump14.wav").c_str())); + fallSound.push_back(JA_LoadSound(asset_->get("jump15.wav").c_str())); + fallSound.push_back(JA_LoadSound(asset_->get("jump16.wav").c_str())); + fallSound.push_back(JA_LoadSound(asset_->get("jump17.wav").c_str())); + fallSound.push_back(JA_LoadSound(asset_->get("jump18.wav").c_str())); + fallSound.push_back(JA_LoadSound(asset_->get("jump19.wav").c_str())); + fallSound.push_back(JA_LoadSound(asset_->get("jump20.wav").c_str())); + fallSound.push_back(JA_LoadSound(asset_->get("jump21.wav").c_str())); + fallSound.push_back(JA_LoadSound(asset_->get("jump22.wav").c_str())); + fallSound.push_back(JA_LoadSound(asset_->get("jump23.wav").c_str())); + fallSound.push_back(JA_LoadSound(asset_->get("jump24.wav").c_str())); jumpCounter = 0; fallCounter = 0; @@ -118,7 +117,7 @@ Player::Player(player_t player) // Destructor Player::~Player() { - delete sprite; + delete sprite_; for (auto s : jumpSound) { @@ -129,38 +128,38 @@ Player::~Player() // Pinta el jugador en pantalla void Player::render() { - sprite->getTexture()->setColor(color.r, color.g, color.b); - sprite->render(); + sprite_->getTexture()->setColor(color.r, color.g, color.b); + sprite_->render(); #ifdef DEBUG - if (debug->getEnabled()) + if (debug_->getEnabled()) { // Pinta los underfeet - SDL_SetRenderDrawColor(renderer, 255, 0, 255, 255); - SDL_RenderDrawPoint(renderer, underFeet[0].x, underFeet[0].y); - SDL_RenderDrawPoint(renderer, underFeet[1].x, underFeet[1].y); + SDL_SetRenderDrawColor(renderer_, 255, 0, 255, 255); + SDL_RenderDrawPoint(renderer_, underFeet[0].x, underFeet[0].y); + SDL_RenderDrawPoint(renderer_, underFeet[1].x, underFeet[1].y); // Pinta rectangulo del jugador - SDL_SetRenderDrawColor(renderer, debugColor.r, debugColor.g, debugColor.b, 192); + SDL_SetRenderDrawColor(renderer_, debugColor.r, debugColor.g, debugColor.b, 192); SDL_Rect rect = getRect(); - SDL_RenderFillRect(renderer, &rect); - SDL_SetRenderDrawColor(renderer, 0, 255, 255, 255); - SDL_RenderDrawRect(renderer, &rect); + 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); + SDL_SetRenderDrawColor(renderer_, 255, 0, 0, 255); if (vx != 0.0f) { - SDL_RenderFillRect(renderer, &rx); + SDL_RenderFillRect(renderer_, &rx); } if (vy != 0.0f) { - SDL_RenderFillRect(renderer, &ry); + SDL_RenderFillRect(renderer_, &ry); } // Pinta el punto de debug - SDL_SetRenderDrawColor(renderer, rand() % 256, rand() % 256, rand() % 256, 255); - SDL_RenderDrawPoint(renderer, debugPoint.x, debugPoint.y); + SDL_SetRenderDrawColor(renderer_, rand() % 256, rand() % 256, rand() % 256, 255); + SDL_RenderDrawPoint(renderer_, debugPoint.x, debugPoint.y); } #endif } @@ -192,16 +191,16 @@ void Player::checkInput() if (!autoMovement) { // Comprueba las entradas de desplazamiento lateral solo en el caso de no estar enganchado a una superficie automatica - if (input->checkInput(input_left)) + if (input_->checkInput(input_left)) { vx = -0.6f; - sprite->setFlipH(true); + sprite_->setFlipH(true); } - else if (input->checkInput(input_right)) + else if (input_->checkInput(input_right)) { vx = 0.6f; - sprite->setFlipH(false); + sprite_->setFlipH(false); } else @@ -215,19 +214,19 @@ void Player::checkInput() } else { // El movimiento lo proporciona la superficie - vx = 0.6f * room->getAutoSurfaceDirection(); + vx = 0.6f * room_->getAutoSurfaceDirection(); if (vx > 0.0f) { - sprite->setFlipH(false); + sprite_->setFlipH(false); } else { - sprite->setFlipH(true); + sprite_->setFlipH(true); } } - if (input->checkInput(input_jump)) + if (input_->checkInput(input_jump)) { // Solo puede saltar si ademas de estar (state == s_standing) // Esta sobre el suelo, rampa o suelo que se mueve @@ -409,7 +408,7 @@ void Player::move() #endif // Comprueba la colisión con las superficies - const int pos = room->checkRightSurfaces(&proj); + const int pos = room_->checkRightSurfaces(&proj); // Calcula la nueva posición if (pos == -1) @@ -425,7 +424,7 @@ void Player::move() if (state != s_jumping) { v_line_t leftSide = {(int)x, (int)y + h - 2, (int)y + h - 1}; // Comprueba solo los dos pixels de abajo - const int ly = room->checkLeftSlopes(&leftSide); + const int ly = room_->checkLeftSlopes(&leftSide); if (ly > -1) { y = ly - h; @@ -454,7 +453,7 @@ void Player::move() #endif // Comprueba la colisión - const int pos = room->checkLeftSurfaces(&proj); + const int pos = room_->checkLeftSurfaces(&proj); // Calcula la nueva posición if (pos == -1) @@ -470,7 +469,7 @@ void Player::move() if (state != s_jumping) { v_line_t rightSide = {(int)x + w - 1, (int)y + h - 2, (int)y + h - 1}; // Comprueba solo los dos pixels de abajo - const int ry = room->checkRightSlopes(&rightSide); + const int ry = room_->checkRightSlopes(&rightSide); if (ry > -1) { y = ry - h; @@ -515,7 +514,7 @@ void Player::move() #endif // Comprueba la colisión - const int pos = room->checkBottomSurfaces(&proj); + const int pos = room_->checkBottomSurfaces(&proj); // Calcula la nueva posición if (pos == -1) @@ -544,7 +543,7 @@ void Player::move() #endif // Comprueba la colisión con las superficies normales y las automáticas - const int pos = std::max(room->checkTopSurfaces(&proj), room->checkAutoSurfaces(&proj)); + const int pos = std::max(room_->checkTopSurfaces(&proj), room_->checkAutoSurfaces(&proj)); if (pos > -1) { // Si hay colisión lo mueve hasta donde no colisiona y pasa a estar sobre la superficie y = pos - h; @@ -559,7 +558,7 @@ void Player::move() { // Las rampas no se miran si se está saltando v_line_t leftSide = {proj.x, proj.y, proj.y + proj.h - 1}; v_line_t rightSide = {proj.x + proj.w - 1, proj.y, proj.y + proj.h - 1}; - const int p = std::max(room->checkRightSlopes(&rightSide), room->checkLeftSlopes(&leftSide)); + const int p = std::max(room_->checkRightSlopes(&rightSide), room_->checkLeftSlopes(&leftSide)); if (p > -1) { // No está saltando y hay colisión con una rampa // Calcula la nueva posición @@ -588,12 +587,12 @@ void Player::move() } // Actualiza la posición del sprite - sprite->setPosX(x); - sprite->setPosY(y); + sprite_->setPosX(x); + sprite_->setPosY(y); #ifdef DEBUG - debug->add("RECT_X: " + std::to_string(rx.x) + "," + std::to_string(rx.y) + "," + std::to_string(rx.w) + "," + std::to_string(rx.h)); - debug->add("RECT_Y: " + std::to_string(ry.x) + "," + std::to_string(ry.y) + "," + std::to_string(ry.w) + "," + std::to_string(ry.h)); + debug_->add("RECT_X: " + std::to_string(rx.x) + "," + std::to_string(rx.y) + "," + std::to_string(rx.w) + "," + std::to_string(rx.h)); + debug_->add("RECT_Y: " + std::to_string(ry.x) + "," + std::to_string(ry.y) + "," + std::to_string(ry.w) + "," + std::to_string(ry.h)); #endif } @@ -602,7 +601,7 @@ void Player::animate() { if (vx != 0) { - sprite->animate(); + sprite_->animate(); } } @@ -632,7 +631,7 @@ void Player::playJumpSound() } #ifdef DEBUG - debug->add("JUMP: " + std::to_string(jumpCounter / 4)); + debug_->add("JUMP: " + std::to_string(jumpCounter / 4)); #endif } @@ -645,7 +644,7 @@ void Player::playFallSound() } #ifdef DEBUG - debug->add("FALL: " + std::to_string(fallCounter / 4)); + debug_->add("FALL: " + std::to_string(fallCounter / 4)); #endif } @@ -661,28 +660,28 @@ bool Player::isOnFloor() // Comprueba las superficies for (auto f : underFeet) { - onFloor |= room->checkTopSurfaces(&f); - onFloor |= room->checkAutoSurfaces(&f); + onFloor |= room_->checkTopSurfaces(&f); + onFloor |= room_->checkAutoSurfaces(&f); } // Comprueba las rampas - onSlopeL = room->checkLeftSlopes(&underFeet[0]); - onSlopeR = room->checkRightSlopes(&underFeet[1]); + onSlopeL = room_->checkLeftSlopes(&underFeet[0]); + onSlopeR = room_->checkRightSlopes(&underFeet[1]); #ifdef DEBUG if (onFloor) { - debug->add("ON_FLOOR"); + debug_->add("ON_FLOOR"); } if (onSlopeL) { - debug->add("ON_SLOPE_L: " + std::to_string(underFeet[0].x) + "," + std::to_string(underFeet[0].y)); + debug_->add("ON_SLOPE_L: " + std::to_string(underFeet[0].x) + "," + std::to_string(underFeet[0].y)); } if (onSlopeR) { - debug->add("ON_SLOPE_R: " + std::to_string(underFeet[1].x) + "," + std::to_string(underFeet[1].y)); + debug_->add("ON_SLOPE_R: " + std::to_string(underFeet[1].x) + "," + std::to_string(underFeet[1].y)); } #endif @@ -699,13 +698,13 @@ bool Player::isOnAutoSurface() // Comprueba las superficies for (auto f : underFeet) { - onAutoSurface |= room->checkAutoSurfaces(&f); + onAutoSurface |= room_->checkAutoSurfaces(&f); } #ifdef DEBUG if (onAutoSurface) { - debug->add("ON_AUTO_SURFACE"); + debug_->add("ON_AUTO_SURFACE"); } #endif @@ -725,13 +724,13 @@ bool Player::isOnDownSlope() underFeet[1].y += 1; // Comprueba las rampas - onSlope |= room->checkLeftSlopes(&underFeet[0]); - onSlope |= room->checkRightSlopes(&underFeet[1]); + onSlope |= room_->checkLeftSlopes(&underFeet[0]); + onSlope |= room_->checkRightSlopes(&underFeet[1]); #ifdef DEBUG if (onSlope) { - debug->add("ON_DOWN_SLOPE"); + debug_->add("ON_DOWN_SLOPE"); } #endif @@ -749,7 +748,7 @@ bool Player::checkKillingTiles() for (auto c : colliderPoints) { - check |= (room->getTile(c) == t_kill); + check |= (room_->getTile(c) == t_kill); } // Mata al jugador si hay colisión @@ -772,7 +771,7 @@ playerSpawn_t Player::getSpawnParams() params.vy = vy; params.jumpIni = jumpIni; params.state = state; - params.flipH = sprite->getFlipH(); + params.flipH = sprite_->getFlipH(); return params; } @@ -780,7 +779,7 @@ playerSpawn_t Player::getSpawnParams() // Recarga la textura void Player::reLoadTexture() { - sprite->getTexture()->reLoad(); + sprite_->getTexture()->reLoad(); } // Recarga la paleta @@ -800,7 +799,7 @@ void Player::reLoadPalette() // Establece el valor de la variable void Player::setRoom(Room *room) { - this->room = room; + this->room_ = room; } // Actualiza los puntos de colisión diff --git a/source/player.h b/source/player.h index 0c8f384..1815d15 100644 --- a/source/player.h +++ b/source/player.h @@ -36,25 +36,20 @@ struct player_t playerSpawn_t spawn; std::string png; std::string animation; - SDL_Renderer *renderer; - Resource *resource; - Asset *asset; - Input *input; Room *room; - Debug *debug; }; class Player { public: // Objetos y punteros - SDL_Renderer *renderer; // El renderizador de la ventana - Input *input; // Objeto para gestionar la entrada - Resource *resource; // Objeto con los recursos - Asset *asset; // Objeto con la ruta a todos los ficheros de recursos - Room *room; // Objeto encargado de gestionar cada habitación del juego - AnimatedSprite *sprite; // Sprite del enemigo - Debug *debug; // Objeto para gestionar la información de debug + SDL_Renderer *renderer_; // El renderizador de la ventana + Input *input_; // Objeto para gestionar la entrada + Resource *resource_; // Objeto con los recursos + Asset *asset_; // Objeto con la ruta a todos los ficheros de recursos + Room *room_; // Objeto encargado de gestionar cada habitación del juego + AnimatedSprite *sprite_; // Sprite del jugador + Debug *debug_; // Objeto para gestionar la información de debug // Variables float x; // Posición del jugador en el eje X diff --git a/source/resource.cpp b/source/resource.cpp index 866ab95..849e956 100644 --- a/source/resource.cpp +++ b/source/resource.cpp @@ -11,6 +11,27 @@ #include "screen.h" #include "options.h" +// [SINGLETON] +Resource *Resource::resource_ = nullptr; + +// [SINGLETON] Crearemos el objeto con esta función estática +void Resource::init() +{ + Resource::resource_ = new Resource(); +} + +// [SINGLETON] Destruiremos el objeto con esta función estática +void Resource::destroy() +{ + delete Resource::resource_; +} + +// [SINGLETON] Con este método obtenemos el objeto y podemos trabajar con él +Resource *Resource::get() +{ + return Resource::resource_; +} + // Carga las texturas de una lista void Resource::loadTextures(std::vector<std::string> list) { diff --git a/source/resource.h b/source/resource.h index 2765553..5e24e42 100644 --- a/source/resource.h +++ b/source/resource.h @@ -44,6 +44,9 @@ struct res_room_t class Resource { private: + // [SINGLETON] Objeto privado + static Resource *resource_; + // Variables std::vector<res_texture_t> textures_; std::vector<res_animation_t> animations_; @@ -51,13 +54,22 @@ private: std::vector<res_tileMap_t> tile_maps_; std::vector<res_room_t> rooms_; -public: // Constructor Resource() = default; // Destructor ~Resource() = default; +public: + // [SINGLETON] Crearemos el objeto con esta función estática + static void init(); + + // [SINGLETON] Destruiremos el objeto con esta función estática + static void destroy(); + + // [SINGLETON] Con este método obtenemos el objeto y podemos trabajar con él + static Resource *get(); + // Carga las texturas de una lista void loadTextures(std::vector<std::string> list); diff --git a/source/room.cpp b/source/room.cpp index 8512a04..c0088a3 100644 --- a/source/room.cpp +++ b/source/room.cpp @@ -404,16 +404,14 @@ bool setItem(item_t *item, std::string var, std::string value) } // Constructor -Room::Room(room_t *room, SDL_Renderer *renderer, Screen *screen, Asset *asset, ItemTracker *itemTracker, int *itemsPicked, bool jailEnabled, Debug *debug) +Room::Room(room_t *room, ItemTracker *itemTracker, int *itemsPicked, bool jailEnabled) + : screen(Screen::get()), + renderer(Screen::get()->getRenderer()), + asset(Asset::get()), + debug(Debug::get()), + itemTracker(itemTracker), + itemsPicked(itemsPicked) { - // Copia los punteros a objetos - this->renderer = renderer; - this->asset = asset; - this->screen = screen; - this->itemTracker = itemTracker; - this->itemsPicked = itemsPicked; - this->debug = debug; - number = room->number; name = room->name; bgColor = room->bgColor; diff --git a/source/room.h b/source/room.h index b0b77ab..cfedd37 100644 --- a/source/room.h +++ b/source/room.h @@ -73,18 +73,18 @@ 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<Enemy *> enemies; // Listado con los enemigos de la habitación std::vector<Item *> items; // Listado con los items que hay en la habitación Texture *texture; // Textura con los graficos de la habitación Texture *textureA; // Textura con los graficos de la habitación Texture *textureB; // Textura con los graficos de la habitación - Asset *asset; // Objeto con la ruta a todos los ficheros de recursos - Screen *screen; // Objeto encargado de dibujar en pantalla ItemTracker *itemTracker; // Lleva el control de los objetos recogidos - SDL_Renderer *renderer; // El renderizador de la ventana 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 - Debug *debug; // Objeto para gestionar la información de debug // Variables std::string number; // Numero de la habitación @@ -159,7 +159,7 @@ private: public: // Constructor - Room(room_t *room, SDL_Renderer *renderer, Screen *screen, Asset *asset, ItemTracker *itemTracker, int *itemsPicked, bool jailEnabled, Debug *debug); + Room(room_t *room, ItemTracker *itemTracker, int *itemsPicked, bool jailEnabled); // Destructor ~Room(); diff --git a/source/scoreboard.cpp b/source/scoreboard.cpp index 18150d0..4e5524a 100644 --- a/source/scoreboard.cpp +++ b/source/scoreboard.cpp @@ -7,17 +7,17 @@ #include "text.h" // Para Text #include "texture.h" // Para Texture #include "options.h" +#include "screen.h" +#include "asset.h" class Asset; // Constructor -ScoreBoard::ScoreBoard(SDL_Renderer *renderer, Resource *resource, Asset *asset, board_t *board) +Scoreboard::Scoreboard(board_t *board) + : renderer(Screen::get()->getRenderer()), + resource(Resource::get()), + asset(Asset::get()), + board(board) { - // Obten punteros a objetos - this->renderer = renderer; - this->resource = resource; - this->asset = asset; - this->board = board; - // Reserva memoria para los objetos itemTexture = resource->getTexture("items.png"); const std::string playerANI = options.cheat.altSkin ? "player2.ani" : "player.ani"; @@ -42,14 +42,14 @@ ScoreBoard::ScoreBoard(SDL_Renderer *renderer, Resource *resource, Asset *asset, } // Destructor -ScoreBoard::~ScoreBoard() +Scoreboard::~Scoreboard() { delete sprite; delete text; } // Pinta el objeto en pantalla -void ScoreBoard::render() +void Scoreboard::render() { // Anclas const int line1 = 19 * BLOCK; @@ -96,7 +96,7 @@ void ScoreBoard::render() } // Actualiza las variables del objeto -void ScoreBoard::update() +void Scoreboard::update() { counter++; sprite->update(); @@ -111,7 +111,7 @@ void ScoreBoard::update() } // Obtiene el tiempo transcurrido de partida -ScoreBoard::clock_t ScoreBoard::getTime() +Scoreboard::clock_t Scoreboard::getTime() { const Uint32 timeElapsed = SDL_GetTicks() - board->iniClock - totalTimePaused; @@ -125,7 +125,7 @@ ScoreBoard::clock_t ScoreBoard::getTime() } // Recarga la textura -void ScoreBoard::reLoadTexture() +void Scoreboard::reLoadTexture() { sprite->getTexture()->reLoad(); // playerTexture->reLoad(); @@ -134,7 +134,7 @@ void ScoreBoard::reLoadTexture() } // Recarga la paleta -void ScoreBoard::reLoadPalette() +void Scoreboard::reLoadPalette() { // Reinicia el vector de colores const std::vector<std::string> vColors = {"blue", "magenta", "green", "cyan", "yellow", "white", "bright_blue", "bright_magenta", "bright_green", "bright_cyan", "bright_yellow", "bright_white"}; @@ -146,21 +146,21 @@ void ScoreBoard::reLoadPalette() } // Pone el marcador en modo pausa -void ScoreBoard::pause() +void Scoreboard::pause() { paused = true; timePaused = SDL_GetTicks(); } // Quita el modo pausa del marcador -void ScoreBoard::resume() +void Scoreboard::resume() { paused = false; totalTimePaused += SDL_GetTicks() - timePaused; } // Actualiza el color de la cantidad de items recogidos -void ScoreBoard::updateItemsColor() +void Scoreboard::updateItemsColor() { if (!board->jailEnabled) { @@ -178,7 +178,7 @@ void ScoreBoard::updateItemsColor() } // Devuelve la cantidad de minutos de juego transcurridos -int ScoreBoard::getMinutes() +int Scoreboard::getMinutes() { return getTime().minutes; } \ No newline at end of file diff --git a/source/scoreboard.h b/source/scoreboard.h index 1958d34..7be98c4 100644 --- a/source/scoreboard.h +++ b/source/scoreboard.h @@ -22,7 +22,7 @@ struct board_t bool jailEnabled; // Indica si se puede entrar a la Jail }; -class ScoreBoard +class Scoreboard { private: struct clock_t @@ -60,10 +60,10 @@ private: public: // Constructor - ScoreBoard(SDL_Renderer *renderer, Resource *resource, Asset *asset, board_t *board); + Scoreboard(board_t *board); // Destructor - ~ScoreBoard(); + ~Scoreboard(); // Pinta el objeto en pantalla void render(); diff --git a/source/screen.cpp b/source/screen.cpp index 8255afe..894bf8d 100644 --- a/source/screen.cpp +++ b/source/screen.cpp @@ -435,25 +435,10 @@ void Screen::renderFX() renderSpectrumFade(); } -// Actualiza el notificador -void Screen::updateNotifier() -{ - Notifier::get()->update(); -} - -// Muestra una notificación de texto por pantalla; -void Screen::showNotification(std::string text1, std::string text2, int icon) -{ - Notifier::get()->showText(text1, text2, icon); -} - // Dibuja las notificaciones void Screen::renderNotifications() { - if (Notifier::get()->active()) - { - Notifier::get()->render(); - } + Notifier::get()->render(); } // Copia el gameCanvas en el borderCanvas @@ -498,4 +483,10 @@ void Screen::toggleShaders() { options.shaders = !options.shaders; setVideoMode(options.videoMode); +} + +// Actualiza la lógica de la clase +void Screen::update() +{ + Notifier::get()->update(); } \ No newline at end of file diff --git a/source/screen.h b/source/screen.h index 1ce3b85..c3ecf2d 100644 --- a/source/screen.h +++ b/source/screen.h @@ -99,6 +99,9 @@ public: // Vuelca el contenido del renderizador en pantalla void render(); + // Actualiza la lógica de la clase + void update(); + // Establece el modo de video void setVideoMode(int videoMode); @@ -148,12 +151,6 @@ public: // Dibuja los efectos void renderFX(); - // Actualiza el notificador - void updateNotifier(); - - // Muestra una notificación de texto por pantalla; - void showNotification(std::string text1 = "", std::string text2 = "", int icon = -1); - // Cambia el estado de los shaders void toggleShaders(); diff --git a/source/title.cpp b/source/title.cpp index 93b59f1..82c1c08 100644 --- a/source/title.cpp +++ b/source/title.cpp @@ -18,26 +18,26 @@ #include "options.h" // Constructor -Title::Title(Resource *resource) +Title::Title() : screen_(Screen::get()), renderer_(Screen::get()->getRenderer()), - resource_(resource), + resource_(Resource::get()), input_(Input::get()) { // Reserva memoria para los punteros event_handler_ = new SDL_Event(); - cheevos_ = std::make_unique<Cheevos>(screen_, Asset::get()->get("cheevos.bin")); + cheevos_ = std::make_unique<Cheevos>(Asset::get()->get("cheevos.bin")); if (options.palette == p_zxspectrum) { - texture_ = resource->getTexture("title_logo.png"); + texture_ = resource_->getTexture("title_logo.png"); } else if (options.palette == p_zxarne) { - texture_ = resource->getTexture("title_logo.png"); + texture_ = resource_->getTexture("title_logo.png"); } sprite_ = new Sprite(0, 0, texture_->getWidth(), texture_->getHeight(), texture_, renderer_); - text_ = new Text(resource->getOffset("smb2.txt"), resource->getTexture("smb2.png"), renderer_); - info_text_ = new Text(resource->getOffset("subatomic.txt"), resource->getTexture("subatomic.png"), renderer_); + text_ = new Text(resource_->getOffset("smb2.txt"), resource_->getTexture("smb2.png"), renderer_); + info_text_ = new Text(resource_->getOffset("subatomic.txt"), resource_->getTexture("subatomic.png"), renderer_); // Crea la textura para los graficos que aparecen en el fondo de la pantalla de titulo bg_texture_ = SDL_CreateTexture(renderer_, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, GAMECANVAS_WIDTH, GAMECANVAS_HEIGHT); @@ -271,8 +271,7 @@ void Title::update() // Comprueba las entradas checkInput(); - // Actualiza las notificaciones - screen_->updateNotifier(); + screen_->update(); // Incrementa el contador counter_++; @@ -447,7 +446,7 @@ void Title::fillTexture() void Title::createCheevosTexture() { // Crea la textura con el listado de logros - const std::vector<cheevos_t> cheevosList = cheevos_->list(); + const auto cheevosList = cheevos_->list(); const int cheevosTextureWidth = 200; const int cheevosTextureViewHeight = 110; const int cheevosTexturePosY = 73; diff --git a/source/title.h b/source/title.h index c4fab48..cbb394a 100644 --- a/source/title.h +++ b/source/title.h @@ -107,7 +107,7 @@ private: public: // Constructor - Title(Resource *resource); + Title(); // Destructor ~Title();