diff --git a/source/cheevos.cpp b/source/cheevos.cpp index af2dd46..d618f47 100644 --- a/source/cheevos.cpp +++ b/source/cheevos.cpp @@ -2,7 +2,7 @@ #include // Constructor -Cheevos::Cheevos(Screen *screen, options_t *options, string file) +Cheevos::Cheevos(Screen *screen, options_t *options, std::string file) { // Copia la dirección de los objetos this->options = options; @@ -169,7 +169,7 @@ void Cheevos::loadFromFile() { if (options->console) { - cout << "Warning: Unable to open file! SDL Error: " << SDL_GetError() << endl; + std::cout << "Warning: Unable to open file! SDL Error: " << SDL_GetError() << std::endl; } // Crea el fichero en modo escritura @@ -179,7 +179,7 @@ void Cheevos::loadFromFile() { if (options->console) { - cout << "New file created!" << endl; + std::cout << "New file created!" << std::endl; } // Guarda la información @@ -195,7 +195,7 @@ void Cheevos::loadFromFile() { if (options->console) { - cout << "Error: Unable to create file! SDL Error: " << SDL_GetError() << endl; + std::cout << "Error: Unable to create file! SDL Error: " << SDL_GetError() << std::endl; } } } @@ -205,7 +205,7 @@ void Cheevos::loadFromFile() // Carga los datos if (options->console) { - cout << "Reading file...!" << endl; + std::cout << "Reading file...!" << std::endl; } for (int i = 0; i < (int)cheevos.size(); ++i) { @@ -237,13 +237,13 @@ void Cheevos::saveToFile() { if (options->console) { - cout << "Error: Unable to save file! " << SDL_GetError() << endl; + std::cout << "Error: Unable to save file! " << SDL_GetError() << std::endl; } } } // Lista los logros -vector Cheevos::list() +std::vector Cheevos::list() { return cheevos; } diff --git a/source/cheevos.h b/source/cheevos.h index b140a28..d4947a1 100644 --- a/source/cheevos.h +++ b/source/cheevos.h @@ -8,16 +8,14 @@ #ifndef CHEEVOS_H #define CHEEVOS_H -using namespace std; - struct cheevos_t { - int id; // Identificador del logro - string caption; // Texto con el nombre del logro - string description; // Texto que describe el logro - 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 + int id; // Identificador del logro + std::string caption; // Texto con el nombre del logro + std::string description; // Texto que describe el logro + 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 }; class Cheevos @@ -28,9 +26,9 @@ private: options_t *options; // Puntero a las opciones del juego // Variables - vector cheevos; // Listado de logros - bool enabled; // Indica si los logros se pueden obtener - string file; // Fichero done leer/almacenar el estado de los logros + 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 // Inicializa los logros void init(); @@ -46,7 +44,7 @@ private: public: // Constructor - Cheevos(Screen *screen, options_t *options, string file); + Cheevos(Screen *screen, options_t *options, std::string file); // Destructor ~Cheevos(); @@ -61,7 +59,7 @@ public: void enable(bool value); // Lista los logros - vector list(); + std::vector list(); // Devuelve el número total de logros desbloqueados int unlocked(); diff --git a/source/credits.cpp b/source/credits.cpp index e23d3e5..478fa2d 100644 --- a/source/credits.cpp +++ b/source/credits.cpp @@ -37,7 +37,7 @@ Credits::Credits(SDL_Renderer *renderer, Screen *screen, Resource *resource, Ass { if (options->console) { - cout << "Error: textTexture could not be created!\nSDL Error: " << SDL_GetError() << endl; + std::cout << "Error: textTexture could not be created!\nSDL Error: " << SDL_GetError() << std::endl; } } SDL_SetTextureBlendMode(textTexture, SDL_BLENDMODE_BLEND); @@ -48,7 +48,7 @@ Credits::Credits(SDL_Renderer *renderer, Screen *screen, Resource *resource, Ass { if (options->console) { - cout << "Error: textTexture could not be created!\nSDL Error: " << SDL_GetError() << endl; + std::cout << "Error: textTexture could not be created!\nSDL Error: " << SDL_GetError() << std::endl; } } SDL_SetTextureBlendMode(coverTexture, SDL_BLENDMODE_BLEND); @@ -126,7 +126,7 @@ void Credits::checkInput() // Inicializa los textos void Credits::iniTexts() { - string keys = ""; + std::string keys = ""; if (options->keys == ctrl_cursor) { keys = "CURSORS"; @@ -331,7 +331,7 @@ void Credits::render() SDL_RenderCopy(renderer, textTexture, nullptr, nullptr); // Dibuja la textura que cubre el texto - const int offset = min(counter / 8, 192 / 2); + const int offset = std::min(counter / 8, 192 / 2); SDL_Rect srcRect = {0, 0, 256, 192 - (offset * 2)}; SDL_Rect dstRect = {0, offset * 2, 256, 192 - (offset * 2)}; SDL_RenderCopy(renderer, coverTexture, &srcRect, &dstRect); diff --git a/source/credits.h b/source/credits.h index 539a782..7e8e4c9 100644 --- a/source/credits.h +++ b/source/credits.h @@ -17,15 +17,13 @@ #ifndef CREDITS_H #define CREDITS_H -using namespace std; - class Credits { private: struct captions_t { - string label; // Texto a escribir - color_t color; // Color del texto + std::string label; // Texto a escribir + color_t color; // Color del texto }; // Objetos y punteros @@ -43,12 +41,12 @@ private: section_t *section; // Estado del bucle principal para saber si continua o se sale // Variables - int counter; // Contador - bool counterEnabled; // Indica si esta activo el contador - int subCounter; // Contador secundario - Uint32 ticks; // Contador de ticks para ajustar la velocidad del programa - Uint32 ticksSpeed; // Velocidad a la que se repiten los bucles del programa - vector texts; // Vector con los textos + int counter; // Contador + bool counterEnabled; // Indica si esta activo el contador + int subCounter; // Contador secundario + Uint32 ticks; // Contador de ticks para ajustar la velocidad del programa + Uint32 ticksSpeed; // Velocidad a la que se repiten los bucles del programa + std::vector texts; // Vector con los textos // Actualiza las variables void update(); diff --git a/source/demo.cpp b/source/demo.cpp index 57d6d9a..6986d4c 100644 --- a/source/demo.cpp +++ b/source/demo.cpp @@ -192,7 +192,7 @@ void Demo::reLoadTextures() { if (options->console) { - cout << "** RELOAD REQUESTED" << endl; + std::cout << "** RELOAD REQUESTED" << std::endl; } room->reLoadTexture(); scoreboard->reLoadTexture(); @@ -220,7 +220,7 @@ void Demo::switchPalette() } // Cambia de habitación -bool Demo::changeRoom(string file) +bool Demo::changeRoom(std::string file) { // En las habitaciones los limites tienen la cadena del fichero o un 0 en caso de no limitar con nada if (file != "0") diff --git a/source/demo.h b/source/demo.h index 6c53556..f9d9b21 100644 --- a/source/demo.h +++ b/source/demo.h @@ -20,8 +20,6 @@ #ifndef DEMO_H #define DEMO_H -using namespace std; - class Demo { private: @@ -41,14 +39,14 @@ private: section_t *section; // Seccion actual dentro del juego // Variables - Uint32 ticks; // Contador de ticks para ajustar la velocidad del programa - Uint32 ticksSpeed; // Velocidad a la que se repiten los bucles del programa - string currentRoom; // Fichero de la habitación actual - board_t board; // Estructura con los datos del marcador - int counter; // Contador para el modo demo - int roomTime; // Tiempo que se muestra cada habitacion - int roomIndex; // Indice para el vector de habitaciones - vector rooms; // Listado con los mapas de la demo + Uint32 ticks; // Contador de ticks para ajustar la velocidad del programa + Uint32 ticksSpeed; // Velocidad a la que se repiten los bucles del programa + std::string currentRoom; // Fichero de la habitación actual + board_t board; // Estructura con los datos del marcador + int counter; // Contador para el modo demo + int roomTime; // Tiempo que se muestra cada habitacion + int roomIndex; // Indice para el vector de habitaciones + std::vector rooms; // Listado con los mapas de la demo // Actualiza el juego, las variables, comprueba la entrada, etc. void update(); @@ -72,7 +70,7 @@ private: void switchPalette(); // Cambia de habitación - bool changeRoom(string file); + bool changeRoom(std::string file); // Comprueba si se ha de cambiar de habitación void checkRoomChange(); diff --git a/source/director.cpp b/source/director.cpp index 30b3d4f..4944703 100644 --- a/source/director.cpp +++ b/source/director.cpp @@ -100,11 +100,11 @@ void Director::initOnline() { // Establece el servidor y el puerto jscore::init(options->online.server, options->online.port); - const string caption = options->online.jailerID + " IS LOGGED IN"; + const std::string caption = options->online.jailerID + " IS LOGGED IN"; screen->showNotification(caption); if (options->console) { - cout << caption << endl; + std::cout << caption << std::endl; } } } @@ -214,12 +214,12 @@ bool Director::loadConfig() bool success = true; // Versión actual del fichero - const string configVersion = options->configVersion; + const std::string configVersion = options->configVersion; options->configVersion = ""; // Variables para manejar el fichero - string line; - ifstream file(asset->get("config.txt")); + std::string line; + std::ifstream file(asset->get("config.txt")); // Si el fichero se puede abrir if (file.good()) @@ -227,9 +227,9 @@ bool Director::loadConfig() // Procesa el fichero linea a linea if (options->console) { - cout << "Reading file config.txt\n"; + std::cout << "Reading file config.txt\n"; } - while (getline(file, line)) + while (std::getline(file, line)) { // Comprueba que la linea no sea un comentario if (line.substr(0, 1) != "#") @@ -241,8 +241,8 @@ bool Director::loadConfig() { if (options->console) { - cout << "Warning: file config.txt\n"; - cout << "unknown parameter " << line.substr(0, pos).c_str() << endl; + std::cout << "Warning: file config.txt\n"; + std::cout << "unknown parameter " << line.substr(0, pos).c_str() << std::endl; } success = false; } @@ -252,7 +252,7 @@ bool Director::loadConfig() // Cierra el fichero if (options->console) { - cout << "Closing file config.txt\n\n"; + std::cout << "Closing file config.txt\n\n"; } file.close(); } @@ -307,20 +307,20 @@ bool Director::saveConfig() bool success = true; // Crea y abre el fichero de texto - ofstream file(asset->get("config.txt")); + std::ofstream file(asset->get("config.txt")); if (file.good()) { if (options->console) { - cout << asset->get("config.txt") << " open for writing" << endl; + std::cout << asset->get("config.txt") << " open for writing" << std::endl; } } else { if (options->console) { - cout << asset->get("config.txt") << " can't be opened" << endl; + std::cout << asset->get("config.txt") << " can't be opened" << std::endl; } } @@ -359,7 +359,7 @@ bool Director::saveConfig() file << "videoMode=SDL_WINDOW_FULLSCREEN_DESKTOP\n"; } - file << "windowSize=" + to_string(options->windowSize) + "\n"; + file << "windowSize=" + std::to_string(options->windowSize) + "\n"; if (options->filter == FILTER_NEAREST) { @@ -374,14 +374,14 @@ bool Director::saveConfig() file << "integerScale=" + boolToString(options->integerScale) + "\n"; file << "keepAspect=" + boolToString(options->keepAspect) + "\n"; file << "borderEnabled=" + boolToString(options->borderEnabled) + "\n"; - file << "borderWidth=" + to_string(options->borderWidth) + "\n"; - file << "borderHeight=" + to_string(options->borderHeight) + "\n"; - file << "palette=" + to_string(options->palette) + "\n"; + file << "borderWidth=" + std::to_string(options->borderWidth) + "\n"; + file << "borderHeight=" + std::to_string(options->borderHeight) + "\n"; + file << "palette=" + std::to_string(options->palette) + "\n"; file << "\n## ONLINE OPTIONS\n"; file << "enabled=" + boolToString(options->online.enabled) + "\n"; file << "server=" + options->online.server + "\n"; - file << "port=" + to_string(options->online.port) + "\n"; + file << "port=" + std::to_string(options->online.port) + "\n"; file << "jailerID=" + options->online.jailerID + "\n"; file << "\n## NOTIFICATION OPTIONS\n"; @@ -418,18 +418,18 @@ bool Director::saveConfig() } // Crea la carpeta del sistema donde guardar datos -void Director::createSystemFolder(string folder) +void Director::createSystemFolder(std::string folder) { #ifdef _WIN32 - systemFolder = string(getenv("APPDATA")) + "/" + folder; + systemFolder = std::string(getenv("APPDATA")) + "/" + folder; #elif __APPLE__ struct passwd *pw = getpwuid(getuid()); const char *homedir = pw->pw_dir; - systemFolder = string(homedir) + "/Library/Application Support" + "/" + folder; + systemFolder = std::string(homedir) + "/Library/Application Support" + "/" + folder; #elif __linux__ struct passwd *pw = getpwuid(getuid()); const char *homedir = pw->pw_dir; - systemFolder = string(homedir) + "/." + folder; + systemFolder = std::string(homedir) + "/." + folder; #endif struct stat st = {0}; @@ -471,12 +471,12 @@ void Director::loadResources(section_t *section) { if (options->console) { - cout << "** LOAD RESOURCES" << endl; + std::cout << "** LOAD RESOURCES" << std::endl; } if (section->name == SECTION_PROG_LOGO) { - vector textureList; + std::vector textureList; textureList.push_back("jailgames.png"); textureList.push_back("since_1998.png"); @@ -485,7 +485,7 @@ void Director::loadResources(section_t *section) else if (section->name == SECTION_PROG_INTRO) { - vector textureList; + std::vector textureList; textureList.push_back("loading_screen_bn.png"); textureList.push_back("loading_screen_color.png"); textureList.push_back("loading_screen_bn_zxarne.png"); @@ -496,7 +496,7 @@ void Director::loadResources(section_t *section) else if (section->name == SECTION_PROG_TITLE) { - vector textureList; + std::vector textureList; textureList.push_back("loading_screen_color.png"); textureList.push_back("loading_screen_color_zxarne.png"); textureList.push_back("smb2.png"); @@ -506,7 +506,7 @@ void Director::loadResources(section_t *section) resource->loadTextures(textureList); // Offsets - vector offsetsList; + std::vector offsetsList; offsetsList.push_back("smb2.txt"); offsetsList.push_back("debug.txt"); @@ -516,20 +516,20 @@ void Director::loadResources(section_t *section) else if (section->name == SECTION_PROG_CREDITS) { // Texturas - vector textureList; + std::vector textureList; textureList.push_back("shine.png"); textureList.push_back("smb2.png"); resource->loadTextures(textureList); // Animaciones - vector animationList; + std::vector animationList; animationList.push_back("shine.ani"); resource->loadAnimations(animationList); // Offsets - vector offsetsList; + std::vector offsetsList; offsetsList.push_back("smb2.txt"); resource->loadOffsets(offsetsList); @@ -538,7 +538,7 @@ void Director::loadResources(section_t *section) else if (section->name == SECTION_PROG_ENDING) { // Texturas - vector textureList; + std::vector textureList; textureList.push_back("ending1.png"); textureList.push_back("ending1_zxarne.png"); textureList.push_back("ending2.png"); @@ -554,7 +554,7 @@ void Director::loadResources(section_t *section) resource->loadTextures(textureList); // Offsets - vector offsetsList; + std::vector offsetsList; offsetsList.push_back("smb2.txt"); resource->loadOffsets(offsetsList); @@ -563,7 +563,7 @@ void Director::loadResources(section_t *section) else if (section->name == SECTION_PROG_ENDING2) { // Texturas - vector textureList; + std::vector textureList; // Texto textureList.push_back("smb2.png"); @@ -629,7 +629,7 @@ void Director::loadResources(section_t *section) resource->loadTextures(textureList); // Animaciones - vector animationList; + std::vector animationList; // Enemigos animationList.push_back("abad.ani"); @@ -692,7 +692,7 @@ void Director::loadResources(section_t *section) resource->loadAnimations(animationList); // Offsets - vector offsetsList; + std::vector offsetsList; offsetsList.push_back("smb2.txt"); resource->loadOffsets(offsetsList); @@ -701,7 +701,7 @@ void Director::loadResources(section_t *section) else if (section->name == SECTION_PROG_GAME_OVER) { // Texturas - vector textureList; + std::vector textureList; textureList.push_back("smb2.png"); textureList.push_back("player_game_over.png"); textureList.push_back("tv.png"); @@ -709,14 +709,14 @@ void Director::loadResources(section_t *section) resource->loadTextures(textureList); // Animaciones - vector animationList; + std::vector animationList; animationList.push_back("player_game_over.ani"); animationList.push_back("tv.ani"); resource->loadAnimations(animationList); // Offsets - vector offsetsList; + std::vector offsetsList; offsetsList.push_back("smb2.txt"); resource->loadOffsets(offsetsList); @@ -725,7 +725,7 @@ void Director::loadResources(section_t *section) else if (section->name == SECTION_PROG_GAME || section->name == SECTION_PROG_DEMO) { // Texturas - vector textureList; + std::vector textureList; // Jugador if (options->cheat.altSkin) @@ -810,7 +810,7 @@ void Director::loadResources(section_t *section) resource->loadTextures(textureList); // Animaciones - vector animationList; + std::vector animationList; // Jugador if (options->cheat.altSkin) @@ -884,14 +884,14 @@ void Director::loadResources(section_t *section) resource->loadAnimations(animationList); // Offsets - vector offsetsList; + std::vector offsetsList; offsetsList.push_back("smb2.txt"); offsetsList.push_back("debug.txt"); resource->loadOffsets(offsetsList); // TileMaps - vector tileMapList; + std::vector tileMapList; tileMapList.push_back("01.tmx"); tileMapList.push_back("02.tmx"); tileMapList.push_back("03.tmx"); @@ -956,7 +956,7 @@ void Director::loadResources(section_t *section) resource->loadTileMaps(tileMapList); // Habitaciones - vector roomList; + std::vector roomList; roomList.push_back("01.room"); roomList.push_back("02.room"); roomList.push_back("03.room"); @@ -1023,12 +1023,12 @@ void Director::loadResources(section_t *section) if (options->console) { - cout << "** RESOURCES LOADED" << endl; + std::cout << "** RESOURCES LOADED" << std::endl; } } // Asigna variables a partir de dos cadenas -bool Director::setOptions(options_t *options, string var, string value) +bool Director::setOptions(options_t *options, std::string var, std::string value) { // Indicador de éxito en la asignación bool success = true; @@ -1072,7 +1072,7 @@ bool Director::setOptions(options_t *options, string var, string value) else if (var == "windowSize") { - options->windowSize = stoi(value); + options->windowSize = std::stoi(value); if ((options->windowSize < 1) || (options->windowSize > 4)) { options->windowSize = 3; @@ -1113,17 +1113,17 @@ bool Director::setOptions(options_t *options, string var, string value) else if (var == "borderWidth") { - options->borderWidth = stoi(value); + options->borderWidth = std::stoi(value); } else if (var == "borderHeight") { - options->borderHeight = stoi(value); + options->borderHeight = std::stoi(value); } else if (var == "palette") { - const int pal = stoi(value); + const int pal = std::stoi(value); if (pal == 0) { @@ -1152,7 +1152,7 @@ bool Director::setOptions(options_t *options, string var, string value) { value = "0"; } - options->online.port = stoi(value); + options->online.port = std::stoi(value); } else if (var == "jailerID") @@ -1222,6 +1222,7 @@ void Director::initInput() input->bindKey(input_right, SDL_SCANCODE_RIGHT); input->bindKey(input_up, SDL_SCANCODE_UP); input->bindKey(input_down, SDL_SCANCODE_DOWN); + } else if (options->keys == ctrl_opqa) { @@ -1289,21 +1290,21 @@ bool Director::initSDL() { if (options->console) { - cout << "SDL could not initialize!\nSDL Error: " << SDL_GetError() << endl; + std::cout << "SDL could not initialize!\nSDL Error: " << SDL_GetError() << std::endl; } success = false; } else { // Inicia el generador de numeros aleatorios - srand(static_cast(SDL_GetTicks())); + std::srand(static_cast(SDL_GetTicks())); // Establece el filtro de la textura a nearest - if (!SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, to_string(options->filter).c_str())) + if (!SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, std::to_string(options->filter).c_str())) { if (options->console) { - cout << "Warning: Nearest texture filtering not enabled!\n"; + std::cout << "Warning: Nearest texture filtering not enabled!\n"; } } @@ -1321,7 +1322,7 @@ bool Director::initSDL() { if (options->console) { - cout << "Window could not be created!\nSDL Error: " << SDL_GetError() << endl; + std::cout << "Window could not be created!\nSDL Error: " << SDL_GetError() << std::endl; } success = false; } @@ -1341,7 +1342,7 @@ bool Director::initSDL() { if (options->console) { - cout << "Renderer could not be created!\nSDL Error: " << SDL_GetError() << endl; + std::cout << "Renderer could not be created!\nSDL Error: " << SDL_GetError() << std::endl; } success = false; } @@ -1361,7 +1362,7 @@ bool Director::initSDL() if (options->console) { - cout << endl; + std::cout << std::endl; } return success; } @@ -1370,9 +1371,9 @@ bool Director::initSDL() bool Director::setFileList() { #ifdef MACOS_BUNDLE - const string prefix = "/../Resources"; + const std::string prefix = "/../Resources"; #else - const string prefix = ""; + const std::string prefix = ""; #endif // Texto @@ -1721,7 +1722,7 @@ void Director::runLogo() { if (options->console) { - cout << "\n* SECTION: LOGO" << endl; + std::cout << "\n* SECTION: LOGO" << std::endl; } loadResources(section); logo = new Logo(renderer, screen, resource, asset, input, options, section); @@ -1735,7 +1736,7 @@ void Director::runIntro() { if (options->console) { - cout << "\n* SECTION: INTRO" << endl; + std::cout << "\n* SECTION: INTRO" << std::endl; } loadResources(section); intro = new Intro(renderer, screen, resource, asset, input, options, section); @@ -1749,7 +1750,7 @@ void Director::runTitle() { if (options->console) { - cout << "\n* SECTION: TITLE" << endl; + std::cout << "\n* SECTION: TITLE" << std::endl; } if ((JA_GetMusicState() == JA_MUSIC_INVALID) || (JA_GetMusicState() == JA_MUSIC_STOPPED)) { @@ -1767,7 +1768,7 @@ void Director::runCredits() { if (options->console) { - cout << "\n* SECTION: CREDITS" << endl; + std::cout << "\n* SECTION: CREDITS" << std::endl; } loadResources(section); credits = new Credits(renderer, screen, resource, asset, input, options, section); @@ -1781,7 +1782,7 @@ void Director::runDemo() { if (options->console) { - cout << "\n* SECTION: DEMO" << endl; + std::cout << "\n* SECTION: DEMO" << std::endl; } loadResources(section); demo = new Demo(renderer, screen, resource, asset, input, options, section, debug); @@ -1795,7 +1796,7 @@ void Director::runEnterID() { if (options->console) { - cout << "\n* SECTION: ENTER_ID" << endl; + std::cout << "\n* SECTION: ENTER_ID" << std::endl; } // loadResources(section); enterID = new EnterID(renderer, screen, asset, options, section); @@ -1809,7 +1810,7 @@ void Director::runEnding() { if (options->console) { - cout << "\n* SECTION: ENDING" << endl; + std::cout << "\n* SECTION: ENDING" << std::endl; } loadResources(section); ending = new Ending(renderer, screen, resource, asset, input, options, section); @@ -1823,7 +1824,7 @@ void Director::runEnding2() { if (options->console) { - cout << "\n* SECTION: ENDING2" << endl; + std::cout << "\n* SECTION: ENDING2" << std::endl; } loadResources(section); ending2 = new Ending2(renderer, screen, resource, asset, input, options, section); @@ -1837,7 +1838,7 @@ void Director::runGameOver() { if (options->console) { - cout << "\n* SECTION: GAME OVER" << endl; + std::cout << "\n* SECTION: GAME OVER" << std::endl; } loadResources(section); gameOver = new GameOver(renderer, screen, resource, asset, input, options, section); @@ -1851,7 +1852,7 @@ void Director::runGame() { if (options->console) { - cout << "\n* SECTION: GAME" << endl; + std::cout << "\n* SECTION: GAME" << std::endl; } JA_StopMusic(); loadResources(section); diff --git a/source/director.h b/source/director.h index 8d3e31e..60c0ccd 100644 --- a/source/director.h +++ b/source/director.h @@ -24,8 +24,6 @@ #ifndef DIRECTOR_H #define DIRECTOR_H -using namespace std; - class Director { private: @@ -51,9 +49,9 @@ private: section_t *section; // Sección y subsección actual del programa; // Variables - JA_Music_t *music; // Musica del titulo - string executablePath; // Path del ejecutable - string systemFolder; // Carpeta del sistema donde guardar datos + JA_Music_t *music; // Musica del titulo + std::string executablePath; // Path del ejecutable + std::string systemFolder; // Carpeta del sistema donde guardar datos // Crea e inicializa las opciones del programa void initOptions(); @@ -71,13 +69,13 @@ private: bool saveConfig(); // Crea la carpeta del sistema donde guardar datos - void createSystemFolder(string folder); + void createSystemFolder(std::string folder); // Carga los recursos void loadResources(section_t *section); // Asigna variables a partir de dos cadenas - bool setOptions(options_t *options, string var, string value); + bool setOptions(options_t *options, std::string var, std::string value); // Inicializa jail_audio void initJailAudio(); diff --git a/source/ending.cpp b/source/ending.cpp index b4b9dbc..5ee50ed 100644 --- a/source/ending.cpp +++ b/source/ending.cpp @@ -45,7 +45,7 @@ Ending::Ending(SDL_Renderer *renderer, Screen *screen, Resource *resource, Asset { if (options->console) { - cout << "Error: canvasTexture could not be created!\nSDL Error: " << SDL_GetError() << endl; + std::cout << "Error: canvasTexture could not be created!\nSDL Error: " << SDL_GetError() << std::endl; } } SDL_SetTextureBlendMode(coverTexture, SDL_BLENDMODE_BLEND); @@ -140,7 +140,7 @@ void Ending::render() // Dibuja la cortinilla de cambio de escena renderCoverTexture(); - // text->write(0, 0, to_string(counter)); + // text->write(0, 0, std::to_string(counter)); // Vuelca el contenido del renderizador en pantalla screen->blit(); @@ -201,7 +201,7 @@ void Ending::checkInput() void Ending::iniTexts() { // Vector con los textos - vector texts; + std::vector texts; // Escena #0 texts.push_back({"HE FINALLY MANAGED", 32}); @@ -307,7 +307,7 @@ void Ending::iniTexts() void Ending::iniPics() { // Vector con las rutas y la posición - vector pics; + std::vector pics; if (options->palette == p_zxspectrum) { @@ -605,7 +605,7 @@ void Ending::renderCoverTexture() { if (coverCounter > 0) { // Dibuja la textura que cubre el texto - const int offset = min(coverCounter, 100); + const int offset = std::min(coverCounter, 100); SDL_Rect srcRect = {0, 200 - (coverCounter * 2), 256, offset * 2}; SDL_Rect dstRect = {0, 0, 256, offset * 2}; SDL_RenderCopy(renderer, coverTexture, &srcRect, &dstRect); diff --git a/source/ending.h b/source/ending.h index 5d10597..8f95383 100644 --- a/source/ending.h +++ b/source/ending.h @@ -17,8 +17,6 @@ #ifndef ENDING_H #define ENDING_H -using namespace std; - class Ending { private: @@ -35,8 +33,8 @@ private: struct textAndPos_t // Estructura con un texto y su posición en el eje Y { - string caption; // Texto - int pos; // Posición + std::string caption; // Texto + int pos; // Posición }; struct asdhk @@ -47,9 +45,9 @@ private: struct scene_t // Estructura para crear cada una de las escenas del final { - vector textIndex; // Indices del vector de textos a mostrar y su disparador - int pictureIndex; // Indice del vector de imagenes a mostrar - int counterEnd; // Valor del contador en el que finaliza la escena + std::vector textIndex; // Indices del vector de textos a mostrar y su disparador + int pictureIndex; // Indice del vector de imagenes a mostrar + int counterEnd; // Valor del contador en el que finaliza la escena }; // Objetos y punteros @@ -65,16 +63,16 @@ private: section_t *section; // Estado del bucle principal para saber si continua o se sale // Variables - int counter; // Contador - int preCounter; // Contador previo - int coverCounter; // Contador para la cortinilla - Uint32 ticks; // Contador de ticks para ajustar la velocidad del programa - Uint32 ticksSpeed; // Velocidad a la que se repiten los bucles del programa - vector spriteTexts; // Vector con los sprites de texto con su cortinilla - vector spritePics; // Vector con los sprites de texto con su cortinilla - int scene; // Escena actual - vector scenes; // Vector con los textos e imagenes de cada escena - JA_Music_t *music; // Musica que suena durante el final + int counter; // Contador + int preCounter; // Contador previo + int coverCounter; // Contador para la cortinilla + Uint32 ticks; // Contador de ticks para ajustar la velocidad del programa + Uint32 ticksSpeed; // Velocidad a la que se repiten los bucles del programa + std::vector spriteTexts; // Vector con los sprites de texto con su cortinilla + std::vector spritePics; // Vector con los sprites de texto con su cortinilla + int scene; // Escena actual + std::vector scenes; // Vector con los textos e imagenes de cada escena + JA_Music_t *music; // Musica que suena durante el final // Actualiza el objeto void update(); diff --git a/source/ending2.cpp b/source/ending2.cpp index 3eeb164..95cdb85 100644 --- a/source/ending2.cpp +++ b/source/ending2.cpp @@ -34,7 +34,7 @@ Ending2::Ending2(SDL_Renderer *renderer, Screen *screen, Resource *resource, Ass secondCol = GAMECANVAS_THIRD_QUARTER_X - (GAMECANVAS_WIDTH / 16); // Inicializa el vector de colores - const vector colorList = {"white", "yellow", "cyan", "green", "magenta", "red", "blue", "black"}; + const std::vector colorList = {"white", "yellow", "cyan", "green", "magenta", "red", "blue", "black"}; for (auto cl : colorList) { colors.push_back(stringToColor(options->palette, cl)); @@ -131,7 +131,7 @@ void Ending2::render() // Dibuja los sprites con el texto del final renderTexts(); - const string txt = to_string(postCounter); + const std::string txt = std::to_string(postCounter); // text->write(0, 192 - 8, txt); // Dibuja la cuadricula @@ -363,8 +363,8 @@ void Ending2::loadSprites() for (auto sl : spriteList) { sprites.push_back(new AnimatedSprite(renderer, resource->getAnimation(sl + ".ani"))); - maxSpriteWidth = max(sprites.back()->getAnimationClip(0, 0).w, maxSpriteWidth); - maxSpriteHeight = max(sprites.back()->getAnimationClip(0, 0).h, maxSpriteHeight); + maxSpriteWidth = std::max(sprites.back()->getAnimationClip(0, 0).w, maxSpriteWidth); + maxSpriteHeight = std::max(sprites.back()->getAnimationClip(0, 0).h, maxSpriteHeight); } } @@ -488,8 +488,8 @@ void Ending2::createSpriteTexts() for (int i = 0; i < (int)spriteList.size(); ++i) { // Calcula constantes - string txt = spriteList[i]; - replace(txt.begin(), txt.end(), '_', ' '); + std::string txt = spriteList[i]; + std::replace(txt.begin(), txt.end(), '_', ' '); txt = txt == "player" ? "JAILDOCTOR" : txt; // Reemplaza el texto const int w = text->lenght(txt, 1); const int h = text->getCharacterSize(); @@ -520,7 +520,7 @@ void Ending2::createTexts() deleteTexts(); // Crea los primeros textos - vector list; + std::vector list; list.push_back("STARRING"); // Crea los sprites de texto a partir de la lista @@ -610,7 +610,7 @@ void Ending2::deleteTexts() void Ending2::updateFinalFade() { // La variable step va de 0 a 40 en el tramo de postCounter que va de 500 a 540. Al dividirlo por 40, va de 0.0f a 1.0f - const float step = min(max(postCounter, 500) - 500, 40) / 40.0f; + const float step = std::min(std::max(postCounter, 500) - 500, 40) / 40.0f; const int index = (colors.size() - 1) * step; for (auto t : texts) diff --git a/source/ending2.h b/source/ending2.h index d3221e7..21e5262 100644 --- a/source/ending2.h +++ b/source/ending2.h @@ -17,42 +17,40 @@ #ifndef ENDING2_H #define ENDING2_H -using namespace std; - 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 - Input *input; // Objeto pata gestionar la entrada - Text *text; // Objeto para escribir texto en pantalla - options_t *options; // Puntero a las opciones del juego - vector sprites; // Vector con todos los sprites a dibujar - vector spriteTexts; // Vector con los sprites de texto de los sprites - vector texts; // Vector con los sprites de texto - section_t *section; // Estado del bucle principal para saber si continua o se sale + 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 + Input *input; // Objeto pata gestionar la entrada + Text *text; // Objeto para escribir texto en pantalla + options_t *options; // Puntero a las opciones del juego + std::vector sprites; // Vector con todos los sprites a dibujar + std::vector spriteTexts; // Vector con los sprites de texto de los sprites + std::vector texts; // Vector con los sprites de texto + section_t *section; // Estado del bucle principal para saber si continua o se sale // Variables - bool counterEnabled; // Indica si está el contador habilitado - int preCounter; // Contador previo - int postCounter; // Contador posterior - bool postCounterEnabled; // Indica si está habilitado el contador - Uint32 ticks; // Contador de ticks para ajustar la velocidad del programa - Uint32 ticksSpeed; // Velocidad a la que se repiten los bucles del programa - JA_Music_t *music; // Musica que suena durante el final - vector spriteList; // Lista con todos los sprites a dibujar - vector colors; // Vector con los colores para el fade - int maxSpriteWidth; // El valor de ancho del sprite mas ancho - int maxSpriteHeight; // El valor de alto del sprite mas alto - int distSpriteText; // Distancia entre el sprite y el texto que lo acompaña - int distSpriteSprite; // Distancia entre dos sprites de la misma columna - float despSpeed; // Velocidad de desplazamiento de los sprites - int firstCol; // Primera columna por donde desfilan los sprites - int secondCol; // Segunda columna por donde desfilan los sprites + bool counterEnabled; // Indica si está el contador habilitado + int preCounter; // Contador previo + int postCounter; // Contador posterior + bool postCounterEnabled; // Indica si está habilitado el contador + Uint32 ticks; // Contador de ticks para ajustar la velocidad del programa + Uint32 ticksSpeed; // Velocidad a la que se repiten los bucles del programa + JA_Music_t *music; // Musica que suena durante el final + std::vector spriteList; // Lista con todos los sprites a dibujar + std::vector colors; // Vector con los colores para el fade + int maxSpriteWidth; // El valor de ancho del sprite mas ancho + int maxSpriteHeight; // El valor de alto del sprite mas alto + int distSpriteText; // Distancia entre el sprite y el texto que lo acompaña + int distSpriteSprite; // Distancia entre dos sprites de la misma columna + float despSpeed; // Velocidad de desplazamiento de los sprites + int firstCol; // Primera columna por donde desfilan los sprites + int secondCol; // Segunda columna por donde desfilan los sprites // Actualiza el objeto void update(); diff --git a/source/enemy.cpp b/source/enemy.cpp index 29ec107..4075fed 100644 --- a/source/enemy.cpp +++ b/source/enemy.cpp @@ -40,7 +40,7 @@ Enemy::Enemy(enemy_t enemy) } else { - sprite->setCurrentFrame(min(enemy.frame, sprite->getNumFrames() - 1)); + sprite->setCurrentFrame(std::min(enemy.frame, sprite->getNumFrames() - 1)); } } diff --git a/source/enemy.h b/source/enemy.h index 1249ffc..6520647 100644 --- a/source/enemy.h +++ b/source/enemy.h @@ -9,14 +9,12 @@ #ifndef ENEMY_H #define ENEMY_H -using namespace std; - // Estructura para pasar los datos de un enemigo struct enemy_t { SDL_Renderer *renderer; // El renderizador de la ventana animatedSprite_t *animation; // Puntero a las animaciones del enemigo - string animationString; // Ruta al fichero con la animación + std::string animationString; // Ruta al fichero con la animación int w; // Anchura del enemigo int h; // Altura del enemigo float x; // Posición inicial en el eje X @@ -30,7 +28,7 @@ struct enemy_t bool flip; // Indica si el enemigo hace flip al terminar su ruta bool mirror; // Indica si el enemigo está volteado verticalmente int frame; // Frame inicial para la animación del enemigo - string color; // Color del enemigo + std::string color; // Color del enemigo palette_e palette; // Paleta de colores }; @@ -41,16 +39,16 @@ private: AnimatedSprite *sprite; // Sprite del enemigo // Variables - color_t color; // Color del enemigo - string colorString; // Color del enemigo en formato texto - palette_e palette; // Paleta de colores - int x1; // Limite izquierdo de la ruta en el eje X - int x2; // Limite derecho de la ruta en el eje X - int y1; // Limite superior de la ruta en el eje Y - int y2; // Limite inferior de la ruta en el eje Y - SDL_Rect collider; // Caja de colisión - bool doFlip; // Indica si el enemigo hace flip al terminar su ruta - bool mirror; // Indica si el enemigo se dibuja volteado verticalmente + color_t color; // Color del enemigo + std::string colorString; // Color del enemigo en formato texto + palette_e palette; // Paleta de colores + int x1; // Limite izquierdo de la ruta en el eje X + int x2; // Limite derecho de la ruta en el eje X + int y1; // Limite superior de la ruta en el eje Y + int y2; // Limite inferior de la ruta en el eje Y + SDL_Rect collider; // Caja de colisión + bool doFlip; // Indica si el enemigo hace flip al terminar su ruta + bool mirror; // Indica si el enemigo se dibuja volteado verticalmente // Comprueba si ha llegado al limite del recorrido para darse media vuelta void checkPath(); diff --git a/source/enter_id.cpp b/source/enter_id.cpp index bed2e3b..87f97fc 100644 --- a/source/enter_id.cpp +++ b/source/enter_id.cpp @@ -25,7 +25,7 @@ EnterID::EnterID(SDL_Renderer *renderer, Screen *screen, Asset *asset, options_t { if (options->console) { - cout << "Error: textTexture could not be created!\nSDL Error: " << SDL_GetError() << endl; + std::cout << "Error: textTexture could not be created!\nSDL Error: " << SDL_GetError() << std::endl; } } SDL_SetTextureBlendMode(textTexture, SDL_BLENDMODE_BLEND); @@ -90,7 +90,7 @@ void EnterID::checkEventHandler() { if (eventHandler->key.keysym.scancode == SDL_SCANCODE_RETURN) { - options->online.jailerID = (string)name; + options->online.jailerID = (std::string)name; endSection(); break; } @@ -206,7 +206,7 @@ void EnterID::render() SDL_RenderCopy(renderer, textTexture, nullptr, nullptr); // Escribe el jailerID - const string jailerID = (string)name + cursor; + const std::string jailerID = (std::string)name + cursor; const color_t color = stringToColor(options->palette, "white"); text->writeDX(TXT_CENTER | TXT_COLOR, GAMECANVAS_CENTER_X, (16 * 8 + 1), jailerID, 1, color); @@ -296,14 +296,14 @@ void EnterID::initOnline() jscore::init(options->online.server, options->online.port); #ifdef DEBUG - const string caption = "IS LOGGED IN (DEBUG)"; + const std::string caption = "IS LOGGED IN (DEBUG)"; #else - const string caption = "IS LOGGED IN"; + const std::string caption = "IS LOGGED IN"; #endif screen->showNotification(options->online.jailerID, caption, 12); if (options->console) { - cout << caption << endl; + std::cout << caption << std::endl; } } } diff --git a/source/enter_id.h b/source/enter_id.h index 4634499..c60dca9 100644 --- a/source/enter_id.h +++ b/source/enter_id.h @@ -9,17 +9,15 @@ #include #ifndef ENTER_ID_H -#define ENTER_ID_H - -using namespace std; +#define ASK_ME_H class EnterID { private: struct captions_t { - string label; // Texto a escribir - color_t color; // Color del texto + std::string label; // Texto a escribir + color_t color; // Color del texto }; // Punteros y objetos @@ -34,11 +32,11 @@ private: section_t *section; // Estado del bucle principal para saber si continua o se sale // Variables - int counter; // Contador - Uint32 ticks; // Contador de ticks para ajustar la velocidad del programa - Uint32 ticksSpeed; // Velocidad a la que se repiten los bucles del programa - vector texts; // Vector con los textos - string cursor; // Contiene el caracter que se muestra como cursor + int counter; // Contador + Uint32 ticks; // Contador de ticks para ajustar la velocidad del programa + Uint32 ticksSpeed; // Velocidad a la que se repiten los bucles del programa + std::vector texts; // Vector con los textos + std::string cursor; // Contiene el caracter que se muestra como cursor char name[15]; int pos; diff --git a/source/game.cpp b/source/game.cpp index 4ad799b..517ec77 100644 --- a/source/game.cpp +++ b/source/game.cpp @@ -35,8 +35,8 @@ Game::Game(SDL_Renderer *renderer, Screen *screen, Resource *resource, Asset *as itemTracker = new ItemTracker(); roomTracker = new RoomTracker(); room = new Room(resource->getRoom(currentRoom), renderer, screen, asset, options, itemTracker, &board.items, false, debug); - const string playerPNG = options->cheat.altSkin ? "player2.png" : "player.png"; - const string playerANI = options->cheat.altSkin ? "player2.ani" : "player.ani"; + 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 = {spawnPoint, playerPNG, playerANI, renderer, resource, asset, options, input, room, debug}; this->player = new Player(player); eventHandler = new SDL_Event(); @@ -51,7 +51,7 @@ Game::Game(SDL_Renderer *renderer, Screen *screen, Resource *resource, Asset *as { if (options->console) { - cout << "Error: roomNameTexture could not be created!\nSDL Error: " << SDL_GetError() << endl; + std::cout << "Error: roomNameTexture could not be created!\nSDL Error: " << SDL_GetError() << std::endl; } } @@ -322,9 +322,9 @@ void Game::render() // Pasa la información de debug void Game::updateDebugInfo() { - debug->add("X = " + to_string((int)player->x) + ", Y = " + to_string((int)player->y)); - debug->add("VX = " + to_string(player->vx).substr(0, 4) + ", VY = " + to_string(player->vy).substr(0, 4)); - debug->add("STATE = " + to_string(player->state)); + debug->add("X = " + std::to_string((int)player->x) + ", Y = " + std::to_string((int)player->y)); + debug->add("VX = " + std::to_string(player->vx).substr(0, 4) + ", VY = " + std::to_string(player->vy).substr(0, 4)); + debug->add("STATE = " + std::to_string(player->state)); } // Pone la información de debug en pantalla @@ -365,7 +365,7 @@ void Game::renderRoomName() } // Cambia de habitación -bool Game::changeRoom(string file) +bool Game::changeRoom(std::string file) { // En las habitaciones los limites tienen la cadena del fichero o un 0 en caso de no limitar con nada if (file == "0") @@ -413,7 +413,7 @@ void Game::checkPlayerOnBorder() { if (player->getOnBorder()) { - const string roomName = room->getRoom(player->getBorder()); + const std::string roomName = room->getRoom(player->getBorder()); if (changeRoom(roomName)) { player->switchBorders(); @@ -490,8 +490,8 @@ void Game::killPlayer() // Crea la nueva habitación y el nuevo jugador room = new Room(resource->getRoom(currentRoom), renderer, screen, asset, options, itemTracker, &board.items, board.jailEnabled, debug); - const string playerPNG = options->cheat.altSkin ? "player2.png" : "player.png"; - const string playerANI = options->cheat.altSkin ? "player2.ani" : "player.ani"; + 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 = {spawnPoint, playerPNG, playerANI, renderer, resource, asset, options, input, room, debug}; this->player = new Player(player); @@ -505,7 +505,7 @@ void Game::reLoadTextures() { if (options->console) { - cout << "** RELOAD REQUESTED" << endl; + std::cout << "** RELOAD REQUESTED" << std::endl; } player->reLoadTexture(); room->reLoadTexture(); @@ -518,7 +518,7 @@ void Game::switchPalette() { if (options->console) { - cout << "** PALETTE SWITCH REQUESTED" << endl; + std::cout << "** PALETTE SWITCH REQUESTED" << std::endl; } // Modifica la variable @@ -608,7 +608,7 @@ bool Game::checkEndGame() int Game::getTotalItems() { int items = 0; - vector *rooms = new vector; + std::vector *rooms = new std::vector; rooms = resource->getAllRooms(); for (auto room : *rooms) @@ -622,7 +622,7 @@ int Game::getTotalItems() // Va a la habitación designada void Game::goToRoom(int border) { - const string roomName = room->getRoom(border); + const std::string roomName = room->getRoom(border); if (changeRoom(roomName)) { currentRoom = roomName; @@ -682,7 +682,7 @@ void Game::checkRestoringJail() // Inicializa el diccionario de las estadísticas void Game::initStats() { - vector *rooms = new vector; + std::vector *rooms = new std::vector; rooms = resource->getAllRooms(); for (auto room : *rooms) diff --git a/source/game.h b/source/game.h index c5fe89f..5420f81 100644 --- a/source/game.h +++ b/source/game.h @@ -23,8 +23,6 @@ #ifndef GAME_H #define GAME_H -using namespace std; - class Game { private: @@ -52,7 +50,7 @@ private: JA_Music_t *music; // Musica que suena durante el juego Uint32 ticks; // Contador de ticks para ajustar la velocidad del programa Uint32 ticksSpeed; // Velocidad a la que se repiten los bucles del programa - string currentRoom; // Fichero de la habitación actual + std::string currentRoom; // Fichero de la habitación actual playerSpawn_t spawnPoint; // Lugar de la habitación donde aparece el jugador JA_Sound_t *deathSound; // Sonido a reproducir cuando muere el jugador board_t board; // Estructura con los datos del marcador @@ -83,7 +81,7 @@ private: void renderRoomName(); // Cambia de habitación - bool changeRoom(string file); + bool changeRoom(std::string file); // Comprueba el teclado void checkInput(); diff --git a/source/game_over.cpp b/source/game_over.cpp index dd8cdff..952e5cc 100644 --- a/source/game_over.cpp +++ b/source/game_over.cpp @@ -35,7 +35,7 @@ GameOver::GameOver(SDL_Renderer *renderer, Screen *screen, Resource *resource, A tvSprite->setPosY(30); // Inicializa el vector de colores - const vector colorList = {"white", "yellow", "cyan", "green", "magenta", "red", "blue", "black"}; + const std::vector colorList = {"white", "yellow", "cyan", "green", "magenta", "red", "blue", "black"}; for (auto cl : colorList) { colors.push_back(stringToColor(options->palette, cl)); @@ -104,8 +104,8 @@ void GameOver::render() renderSprites(); // Escribe el texto con las habitaciones y los items - const string itemsTxt = to_string(options->stats.items / 100) + to_string((options->stats.items % 100) / 10) + to_string(options->stats.items % 10); - const string roomsTxt = to_string(options->stats.rooms / 100) + to_string((options->stats.rooms % 100) / 10) + to_string(options->stats.rooms % 10); + const std::string itemsTxt = std::to_string(options->stats.items / 100) + std::to_string((options->stats.items % 100) / 10) + std::to_string(options->stats.items % 10); + const std::string roomsTxt = std::to_string(options->stats.rooms / 100) + std::to_string((options->stats.rooms % 100) / 10) + std::to_string(options->stats.rooms % 10); text->writeDX(TXT_CENTER | TXT_COLOR, GAMECANVAS_CENTER_X, y + 80, "ITEMS: " + itemsTxt, 1, color); text->writeDX(TXT_CENTER | TXT_COLOR, GAMECANVAS_CENTER_X, y + 90, "ROOMS: " + roomsTxt, 1, color); @@ -185,13 +185,13 @@ void GameOver::updateColor() if (counter < half) { - const float step = min(counter, fadeLenght) / (float)fadeLenght; + const float step = std::min(counter, fadeLenght) / (float)fadeLenght; const int index = (colors.size() - 1) - int((colors.size() - 1) * step); color = colors[index]; } else { - const float step = min(max(counter, iniFade) - iniFade, fadeLenght) / (float)fadeLenght; + const float step = std::min(std::max(counter, iniFade) - iniFade, fadeLenght) / (float)fadeLenght; const int index = (colors.size() - 1) * step; color = colors[index]; } diff --git a/source/game_over.h b/source/game_over.h index bedccf1..5a86491 100644 --- a/source/game_over.h +++ b/source/game_over.h @@ -16,8 +16,6 @@ #ifndef GAME_OVER_H #define GAME_OVER_H -using namespace std; - class GameOver { private: @@ -35,16 +33,16 @@ private: section_t *section; // Estado del bucle principal para saber si continua o se sale // Variables - int preCounter; // Contador previo - int counter; // Contador - Uint32 ticks; // Contador de ticks para ajustar la velocidad del programa - Uint32 ticksSpeed; // Velocidad a la que se repiten los bucles del programa - vector colors; // Vector con los colores para el fade - color_t color; // Color usado para el texto y los sprites - int endSection; // Contador: cuando acaba la sección - int iniFade; // Contador: cuando emiepza el fade - int fadeLenght; // Contador: duración del fade - JA_Music_t *music; // Musica que suena durante el juego + int preCounter; // Contador previo + int counter; // Contador + Uint32 ticks; // Contador de ticks para ajustar la velocidad del programa + Uint32 ticksSpeed; // Velocidad a la que se repiten los bucles del programa + std::vector colors; // Vector con los colores para el fade + color_t color; // Color usado para el texto y los sprites + int endSection; // Contador: cuando acaba la sección + int iniFade; // Contador: cuando emiepza el fade + int fadeLenght; // Contador: duración del fade + JA_Music_t *music; // Musica que suena durante el juego // Actualiza el objeto void update(); diff --git a/source/item.h b/source/item.h index 1e95a03..e194f1c 100644 --- a/source/item.h +++ b/source/item.h @@ -9,19 +9,17 @@ #ifndef ITEM_H #define ITEM_H -using namespace std; - struct item_t { - SDL_Renderer *renderer; // El renderizador de la ventana - Texture *texture; // Textura con los graficos del item - string tileSetFile; // Ruta al fichero con los graficos del item - int x; // Posicion del item en pantalla - int y; // Posicion del item en pantalla - int tile; // Numero de tile dentro de la textura - int counter; // Contador inicial. Es el que lo hace cambiar de color - color_t color1; // Uno de los dos colores que se utiliza para el item - color_t color2; // Uno de los dos colores que se utiliza para el item + SDL_Renderer *renderer; // El renderizador de la ventana + Texture *texture; // Textura con los graficos del item + std::string tileSetFile; // Ruta al fichero con los graficos del item + int x; // Posicion del item en pantalla + int y; // Posicion del item en pantalla + int tile; // Numero de tile dentro de la textura + int counter; // Contador inicial. Es el que lo hace cambiar de color + color_t color1; // Uno de los dos colores que se utiliza para el item + color_t color2; // Uno de los dos colores que se utiliza para el item }; class Item @@ -31,10 +29,10 @@ private: Sprite *sprite; // Sprite del objeto // Variables - vector color; // Vector con los colores del objeto - int counter; // Contador interno - SDL_Rect collider; // Rectangulo de colisión - int colorChangeSpeed; // Cuanto mas alto, mas tarda en cambiar de color + std::vector color; // Vector con los colores del objeto + int counter; // Contador interno + SDL_Rect collider; // Rectangulo de colisión + int colorChangeSpeed; // Cuanto mas alto, mas tarda en cambiar de color public: // Constructor diff --git a/source/item_tracker.cpp b/source/item_tracker.cpp index 96a19d8..3699bc3 100644 --- a/source/item_tracker.cpp +++ b/source/item_tracker.cpp @@ -7,7 +7,7 @@ ItemTracker::~ItemTracker() } // Comprueba si el objeto ya ha sido cogido -bool ItemTracker::hasBeenPicked(string name, SDL_Point pos) +bool ItemTracker::hasBeenPicked(std::string name, SDL_Point pos) { bool success = false; @@ -26,7 +26,7 @@ bool ItemTracker::hasBeenPicked(string name, SDL_Point pos) } // Añade el objeto a la lista de objetos cogidos -void ItemTracker::addItem(string name, SDL_Point pos) +void ItemTracker::addItem(std::string name, SDL_Point pos) { // Comprueba si el objeto no ha sido recogido con anterioridad if (!hasBeenPicked(name, pos)) @@ -50,7 +50,7 @@ void ItemTracker::addItem(string name, SDL_Point pos) } // Busca una entrada en la lista por nombre -int ItemTracker::findByName(string name) +int ItemTracker::findByName(std::string name) { int i = 0; @@ -71,7 +71,7 @@ int ItemTracker::findByPos(int index, SDL_Point pos) { int i = 0; - for (auto l : list[index].pos) + for (auto l:list[index].pos) { if ((l.x == pos.x) && (l.y == pos.y)) { diff --git a/source/item_tracker.h b/source/item_tracker.h index bae10a0..fed3dc6 100644 --- a/source/item_tracker.h +++ b/source/item_tracker.h @@ -7,22 +7,20 @@ #ifndef ITEM_TRACKER_H #define ITEM_TRACKER_H -using namespace std; - struct item_tracker_t { - string name; // Nombre de la habitación donde se encuentra el objeto - vector pos; // Lista de objetos cogidos de la habitación + std::string name; // Nombre de la habitación donde se encuentra el objeto + std::vector pos; // Lista de objetos cogidos de la habitación }; class ItemTracker { private: // Variables - vector list; // Lista con todos los objetos recogidos + std::vector list; // Lista con todos los objetos recogidos // Busca una entrada en la lista por nombre - int findByName(string name); + int findByName(std::string name); // Busca una entrada en la lista por posición int findByPos(int index, SDL_Point pos); @@ -32,10 +30,10 @@ public: ~ItemTracker(); // Comprueba si el objeto ya ha sido cogido - bool hasBeenPicked(string name, SDL_Point pos); + bool hasBeenPicked(std::string name, SDL_Point pos); // Añade el objeto a la lista de objetos cogidos - void addItem(string name, SDL_Point pos); + void addItem(std::string name, SDL_Point pos); }; #endif diff --git a/source/logo.cpp b/source/logo.cpp index 281be87..e9ed850 100644 --- a/source/logo.cpp +++ b/source/logo.cpp @@ -47,7 +47,7 @@ Logo::Logo(SDL_Renderer *renderer, Screen *screen, Resource *resource, Asset *as postLogo = 20; // Inicializa el vector de colores - const vector vColors = {"black", "blue", "red", "magenta", "green", "cyan", "yellow", "bright_white"}; + const std::vector vColors = {"black", "blue", "red", "magenta", "green", "cyan", "yellow", "bright_white"}; for (auto v : vColors) { color.push_back(stringToColor(options->palette, v)); diff --git a/source/logo.h b/source/logo.h index 57acbcb..1c28d17 100644 --- a/source/logo.h +++ b/source/logo.h @@ -14,33 +14,31 @@ #ifndef LOGO_H #define LOGO_H -using namespace std; - class Logo { private: // Objetos y punteros - SDL_Renderer *renderer; // El renderizador de la ventana - Screen *screen; // Objeto encargado de dibujar en pantalla - Resource *resource; // Objeto con los recursos - Asset *asset; // Objeto con los ficheros de recursos - Input *input; // Objeto pata gestionar la entrada - Texture *texture; // Textura con los graficos "JAILGAMES" - Texture *texture2; // Textura con los graficos "Since 1998" - SDL_Event *eventHandler; // Manejador de eventos - vector sprite; // Vector con los sprites de cada linea que forman el bitmap JAILGAMES - Sprite *sprite2; // Sprite para manejar la textura2 - options_t *options; // Puntero a las opciones del juego - section_t *section; // Estado del bucle principal para saber si continua o se sale + SDL_Renderer *renderer; // El renderizador de la ventana + Screen *screen; // Objeto encargado de dibujar en pantalla + Resource *resource; // Objeto con los recursos + Asset *asset; // Objeto con los ficheros de recursos + Input *input; // Objeto pata gestionar la entrada + Texture *texture; // Textura con los graficos "JAILGAMES" + Texture *texture2; // Textura con los graficos "Since 1998" + SDL_Event *eventHandler; // Manejador de eventos + std::vector sprite; // Vector con los sprites de cada linea que forman el bitmap JAILGAMES + Sprite *sprite2; // Sprite para manejar la textura2 + options_t *options; // Puntero a las opciones del juego + section_t *section; // Estado del bucle principal para saber si continua o se sale // Variables - vector color; // Vector con los colores para el fade - int counter; // Contador - Uint32 ticks; // Contador de ticks para ajustar la velocidad del programa - Uint32 ticksSpeed; // Velocidad a la que se repiten los bucles del programa - int initFade; // Tiempo del contador cuando inicia el fade a negro - int endLogo; // Tiempo del contador para terminar el logo - int postLogo; // Tiempo que dura el logo con el fade al maximo + std::vector color; // Vector con los colores para el fade + int counter; // Contador + Uint32 ticks; // Contador de ticks para ajustar la velocidad del programa + Uint32 ticksSpeed; // Velocidad a la que se repiten los bucles del programa + int initFade; // Tiempo del contador cuando inicia el fade a negro + int endLogo; // Tiempo del contador para terminar el logo + int postLogo; // Tiempo que dura el logo con el fade al maximo // Actualiza las variables void update(); diff --git a/source/player.cpp b/source/player.cpp index d883864..e6d490f 100644 --- a/source/player.cpp +++ b/source/player.cpp @@ -533,7 +533,7 @@ void Player::move() #endif // Comprueba la colisión con las superficies normales y las automáticas - const int pos = 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; @@ -548,7 +548,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 = 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 @@ -581,8 +581,8 @@ void Player::move() sprite->setPosY(y); #ifdef DEBUG - debug->add("RECT_X: " + to_string(rx.x) + "," + to_string(rx.y) + "," + to_string(rx.w) + "," + to_string(rx.h)); - debug->add("RECT_Y: " + to_string(ry.x) + "," + to_string(ry.y) + "," + to_string(ry.w) + "," + 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 } @@ -621,7 +621,7 @@ void Player::playJumpSound() } #ifdef DEBUG - debug->add("JUMP: " + to_string(jumpCounter / 4)); + debug->add("JUMP: " + std::to_string(jumpCounter / 4)); #endif } @@ -630,11 +630,11 @@ void Player::playFallSound() { if (fallCounter % 4 == 0) { - JA_PlaySound(fallSound[min((fallCounter / 4), (int)fallSound.size() - 1)]); + JA_PlaySound(fallSound[std::min((fallCounter / 4), (int)fallSound.size() - 1)]); } #ifdef DEBUG - debug->add("FALL: " + to_string(fallCounter / 4)); + debug->add("FALL: " + std::to_string(fallCounter / 4)); #endif } @@ -666,12 +666,12 @@ bool Player::isOnFloor() if (onSlopeL) { - debug->add("ON_SLOPE_L: " + to_string(underFeet[0].x) + "," + 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: " + to_string(underFeet[1].x) + "," + to_string(underFeet[1].y)); + debug->add("ON_SLOPE_R: " + std::to_string(underFeet[1].x) + "," + std::to_string(underFeet[1].y)); } #endif diff --git a/source/player.h b/source/player.h index 1bff488..3bea553 100644 --- a/source/player.h +++ b/source/player.h @@ -15,8 +15,6 @@ #ifndef PLAYER_H #define PLAYER_H -using namespace std; - enum state_e { s_standing, @@ -38,8 +36,8 @@ struct playerSpawn_t struct player_t { playerSpawn_t spawn; - string png; - string animation; + std::string png; + std::string animation; SDL_Renderer *renderer; Resource *resource; Asset *asset; @@ -63,32 +61,32 @@ public: options_t *options; // Puntero a las opciones del juego // Variables - float x; // Posición del jugador en el eje X - float y; // Posición del jugador en el eje Y - float vx; // Velocidad/desplazamiento del jugador en el eje X - float vy; // Velocidad/desplazamiento del jugador en el eje Y - int w; // Ancho del jugador - int h; // ALto del jugador - color_t color; // Color del jugador - SDL_Rect colliderBox; // Caja de colisión con los enemigos u objetos - vector colliderPoints; // Puntos de colisión con el mapa - vector underFeet; // Contiene los puntos que hay bajo cada pie del jugador - vector feet; // Contiene los puntos que hay en el pie del jugador - state_e state; // Estado en el que se encuentra el jugador. Util apara saber si está saltando o cayendo - state_e prevState; // Estado previo en el que se encontraba el jugador - bool onBorder; // Indica si el jugador esta en uno de los cuatro bordes de la pantalla - int border; // Indica en cual de los cuatro bordes se encuentra - bool autoMovement; // Indica si esta siendo arrastrado por una superficie automatica - bool paused; // Indica si el jugador esta en modo pausa - SDL_Rect lastPosition; // Contiene la ultima posición del jugador, por si hay que deshacer algun movimiento - int jumpIni; // Valor del eje Y en el que se inicia el salto - float maxVY; // Velocidad máxima que puede alcanzar al desplazarse en vertical - vector jumpSound; // Vecor con todos los sonidos del salto - vector fallSound; // Vecor con todos los sonidos de la caída - int jumpCounter; // Cuenta el tiempo de salto - int fallCounter; // Cuenta el tiempo de caida - bool alive; // Indica si el jugador esta vivo o no - int maxFallHeight; // Altura maxima permitida de caída. + float x; // Posición del jugador en el eje X + float y; // Posición del jugador en el eje Y + float vx; // Velocidad/desplazamiento del jugador en el eje X + float vy; // Velocidad/desplazamiento del jugador en el eje Y + int w; // Ancho del jugador + int h; // ALto del jugador + color_t color; // Color del jugador + SDL_Rect colliderBox; // Caja de colisión con los enemigos u objetos + std::vector colliderPoints; // Puntos de colisión con el mapa + std::vector underFeet; // Contiene los puntos que hay bajo cada pie del jugador + std::vector feet; // Contiene los puntos que hay en el pie del jugador + state_e state; // Estado en el que se encuentra el jugador. Util apara saber si está saltando o cayendo + state_e prevState; // Estado previo en el que se encontraba el jugador + bool onBorder; // Indica si el jugador esta en uno de los cuatro bordes de la pantalla + int border; // Indica en cual de los cuatro bordes se encuentra + bool autoMovement; // Indica si esta siendo arrastrado por una superficie automatica + bool paused; // Indica si el jugador esta en modo pausa + SDL_Rect lastPosition; // Contiene la ultima posición del jugador, por si hay que deshacer algun movimiento + int jumpIni; // Valor del eje Y en el que se inicia el salto + float maxVY; // Velocidad máxima que puede alcanzar al desplazarse en vertical + std::vector jumpSound; // Vecor con todos los sonidos del salto + std::vector fallSound; // Vecor con todos los sonidos de la caída + int jumpCounter; // Cuenta el tiempo de salto + int fallCounter; // Cuenta el tiempo de caida + bool alive; // Indica si el jugador esta vivo o no + int maxFallHeight; // Altura maxima permitida de caída. #ifdef DEBUG SDL_Rect rx; // Rectangulo de desplazamiento para el modo debug diff --git a/source/room.cpp b/source/room.cpp index 35d781e..85fa0bd 100644 --- a/source/room.cpp +++ b/source/room.cpp @@ -4,34 +4,34 @@ #include // Carga las variables y texturas desde un fichero de mapa de tiles -vector loadRoomTileFile(string file_path, bool verbose) +std::vector loadRoomTileFile(std::string file_path, bool verbose) { - vector tileMapFile; - const string filename = file_path.substr(file_path.find_last_of("\\/") + 1); - string line; - ifstream file(file_path); + std::vector tileMapFile; + 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 - while (getline(file, line)) + while (std::getline(file, line)) { // Lee el fichero linea a linea - if (line.find("data encoding") != string::npos) + if (line.find("data encoding") != std::string::npos) { // Lee la primera linea - getline(file, line); + std::getline(file, line); while (line != "") { // Procesa lineas mientras haya - stringstream ss(line); - string tmp; + std::stringstream ss(line); + std::string tmp; while (getline(ss, tmp, ',')) { - tileMapFile.push_back(stoi(tmp) - 1); + tileMapFile.push_back(std::stoi(tmp) - 1); } // Lee la siguiente linea - getline(file, line); + std::getline(file, line); } } } @@ -39,7 +39,7 @@ vector loadRoomTileFile(string file_path, bool verbose) // Cierra el fichero if (verbose) { - cout << "TileMap loaded: " << filename.c_str() << endl; + std::cout << "TileMap loaded: " << filename.c_str() << std::endl; } file.close(); } @@ -48,7 +48,7 @@ vector loadRoomTileFile(string file_path, bool verbose) { // El fichero no se puede abrir if (verbose) { - cout << "Warning: Unable to open " << filename.c_str() << " file" << endl; + std::cout << "Warning: Unable to open " << filename.c_str() << " file" << std::endl; } } @@ -56,24 +56,24 @@ vector loadRoomTileFile(string file_path, bool verbose) } // Carga las variables desde un fichero de mapa -room_t loadRoomFile(string file_path, bool verbose) +room_t loadRoomFile(std::string file_path, bool verbose) { room_t room; room.itemColor1 = "yellow"; room.itemColor2 = "magenta"; room.autoSurfaceDirection = 1; - const string fileName = file_path.substr(file_path.find_last_of("\\/") + 1); + const std::string fileName = file_path.substr(file_path.find_last_of("\\/") + 1); room.number = fileName.substr(0, fileName.find_last_of(".")); - string line; - ifstream file(file_path); + std::string line; + std::ifstream file(file_path); // El fichero se puede abrir if (file.good()) { // Procesa el fichero linea a linea - while (getline(file, line)) + while (std::getline(file, line)) { // Si la linea contiene el texto [enemy] se realiza el proceso de carga de un enemigo if (line == "[enemy]") @@ -86,7 +86,7 @@ room_t loadRoomFile(string file_path, bool verbose) do { - getline(file, line); + std::getline(file, line); // Encuentra la posición del caracter '=' int pos = line.find("="); @@ -96,7 +96,7 @@ room_t loadRoomFile(string file_path, bool verbose) { if (verbose) { - cout << "Warning: file " << fileName.c_str() << "\n, unknown parameter \"" << line.substr(0, pos).c_str() << "\"" << endl; + std::cout << "Warning: file " << fileName.c_str() << "\n, unknown parameter \"" << line.substr(0, pos).c_str() << "\"" << std::endl; } } } while (line != "[/enemy]"); @@ -115,7 +115,7 @@ room_t loadRoomFile(string file_path, bool verbose) do { - getline(file, line); + std::getline(file, line); // Encuentra la posición del caracter '=' int pos = line.find("="); @@ -125,7 +125,7 @@ room_t loadRoomFile(string file_path, bool verbose) { if (verbose) { - cout << "Warning: file " << fileName.c_str() << "\n, unknown parameter \"" << line.substr(0, pos).c_str() << "\"" << endl; + std::cout << "Warning: file " << fileName.c_str() << "\n, unknown parameter \"" << line.substr(0, pos).c_str() << "\"" << std::endl; } } @@ -145,7 +145,7 @@ room_t loadRoomFile(string file_path, bool verbose) { if (verbose) { - cout << "Warning: file " << fileName.c_str() << "\n, unknown parameter \"" << line.substr(0, pos).c_str() << "\"" << endl; + std::cout << "Warning: file " << fileName.c_str() << "\n, unknown parameter \"" << line.substr(0, pos).c_str() << "\"" << std::endl; } } } @@ -154,7 +154,7 @@ room_t loadRoomFile(string file_path, bool verbose) // Cierra el fichero if (verbose) { - cout << "Room loaded: " << fileName.c_str() << endl; + std::cout << "Room loaded: " << fileName.c_str() << std::endl; } file.close(); } @@ -162,7 +162,7 @@ room_t loadRoomFile(string file_path, bool verbose) else { { - cout << "Warning: Unable to open " << fileName.c_str() << " file" << endl; + std::cout << "Warning: Unable to open " << fileName.c_str() << " file" << std::endl; } } @@ -170,7 +170,7 @@ room_t loadRoomFile(string file_path, bool verbose) } // Asigna variables a partir de dos cadenas -bool setVars(room_t *room, string var, string value) +bool setVars(room_t *room, std::string var, std::string value) { // Indicador de éxito en la asignación bool success = true; @@ -255,7 +255,7 @@ bool setVars(room_t *room, string var, string value) } // Asigna variables a una estructura enemy_t -bool setEnemy(enemy_t *enemy, string var, string value) +bool setEnemy(enemy_t *enemy, std::string var, std::string value) { // Indicador de éxito en la asignación bool success = true; @@ -267,52 +267,52 @@ bool setEnemy(enemy_t *enemy, string var, string value) else if (var == "width") { - enemy->w = stof(value); + enemy->w = std::stof(value); } else if (var == "height") { - enemy->h = stof(value); + enemy->h = std::stof(value); } else if (var == "x") { - enemy->x = stof(value) * BLOCK; + enemy->x = std::stof(value) * BLOCK; } else if (var == "y") { - enemy->y = stof(value) * BLOCK; + enemy->y = std::stof(value) * BLOCK; } else if (var == "vx") { - enemy->vx = stof(value); + enemy->vx = std::stof(value); } else if (var == "vy") { - enemy->vy = stof(value); + enemy->vy = std::stof(value); } else if (var == "x1") { - enemy->x1 = stoi(value) * BLOCK; + enemy->x1 = std::stoi(value) * BLOCK; } else if (var == "x2") { - enemy->x2 = stoi(value) * BLOCK; + enemy->x2 = std::stoi(value) * BLOCK; } else if (var == "y1") { - enemy->y1 = stoi(value) * BLOCK; + enemy->y1 = std::stoi(value) * BLOCK; } else if (var == "y2") { - enemy->y2 = stoi(value) * BLOCK; + enemy->y2 = std::stoi(value) * BLOCK; } else if (var == "flip") @@ -332,7 +332,7 @@ bool setEnemy(enemy_t *enemy, string var, string value) else if (var == "frame") { - enemy->frame = stoi(value); + enemy->frame = std::stoi(value); } else if (var == "[/enemy]" || var == "tileSetFile" || var.substr(0, 1) == "#") @@ -348,7 +348,7 @@ bool setEnemy(enemy_t *enemy, string var, string value) } // Asigna variables a una estructura item_t -bool setItem(item_t *item, string var, string value) +bool setItem(item_t *item, std::string var, std::string value) { // Indicador de éxito en la asignación bool success = true; @@ -360,22 +360,22 @@ bool setItem(item_t *item, string var, string value) else if (var == "counter") { - item->counter = stoi(value); + item->counter = std::stoi(value); } else if (var == "x") { - item->x = stof(value) * BLOCK; + item->x = std::stof(value) * BLOCK; } else if (var == "y") { - item->y = stof(value) * BLOCK; + item->y = std::stof(value) * BLOCK; } else if (var == "tile") { - item->tile = stof(value); + item->tile = std::stof(value); } else if (var == "[/item]") @@ -478,7 +478,7 @@ Room::Room(room_t *room, SDL_Renderer *renderer, Screen *screen, Asset *asset, o { if (options->console) { - cout << "Error: mapTexture could not be created!\nSDL Error: " << SDL_GetError() << endl; + std::cout << "Error: mapTexture could not be created!\nSDL Error: " << SDL_GetError() << std::endl; } } SDL_SetTextureBlendMode(mapTexture, SDL_BLENDMODE_BLEND); @@ -514,7 +514,7 @@ Room::~Room() } // Devuelve el nombre de la habitación -string Room::getName() +std::string Room::getName() { return name; } @@ -723,7 +723,7 @@ void Room::update() } // Devuelve la cadena del fichero de la habitación contigua segun el borde -string Room::getRoom(int border) +std::string Room::getRoom(int border) { switch (border) { @@ -897,13 +897,13 @@ int Room::getSlopeHeight(SDL_Point p, tile_e slope) // Calcula la base del tile int base = ((p.y / tileSize) * tileSize) + tileSize; #ifdef DEBUG - debug->add("BASE = " + to_string(base)); + debug->add("BASE = " + std::to_string(base)); #endif // Calcula cuanto se ha entrado en el tile horizontalmente const int pos = (p.x % tileSize); // Esto da un valor entre 0 y 7 #ifdef DEBUG - debug->add("POS = " + to_string(pos)); + debug->add("POS = " + std::to_string(pos)); #endif // Se resta a la base la cantidad de pixeles pos en funcion de la rampa @@ -911,14 +911,14 @@ int Room::getSlopeHeight(SDL_Point p, tile_e slope) { base -= pos + 1; #ifdef DEBUG - debug->add("BASE_R = " + to_string(base)); + debug->add("BASE_R = " + std::to_string(base)); #endif } else { base -= (tileSize - pos); #ifdef DEBUG - debug->add("BASE_L = " + to_string(base)); + debug->add("BASE_L = " + std::to_string(base)); #endif } @@ -928,7 +928,7 @@ int Room::getSlopeHeight(SDL_Point p, tile_e slope) // Calcula las superficies inferiores void Room::setBottomSurfaces() { - vector tile; + std::vector tile; // Busca todos los tiles de tipo muro que no tengan debajo otro muro // Hay que recorrer la habitación por filas (excepto los de la última fila) @@ -991,7 +991,7 @@ void Room::setBottomSurfaces() // Calcula las superficies superiores void Room::setTopSurfaces() { - vector tile; + std::vector tile; // Busca todos los tiles de tipo muro o pasable que no tengan encima un muro // Hay que recorrer la habitación por filas (excepto los de la primera fila) @@ -1054,7 +1054,7 @@ void Room::setTopSurfaces() // Calcula las superficies laterales izquierdas void Room::setLeftSurfaces() { - vector tile; + std::vector tile; // Busca todos los tiles de tipo muro que no tienen a su izquierda un tile de tipo muro // Hay que recorrer la habitación por columnas (excepto los de la primera columna) @@ -1102,7 +1102,7 @@ void Room::setLeftSurfaces() // Calcula las superficies laterales derechas void Room::setRightSurfaces() { - vector tile; + std::vector tile; // Busca todos los tiles de tipo muro que no tienen a su derecha un tile de tipo muro // Hay que recorrer la habitación por columnas (excepto los de la última columna) @@ -1151,7 +1151,7 @@ void Room::setRightSurfaces() void Room::setLeftSlopes() { // Recorre la habitación entera por filas buscando tiles de tipo t_slope_l - vector found; + std::vector found; for (int i = 0; i < (int)tileMap.size(); ++i) { if (getTile(i) == t_slope_l) @@ -1192,7 +1192,7 @@ void Room::setLeftSlopes() void Room::setRightSlopes() { // Recorre la habitación entera por filas buscando tiles de tipo t_slope_r - vector found; + std::vector found; for (int i = 0; i < (int)tileMap.size(); ++i) { if (getTile(i) == t_slope_r) @@ -1232,7 +1232,7 @@ void Room::setRightSlopes() // Calcula las superficies automaticas void Room::setAutoSurfaces() { - vector tile; + std::vector tile; // Busca todos los tiles de tipo animado // Hay que recorrer la habitación por filas (excepto los de la primera fila) diff --git a/source/room.h b/source/room.h index 993e1c8..7d97f11 100644 --- a/source/room.h +++ b/source/room.h @@ -17,8 +17,6 @@ #ifndef ROOM_H #define ROOM_H -using namespace std; - enum tile_e { t_empty, @@ -38,90 +36,90 @@ struct aTile_t struct room_t { - string number; // Numero de la habitación - string name; // Nombre de la habitación - string bgColor; // Color de fondo de la habitación - string borderColor; // Color del borde de la pantalla - string itemColor1; // Color 1 para los items de la habitación - string itemColor2; // Color 2 para los items de la habitación - string roomUp; // Identificador de la habitación que se encuentra arriba - string roomDown; // Identificador de la habitación que se encuentra abajp - string roomLeft; // Identificador de la habitación que se encuentra a la izquierda - string roomRight; // Identificador de la habitación que se encuentra a la derecha - string tileSetFile; // Imagen con los graficos para la habitación - string tileMapFile; // Fichero con el mapa de indices de tile - vector *tileMap; // Indice de los tiles a dibujar en la habitación - int autoSurfaceDirection; // Sentido en el que arrastran las superficies automáticas de la habitación - vector enemies; // Listado con los enemigos de la habitación - vector items; // Listado con los items que hay en la habitación - Texture *textureA; // Textura con los graficos de la habitación - Texture *textureB; // Textura con los graficos de la habitación + std::string number; // Numero de la habitación + std::string name; // Nombre de la habitación + std::string bgColor; // Color de fondo de la habitación + std::string borderColor; // Color del borde de la pantalla + std::string itemColor1; // Color 1 para los items de la habitación + std::string itemColor2; // Color 2 para los items de la habitación + std::string roomUp; // Identificador de la habitación que se encuentra arriba + std::string roomDown; // Identificador de la habitación que se encuentra abajp + std::string roomLeft; // Identificador de la habitación que se encuentra a la izquierda + std::string roomRight; // Identificador de la habitación que se encuentra a la derecha + std::string tileSetFile; // Imagen con los graficos para la habitación + std::string tileMapFile; // Fichero con el mapa de indices de tile + std::vector *tileMap; // Indice de los tiles a dibujar en la habitación + int autoSurfaceDirection; // Sentido en el que arrastran las superficies automáticas de la habitación + std::vector enemies; // Listado con los enemigos de la habitación + std::vector items; // Listado con los items que hay en la habitación + Texture *textureA; // Textura con los graficos de la habitación + Texture *textureB; // Textura con los graficos de la habitación }; // Carga las variables desde un fichero de mapa -room_t loadRoomFile(string file, bool verbose = false); +room_t loadRoomFile(std::string file, bool verbose = false); // Carga las variables y texturas desde un fichero de mapa de tiles -vector loadRoomTileFile(string file_path, bool verbose = false); +std::vector loadRoomTileFile(std::string file_path, bool verbose = false); // Asigna variables a partir de dos cadenas -bool setVars(room_t *room, string var, string value); +bool setVars(room_t *room, std::string var, std::string value); // Asigna variables a una estructura enemy_t -bool setEnemy(enemy_t *enemy, string var, string value); +bool setEnemy(enemy_t *enemy, std::string var, std::string value); // Asigna variables a una estructura item_t -bool setItem(item_t *item, string var, string value); +bool setItem(item_t *item, std::string var, std::string value); class Room { private: // Objetos y punteros - vector enemies; // Listado con los enemigos de la habitación - vector 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 - options_t *options; // Puntero a las opciones del juego + std::vector enemies; // Listado con los enemigos de la habitación + std::vector 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 + options_t *options; // Puntero a las opciones del juego // Variables - string number; // Numero de la habitación - string name; // Nombre de la habitación - string bgColor; // Color de fondo de la habitación - string borderColor; // Color del borde de la pantalla - string itemColor1; // Color 1 para los items de la habitación - string itemColor2; // Color 2 para los items de la habitación - string roomUp; // Identificador de la habitación que se encuentra arriba - string roomDown; // Identificador de la habitación que se encuentra abajp - string roomLeft; // Identificador de la habitación que se encuentra a la izquierda - string roomRight; // Identificador de la habitación que se encuentra a la derecha - string tileSetFile; // Imagen con los graficos para la habitación - string tileMapFile; // Fichero con el mapa de indices de tile - vector tileMap; // Indice de los tiles a dibujar en la habitación - int autoSurfaceDirection; // Sentido en el que arrastran las superficies automáticas de la habitación - JA_Sound_t *itemSound; // Sonido producido al coger un objeto - vector bottomSurfaces; // Lista con las superficies inferiores de la habitación - vector topSurfaces; // Lista con las superficies superiores de la habitación - vector leftSurfaces; // Lista con las superficies laterales de la parte izquierda de la habitación - vector rightSurfaces; // Lista con las superficies laterales de la parte derecha de la habitación - vector leftSlopes; // Lista con todas las rampas que suben hacia la izquierda - vector rightSlopes; // Lista con todas las rampas que suben hacia la derecha - int counter; // Contador para lo que haga falta - bool paused; // Indica si el mapa esta en modo pausa - vector aTile; // Vector con los indices de tiles animados - vector autoSurfaces; // Lista con las superficies automaticas de la habitación - int tileSize; // Ancho del tile en pixels - int mapWidth; // Ancho del mapa en tiles - int mapHeight; // Alto del mapa en tiles - int tileSetWidth; // Ancho del tileset en tiles - bool jailEnabled; // Indica si hay acceso a la Jail + std::string number; // Numero de la habitación + std::string name; // Nombre de la habitación + std::string bgColor; // Color de fondo de la habitación + std::string borderColor; // Color del borde de la pantalla + std::string itemColor1; // Color 1 para los items de la habitación + std::string itemColor2; // Color 2 para los items de la habitación + std::string roomUp; // Identificador de la habitación que se encuentra arriba + std::string roomDown; // Identificador de la habitación que se encuentra abajp + std::string roomLeft; // Identificador de la habitación que se encuentra a la izquierda + std::string roomRight; // Identificador de la habitación que se encuentra a la derecha + std::string tileSetFile; // Imagen con los graficos para la habitación + std::string tileMapFile; // Fichero con el mapa de indices de tile + std::vector tileMap; // Indice de los tiles a dibujar en la habitación + int autoSurfaceDirection; // Sentido en el que arrastran las superficies automáticas de la habitación + JA_Sound_t *itemSound; // Sonido producido al coger un objeto + std::vector bottomSurfaces; // Lista con las superficies inferiores de la habitación + std::vector topSurfaces; // Lista con las superficies superiores de la habitación + std::vector leftSurfaces; // Lista con las superficies laterales de la parte izquierda de la habitación + std::vector rightSurfaces; // Lista con las superficies laterales de la parte derecha de la habitación + std::vector leftSlopes; // Lista con todas las rampas que suben hacia la izquierda + std::vector rightSlopes; // Lista con todas las rampas que suben hacia la derecha + int counter; // Contador para lo que haga falta + bool paused; // Indica si el mapa esta en modo pausa + std::vector aTile; // Vector con los indices de tiles animados + std::vector autoSurfaces; // Lista con las superficies automaticas de la habitación + int tileSize; // Ancho del tile en pixels + int mapWidth; // Ancho del mapa en tiles + int mapHeight; // Alto del mapa en tiles + int tileSetWidth; // Ancho del tileset en tiles + bool jailEnabled; // Indica si hay acceso a la Jail // Pinta el mapa de la habitación en la textura void fillMapTexture(); @@ -170,7 +168,7 @@ public: ~Room(); // Devuelve el nombre de la habitación - string getName(); + std::string getName(); // Devuelve el color de la habitación color_t getBGColor(); @@ -191,7 +189,7 @@ public: void update(); // Devuelve la cadena del fichero de la habitación contigua segun el borde - string getRoom(int border); + std::string getRoom(int border); // Devuelve el tipo de tile que hay en ese pixel tile_e getTile(SDL_Point point); diff --git a/source/room_tracker.cpp b/source/room_tracker.cpp index 334c427..e0822e8 100644 --- a/source/room_tracker.cpp +++ b/source/room_tracker.cpp @@ -12,7 +12,7 @@ RoomTracker::~RoomTracker() } // Comprueba si la habitación ya ha sido visitada -bool RoomTracker::hasBeenVisited(string name) +bool RoomTracker::hasBeenVisited(std::string name) { for (auto l : list) { @@ -26,7 +26,7 @@ bool RoomTracker::hasBeenVisited(string name) } // Añade la habitación a la lista -bool RoomTracker::addRoom(string name) +bool RoomTracker::addRoom(std::string name) { // Comprueba si la habitación ya ha sido visitada if (!hasBeenVisited(name)) diff --git a/source/room_tracker.h b/source/room_tracker.h index fe03dd0..c8da537 100644 --- a/source/room_tracker.h +++ b/source/room_tracker.h @@ -8,16 +8,14 @@ #ifndef ROOM_TRACKER_H #define ROOM_TRACKER_H -using namespace std; - class RoomTracker { private: // Variables - vector list; // Lista con las habitaciones visitadas + std::vector list; // Lista con las habitaciones visitadas // Comprueba si la habitación ya ha sido visitada - bool hasBeenVisited(string name); + bool hasBeenVisited(std::string name); public: // Constructor @@ -27,7 +25,7 @@ public: ~RoomTracker(); // Añade la habitación a la lista - bool addRoom(string name); + bool addRoom(std::string name); }; #endif diff --git a/source/scoreboard.cpp b/source/scoreboard.cpp index 30faa6a..7b4c420 100644 --- a/source/scoreboard.cpp +++ b/source/scoreboard.cpp @@ -14,7 +14,7 @@ ScoreBoard::ScoreBoard(SDL_Renderer *renderer, Resource *resource, Asset *asset, // Reserva memoria para los objetos itemTexture = resource->getTexture("items.png"); - const string playerANI = options->cheat.altSkin ? "player2.ani" : "player.ani"; + const std::string playerANI = options->cheat.altSkin ? "player2.ani" : "player.ani"; sprite = new AnimatedSprite(renderer, resource->getAnimation(playerANI)); sprite->setCurrentAnimation("walk_menu"); text = new Text(resource->getOffset("smb2.txt"), resource->getTexture("smb2.png"), renderer); @@ -28,7 +28,7 @@ ScoreBoard::ScoreBoard(SDL_Renderer *renderer, Resource *resource, Asset *asset, itemsColor = stringToColor(options->palette, "white"); // Inicializa el vector de colores - const vector vColors = {"blue", "magenta", "green", "cyan", "yellow", "white", "bright_blue", "bright_magenta", "bright_green", "bright_cyan", "bright_yellow", "bright_white"}; + const std::vector vColors = {"blue", "magenta", "green", "cyan", "yellow", "white", "bright_blue", "bright_magenta", "bright_green", "bright_cyan", "bright_yellow", "bright_white"}; for (auto v : vColors) { color.push_back(stringToColor(options->palette, v)); @@ -77,14 +77,14 @@ void ScoreBoard::render() } // Escribe los textos - const string timeTxt = to_string((clock.minutes % 100) / 10) + to_string(clock.minutes % 10) + clock.separator + to_string((clock.seconds % 60) / 10) + to_string(clock.seconds % 10); - const string itemsTxt = to_string(board->items / 100) + to_string((board->items % 100) / 10) + to_string(board->items % 10); + const std::string timeTxt = std::to_string((clock.minutes % 100) / 10) + std::to_string(clock.minutes % 10) + clock.separator + std::to_string((clock.seconds % 60) / 10) + std::to_string(clock.seconds % 10); + const std::string itemsTxt = std::to_string(board->items / 100) + std::to_string((board->items % 100) / 10) + std::to_string(board->items % 10); this->text->writeColored(BLOCK, line1, "Items collected ", board->color); this->text->writeColored(17 * BLOCK, line1, itemsTxt, itemsColor); this->text->writeColored(20 * BLOCK, line1, " Time ", board->color); this->text->writeColored(26 * BLOCK, line1, timeTxt, stringToColor(options->palette, "white")); - const string roomsTxt = to_string(board->rooms / 100) + to_string((board->rooms % 100) / 10) + to_string(board->rooms % 10); + const std::string roomsTxt = std::to_string(board->rooms / 100) + std::to_string((board->rooms % 100) / 10) + std::to_string(board->rooms % 10); this->text->writeColored(22 * BLOCK, line2, "Rooms", stringToColor(options->palette, "white")); this->text->writeColored(28 * BLOCK, line2, roomsTxt, stringToColor(options->palette, "white")); } @@ -131,7 +131,7 @@ void ScoreBoard::reLoadTexture() void ScoreBoard::reLoadPalette() { // Reinicia el vector de colores - const vector vColors = {"blue", "magenta", "green", "cyan", "yellow", "white", "bright_blue", "bright_magenta", "bright_green", "bright_cyan", "bright_yellow", "bright_white"}; + const std::vector vColors = {"blue", "magenta", "green", "cyan", "yellow", "white", "bright_blue", "bright_magenta", "bright_green", "bright_cyan", "bright_yellow", "bright_white"}; color.clear(); for (auto v : vColors) { diff --git a/source/scoreboard.h b/source/scoreboard.h index f42d70d..463fc52 100644 --- a/source/scoreboard.h +++ b/source/scoreboard.h @@ -12,8 +12,6 @@ #ifndef SCOREBOARD_H #define SCOREBOARD_H -using namespace std; - struct board_t { int items; // Lleva la cuenta de los objetos recogidos @@ -33,7 +31,7 @@ private: int hours; int minutes; int seconds; - string separator; + std::string separator; }; // Objetos y punteros @@ -47,14 +45,14 @@ private: options_t *options; // Puntero a las opciones del juego // Variables - vector color; // Vector con los colores del objeto - int counter; // Contador interno - int colorChangeSpeed; // Cuanto mas alto, mas tarda en cambiar de color - bool paused; // Indica si el marcador esta en modo pausa - Uint32 timePaused; // Milisegundos que ha estado el marcador en pausa - Uint32 totalTimePaused; // Tiempo acumulado en pausa - clock_t clock; // Contiene las horas, minutos y segundos transcurridos desde el inicio de la partida - color_t itemsColor; // Color de la cantidad de items recogidos + std::vector color; // Vector con los colores del objeto + int counter; // Contador interno + int colorChangeSpeed; // Cuanto mas alto, mas tarda en cambiar de color + bool paused; // Indica si el marcador esta en modo pausa + Uint32 timePaused; // Milisegundos que ha estado el marcador en pausa + Uint32 totalTimePaused; // Tiempo acumulado en pausa + clock_t clock; // Contiene las horas, minutos y segundos transcurridos desde el inicio de la partida + color_t itemsColor; // Color de la cantidad de items recogidos // Obtiene el tiempo transcurrido de partida clock_t getTime(); diff --git a/source/stats.cpp b/source/stats.cpp index dc73d3a..5d44256 100644 --- a/source/stats.cpp +++ b/source/stats.cpp @@ -6,7 +6,7 @@ #include // Constructor -Stats::Stats(string file, string buffer, options_t *options) +Stats::Stats(std::string file, std::string buffer, options_t *options) { this->options = options; bufferPath = buffer; @@ -51,10 +51,10 @@ void Stats::init() } // Añade una muerte a las estadisticas -void Stats::addDeath(string name) +void Stats::addDeath(std::string name) { // Normaliza el nombre - // replace(name.begin(), name.end(), ' ', '_'); + // std::replace(name.begin(), name.end(), ' ', '_'); // Primero busca si ya hay una entrada con ese nombre const int index = findByName(name, bufferList); @@ -75,10 +75,10 @@ void Stats::addDeath(string name) } // Añade una visita a las estadisticas -void Stats::addVisit(string name) +void Stats::addVisit(std::string name) { // Normaliza el nombre - // replace(name.begin(), name.end(), ' ', '_'); + // std::replace(name.begin(), name.end(), ' ', '_'); // Primero busca si ya hay una entrada con ese nombre const int index = findByName(name, bufferList); @@ -99,7 +99,7 @@ void Stats::addVisit(string name) } // Busca una entrada en la lista por nombre -int Stats::findByName(string name, vector &list) +int Stats::findByName(std::string name, std::vector &list) { int i = 0; @@ -116,7 +116,7 @@ int Stats::findByName(string name, vector &list) } // Carga las estadisticas desde un fichero -bool Stats::loadFromFile(string filePath, vector &list) +bool Stats::loadFromFile(std::string filePath, std::vector &list) { list.clear(); @@ -124,21 +124,21 @@ bool Stats::loadFromFile(string filePath, vector &list) bool success = true; // Variables para manejar el fichero - string line; - ifstream file(filePath); + std::string line; + std::ifstream file(filePath); // Si el fichero se puede abrir if (file.good()) { // Procesa el fichero linea a linea - while (getline(file, line)) + while (std::getline(file, line)) { // Comprueba que la linea no sea un comentario if (line.substr(0, 1) != "#") { stats_t stat; - stringstream ss(line); - string tmp; + std::stringstream ss(line); + std::string tmp; // Obtiene el nombre getline(ss, tmp, ';'); @@ -146,11 +146,11 @@ bool Stats::loadFromFile(string filePath, vector &list) // Obtiene las visitas getline(ss, tmp, ';'); - stat.visited = stoi(tmp); + stat.visited = std::stoi(tmp); // Obtiene las muertes getline(ss, tmp, ';'); - stat.died = stoi(tmp); + stat.died = std::stoi(tmp); list.push_back(stat); } @@ -177,14 +177,14 @@ void Stats::loadFromServer() list.clear(); - string data; + std::string data; if (options->online.enabled) { data = jscore::getUserData(options->online.gameID, options->online.jailerID); } - stringstream ss(data); - string tmp; + std::stringstream ss(data); + std::string tmp; int count = 0; @@ -206,11 +206,11 @@ void Stats::loadFromServer() // Obtiene las visitas getline(ss, tmp, ';'); - stat.visited = stoi(tmp); + stat.visited = std::stoi(tmp); // Obtiene las muertes getline(ss, tmp, ';'); - stat.died = stoi(tmp); + stat.died = std::stoi(tmp); list.push_back(stat); count = count - 3; @@ -218,16 +218,16 @@ void Stats::loadFromServer() } // Guarda las estadisticas en un fichero -void Stats::saveToFile(string filePath, vector &list) +void Stats::saveToFile(std::string filePath, std::vector &list) { // Crea y abre el fichero de texto - ofstream file(filePath); + std::ofstream file(filePath); // Escribe en el fichero - file << "# ROOM NAME;VISITS;DEATHS" << endl; + file << "# ROOM NAME;VISITS;DEATHS" << std::endl; for (auto item : list) { - file << item.name << ";" << item.visited << ";" << item.died << endl; + file << item.name << ";" << item.visited << ";" << item.died << std::endl; } // Cierra el fichero @@ -237,12 +237,12 @@ void Stats::saveToFile(string filePath, vector &list) // Guarda las estadisticas en un servidor void Stats::saveToServer() { - string data = ""; + std::string data = ""; if (options->online.enabled) { for (auto item : list) { - data = data + nameToNumber(item.name) + ";" + to_string(item.visited) + ";" + to_string(item.died) + ";"; + data = data + nameToNumber(item.name) + ";" + std::to_string(item.visited) + ";" + std::to_string(item.died) + ";"; } jscore::setUserData(options->online.gameID, options->online.jailerID, data); } @@ -263,13 +263,13 @@ void Stats::checkWorstNightmare() } // Añade una entrada al diccionario -void Stats::addDictionary(string number, string name) +void Stats::addDictionary(std::string number, std::string name) { dictionary.push_back({number, name}); } // Obtiene el nombre de una habitación a partir del número -string Stats::numberToName(string number) +std::string Stats::numberToName(std::string number) { for (auto l : dictionary) { @@ -282,7 +282,7 @@ string Stats::numberToName(string number) } // Obtiene el número de una habitación a partir del nombre -string Stats::nameToNumber(string name) +std::string Stats::nameToNumber(std::string name) { for (auto l : dictionary) { diff --git a/source/stats.h b/source/stats.h index 1c4470d..f6a81bc 100644 --- a/source/stats.h +++ b/source/stats.h @@ -7,45 +7,43 @@ #ifndef STATS_H #define STATS_H -using namespace std; - class Stats { private: struct stats_t { - string name; // Nombre de la habitación - int visited; // Cuenta las veces que se ha visitado una habitación - int died; // Cuenta las veces que se ha muerto en una habitación + std::string name; // Nombre de la habitación + int visited; // Cuenta las veces que se ha visitado una habitación + int died; // Cuenta las veces que se ha muerto en una habitación }; struct stats_dictionary_t { - string number; // Numero de la habitación - string name; // Nombre de la habitación + std::string number; // Numero de la habitación + std::string name; // Nombre de la habitación }; // Punteros y objetos options_t *options; // Variables - vector dictionary; // Lista con la equivalencia nombre-numero de habitacion - vector bufferList; // Lista con las estadisticas temporales por habitación - vector list; // Lista con las estadisticas completas por habitación - string bufferPath; // Fichero con las estadísticas temporales - string filePath; // Fichero con las estadísticas completas + std::vector dictionary; // Lista con la equivalencia nombre-numero de habitacion + std::vector bufferList; // Lista con las estadisticas temporales por habitación + std::vector list; // Lista con las estadisticas completas por habitación + std::string bufferPath; // Fichero con las estadísticas temporales + std::string filePath; // Fichero con las estadísticas completas // Busca una entrada en la lista por nombre - int findByName(string name, vector &list); + int findByName(std::string name, std::vector &list); // Carga las estadisticas desde un fichero - bool loadFromFile(string filePath, vector &list); + bool loadFromFile(std::string filePath, std::vector &list); // Carga las estadisticas desde un servidor void loadFromServer(); // Guarda las estadisticas en un fichero - void saveToFile(string filePath, vector &list); + void saveToFile(std::string filePath, std::vector &list); // Guarda las estadisticas en un servidor void saveToServer(); @@ -54,10 +52,10 @@ private: void checkWorstNightmare(); // Obtiene el nombre de una habitación a partir del número - string numberToName(string number); + std::string numberToName(std::string number); // Obtiene el número de una habitación a partir del nombre - string nameToNumber(string name); + std::string nameToNumber(std::string name); // Vuelca los datos del buffer en la lista de estadisticas void updateListFromBuffer(); @@ -67,7 +65,7 @@ private: public: // Constructor - Stats(string file, string buffer, options_t *options); + Stats(std::string file, std::string buffer, options_t *options); // Destructor ~Stats(); @@ -77,13 +75,13 @@ public: void init(); // Añade una muerte a las estadisticas - void addDeath(string name); + void addDeath(std::string name); // Añade una visita a las estadisticas - void addVisit(string name); + void addVisit(std::string name); // Añade una entrada al diccionario - void addDictionary(string number, string name); + void addDictionary(std::string number, std::string name); }; #endif