Revert "Eliminados todos los std:: del código"

This reverts commit 4a2d27dc59.
This commit is contained in:
2023-09-16 16:44:15 +02:00
parent 4a2d27dc59
commit 0ea7eb0b9c
35 changed files with 504 additions and 539 deletions

View File

@@ -2,7 +2,7 @@
#include <iostream> #include <iostream>
// Constructor // 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 // Copia la dirección de los objetos
this->options = options; this->options = options;
@@ -169,7 +169,7 @@ void Cheevos::loadFromFile()
{ {
if (options->console) 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 // Crea el fichero en modo escritura
@@ -179,7 +179,7 @@ void Cheevos::loadFromFile()
{ {
if (options->console) if (options->console)
{ {
cout << "New file created!" << endl; std::cout << "New file created!" << std::endl;
} }
// Guarda la información // Guarda la información
@@ -195,7 +195,7 @@ void Cheevos::loadFromFile()
{ {
if (options->console) 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 // Carga los datos
if (options->console) if (options->console)
{ {
cout << "Reading file...!" << endl; std::cout << "Reading file...!" << std::endl;
} }
for (int i = 0; i < (int)cheevos.size(); ++i) for (int i = 0; i < (int)cheevos.size(); ++i)
{ {
@@ -237,13 +237,13 @@ void Cheevos::saveToFile()
{ {
if (options->console) 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 // Lista los logros
vector<cheevos_t> Cheevos::list() std::vector<cheevos_t> Cheevos::list()
{ {
return cheevos; return cheevos;
} }

View File

@@ -8,13 +8,11 @@
#ifndef CHEEVOS_H #ifndef CHEEVOS_H
#define CHEEVOS_H #define CHEEVOS_H
using namespace std;
struct cheevos_t struct cheevos_t
{ {
int id; // Identificador del logro int id; // Identificador del logro
string caption; // Texto con el nombre del logro std::string caption; // Texto con el nombre del logro
string description; // Texto que describe el logro std::string description; // Texto que describe el logro
int icon; // Indice del icono a utilizar en la notificación int icon; // Indice del icono a utilizar en la notificación
bool completed; // Indica si se ha obtenido el logro bool completed; // Indica si se ha obtenido el logro
bool valid; // Indica si se puede obtener el logro bool valid; // Indica si se puede obtener el logro
@@ -28,9 +26,9 @@ private:
options_t *options; // Puntero a las opciones del juego options_t *options; // Puntero a las opciones del juego
// Variables // Variables
vector<cheevos_t> cheevos; // Listado de logros std::vector<cheevos_t> cheevos; // Listado de logros
bool enabled; // Indica si los logros se pueden obtener bool enabled; // Indica si los logros se pueden obtener
string file; // Fichero done leer/almacenar el estado de los logros std::string file; // Fichero done leer/almacenar el estado de los logros
// Inicializa los logros // Inicializa los logros
void init(); void init();
@@ -46,7 +44,7 @@ private:
public: public:
// Constructor // Constructor
Cheevos(Screen *screen, options_t *options, string file); Cheevos(Screen *screen, options_t *options, std::string file);
// Destructor // Destructor
~Cheevos(); ~Cheevos();
@@ -61,7 +59,7 @@ public:
void enable(bool value); void enable(bool value);
// Lista los logros // Lista los logros
vector<cheevos_t> list(); std::vector<cheevos_t> list();
// Devuelve el número total de logros desbloqueados // Devuelve el número total de logros desbloqueados
int unlocked(); int unlocked();

View File

@@ -37,7 +37,7 @@ Credits::Credits(SDL_Renderer *renderer, Screen *screen, Resource *resource, Ass
{ {
if (options->console) 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); SDL_SetTextureBlendMode(textTexture, SDL_BLENDMODE_BLEND);
@@ -48,7 +48,7 @@ Credits::Credits(SDL_Renderer *renderer, Screen *screen, Resource *resource, Ass
{ {
if (options->console) 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); SDL_SetTextureBlendMode(coverTexture, SDL_BLENDMODE_BLEND);
@@ -126,7 +126,7 @@ void Credits::checkInput()
// Inicializa los textos // Inicializa los textos
void Credits::iniTexts() void Credits::iniTexts()
{ {
string keys = ""; std::string keys = "";
if (options->keys == ctrl_cursor) if (options->keys == ctrl_cursor)
{ {
keys = "CURSORS"; keys = "CURSORS";
@@ -331,7 +331,7 @@ void Credits::render()
SDL_RenderCopy(renderer, textTexture, nullptr, nullptr); SDL_RenderCopy(renderer, textTexture, nullptr, nullptr);
// Dibuja la textura que cubre el texto // 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 srcRect = {0, 0, 256, 192 - (offset * 2)};
SDL_Rect dstRect = {0, offset * 2, 256, 192 - (offset * 2)}; SDL_Rect dstRect = {0, offset * 2, 256, 192 - (offset * 2)};
SDL_RenderCopy(renderer, coverTexture, &srcRect, &dstRect); SDL_RenderCopy(renderer, coverTexture, &srcRect, &dstRect);

View File

@@ -17,14 +17,12 @@
#ifndef CREDITS_H #ifndef CREDITS_H
#define CREDITS_H #define CREDITS_H
using namespace std;
class Credits class Credits
{ {
private: private:
struct captions_t struct captions_t
{ {
string label; // Texto a escribir std::string label; // Texto a escribir
color_t color; // Color del texto color_t color; // Color del texto
}; };
@@ -48,7 +46,7 @@ private:
int subCounter; // Contador secundario int subCounter; // Contador secundario
Uint32 ticks; // Contador de ticks para ajustar la velocidad del programa Uint32 ticks; // Contador de ticks para ajustar la velocidad del programa
Uint32 ticksSpeed; // Velocidad a la que se repiten los bucles del programa Uint32 ticksSpeed; // Velocidad a la que se repiten los bucles del programa
vector<captions_t> texts; // Vector con los textos std::vector<captions_t> texts; // Vector con los textos
// Actualiza las variables // Actualiza las variables
void update(); void update();

View File

@@ -192,7 +192,7 @@ void Demo::reLoadTextures()
{ {
if (options->console) if (options->console)
{ {
cout << "** RELOAD REQUESTED" << endl; std::cout << "** RELOAD REQUESTED" << std::endl;
} }
room->reLoadTexture(); room->reLoadTexture();
scoreboard->reLoadTexture(); scoreboard->reLoadTexture();
@@ -220,7 +220,7 @@ void Demo::switchPalette()
} }
// Cambia de habitación // 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 // En las habitaciones los limites tienen la cadena del fichero o un 0 en caso de no limitar con nada
if (file != "0") if (file != "0")

View File

@@ -20,8 +20,6 @@
#ifndef DEMO_H #ifndef DEMO_H
#define DEMO_H #define DEMO_H
using namespace std;
class Demo class Demo
{ {
private: private:
@@ -43,12 +41,12 @@ private:
// Variables // Variables
Uint32 ticks; // Contador de ticks para ajustar la velocidad del programa Uint32 ticks; // Contador de ticks para ajustar la velocidad del programa
Uint32 ticksSpeed; // Velocidad a la que se repiten los bucles 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
board_t board; // Estructura con los datos del marcador board_t board; // Estructura con los datos del marcador
int counter; // Contador para el modo demo int counter; // Contador para el modo demo
int roomTime; // Tiempo que se muestra cada habitacion int roomTime; // Tiempo que se muestra cada habitacion
int roomIndex; // Indice para el vector de habitaciones int roomIndex; // Indice para el vector de habitaciones
vector<string> rooms; // Listado con los mapas de la demo std::vector<std::string> rooms; // Listado con los mapas de la demo
// Actualiza el juego, las variables, comprueba la entrada, etc. // Actualiza el juego, las variables, comprueba la entrada, etc.
void update(); void update();
@@ -72,7 +70,7 @@ private:
void switchPalette(); void switchPalette();
// Cambia de habitación // Cambia de habitación
bool changeRoom(string file); bool changeRoom(std::string file);
// Comprueba si se ha de cambiar de habitación // Comprueba si se ha de cambiar de habitación
void checkRoomChange(); void checkRoomChange();

View File

@@ -100,11 +100,11 @@ void Director::initOnline()
{ // Establece el servidor y el puerto { // Establece el servidor y el puerto
jscore::init(options->online.server, options->online.port); 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); screen->showNotification(caption);
if (options->console) if (options->console)
{ {
cout << caption << endl; std::cout << caption << std::endl;
} }
} }
} }
@@ -214,12 +214,12 @@ bool Director::loadConfig()
bool success = true; bool success = true;
// Versión actual del fichero // Versión actual del fichero
const string configVersion = options->configVersion; const std::string configVersion = options->configVersion;
options->configVersion = ""; options->configVersion = "";
// Variables para manejar el fichero // Variables para manejar el fichero
string line; std::string line;
ifstream file(asset->get("config.txt")); std::ifstream file(asset->get("config.txt"));
// Si el fichero se puede abrir // Si el fichero se puede abrir
if (file.good()) if (file.good())
@@ -227,9 +227,9 @@ bool Director::loadConfig()
// Procesa el fichero linea a linea // Procesa el fichero linea a linea
if (options->console) 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 // Comprueba que la linea no sea un comentario
if (line.substr(0, 1) != "#") if (line.substr(0, 1) != "#")
@@ -241,8 +241,8 @@ bool Director::loadConfig()
{ {
if (options->console) if (options->console)
{ {
cout << "Warning: file config.txt\n"; std::cout << "Warning: file config.txt\n";
cout << "unknown parameter " << line.substr(0, pos).c_str() << endl; std::cout << "unknown parameter " << line.substr(0, pos).c_str() << std::endl;
} }
success = false; success = false;
} }
@@ -252,7 +252,7 @@ bool Director::loadConfig()
// Cierra el fichero // Cierra el fichero
if (options->console) if (options->console)
{ {
cout << "Closing file config.txt\n\n"; std::cout << "Closing file config.txt\n\n";
} }
file.close(); file.close();
} }
@@ -307,20 +307,20 @@ bool Director::saveConfig()
bool success = true; bool success = true;
// Crea y abre el fichero de texto // Crea y abre el fichero de texto
ofstream file(asset->get("config.txt")); std::ofstream file(asset->get("config.txt"));
if (file.good()) if (file.good())
{ {
if (options->console) if (options->console)
{ {
cout << asset->get("config.txt") << " open for writing" << endl; std::cout << asset->get("config.txt") << " open for writing" << std::endl;
} }
} }
else else
{ {
if (options->console) 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 << "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) if (options->filter == FILTER_NEAREST)
{ {
@@ -374,14 +374,14 @@ bool Director::saveConfig()
file << "integerScale=" + boolToString(options->integerScale) + "\n"; file << "integerScale=" + boolToString(options->integerScale) + "\n";
file << "keepAspect=" + boolToString(options->keepAspect) + "\n"; file << "keepAspect=" + boolToString(options->keepAspect) + "\n";
file << "borderEnabled=" + boolToString(options->borderEnabled) + "\n"; file << "borderEnabled=" + boolToString(options->borderEnabled) + "\n";
file << "borderWidth=" + to_string(options->borderWidth) + "\n"; file << "borderWidth=" + std::to_string(options->borderWidth) + "\n";
file << "borderHeight=" + to_string(options->borderHeight) + "\n"; file << "borderHeight=" + std::to_string(options->borderHeight) + "\n";
file << "palette=" + to_string(options->palette) + "\n"; file << "palette=" + std::to_string(options->palette) + "\n";
file << "\n## ONLINE OPTIONS\n"; file << "\n## ONLINE OPTIONS\n";
file << "enabled=" + boolToString(options->online.enabled) + "\n"; file << "enabled=" + boolToString(options->online.enabled) + "\n";
file << "server=" + options->online.server + "\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 << "jailerID=" + options->online.jailerID + "\n";
file << "\n## NOTIFICATION OPTIONS\n"; file << "\n## NOTIFICATION OPTIONS\n";
@@ -418,18 +418,18 @@ bool Director::saveConfig()
} }
// Crea la carpeta del sistema donde guardar datos // Crea la carpeta del sistema donde guardar datos
void Director::createSystemFolder(string folder) void Director::createSystemFolder(std::string folder)
{ {
#ifdef _WIN32 #ifdef _WIN32
systemFolder = string(getenv("APPDATA")) + "/" + folder; systemFolder = std::string(getenv("APPDATA")) + "/" + folder;
#elif __APPLE__ #elif __APPLE__
struct passwd *pw = getpwuid(getuid()); struct passwd *pw = getpwuid(getuid());
const char *homedir = pw->pw_dir; const char *homedir = pw->pw_dir;
systemFolder = string(homedir) + "/Library/Application Support" + "/" + folder; systemFolder = std::string(homedir) + "/Library/Application Support" + "/" + folder;
#elif __linux__ #elif __linux__
struct passwd *pw = getpwuid(getuid()); struct passwd *pw = getpwuid(getuid());
const char *homedir = pw->pw_dir; const char *homedir = pw->pw_dir;
systemFolder = string(homedir) + "/." + folder; systemFolder = std::string(homedir) + "/." + folder;
#endif #endif
struct stat st = {0}; struct stat st = {0};
@@ -471,12 +471,12 @@ void Director::loadResources(section_t *section)
{ {
if (options->console) if (options->console)
{ {
cout << "** LOAD RESOURCES" << endl; std::cout << "** LOAD RESOURCES" << std::endl;
} }
if (section->name == SECTION_PROG_LOGO) if (section->name == SECTION_PROG_LOGO)
{ {
vector<string> textureList; std::vector<std::string> textureList;
textureList.push_back("jailgames.png"); textureList.push_back("jailgames.png");
textureList.push_back("since_1998.png"); textureList.push_back("since_1998.png");
@@ -485,7 +485,7 @@ void Director::loadResources(section_t *section)
else if (section->name == SECTION_PROG_INTRO) else if (section->name == SECTION_PROG_INTRO)
{ {
vector<string> textureList; std::vector<std::string> textureList;
textureList.push_back("loading_screen_bn.png"); textureList.push_back("loading_screen_bn.png");
textureList.push_back("loading_screen_color.png"); textureList.push_back("loading_screen_color.png");
textureList.push_back("loading_screen_bn_zxarne.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) else if (section->name == SECTION_PROG_TITLE)
{ {
vector<string> textureList; std::vector<std::string> textureList;
textureList.push_back("loading_screen_color.png"); textureList.push_back("loading_screen_color.png");
textureList.push_back("loading_screen_color_zxarne.png"); textureList.push_back("loading_screen_color_zxarne.png");
textureList.push_back("smb2.png"); textureList.push_back("smb2.png");
@@ -506,7 +506,7 @@ void Director::loadResources(section_t *section)
resource->loadTextures(textureList); resource->loadTextures(textureList);
// Offsets // Offsets
vector<string> offsetsList; std::vector<std::string> offsetsList;
offsetsList.push_back("smb2.txt"); offsetsList.push_back("smb2.txt");
offsetsList.push_back("debug.txt"); offsetsList.push_back("debug.txt");
@@ -516,20 +516,20 @@ void Director::loadResources(section_t *section)
else if (section->name == SECTION_PROG_CREDITS) else if (section->name == SECTION_PROG_CREDITS)
{ {
// Texturas // Texturas
vector<string> textureList; std::vector<std::string> textureList;
textureList.push_back("shine.png"); textureList.push_back("shine.png");
textureList.push_back("smb2.png"); textureList.push_back("smb2.png");
resource->loadTextures(textureList); resource->loadTextures(textureList);
// Animaciones // Animaciones
vector<string> animationList; std::vector<std::string> animationList;
animationList.push_back("shine.ani"); animationList.push_back("shine.ani");
resource->loadAnimations(animationList); resource->loadAnimations(animationList);
// Offsets // Offsets
vector<string> offsetsList; std::vector<std::string> offsetsList;
offsetsList.push_back("smb2.txt"); offsetsList.push_back("smb2.txt");
resource->loadOffsets(offsetsList); resource->loadOffsets(offsetsList);
@@ -538,7 +538,7 @@ void Director::loadResources(section_t *section)
else if (section->name == SECTION_PROG_ENDING) else if (section->name == SECTION_PROG_ENDING)
{ {
// Texturas // Texturas
vector<string> textureList; std::vector<std::string> textureList;
textureList.push_back("ending1.png"); textureList.push_back("ending1.png");
textureList.push_back("ending1_zxarne.png"); textureList.push_back("ending1_zxarne.png");
textureList.push_back("ending2.png"); textureList.push_back("ending2.png");
@@ -554,7 +554,7 @@ void Director::loadResources(section_t *section)
resource->loadTextures(textureList); resource->loadTextures(textureList);
// Offsets // Offsets
vector<string> offsetsList; std::vector<std::string> offsetsList;
offsetsList.push_back("smb2.txt"); offsetsList.push_back("smb2.txt");
resource->loadOffsets(offsetsList); resource->loadOffsets(offsetsList);
@@ -563,7 +563,7 @@ void Director::loadResources(section_t *section)
else if (section->name == SECTION_PROG_ENDING2) else if (section->name == SECTION_PROG_ENDING2)
{ {
// Texturas // Texturas
vector<string> textureList; std::vector<std::string> textureList;
// Texto // Texto
textureList.push_back("smb2.png"); textureList.push_back("smb2.png");
@@ -629,7 +629,7 @@ void Director::loadResources(section_t *section)
resource->loadTextures(textureList); resource->loadTextures(textureList);
// Animaciones // Animaciones
vector<string> animationList; std::vector<std::string> animationList;
// Enemigos // Enemigos
animationList.push_back("abad.ani"); animationList.push_back("abad.ani");
@@ -692,7 +692,7 @@ void Director::loadResources(section_t *section)
resource->loadAnimations(animationList); resource->loadAnimations(animationList);
// Offsets // Offsets
vector<string> offsetsList; std::vector<std::string> offsetsList;
offsetsList.push_back("smb2.txt"); offsetsList.push_back("smb2.txt");
resource->loadOffsets(offsetsList); resource->loadOffsets(offsetsList);
@@ -701,7 +701,7 @@ void Director::loadResources(section_t *section)
else if (section->name == SECTION_PROG_GAME_OVER) else if (section->name == SECTION_PROG_GAME_OVER)
{ {
// Texturas // Texturas
vector<string> textureList; std::vector<std::string> textureList;
textureList.push_back("smb2.png"); textureList.push_back("smb2.png");
textureList.push_back("player_game_over.png"); textureList.push_back("player_game_over.png");
textureList.push_back("tv.png"); textureList.push_back("tv.png");
@@ -709,14 +709,14 @@ void Director::loadResources(section_t *section)
resource->loadTextures(textureList); resource->loadTextures(textureList);
// Animaciones // Animaciones
vector<string> animationList; std::vector<std::string> animationList;
animationList.push_back("player_game_over.ani"); animationList.push_back("player_game_over.ani");
animationList.push_back("tv.ani"); animationList.push_back("tv.ani");
resource->loadAnimations(animationList); resource->loadAnimations(animationList);
// Offsets // Offsets
vector<string> offsetsList; std::vector<std::string> offsetsList;
offsetsList.push_back("smb2.txt"); offsetsList.push_back("smb2.txt");
resource->loadOffsets(offsetsList); 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) else if (section->name == SECTION_PROG_GAME || section->name == SECTION_PROG_DEMO)
{ {
// Texturas // Texturas
vector<string> textureList; std::vector<std::string> textureList;
// Jugador // Jugador
if (options->cheat.altSkin) if (options->cheat.altSkin)
@@ -810,7 +810,7 @@ void Director::loadResources(section_t *section)
resource->loadTextures(textureList); resource->loadTextures(textureList);
// Animaciones // Animaciones
vector<string> animationList; std::vector<std::string> animationList;
// Jugador // Jugador
if (options->cheat.altSkin) if (options->cheat.altSkin)
@@ -884,14 +884,14 @@ void Director::loadResources(section_t *section)
resource->loadAnimations(animationList); resource->loadAnimations(animationList);
// Offsets // Offsets
vector<string> offsetsList; std::vector<std::string> offsetsList;
offsetsList.push_back("smb2.txt"); offsetsList.push_back("smb2.txt");
offsetsList.push_back("debug.txt"); offsetsList.push_back("debug.txt");
resource->loadOffsets(offsetsList); resource->loadOffsets(offsetsList);
// TileMaps // TileMaps
vector<string> tileMapList; std::vector<std::string> tileMapList;
tileMapList.push_back("01.tmx"); tileMapList.push_back("01.tmx");
tileMapList.push_back("02.tmx"); tileMapList.push_back("02.tmx");
tileMapList.push_back("03.tmx"); tileMapList.push_back("03.tmx");
@@ -956,7 +956,7 @@ void Director::loadResources(section_t *section)
resource->loadTileMaps(tileMapList); resource->loadTileMaps(tileMapList);
// Habitaciones // Habitaciones
vector<string> roomList; std::vector<std::string> roomList;
roomList.push_back("01.room"); roomList.push_back("01.room");
roomList.push_back("02.room"); roomList.push_back("02.room");
roomList.push_back("03.room"); roomList.push_back("03.room");
@@ -1023,12 +1023,12 @@ void Director::loadResources(section_t *section)
if (options->console) if (options->console)
{ {
cout << "** RESOURCES LOADED" << endl; std::cout << "** RESOURCES LOADED" << std::endl;
} }
} }
// Asigna variables a partir de dos cadenas // 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 // Indicador de éxito en la asignación
bool success = true; bool success = true;
@@ -1072,7 +1072,7 @@ bool Director::setOptions(options_t *options, string var, string value)
else if (var == "windowSize") else if (var == "windowSize")
{ {
options->windowSize = stoi(value); options->windowSize = std::stoi(value);
if ((options->windowSize < 1) || (options->windowSize > 4)) if ((options->windowSize < 1) || (options->windowSize > 4))
{ {
options->windowSize = 3; options->windowSize = 3;
@@ -1113,17 +1113,17 @@ bool Director::setOptions(options_t *options, string var, string value)
else if (var == "borderWidth") else if (var == "borderWidth")
{ {
options->borderWidth = stoi(value); options->borderWidth = std::stoi(value);
} }
else if (var == "borderHeight") else if (var == "borderHeight")
{ {
options->borderHeight = stoi(value); options->borderHeight = std::stoi(value);
} }
else if (var == "palette") else if (var == "palette")
{ {
const int pal = stoi(value); const int pal = std::stoi(value);
if (pal == 0) if (pal == 0)
{ {
@@ -1152,7 +1152,7 @@ bool Director::setOptions(options_t *options, string var, string value)
{ {
value = "0"; value = "0";
} }
options->online.port = stoi(value); options->online.port = std::stoi(value);
} }
else if (var == "jailerID") else if (var == "jailerID")
@@ -1222,6 +1222,7 @@ void Director::initInput()
input->bindKey(input_right, SDL_SCANCODE_RIGHT); input->bindKey(input_right, SDL_SCANCODE_RIGHT);
input->bindKey(input_up, SDL_SCANCODE_UP); input->bindKey(input_up, SDL_SCANCODE_UP);
input->bindKey(input_down, SDL_SCANCODE_DOWN); input->bindKey(input_down, SDL_SCANCODE_DOWN);
} }
else if (options->keys == ctrl_opqa) else if (options->keys == ctrl_opqa)
{ {
@@ -1289,21 +1290,21 @@ bool Director::initSDL()
{ {
if (options->console) 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; success = false;
} }
else else
{ {
// Inicia el generador de numeros aleatorios // Inicia el generador de numeros aleatorios
srand(static_cast<unsigned int>(SDL_GetTicks())); std::srand(static_cast<unsigned int>(SDL_GetTicks()));
// Establece el filtro de la textura a nearest // 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) 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) 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; success = false;
} }
@@ -1341,7 +1342,7 @@ bool Director::initSDL()
{ {
if (options->console) 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; success = false;
} }
@@ -1361,7 +1362,7 @@ bool Director::initSDL()
if (options->console) if (options->console)
{ {
cout << endl; std::cout << std::endl;
} }
return success; return success;
} }
@@ -1370,9 +1371,9 @@ bool Director::initSDL()
bool Director::setFileList() bool Director::setFileList()
{ {
#ifdef MACOS_BUNDLE #ifdef MACOS_BUNDLE
const string prefix = "/../Resources"; const std::string prefix = "/../Resources";
#else #else
const string prefix = ""; const std::string prefix = "";
#endif #endif
// Texto // Texto
@@ -1721,7 +1722,7 @@ void Director::runLogo()
{ {
if (options->console) if (options->console)
{ {
cout << "\n* SECTION: LOGO" << endl; std::cout << "\n* SECTION: LOGO" << std::endl;
} }
loadResources(section); loadResources(section);
logo = new Logo(renderer, screen, resource, asset, input, options, section); logo = new Logo(renderer, screen, resource, asset, input, options, section);
@@ -1735,7 +1736,7 @@ void Director::runIntro()
{ {
if (options->console) if (options->console)
{ {
cout << "\n* SECTION: INTRO" << endl; std::cout << "\n* SECTION: INTRO" << std::endl;
} }
loadResources(section); loadResources(section);
intro = new Intro(renderer, screen, resource, asset, input, options, section); intro = new Intro(renderer, screen, resource, asset, input, options, section);
@@ -1749,7 +1750,7 @@ void Director::runTitle()
{ {
if (options->console) 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)) if ((JA_GetMusicState() == JA_MUSIC_INVALID) || (JA_GetMusicState() == JA_MUSIC_STOPPED))
{ {
@@ -1767,7 +1768,7 @@ void Director::runCredits()
{ {
if (options->console) if (options->console)
{ {
cout << "\n* SECTION: CREDITS" << endl; std::cout << "\n* SECTION: CREDITS" << std::endl;
} }
loadResources(section); loadResources(section);
credits = new Credits(renderer, screen, resource, asset, input, options, section); credits = new Credits(renderer, screen, resource, asset, input, options, section);
@@ -1781,7 +1782,7 @@ void Director::runDemo()
{ {
if (options->console) if (options->console)
{ {
cout << "\n* SECTION: DEMO" << endl; std::cout << "\n* SECTION: DEMO" << std::endl;
} }
loadResources(section); loadResources(section);
demo = new Demo(renderer, screen, resource, asset, input, options, section, debug); demo = new Demo(renderer, screen, resource, asset, input, options, section, debug);
@@ -1795,7 +1796,7 @@ void Director::runEnterID()
{ {
if (options->console) if (options->console)
{ {
cout << "\n* SECTION: ENTER_ID" << endl; std::cout << "\n* SECTION: ENTER_ID" << std::endl;
} }
// loadResources(section); // loadResources(section);
enterID = new EnterID(renderer, screen, asset, options, section); enterID = new EnterID(renderer, screen, asset, options, section);
@@ -1809,7 +1810,7 @@ void Director::runEnding()
{ {
if (options->console) if (options->console)
{ {
cout << "\n* SECTION: ENDING" << endl; std::cout << "\n* SECTION: ENDING" << std::endl;
} }
loadResources(section); loadResources(section);
ending = new Ending(renderer, screen, resource, asset, input, options, section); ending = new Ending(renderer, screen, resource, asset, input, options, section);
@@ -1823,7 +1824,7 @@ void Director::runEnding2()
{ {
if (options->console) if (options->console)
{ {
cout << "\n* SECTION: ENDING2" << endl; std::cout << "\n* SECTION: ENDING2" << std::endl;
} }
loadResources(section); loadResources(section);
ending2 = new Ending2(renderer, screen, resource, asset, input, options, section); ending2 = new Ending2(renderer, screen, resource, asset, input, options, section);
@@ -1837,7 +1838,7 @@ void Director::runGameOver()
{ {
if (options->console) if (options->console)
{ {
cout << "\n* SECTION: GAME OVER" << endl; std::cout << "\n* SECTION: GAME OVER" << std::endl;
} }
loadResources(section); loadResources(section);
gameOver = new GameOver(renderer, screen, resource, asset, input, options, section); gameOver = new GameOver(renderer, screen, resource, asset, input, options, section);
@@ -1851,7 +1852,7 @@ void Director::runGame()
{ {
if (options->console) if (options->console)
{ {
cout << "\n* SECTION: GAME" << endl; std::cout << "\n* SECTION: GAME" << std::endl;
} }
JA_StopMusic(); JA_StopMusic();
loadResources(section); loadResources(section);

View File

@@ -24,8 +24,6 @@
#ifndef DIRECTOR_H #ifndef DIRECTOR_H
#define DIRECTOR_H #define DIRECTOR_H
using namespace std;
class Director class Director
{ {
private: private:
@@ -52,8 +50,8 @@ private:
// Variables // Variables
JA_Music_t *music; // Musica del titulo JA_Music_t *music; // Musica del titulo
string executablePath; // Path del ejecutable std::string executablePath; // Path del ejecutable
string systemFolder; // Carpeta del sistema donde guardar datos std::string systemFolder; // Carpeta del sistema donde guardar datos
// Crea e inicializa las opciones del programa // Crea e inicializa las opciones del programa
void initOptions(); void initOptions();
@@ -71,13 +69,13 @@ private:
bool saveConfig(); bool saveConfig();
// Crea la carpeta del sistema donde guardar datos // Crea la carpeta del sistema donde guardar datos
void createSystemFolder(string folder); void createSystemFolder(std::string folder);
// Carga los recursos // Carga los recursos
void loadResources(section_t *section); void loadResources(section_t *section);
// Asigna variables a partir de dos cadenas // 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 // Inicializa jail_audio
void initJailAudio(); void initJailAudio();

View File

@@ -45,7 +45,7 @@ Ending::Ending(SDL_Renderer *renderer, Screen *screen, Resource *resource, Asset
{ {
if (options->console) 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); SDL_SetTextureBlendMode(coverTexture, SDL_BLENDMODE_BLEND);
@@ -140,7 +140,7 @@ void Ending::render()
// Dibuja la cortinilla de cambio de escena // Dibuja la cortinilla de cambio de escena
renderCoverTexture(); renderCoverTexture();
// text->write(0, 0, to_string(counter)); // text->write(0, 0, std::to_string(counter));
// Vuelca el contenido del renderizador en pantalla // Vuelca el contenido del renderizador en pantalla
screen->blit(); screen->blit();
@@ -201,7 +201,7 @@ void Ending::checkInput()
void Ending::iniTexts() void Ending::iniTexts()
{ {
// Vector con los textos // Vector con los textos
vector<textAndPos_t> texts; std::vector<textAndPos_t> texts;
// Escena #0 // Escena #0
texts.push_back({"HE FINALLY MANAGED", 32}); texts.push_back({"HE FINALLY MANAGED", 32});
@@ -307,7 +307,7 @@ void Ending::iniTexts()
void Ending::iniPics() void Ending::iniPics()
{ {
// Vector con las rutas y la posición // Vector con las rutas y la posición
vector<textAndPos_t> pics; std::vector<textAndPos_t> pics;
if (options->palette == p_zxspectrum) if (options->palette == p_zxspectrum)
{ {
@@ -605,7 +605,7 @@ void Ending::renderCoverTexture()
{ {
if (coverCounter > 0) if (coverCounter > 0)
{ // Dibuja la textura que cubre el texto { // 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 srcRect = {0, 200 - (coverCounter * 2), 256, offset * 2};
SDL_Rect dstRect = {0, 0, 256, offset * 2}; SDL_Rect dstRect = {0, 0, 256, offset * 2};
SDL_RenderCopy(renderer, coverTexture, &srcRect, &dstRect); SDL_RenderCopy(renderer, coverTexture, &srcRect, &dstRect);

View File

@@ -17,8 +17,6 @@
#ifndef ENDING_H #ifndef ENDING_H
#define ENDING_H #define ENDING_H
using namespace std;
class Ending class Ending
{ {
private: private:
@@ -35,7 +33,7 @@ private:
struct textAndPos_t // Estructura con un texto y su posición en el eje Y struct textAndPos_t // Estructura con un texto y su posición en el eje Y
{ {
string caption; // Texto std::string caption; // Texto
int pos; // Posición int pos; // Posición
}; };
@@ -47,7 +45,7 @@ private:
struct scene_t // Estructura para crear cada una de las escenas del final struct scene_t // Estructura para crear cada una de las escenas del final
{ {
vector<asdhk> textIndex; // Indices del vector de textos a mostrar y su disparador std::vector<asdhk> textIndex; // Indices del vector de textos a mostrar y su disparador
int pictureIndex; // Indice del vector de imagenes a mostrar int pictureIndex; // Indice del vector de imagenes a mostrar
int counterEnd; // Valor del contador en el que finaliza la escena int counterEnd; // Valor del contador en el que finaliza la escena
}; };
@@ -70,10 +68,10 @@ private:
int coverCounter; // Contador para la cortinilla int coverCounter; // Contador para la cortinilla
Uint32 ticks; // Contador de ticks para ajustar la velocidad del programa Uint32 ticks; // Contador de ticks para ajustar la velocidad del programa
Uint32 ticksSpeed; // Velocidad a la que se repiten los bucles del programa Uint32 ticksSpeed; // Velocidad a la que se repiten los bucles del programa
vector<endingTexture_t> spriteTexts; // Vector con los sprites de texto con su cortinilla std::vector<endingTexture_t> spriteTexts; // Vector con los sprites de texto con su cortinilla
vector<endingTexture_t> spritePics; // Vector con los sprites de texto con su cortinilla std::vector<endingTexture_t> spritePics; // Vector con los sprites de texto con su cortinilla
int scene; // Escena actual int scene; // Escena actual
vector<scene_t> scenes; // Vector con los textos e imagenes de cada escena std::vector<scene_t> scenes; // Vector con los textos e imagenes de cada escena
JA_Music_t *music; // Musica que suena durante el final JA_Music_t *music; // Musica que suena durante el final
// Actualiza el objeto // Actualiza el objeto

View File

@@ -34,7 +34,7 @@ Ending2::Ending2(SDL_Renderer *renderer, Screen *screen, Resource *resource, Ass
secondCol = GAMECANVAS_THIRD_QUARTER_X - (GAMECANVAS_WIDTH / 16); secondCol = GAMECANVAS_THIRD_QUARTER_X - (GAMECANVAS_WIDTH / 16);
// Inicializa el vector de colores // Inicializa el vector de colores
const vector<string> colorList = {"white", "yellow", "cyan", "green", "magenta", "red", "blue", "black"}; const std::vector<std::string> colorList = {"white", "yellow", "cyan", "green", "magenta", "red", "blue", "black"};
for (auto cl : colorList) for (auto cl : colorList)
{ {
colors.push_back(stringToColor(options->palette, cl)); colors.push_back(stringToColor(options->palette, cl));
@@ -131,7 +131,7 @@ void Ending2::render()
// Dibuja los sprites con el texto del final // Dibuja los sprites con el texto del final
renderTexts(); renderTexts();
const string txt = to_string(postCounter); const std::string txt = std::to_string(postCounter);
// text->write(0, 192 - 8, txt); // text->write(0, 192 - 8, txt);
// Dibuja la cuadricula // Dibuja la cuadricula
@@ -363,8 +363,8 @@ void Ending2::loadSprites()
for (auto sl : spriteList) for (auto sl : spriteList)
{ {
sprites.push_back(new AnimatedSprite(renderer, resource->getAnimation(sl + ".ani"))); sprites.push_back(new AnimatedSprite(renderer, resource->getAnimation(sl + ".ani")));
maxSpriteWidth = max(sprites.back()->getAnimationClip(0, 0).w, maxSpriteWidth); maxSpriteWidth = std::max(sprites.back()->getAnimationClip(0, 0).w, maxSpriteWidth);
maxSpriteHeight = max(sprites.back()->getAnimationClip(0, 0).h, maxSpriteHeight); 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) for (int i = 0; i < (int)spriteList.size(); ++i)
{ {
// Calcula constantes // Calcula constantes
string txt = spriteList[i]; std::string txt = spriteList[i];
replace(txt.begin(), txt.end(), '_', ' '); std::replace(txt.begin(), txt.end(), '_', ' ');
txt = txt == "player" ? "JAILDOCTOR" : txt; // Reemplaza el texto txt = txt == "player" ? "JAILDOCTOR" : txt; // Reemplaza el texto
const int w = text->lenght(txt, 1); const int w = text->lenght(txt, 1);
const int h = text->getCharacterSize(); const int h = text->getCharacterSize();
@@ -520,7 +520,7 @@ void Ending2::createTexts()
deleteTexts(); deleteTexts();
// Crea los primeros textos // Crea los primeros textos
vector<string> list; std::vector<std::string> list;
list.push_back("STARRING"); list.push_back("STARRING");
// Crea los sprites de texto a partir de la lista // Crea los sprites de texto a partir de la lista
@@ -610,7 +610,7 @@ void Ending2::deleteTexts()
void Ending2::updateFinalFade() 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 // 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; const int index = (colors.size() - 1) * step;
for (auto t : texts) for (auto t : texts)

View File

@@ -17,8 +17,6 @@
#ifndef ENDING2_H #ifndef ENDING2_H
#define ENDING2_H #define ENDING2_H
using namespace std;
class Ending2 class Ending2
{ {
private: private:
@@ -31,9 +29,9 @@ private:
Input *input; // Objeto pata gestionar la entrada Input *input; // Objeto pata gestionar la entrada
Text *text; // Objeto para escribir texto en pantalla Text *text; // Objeto para escribir texto en pantalla
options_t *options; // Puntero a las opciones del juego options_t *options; // Puntero a las opciones del juego
vector<AnimatedSprite *> sprites; // Vector con todos los sprites a dibujar std::vector<AnimatedSprite *> sprites; // Vector con todos los sprites a dibujar
vector<MovingSprite *> spriteTexts; // Vector con los sprites de texto de los sprites std::vector<MovingSprite *> spriteTexts; // Vector con los sprites de texto de los sprites
vector<MovingSprite *> texts; // Vector con los sprites de texto std::vector<MovingSprite *> texts; // Vector con los sprites de texto
section_t *section; // Estado del bucle principal para saber si continua o se sale section_t *section; // Estado del bucle principal para saber si continua o se sale
// Variables // Variables
@@ -44,8 +42,8 @@ private:
Uint32 ticks; // Contador de ticks para ajustar la velocidad del programa Uint32 ticks; // Contador de ticks para ajustar la velocidad del programa
Uint32 ticksSpeed; // Velocidad a la que se repiten los bucles del programa Uint32 ticksSpeed; // Velocidad a la que se repiten los bucles del programa
JA_Music_t *music; // Musica que suena durante el final JA_Music_t *music; // Musica que suena durante el final
vector<string> spriteList; // Lista con todos los sprites a dibujar std::vector<std::string> spriteList; // Lista con todos los sprites a dibujar
vector<color_t> colors; // Vector con los colores para el fade std::vector<color_t> colors; // Vector con los colores para el fade
int maxSpriteWidth; // El valor de ancho del sprite mas ancho int maxSpriteWidth; // El valor de ancho del sprite mas ancho
int maxSpriteHeight; // El valor de alto del sprite mas alto int maxSpriteHeight; // El valor de alto del sprite mas alto
int distSpriteText; // Distancia entre el sprite y el texto que lo acompaña int distSpriteText; // Distancia entre el sprite y el texto que lo acompaña

View File

@@ -40,7 +40,7 @@ Enemy::Enemy(enemy_t enemy)
} }
else else
{ {
sprite->setCurrentFrame(min(enemy.frame, sprite->getNumFrames() - 1)); sprite->setCurrentFrame(std::min(enemy.frame, sprite->getNumFrames() - 1));
} }
} }

View File

@@ -9,14 +9,12 @@
#ifndef ENEMY_H #ifndef ENEMY_H
#define ENEMY_H #define ENEMY_H
using namespace std;
// Estructura para pasar los datos de un enemigo // Estructura para pasar los datos de un enemigo
struct enemy_t struct enemy_t
{ {
SDL_Renderer *renderer; // El renderizador de la ventana SDL_Renderer *renderer; // El renderizador de la ventana
animatedSprite_t *animation; // Puntero a las animaciones del enemigo 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 w; // Anchura del enemigo
int h; // Altura del enemigo int h; // Altura del enemigo
float x; // Posición inicial en el eje X 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 flip; // Indica si el enemigo hace flip al terminar su ruta
bool mirror; // Indica si el enemigo está volteado verticalmente bool mirror; // Indica si el enemigo está volteado verticalmente
int frame; // Frame inicial para la animación del enemigo 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 palette_e palette; // Paleta de colores
}; };
@@ -42,7 +40,7 @@ private:
// Variables // Variables
color_t color; // Color del enemigo color_t color; // Color del enemigo
string colorString; // Color del enemigo en formato texto std::string colorString; // Color del enemigo en formato texto
palette_e palette; // Paleta de colores palette_e palette; // Paleta de colores
int x1; // Limite izquierdo de la ruta en el eje X int x1; // Limite izquierdo de la ruta en el eje X
int x2; // Limite derecho de la ruta en el eje X int x2; // Limite derecho de la ruta en el eje X

View File

@@ -25,7 +25,7 @@ EnterID::EnterID(SDL_Renderer *renderer, Screen *screen, Asset *asset, options_t
{ {
if (options->console) 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); SDL_SetTextureBlendMode(textTexture, SDL_BLENDMODE_BLEND);
@@ -90,7 +90,7 @@ void EnterID::checkEventHandler()
{ {
if (eventHandler->key.keysym.scancode == SDL_SCANCODE_RETURN) if (eventHandler->key.keysym.scancode == SDL_SCANCODE_RETURN)
{ {
options->online.jailerID = (string)name; options->online.jailerID = (std::string)name;
endSection(); endSection();
break; break;
} }
@@ -206,7 +206,7 @@ void EnterID::render()
SDL_RenderCopy(renderer, textTexture, nullptr, nullptr); SDL_RenderCopy(renderer, textTexture, nullptr, nullptr);
// Escribe el jailerID // 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"); const color_t color = stringToColor(options->palette, "white");
text->writeDX(TXT_CENTER | TXT_COLOR, GAMECANVAS_CENTER_X, (16 * 8 + 1), jailerID, 1, color); 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); jscore::init(options->online.server, options->online.port);
#ifdef DEBUG #ifdef DEBUG
const string caption = "IS LOGGED IN (DEBUG)"; const std::string caption = "IS LOGGED IN (DEBUG)";
#else #else
const string caption = "IS LOGGED IN"; const std::string caption = "IS LOGGED IN";
#endif #endif
screen->showNotification(options->online.jailerID, caption, 12); screen->showNotification(options->online.jailerID, caption, 12);
if (options->console) if (options->console)
{ {
cout << caption << endl; std::cout << caption << std::endl;
} }
} }
} }

View File

@@ -9,16 +9,14 @@
#include <vector> #include <vector>
#ifndef ENTER_ID_H #ifndef ENTER_ID_H
#define ENTER_ID_H #define ASK_ME_H
using namespace std;
class EnterID class EnterID
{ {
private: private:
struct captions_t struct captions_t
{ {
string label; // Texto a escribir std::string label; // Texto a escribir
color_t color; // Color del texto color_t color; // Color del texto
}; };
@@ -37,8 +35,8 @@ private:
int counter; // Contador int counter; // Contador
Uint32 ticks; // Contador de ticks para ajustar la velocidad del programa Uint32 ticks; // Contador de ticks para ajustar la velocidad del programa
Uint32 ticksSpeed; // Velocidad a la que se repiten los bucles del programa Uint32 ticksSpeed; // Velocidad a la que se repiten los bucles del programa
vector<captions_t> texts; // Vector con los textos std::vector<captions_t> texts; // Vector con los textos
string cursor; // Contiene el caracter que se muestra como cursor std::string cursor; // Contiene el caracter que se muestra como cursor
char name[15]; char name[15];
int pos; int pos;

View File

@@ -35,8 +35,8 @@ Game::Game(SDL_Renderer *renderer, Screen *screen, Resource *resource, Asset *as
itemTracker = new ItemTracker(); itemTracker = new ItemTracker();
roomTracker = new RoomTracker(); roomTracker = new RoomTracker();
room = new Room(resource->getRoom(currentRoom), renderer, screen, asset, options, itemTracker, &board.items, false, debug); 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 std::string playerPNG = options->cheat.altSkin ? "player2.png" : "player.png";
const string playerANI = options->cheat.altSkin ? "player2.ani" : "player.ani"; 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}; const player_t player = {spawnPoint, playerPNG, playerANI, renderer, resource, asset, options, input, room, debug};
this->player = new Player(player); this->player = new Player(player);
eventHandler = new SDL_Event(); eventHandler = new SDL_Event();
@@ -51,7 +51,7 @@ Game::Game(SDL_Renderer *renderer, Screen *screen, Resource *resource, Asset *as
{ {
if (options->console) 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 // Pasa la información de debug
void Game::updateDebugInfo() void Game::updateDebugInfo()
{ {
debug->add("X = " + to_string((int)player->x) + ", Y = " + to_string((int)player->y)); debug->add("X = " + std::to_string((int)player->x) + ", Y = " + std::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("VX = " + std::to_string(player->vx).substr(0, 4) + ", VY = " + std::to_string(player->vy).substr(0, 4));
debug->add("STATE = " + to_string(player->state)); debug->add("STATE = " + std::to_string(player->state));
} }
// Pone la información de debug en pantalla // Pone la información de debug en pantalla
@@ -365,7 +365,7 @@ void Game::renderRoomName()
} }
// Cambia de habitación // 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 // En las habitaciones los limites tienen la cadena del fichero o un 0 en caso de no limitar con nada
if (file == "0") if (file == "0")
@@ -413,7 +413,7 @@ void Game::checkPlayerOnBorder()
{ {
if (player->getOnBorder()) if (player->getOnBorder())
{ {
const string roomName = room->getRoom(player->getBorder()); const std::string roomName = room->getRoom(player->getBorder());
if (changeRoom(roomName)) if (changeRoom(roomName))
{ {
player->switchBorders(); player->switchBorders();
@@ -490,8 +490,8 @@ void Game::killPlayer()
// Crea la nueva habitación y el nuevo jugador // 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); 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 std::string playerPNG = options->cheat.altSkin ? "player2.png" : "player.png";
const string playerANI = options->cheat.altSkin ? "player2.ani" : "player.ani"; 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}; const player_t player = {spawnPoint, playerPNG, playerANI, renderer, resource, asset, options, input, room, debug};
this->player = new Player(player); this->player = new Player(player);
@@ -505,7 +505,7 @@ void Game::reLoadTextures()
{ {
if (options->console) if (options->console)
{ {
cout << "** RELOAD REQUESTED" << endl; std::cout << "** RELOAD REQUESTED" << std::endl;
} }
player->reLoadTexture(); player->reLoadTexture();
room->reLoadTexture(); room->reLoadTexture();
@@ -518,7 +518,7 @@ void Game::switchPalette()
{ {
if (options->console) if (options->console)
{ {
cout << "** PALETTE SWITCH REQUESTED" << endl; std::cout << "** PALETTE SWITCH REQUESTED" << std::endl;
} }
// Modifica la variable // Modifica la variable
@@ -608,7 +608,7 @@ bool Game::checkEndGame()
int Game::getTotalItems() int Game::getTotalItems()
{ {
int items = 0; int items = 0;
vector<res_room_t> *rooms = new vector<res_room_t>; std::vector<res_room_t> *rooms = new std::vector<res_room_t>;
rooms = resource->getAllRooms(); rooms = resource->getAllRooms();
for (auto room : *rooms) for (auto room : *rooms)
@@ -622,7 +622,7 @@ int Game::getTotalItems()
// Va a la habitación designada // Va a la habitación designada
void Game::goToRoom(int border) void Game::goToRoom(int border)
{ {
const string roomName = room->getRoom(border); const std::string roomName = room->getRoom(border);
if (changeRoom(roomName)) if (changeRoom(roomName))
{ {
currentRoom = roomName; currentRoom = roomName;
@@ -682,7 +682,7 @@ void Game::checkRestoringJail()
// Inicializa el diccionario de las estadísticas // Inicializa el diccionario de las estadísticas
void Game::initStats() void Game::initStats()
{ {
vector<res_room_t> *rooms = new vector<res_room_t>; std::vector<res_room_t> *rooms = new std::vector<res_room_t>;
rooms = resource->getAllRooms(); rooms = resource->getAllRooms();
for (auto room : *rooms) for (auto room : *rooms)

View File

@@ -23,8 +23,6 @@
#ifndef GAME_H #ifndef GAME_H
#define GAME_H #define GAME_H
using namespace std;
class Game class Game
{ {
private: private:
@@ -52,7 +50,7 @@ private:
JA_Music_t *music; // Musica que suena durante el juego JA_Music_t *music; // Musica que suena durante el juego
Uint32 ticks; // Contador de ticks para ajustar la velocidad del programa Uint32 ticks; // Contador de ticks para ajustar la velocidad del programa
Uint32 ticksSpeed; // Velocidad a la que se repiten los bucles 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 playerSpawn_t spawnPoint; // Lugar de la habitación donde aparece el jugador
JA_Sound_t *deathSound; // Sonido a reproducir cuando muere el jugador JA_Sound_t *deathSound; // Sonido a reproducir cuando muere el jugador
board_t board; // Estructura con los datos del marcador board_t board; // Estructura con los datos del marcador
@@ -83,7 +81,7 @@ private:
void renderRoomName(); void renderRoomName();
// Cambia de habitación // Cambia de habitación
bool changeRoom(string file); bool changeRoom(std::string file);
// Comprueba el teclado // Comprueba el teclado
void checkInput(); void checkInput();

View File

@@ -35,7 +35,7 @@ GameOver::GameOver(SDL_Renderer *renderer, Screen *screen, Resource *resource, A
tvSprite->setPosY(30); tvSprite->setPosY(30);
// Inicializa el vector de colores // Inicializa el vector de colores
const vector<string> colorList = {"white", "yellow", "cyan", "green", "magenta", "red", "blue", "black"}; const std::vector<std::string> colorList = {"white", "yellow", "cyan", "green", "magenta", "red", "blue", "black"};
for (auto cl : colorList) for (auto cl : colorList)
{ {
colors.push_back(stringToColor(options->palette, cl)); colors.push_back(stringToColor(options->palette, cl));
@@ -104,8 +104,8 @@ void GameOver::render()
renderSprites(); renderSprites();
// Escribe el texto con las habitaciones y los items // 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 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 string roomsTxt = to_string(options->stats.rooms / 100) + to_string((options->stats.rooms % 100) / 10) + to_string(options->stats.rooms % 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 + 80, "ITEMS: " + itemsTxt, 1, color);
text->writeDX(TXT_CENTER | TXT_COLOR, GAMECANVAS_CENTER_X, y + 90, "ROOMS: " + roomsTxt, 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) 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); const int index = (colors.size() - 1) - int((colors.size() - 1) * step);
color = colors[index]; color = colors[index];
} }
else 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; const int index = (colors.size() - 1) * step;
color = colors[index]; color = colors[index];
} }

View File

@@ -16,8 +16,6 @@
#ifndef GAME_OVER_H #ifndef GAME_OVER_H
#define GAME_OVER_H #define GAME_OVER_H
using namespace std;
class GameOver class GameOver
{ {
private: private:
@@ -39,7 +37,7 @@ private:
int counter; // Contador int counter; // Contador
Uint32 ticks; // Contador de ticks para ajustar la velocidad del programa Uint32 ticks; // Contador de ticks para ajustar la velocidad del programa
Uint32 ticksSpeed; // Velocidad a la que se repiten los bucles del programa Uint32 ticksSpeed; // Velocidad a la que se repiten los bucles del programa
vector<color_t> colors; // Vector con los colores para el fade std::vector<color_t> colors; // Vector con los colores para el fade
color_t color; // Color usado para el texto y los sprites color_t color; // Color usado para el texto y los sprites
int endSection; // Contador: cuando acaba la sección int endSection; // Contador: cuando acaba la sección
int iniFade; // Contador: cuando emiepza el fade int iniFade; // Contador: cuando emiepza el fade

View File

@@ -9,13 +9,11 @@
#ifndef ITEM_H #ifndef ITEM_H
#define ITEM_H #define ITEM_H
using namespace std;
struct item_t struct item_t
{ {
SDL_Renderer *renderer; // El renderizador de la ventana SDL_Renderer *renderer; // El renderizador de la ventana
Texture *texture; // Textura con los graficos del item Texture *texture; // Textura con los graficos del item
string tileSetFile; // Ruta al fichero con los graficos del item std::string tileSetFile; // Ruta al fichero con los graficos del item
int x; // Posicion del item en pantalla int x; // Posicion del item en pantalla
int y; // Posicion del item en pantalla int y; // Posicion del item en pantalla
int tile; // Numero de tile dentro de la textura int tile; // Numero de tile dentro de la textura
@@ -31,7 +29,7 @@ private:
Sprite *sprite; // Sprite del objeto Sprite *sprite; // Sprite del objeto
// Variables // Variables
vector<color_t> color; // Vector con los colores del objeto std::vector<color_t> color; // Vector con los colores del objeto
int counter; // Contador interno int counter; // Contador interno
SDL_Rect collider; // Rectangulo de colisión SDL_Rect collider; // Rectangulo de colisión
int colorChangeSpeed; // Cuanto mas alto, mas tarda en cambiar de color int colorChangeSpeed; // Cuanto mas alto, mas tarda en cambiar de color

View File

@@ -7,7 +7,7 @@ ItemTracker::~ItemTracker()
} }
// Comprueba si el objeto ya ha sido cogido // 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; 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 // 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 // Comprueba si el objeto no ha sido recogido con anterioridad
if (!hasBeenPicked(name, pos)) if (!hasBeenPicked(name, pos))
@@ -50,7 +50,7 @@ void ItemTracker::addItem(string name, SDL_Point pos)
} }
// Busca una entrada en la lista por nombre // Busca una entrada en la lista por nombre
int ItemTracker::findByName(string name) int ItemTracker::findByName(std::string name)
{ {
int i = 0; int i = 0;
@@ -71,7 +71,7 @@ int ItemTracker::findByPos(int index, SDL_Point pos)
{ {
int i = 0; int i = 0;
for (auto l : list[index].pos) for (auto l:list[index].pos)
{ {
if ((l.x == pos.x) && (l.y == pos.y)) if ((l.x == pos.x) && (l.y == pos.y))
{ {

View File

@@ -7,22 +7,20 @@
#ifndef ITEM_TRACKER_H #ifndef ITEM_TRACKER_H
#define ITEM_TRACKER_H #define ITEM_TRACKER_H
using namespace std;
struct item_tracker_t struct item_tracker_t
{ {
string name; // Nombre de la habitación donde se encuentra el objeto std::string name; // Nombre de la habitación donde se encuentra el objeto
vector<SDL_Point> pos; // Lista de objetos cogidos de la habitación std::vector<SDL_Point> pos; // Lista de objetos cogidos de la habitación
}; };
class ItemTracker class ItemTracker
{ {
private: private:
// Variables // Variables
vector<item_tracker_t> list; // Lista con todos los objetos recogidos std::vector<item_tracker_t> list; // Lista con todos los objetos recogidos
// Busca una entrada en la lista por nombre // 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 // Busca una entrada en la lista por posición
int findByPos(int index, SDL_Point pos); int findByPos(int index, SDL_Point pos);
@@ -32,10 +30,10 @@ public:
~ItemTracker(); ~ItemTracker();
// Comprueba si el objeto ya ha sido cogido // 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 // 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 #endif

View File

@@ -47,7 +47,7 @@ Logo::Logo(SDL_Renderer *renderer, Screen *screen, Resource *resource, Asset *as
postLogo = 20; postLogo = 20;
// Inicializa el vector de colores // Inicializa el vector de colores
const vector<string> vColors = {"black", "blue", "red", "magenta", "green", "cyan", "yellow", "bright_white"}; const std::vector<std::string> vColors = {"black", "blue", "red", "magenta", "green", "cyan", "yellow", "bright_white"};
for (auto v : vColors) for (auto v : vColors)
{ {
color.push_back(stringToColor(options->palette, v)); color.push_back(stringToColor(options->palette, v));

View File

@@ -14,8 +14,6 @@
#ifndef LOGO_H #ifndef LOGO_H
#define LOGO_H #define LOGO_H
using namespace std;
class Logo class Logo
{ {
private: private:
@@ -28,13 +26,13 @@ private:
Texture *texture; // Textura con los graficos "JAILGAMES" Texture *texture; // Textura con los graficos "JAILGAMES"
Texture *texture2; // Textura con los graficos "Since 1998" Texture *texture2; // Textura con los graficos "Since 1998"
SDL_Event *eventHandler; // Manejador de eventos SDL_Event *eventHandler; // Manejador de eventos
vector<Sprite *> sprite; // Vector con los sprites de cada linea que forman el bitmap JAILGAMES std::vector<Sprite *> sprite; // Vector con los sprites de cada linea que forman el bitmap JAILGAMES
Sprite *sprite2; // Sprite para manejar la textura2 Sprite *sprite2; // Sprite para manejar la textura2
options_t *options; // Puntero a las opciones del juego options_t *options; // Puntero a las opciones del juego
section_t *section; // Estado del bucle principal para saber si continua o se sale section_t *section; // Estado del bucle principal para saber si continua o se sale
// Variables // Variables
vector<color_t> color; // Vector con los colores para el fade std::vector<color_t> color; // Vector con los colores para el fade
int counter; // Contador int counter; // Contador
Uint32 ticks; // Contador de ticks para ajustar la velocidad del programa Uint32 ticks; // Contador de ticks para ajustar la velocidad del programa
Uint32 ticksSpeed; // Velocidad a la que se repiten los bucles del programa Uint32 ticksSpeed; // Velocidad a la que se repiten los bucles del programa

View File

@@ -533,7 +533,7 @@ void Player::move()
#endif #endif
// Comprueba la colisión con las superficies normales y las automáticas // 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) if (pos > -1)
{ // Si hay colisión lo mueve hasta donde no colisiona y pasa a estar sobre la superficie { // Si hay colisión lo mueve hasta donde no colisiona y pasa a estar sobre la superficie
y = pos - h; y = pos - h;
@@ -548,7 +548,7 @@ void Player::move()
{ // Las rampas no se miran si se está saltando { // 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 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}; 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) if (p > -1)
{ // No está saltando y hay colisión con una rampa { // No está saltando y hay colisión con una rampa
// Calcula la nueva posición // Calcula la nueva posición
@@ -581,8 +581,8 @@ void Player::move()
sprite->setPosY(y); sprite->setPosY(y);
#ifdef DEBUG #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_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: " + to_string(ry.x) + "," + to_string(ry.y) + "," + to_string(ry.w) + "," + to_string(ry.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 #endif
} }
@@ -621,7 +621,7 @@ void Player::playJumpSound()
} }
#ifdef DEBUG #ifdef DEBUG
debug->add("JUMP: " + to_string(jumpCounter / 4)); debug->add("JUMP: " + std::to_string(jumpCounter / 4));
#endif #endif
} }
@@ -630,11 +630,11 @@ void Player::playFallSound()
{ {
if (fallCounter % 4 == 0) 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 #ifdef DEBUG
debug->add("FALL: " + to_string(fallCounter / 4)); debug->add("FALL: " + std::to_string(fallCounter / 4));
#endif #endif
} }
@@ -666,12 +666,12 @@ bool Player::isOnFloor()
if (onSlopeL) 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) 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 #endif

View File

@@ -15,8 +15,6 @@
#ifndef PLAYER_H #ifndef PLAYER_H
#define PLAYER_H #define PLAYER_H
using namespace std;
enum state_e enum state_e
{ {
s_standing, s_standing,
@@ -38,8 +36,8 @@ struct playerSpawn_t
struct player_t struct player_t
{ {
playerSpawn_t spawn; playerSpawn_t spawn;
string png; std::string png;
string animation; std::string animation;
SDL_Renderer *renderer; SDL_Renderer *renderer;
Resource *resource; Resource *resource;
Asset *asset; Asset *asset;
@@ -71,9 +69,9 @@ public:
int h; // ALto del jugador int h; // ALto del jugador
color_t color; // Color del jugador color_t color; // Color del jugador
SDL_Rect colliderBox; // Caja de colisión con los enemigos u objetos SDL_Rect colliderBox; // Caja de colisión con los enemigos u objetos
vector<SDL_Point> colliderPoints; // Puntos de colisión con el mapa std::vector<SDL_Point> colliderPoints; // Puntos de colisión con el mapa
vector<SDL_Point> underFeet; // Contiene los puntos que hay bajo cada pie del jugador std::vector<SDL_Point> underFeet; // Contiene los puntos que hay bajo cada pie del jugador
vector<SDL_Point> feet; // Contiene los puntos que hay en el pie del jugador std::vector<SDL_Point> 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 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 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 bool onBorder; // Indica si el jugador esta en uno de los cuatro bordes de la pantalla
@@ -83,8 +81,8 @@ public:
SDL_Rect lastPosition; // Contiene la ultima posición del jugador, por si hay que deshacer algun movimiento 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 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 float maxVY; // Velocidad máxima que puede alcanzar al desplazarse en vertical
vector<JA_Sound_t *> jumpSound; // Vecor con todos los sonidos del salto std::vector<JA_Sound_t*> jumpSound; // Vecor con todos los sonidos del salto
vector<JA_Sound_t *> fallSound; // Vecor con todos los sonidos de la caída std::vector<JA_Sound_t*> fallSound; // Vecor con todos los sonidos de la caída
int jumpCounter; // Cuenta el tiempo de salto int jumpCounter; // Cuenta el tiempo de salto
int fallCounter; // Cuenta el tiempo de caida int fallCounter; // Cuenta el tiempo de caida
bool alive; // Indica si el jugador esta vivo o no bool alive; // Indica si el jugador esta vivo o no

View File

@@ -4,34 +4,34 @@
#include <sstream> #include <sstream>
// Carga las variables y texturas desde un fichero de mapa de tiles // Carga las variables y texturas desde un fichero de mapa de tiles
vector<int> loadRoomTileFile(string file_path, bool verbose) std::vector<int> loadRoomTileFile(std::string file_path, bool verbose)
{ {
vector<int> tileMapFile; std::vector<int> tileMapFile;
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);
string line; std::string line;
ifstream file(file_path); std::ifstream file(file_path);
// El fichero se puede abrir // El fichero se puede abrir
if (file.good()) if (file.good())
{ {
// Procesa el fichero linea a linea // Procesa el fichero linea a linea
while (getline(file, line)) while (std::getline(file, line))
{ // Lee el fichero linea a linea { // 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 // Lee la primera linea
getline(file, line); std::getline(file, line);
while (line != "</data>") while (line != "</data>")
{ // Procesa lineas mientras haya { // Procesa lineas mientras haya
stringstream ss(line); std::stringstream ss(line);
string tmp; std::string tmp;
while (getline(ss, tmp, ',')) while (getline(ss, tmp, ','))
{ {
tileMapFile.push_back(stoi(tmp) - 1); tileMapFile.push_back(std::stoi(tmp) - 1);
} }
// Lee la siguiente linea // Lee la siguiente linea
getline(file, line); std::getline(file, line);
} }
} }
} }
@@ -39,7 +39,7 @@ vector<int> loadRoomTileFile(string file_path, bool verbose)
// Cierra el fichero // Cierra el fichero
if (verbose) if (verbose)
{ {
cout << "TileMap loaded: " << filename.c_str() << endl; std::cout << "TileMap loaded: " << filename.c_str() << std::endl;
} }
file.close(); file.close();
} }
@@ -48,7 +48,7 @@ vector<int> loadRoomTileFile(string file_path, bool verbose)
{ // El fichero no se puede abrir { // El fichero no se puede abrir
if (verbose) 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<int> loadRoomTileFile(string file_path, bool verbose)
} }
// Carga las variables desde un fichero de mapa // 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_t room;
room.itemColor1 = "yellow"; room.itemColor1 = "yellow";
room.itemColor2 = "magenta"; room.itemColor2 = "magenta";
room.autoSurfaceDirection = 1; 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(".")); room.number = fileName.substr(0, fileName.find_last_of("."));
string line; std::string line;
ifstream file(file_path); std::ifstream file(file_path);
// El fichero se puede abrir // El fichero se puede abrir
if (file.good()) if (file.good())
{ {
// Procesa el fichero linea a linea // 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 // Si la linea contiene el texto [enemy] se realiza el proceso de carga de un enemigo
if (line == "[enemy]") if (line == "[enemy]")
@@ -86,7 +86,7 @@ room_t loadRoomFile(string file_path, bool verbose)
do do
{ {
getline(file, line); std::getline(file, line);
// Encuentra la posición del caracter '=' // Encuentra la posición del caracter '='
int pos = line.find("="); int pos = line.find("=");
@@ -96,7 +96,7 @@ room_t loadRoomFile(string file_path, bool verbose)
{ {
if (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]"); } while (line != "[/enemy]");
@@ -115,7 +115,7 @@ room_t loadRoomFile(string file_path, bool verbose)
do do
{ {
getline(file, line); std::getline(file, line);
// Encuentra la posición del caracter '=' // Encuentra la posición del caracter '='
int pos = line.find("="); int pos = line.find("=");
@@ -125,7 +125,7 @@ room_t loadRoomFile(string file_path, bool verbose)
{ {
if (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) 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 // Cierra el fichero
if (verbose) if (verbose)
{ {
cout << "Room loaded: " << fileName.c_str() << endl; std::cout << "Room loaded: " << fileName.c_str() << std::endl;
} }
file.close(); file.close();
} }
@@ -162,7 +162,7 @@ room_t loadRoomFile(string file_path, bool verbose)
else 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 // 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 // Indicador de éxito en la asignación
bool success = true; bool success = true;
@@ -255,7 +255,7 @@ bool setVars(room_t *room, string var, string value)
} }
// Asigna variables a una estructura enemy_t // 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 // Indicador de éxito en la asignación
bool success = true; bool success = true;
@@ -267,52 +267,52 @@ bool setEnemy(enemy_t *enemy, string var, string value)
else if (var == "width") else if (var == "width")
{ {
enemy->w = stof(value); enemy->w = std::stof(value);
} }
else if (var == "height") else if (var == "height")
{ {
enemy->h = stof(value); enemy->h = std::stof(value);
} }
else if (var == "x") else if (var == "x")
{ {
enemy->x = stof(value) * BLOCK; enemy->x = std::stof(value) * BLOCK;
} }
else if (var == "y") else if (var == "y")
{ {
enemy->y = stof(value) * BLOCK; enemy->y = std::stof(value) * BLOCK;
} }
else if (var == "vx") else if (var == "vx")
{ {
enemy->vx = stof(value); enemy->vx = std::stof(value);
} }
else if (var == "vy") else if (var == "vy")
{ {
enemy->vy = stof(value); enemy->vy = std::stof(value);
} }
else if (var == "x1") else if (var == "x1")
{ {
enemy->x1 = stoi(value) * BLOCK; enemy->x1 = std::stoi(value) * BLOCK;
} }
else if (var == "x2") else if (var == "x2")
{ {
enemy->x2 = stoi(value) * BLOCK; enemy->x2 = std::stoi(value) * BLOCK;
} }
else if (var == "y1") else if (var == "y1")
{ {
enemy->y1 = stoi(value) * BLOCK; enemy->y1 = std::stoi(value) * BLOCK;
} }
else if (var == "y2") else if (var == "y2")
{ {
enemy->y2 = stoi(value) * BLOCK; enemy->y2 = std::stoi(value) * BLOCK;
} }
else if (var == "flip") else if (var == "flip")
@@ -332,7 +332,7 @@ bool setEnemy(enemy_t *enemy, string var, string value)
else if (var == "frame") else if (var == "frame")
{ {
enemy->frame = stoi(value); enemy->frame = std::stoi(value);
} }
else if (var == "[/enemy]" || var == "tileSetFile" || var.substr(0, 1) == "#") 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 // 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 // Indicador de éxito en la asignación
bool success = true; bool success = true;
@@ -360,22 +360,22 @@ bool setItem(item_t *item, string var, string value)
else if (var == "counter") else if (var == "counter")
{ {
item->counter = stoi(value); item->counter = std::stoi(value);
} }
else if (var == "x") else if (var == "x")
{ {
item->x = stof(value) * BLOCK; item->x = std::stof(value) * BLOCK;
} }
else if (var == "y") else if (var == "y")
{ {
item->y = stof(value) * BLOCK; item->y = std::stof(value) * BLOCK;
} }
else if (var == "tile") else if (var == "tile")
{ {
item->tile = stof(value); item->tile = std::stof(value);
} }
else if (var == "[/item]") else if (var == "[/item]")
@@ -478,7 +478,7 @@ Room::Room(room_t *room, SDL_Renderer *renderer, Screen *screen, Asset *asset, o
{ {
if (options->console) 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); SDL_SetTextureBlendMode(mapTexture, SDL_BLENDMODE_BLEND);
@@ -514,7 +514,7 @@ Room::~Room()
} }
// Devuelve el nombre de la habitación // Devuelve el nombre de la habitación
string Room::getName() std::string Room::getName()
{ {
return name; return name;
} }
@@ -723,7 +723,7 @@ void Room::update()
} }
// Devuelve la cadena del fichero de la habitación contigua segun el borde // 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) switch (border)
{ {
@@ -897,13 +897,13 @@ int Room::getSlopeHeight(SDL_Point p, tile_e slope)
// Calcula la base del tile // Calcula la base del tile
int base = ((p.y / tileSize) * tileSize) + tileSize; int base = ((p.y / tileSize) * tileSize) + tileSize;
#ifdef DEBUG #ifdef DEBUG
debug->add("BASE = " + to_string(base)); debug->add("BASE = " + std::to_string(base));
#endif #endif
// Calcula cuanto se ha entrado en el tile horizontalmente // Calcula cuanto se ha entrado en el tile horizontalmente
const int pos = (p.x % tileSize); // Esto da un valor entre 0 y 7 const int pos = (p.x % tileSize); // Esto da un valor entre 0 y 7
#ifdef DEBUG #ifdef DEBUG
debug->add("POS = " + to_string(pos)); debug->add("POS = " + std::to_string(pos));
#endif #endif
// Se resta a la base la cantidad de pixeles pos en funcion de la rampa // 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; base -= pos + 1;
#ifdef DEBUG #ifdef DEBUG
debug->add("BASE_R = " + to_string(base)); debug->add("BASE_R = " + std::to_string(base));
#endif #endif
} }
else else
{ {
base -= (tileSize - pos); base -= (tileSize - pos);
#ifdef DEBUG #ifdef DEBUG
debug->add("BASE_L = " + to_string(base)); debug->add("BASE_L = " + std::to_string(base));
#endif #endif
} }
@@ -928,7 +928,7 @@ int Room::getSlopeHeight(SDL_Point p, tile_e slope)
// Calcula las superficies inferiores // Calcula las superficies inferiores
void Room::setBottomSurfaces() void Room::setBottomSurfaces()
{ {
vector<int> tile; std::vector<int> tile;
// Busca todos los tiles de tipo muro que no tengan debajo otro muro // 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) // 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 // Calcula las superficies superiores
void Room::setTopSurfaces() void Room::setTopSurfaces()
{ {
vector<int> tile; std::vector<int> tile;
// Busca todos los tiles de tipo muro o pasable que no tengan encima un muro // 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) // 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 // Calcula las superficies laterales izquierdas
void Room::setLeftSurfaces() void Room::setLeftSurfaces()
{ {
vector<int> tile; std::vector<int> tile;
// Busca todos los tiles de tipo muro que no tienen a su izquierda un tile de tipo muro // 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) // 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 // Calcula las superficies laterales derechas
void Room::setRightSurfaces() void Room::setRightSurfaces()
{ {
vector<int> tile; std::vector<int> tile;
// Busca todos los tiles de tipo muro que no tienen a su derecha un tile de tipo muro // 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) // Hay que recorrer la habitación por columnas (excepto los de la última columna)
@@ -1151,7 +1151,7 @@ void Room::setRightSurfaces()
void Room::setLeftSlopes() void Room::setLeftSlopes()
{ {
// Recorre la habitación entera por filas buscando tiles de tipo t_slope_l // Recorre la habitación entera por filas buscando tiles de tipo t_slope_l
vector<int> found; std::vector<int> found;
for (int i = 0; i < (int)tileMap.size(); ++i) for (int i = 0; i < (int)tileMap.size(); ++i)
{ {
if (getTile(i) == t_slope_l) if (getTile(i) == t_slope_l)
@@ -1192,7 +1192,7 @@ void Room::setLeftSlopes()
void Room::setRightSlopes() void Room::setRightSlopes()
{ {
// Recorre la habitación entera por filas buscando tiles de tipo t_slope_r // Recorre la habitación entera por filas buscando tiles de tipo t_slope_r
vector<int> found; std::vector<int> found;
for (int i = 0; i < (int)tileMap.size(); ++i) for (int i = 0; i < (int)tileMap.size(); ++i)
{ {
if (getTile(i) == t_slope_r) if (getTile(i) == t_slope_r)
@@ -1232,7 +1232,7 @@ void Room::setRightSlopes()
// Calcula las superficies automaticas // Calcula las superficies automaticas
void Room::setAutoSurfaces() void Room::setAutoSurfaces()
{ {
vector<int> tile; std::vector<int> tile;
// Busca todos los tiles de tipo animado // Busca todos los tiles de tipo animado
// Hay que recorrer la habitación por filas (excepto los de la primera fila) // Hay que recorrer la habitación por filas (excepto los de la primera fila)

View File

@@ -17,8 +17,6 @@
#ifndef ROOM_H #ifndef ROOM_H
#define ROOM_H #define ROOM_H
using namespace std;
enum tile_e enum tile_e
{ {
t_empty, t_empty,
@@ -38,47 +36,47 @@ struct aTile_t
struct room_t struct room_t
{ {
string number; // Numero de la habitación std::string number; // Numero de la habitación
string name; // Nombre de la habitación std::string name; // Nombre de la habitación
string bgColor; // Color de fondo de la habitación std::string bgColor; // Color de fondo de la habitación
string borderColor; // Color del borde de la pantalla std::string borderColor; // Color del borde de la pantalla
string itemColor1; // Color 1 para los items de la habitación std::string itemColor1; // Color 1 para los items de la habitación
string itemColor2; // Color 2 para los items de la habitación std::string itemColor2; // Color 2 para los items de la habitación
string roomUp; // Identificador de la habitación que se encuentra arriba std::string roomUp; // Identificador de la habitación que se encuentra arriba
string roomDown; // Identificador de la habitación que se encuentra abajp std::string roomDown; // Identificador de la habitación que se encuentra abajp
string roomLeft; // Identificador de la habitación que se encuentra a la izquierda std::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 std::string roomRight; // Identificador de la habitación que se encuentra a la derecha
string tileSetFile; // Imagen con los graficos para la habitación std::string tileSetFile; // Imagen con los graficos para la habitación
string tileMapFile; // Fichero con el mapa de indices de tile std::string tileMapFile; // Fichero con el mapa de indices de tile
vector<int> *tileMap; // Indice de los tiles a dibujar en la habitación std::vector<int> *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 int autoSurfaceDirection; // Sentido en el que arrastran las superficies automáticas de la habitación
vector<enemy_t> enemies; // Listado con los enemigos de la habitación std::vector<enemy_t> enemies; // Listado con los enemigos de la habitación
vector<item_t> items; // Listado con los items que hay en la habitación std::vector<item_t> items; // Listado con los items que hay en la habitación
Texture *textureA; // 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 Texture *textureB; // Textura con los graficos de la habitación
}; };
// Carga las variables desde un fichero de mapa // 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 // Carga las variables y texturas desde un fichero de mapa de tiles
vector<int> loadRoomTileFile(string file_path, bool verbose = false); std::vector<int> loadRoomTileFile(std::string file_path, bool verbose = false);
// Asigna variables a partir de dos cadenas // 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 // 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 // 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 class Room
{ {
private: private:
// Objetos y punteros // Objetos y punteros
vector<Enemy *> enemies; // Listado con los enemigos de la habitación std::vector<Enemy *> enemies; // Listado con los enemigos de la habitación
vector<Item *> items; // Listado con los items que hay en la habitación std::vector<Item *> items; // Listado con los items que hay en la habitación
Texture *texture; // Textura con los graficos de la habitación Texture *texture; // Textura con los graficos de la habitación
Texture *textureA; // 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 Texture *textureB; // Textura con los graficos de la habitación
@@ -92,31 +90,31 @@ private:
options_t *options; // Puntero a las opciones del juego options_t *options; // Puntero a las opciones del juego
// Variables // Variables
string number; // Numero de la habitación std::string number; // Numero de la habitación
string name; // Nombre de la habitación std::string name; // Nombre de la habitación
string bgColor; // Color de fondo de la habitación std::string bgColor; // Color de fondo de la habitación
string borderColor; // Color del borde de la pantalla std::string borderColor; // Color del borde de la pantalla
string itemColor1; // Color 1 para los items de la habitación std::string itemColor1; // Color 1 para los items de la habitación
string itemColor2; // Color 2 para los items de la habitación std::string itemColor2; // Color 2 para los items de la habitación
string roomUp; // Identificador de la habitación que se encuentra arriba std::string roomUp; // Identificador de la habitación que se encuentra arriba
string roomDown; // Identificador de la habitación que se encuentra abajp std::string roomDown; // Identificador de la habitación que se encuentra abajp
string roomLeft; // Identificador de la habitación que se encuentra a la izquierda std::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 std::string roomRight; // Identificador de la habitación que se encuentra a la derecha
string tileSetFile; // Imagen con los graficos para la habitación std::string tileSetFile; // Imagen con los graficos para la habitación
string tileMapFile; // Fichero con el mapa de indices de tile std::string tileMapFile; // Fichero con el mapa de indices de tile
vector<int> tileMap; // Indice de los tiles a dibujar en la habitación std::vector<int> 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 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 JA_Sound_t *itemSound; // Sonido producido al coger un objeto
vector<h_line_t> bottomSurfaces; // Lista con las superficies inferiores de la habitación std::vector<h_line_t> bottomSurfaces; // Lista con las superficies inferiores de la habitación
vector<h_line_t> topSurfaces; // Lista con las superficies superiores de la habitación std::vector<h_line_t> topSurfaces; // Lista con las superficies superiores de la habitación
vector<v_line_t> leftSurfaces; // Lista con las superficies laterales de la parte izquierda de la habitación std::vector<v_line_t> leftSurfaces; // Lista con las superficies laterales de la parte izquierda de la habitación
vector<v_line_t> rightSurfaces; // Lista con las superficies laterales de la parte derecha de la habitación std::vector<v_line_t> rightSurfaces; // Lista con las superficies laterales de la parte derecha de la habitación
vector<d_line_t> leftSlopes; // Lista con todas las rampas que suben hacia la izquierda std::vector<d_line_t> leftSlopes; // Lista con todas las rampas que suben hacia la izquierda
vector<d_line_t> rightSlopes; // Lista con todas las rampas que suben hacia la derecha std::vector<d_line_t> rightSlopes; // Lista con todas las rampas que suben hacia la derecha
int counter; // Contador para lo que haga falta int counter; // Contador para lo que haga falta
bool paused; // Indica si el mapa esta en modo pausa bool paused; // Indica si el mapa esta en modo pausa
vector<aTile_t> aTile; // Vector con los indices de tiles animados std::vector<aTile_t> aTile; // Vector con los indices de tiles animados
vector<h_line_t> autoSurfaces; // Lista con las superficies automaticas de la habitación std::vector<h_line_t> autoSurfaces; // Lista con las superficies automaticas de la habitación
int tileSize; // Ancho del tile en pixels int tileSize; // Ancho del tile en pixels
int mapWidth; // Ancho del mapa en tiles int mapWidth; // Ancho del mapa en tiles
int mapHeight; // Alto del mapa en tiles int mapHeight; // Alto del mapa en tiles
@@ -170,7 +168,7 @@ public:
~Room(); ~Room();
// Devuelve el nombre de la habitación // Devuelve el nombre de la habitación
string getName(); std::string getName();
// Devuelve el color de la habitación // Devuelve el color de la habitación
color_t getBGColor(); color_t getBGColor();
@@ -191,7 +189,7 @@ public:
void update(); void update();
// Devuelve la cadena del fichero de la habitación contigua segun el borde // 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 // Devuelve el tipo de tile que hay en ese pixel
tile_e getTile(SDL_Point point); tile_e getTile(SDL_Point point);

View File

@@ -12,7 +12,7 @@ RoomTracker::~RoomTracker()
} }
// Comprueba si la habitación ya ha sido visitada // Comprueba si la habitación ya ha sido visitada
bool RoomTracker::hasBeenVisited(string name) bool RoomTracker::hasBeenVisited(std::string name)
{ {
for (auto l : list) for (auto l : list)
{ {
@@ -26,7 +26,7 @@ bool RoomTracker::hasBeenVisited(string name)
} }
// Añade la habitación a la lista // 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 // Comprueba si la habitación ya ha sido visitada
if (!hasBeenVisited(name)) if (!hasBeenVisited(name))

View File

@@ -8,16 +8,14 @@
#ifndef ROOM_TRACKER_H #ifndef ROOM_TRACKER_H
#define ROOM_TRACKER_H #define ROOM_TRACKER_H
using namespace std;
class RoomTracker class RoomTracker
{ {
private: private:
// Variables // Variables
vector<string> list; // Lista con las habitaciones visitadas std::vector<std::string> list; // Lista con las habitaciones visitadas
// Comprueba si la habitación ya ha sido visitada // Comprueba si la habitación ya ha sido visitada
bool hasBeenVisited(string name); bool hasBeenVisited(std::string name);
public: public:
// Constructor // Constructor
@@ -27,7 +25,7 @@ public:
~RoomTracker(); ~RoomTracker();
// Añade la habitación a la lista // Añade la habitación a la lista
bool addRoom(string name); bool addRoom(std::string name);
}; };
#endif #endif

View File

@@ -14,7 +14,7 @@ ScoreBoard::ScoreBoard(SDL_Renderer *renderer, Resource *resource, Asset *asset,
// Reserva memoria para los objetos // Reserva memoria para los objetos
itemTexture = resource->getTexture("items.png"); 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 = new AnimatedSprite(renderer, resource->getAnimation(playerANI));
sprite->setCurrentAnimation("walk_menu"); sprite->setCurrentAnimation("walk_menu");
text = new Text(resource->getOffset("smb2.txt"), resource->getTexture("smb2.png"), renderer); 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"); itemsColor = stringToColor(options->palette, "white");
// Inicializa el vector de colores // Inicializa el vector de colores
const vector<string> vColors = {"blue", "magenta", "green", "cyan", "yellow", "white", "bright_blue", "bright_magenta", "bright_green", "bright_cyan", "bright_yellow", "bright_white"}; const std::vector<std::string> vColors = {"blue", "magenta", "green", "cyan", "yellow", "white", "bright_blue", "bright_magenta", "bright_green", "bright_cyan", "bright_yellow", "bright_white"};
for (auto v : vColors) for (auto v : vColors)
{ {
color.push_back(stringToColor(options->palette, v)); color.push_back(stringToColor(options->palette, v));
@@ -77,14 +77,14 @@ void ScoreBoard::render()
} }
// Escribe los textos // 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 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 string itemsTxt = to_string(board->items / 100) + to_string((board->items % 100) / 10) + to_string(board->items % 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(BLOCK, line1, "Items collected ", board->color);
this->text->writeColored(17 * BLOCK, line1, itemsTxt, itemsColor); this->text->writeColored(17 * BLOCK, line1, itemsTxt, itemsColor);
this->text->writeColored(20 * BLOCK, line1, " Time ", board->color); this->text->writeColored(20 * BLOCK, line1, " Time ", board->color);
this->text->writeColored(26 * BLOCK, line1, timeTxt, stringToColor(options->palette, "white")); 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(22 * BLOCK, line2, "Rooms", stringToColor(options->palette, "white"));
this->text->writeColored(28 * BLOCK, line2, roomsTxt, 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() void ScoreBoard::reLoadPalette()
{ {
// Reinicia el vector de colores // Reinicia el vector de colores
const vector<string> vColors = {"blue", "magenta", "green", "cyan", "yellow", "white", "bright_blue", "bright_magenta", "bright_green", "bright_cyan", "bright_yellow", "bright_white"}; const std::vector<std::string> vColors = {"blue", "magenta", "green", "cyan", "yellow", "white", "bright_blue", "bright_magenta", "bright_green", "bright_cyan", "bright_yellow", "bright_white"};
color.clear(); color.clear();
for (auto v : vColors) for (auto v : vColors)
{ {

View File

@@ -12,8 +12,6 @@
#ifndef SCOREBOARD_H #ifndef SCOREBOARD_H
#define SCOREBOARD_H #define SCOREBOARD_H
using namespace std;
struct board_t struct board_t
{ {
int items; // Lleva la cuenta de los objetos recogidos int items; // Lleva la cuenta de los objetos recogidos
@@ -33,7 +31,7 @@ private:
int hours; int hours;
int minutes; int minutes;
int seconds; int seconds;
string separator; std::string separator;
}; };
// Objetos y punteros // Objetos y punteros
@@ -47,7 +45,7 @@ private:
options_t *options; // Puntero a las opciones del juego options_t *options; // Puntero a las opciones del juego
// Variables // Variables
vector<color_t> color; // Vector con los colores del objeto std::vector<color_t> color; // Vector con los colores del objeto
int counter; // Contador interno int counter; // Contador interno
int colorChangeSpeed; // Cuanto mas alto, mas tarda en cambiar de color int colorChangeSpeed; // Cuanto mas alto, mas tarda en cambiar de color
bool paused; // Indica si el marcador esta en modo pausa bool paused; // Indica si el marcador esta en modo pausa

View File

@@ -6,7 +6,7 @@
#include <sstream> #include <sstream>
// Constructor // Constructor
Stats::Stats(string file, string buffer, options_t *options) Stats::Stats(std::string file, std::string buffer, options_t *options)
{ {
this->options = options; this->options = options;
bufferPath = buffer; bufferPath = buffer;
@@ -51,10 +51,10 @@ void Stats::init()
} }
// Añade una muerte a las estadisticas // Añade una muerte a las estadisticas
void Stats::addDeath(string name) void Stats::addDeath(std::string name)
{ {
// Normaliza el nombre // Normaliza el nombre
// replace(name.begin(), name.end(), ' ', '_'); // std::replace(name.begin(), name.end(), ' ', '_');
// Primero busca si ya hay una entrada con ese nombre // Primero busca si ya hay una entrada con ese nombre
const int index = findByName(name, bufferList); const int index = findByName(name, bufferList);
@@ -75,10 +75,10 @@ void Stats::addDeath(string name)
} }
// Añade una visita a las estadisticas // Añade una visita a las estadisticas
void Stats::addVisit(string name) void Stats::addVisit(std::string name)
{ {
// Normaliza el nombre // Normaliza el nombre
// replace(name.begin(), name.end(), ' ', '_'); // std::replace(name.begin(), name.end(), ' ', '_');
// Primero busca si ya hay una entrada con ese nombre // Primero busca si ya hay una entrada con ese nombre
const int index = findByName(name, bufferList); const int index = findByName(name, bufferList);
@@ -99,7 +99,7 @@ void Stats::addVisit(string name)
} }
// Busca una entrada en la lista por nombre // Busca una entrada en la lista por nombre
int Stats::findByName(string name, vector<stats_t> &list) int Stats::findByName(std::string name, std::vector<stats_t> &list)
{ {
int i = 0; int i = 0;
@@ -116,7 +116,7 @@ int Stats::findByName(string name, vector<stats_t> &list)
} }
// Carga las estadisticas desde un fichero // Carga las estadisticas desde un fichero
bool Stats::loadFromFile(string filePath, vector<stats_t> &list) bool Stats::loadFromFile(std::string filePath, std::vector<stats_t> &list)
{ {
list.clear(); list.clear();
@@ -124,21 +124,21 @@ bool Stats::loadFromFile(string filePath, vector<stats_t> &list)
bool success = true; bool success = true;
// Variables para manejar el fichero // Variables para manejar el fichero
string line; std::string line;
ifstream file(filePath); std::ifstream file(filePath);
// Si el fichero se puede abrir // Si el fichero se puede abrir
if (file.good()) if (file.good())
{ {
// Procesa el fichero linea a linea // Procesa el fichero linea a linea
while (getline(file, line)) while (std::getline(file, line))
{ {
// Comprueba que la linea no sea un comentario // Comprueba que la linea no sea un comentario
if (line.substr(0, 1) != "#") if (line.substr(0, 1) != "#")
{ {
stats_t stat; stats_t stat;
stringstream ss(line); std::stringstream ss(line);
string tmp; std::string tmp;
// Obtiene el nombre // Obtiene el nombre
getline(ss, tmp, ';'); getline(ss, tmp, ';');
@@ -146,11 +146,11 @@ bool Stats::loadFromFile(string filePath, vector<stats_t> &list)
// Obtiene las visitas // Obtiene las visitas
getline(ss, tmp, ';'); getline(ss, tmp, ';');
stat.visited = stoi(tmp); stat.visited = std::stoi(tmp);
// Obtiene las muertes // Obtiene las muertes
getline(ss, tmp, ';'); getline(ss, tmp, ';');
stat.died = stoi(tmp); stat.died = std::stoi(tmp);
list.push_back(stat); list.push_back(stat);
} }
@@ -177,14 +177,14 @@ void Stats::loadFromServer()
list.clear(); list.clear();
string data; std::string data;
if (options->online.enabled) if (options->online.enabled)
{ {
data = jscore::getUserData(options->online.gameID, options->online.jailerID); data = jscore::getUserData(options->online.gameID, options->online.jailerID);
} }
stringstream ss(data); std::stringstream ss(data);
string tmp; std::string tmp;
int count = 0; int count = 0;
@@ -206,11 +206,11 @@ void Stats::loadFromServer()
// Obtiene las visitas // Obtiene las visitas
getline(ss, tmp, ';'); getline(ss, tmp, ';');
stat.visited = stoi(tmp); stat.visited = std::stoi(tmp);
// Obtiene las muertes // Obtiene las muertes
getline(ss, tmp, ';'); getline(ss, tmp, ';');
stat.died = stoi(tmp); stat.died = std::stoi(tmp);
list.push_back(stat); list.push_back(stat);
count = count - 3; count = count - 3;
@@ -218,16 +218,16 @@ void Stats::loadFromServer()
} }
// Guarda las estadisticas en un fichero // Guarda las estadisticas en un fichero
void Stats::saveToFile(string filePath, vector<stats_t> &list) void Stats::saveToFile(std::string filePath, std::vector<stats_t> &list)
{ {
// Crea y abre el fichero de texto // Crea y abre el fichero de texto
ofstream file(filePath); std::ofstream file(filePath);
// Escribe en el fichero // Escribe en el fichero
file << "# ROOM NAME;VISITS;DEATHS" << endl; file << "# ROOM NAME;VISITS;DEATHS" << std::endl;
for (auto item : list) for (auto item : list)
{ {
file << item.name << ";" << item.visited << ";" << item.died << endl; file << item.name << ";" << item.visited << ";" << item.died << std::endl;
} }
// Cierra el fichero // Cierra el fichero
@@ -237,12 +237,12 @@ void Stats::saveToFile(string filePath, vector<stats_t> &list)
// Guarda las estadisticas en un servidor // Guarda las estadisticas en un servidor
void Stats::saveToServer() void Stats::saveToServer()
{ {
string data = ""; std::string data = "";
if (options->online.enabled) if (options->online.enabled)
{ {
for (auto item : list) 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); jscore::setUserData(options->online.gameID, options->online.jailerID, data);
} }
@@ -263,13 +263,13 @@ void Stats::checkWorstNightmare()
} }
// Añade una entrada al diccionario // 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}); dictionary.push_back({number, name});
} }
// Obtiene el nombre de una habitación a partir del número // 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) 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 // 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) for (auto l : dictionary)
{ {

View File

@@ -7,45 +7,43 @@
#ifndef STATS_H #ifndef STATS_H
#define STATS_H #define STATS_H
using namespace std;
class Stats class Stats
{ {
private: private:
struct stats_t struct stats_t
{ {
string name; // Nombre de la habitación std::string name; // Nombre de la habitación
int visited; // Cuenta las veces que se ha visitado una 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 int died; // Cuenta las veces que se ha muerto en una habitación
}; };
struct stats_dictionary_t struct stats_dictionary_t
{ {
string number; // Numero de la habitación std::string number; // Numero de la habitación
string name; // Nombre de la habitación std::string name; // Nombre de la habitación
}; };
// Punteros y objetos // Punteros y objetos
options_t *options; options_t *options;
// Variables // Variables
vector<stats_dictionary_t> dictionary; // Lista con la equivalencia nombre-numero de habitacion std::vector<stats_dictionary_t> dictionary; // Lista con la equivalencia nombre-numero de habitacion
vector<stats_t> bufferList; // Lista con las estadisticas temporales por habitación std::vector<stats_t> bufferList; // Lista con las estadisticas temporales por habitación
vector<stats_t> list; // Lista con las estadisticas completas por habitación std::vector<stats_t> list; // Lista con las estadisticas completas por habitación
string bufferPath; // Fichero con las estadísticas temporales std::string bufferPath; // Fichero con las estadísticas temporales
string filePath; // Fichero con las estadísticas completas std::string filePath; // Fichero con las estadísticas completas
// Busca una entrada en la lista por nombre // Busca una entrada en la lista por nombre
int findByName(string name, vector<stats_t> &list); int findByName(std::string name, std::vector<stats_t> &list);
// Carga las estadisticas desde un fichero // Carga las estadisticas desde un fichero
bool loadFromFile(string filePath, vector<stats_t> &list); bool loadFromFile(std::string filePath, std::vector<stats_t> &list);
// Carga las estadisticas desde un servidor // Carga las estadisticas desde un servidor
void loadFromServer(); void loadFromServer();
// Guarda las estadisticas en un fichero // Guarda las estadisticas en un fichero
void saveToFile(string filePath, vector<stats_t> &list); void saveToFile(std::string filePath, std::vector<stats_t> &list);
// Guarda las estadisticas en un servidor // Guarda las estadisticas en un servidor
void saveToServer(); void saveToServer();
@@ -54,10 +52,10 @@ private:
void checkWorstNightmare(); void checkWorstNightmare();
// Obtiene el nombre de una habitación a partir del número // 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 // 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 // Vuelca los datos del buffer en la lista de estadisticas
void updateListFromBuffer(); void updateListFromBuffer();
@@ -67,7 +65,7 @@ private:
public: public:
// Constructor // Constructor
Stats(string file, string buffer, options_t *options); Stats(std::string file, std::string buffer, options_t *options);
// Destructor // Destructor
~Stats(); ~Stats();
@@ -77,13 +75,13 @@ public:
void init(); void init();
// Añade una muerte a las estadisticas // Añade una muerte a las estadisticas
void addDeath(string name); void addDeath(std::string name);
// Añade una visita a las estadisticas // Añade una visita a las estadisticas
void addVisit(string name); void addVisit(std::string name);
// Añade una entrada al diccionario // Añade una entrada al diccionario
void addDictionary(string number, string name); void addDictionary(std::string number, std::string name);
}; };
#endif #endif