Añadidos parametros al programa

This commit is contained in:
2022-11-02 08:36:00 +01:00
parent 12255750f6
commit 8232055d22
13 changed files with 292 additions and 93 deletions

View File

@@ -6,6 +6,7 @@ Asset::Asset(std::string path)
{
executablePath = path;
longestName = 0;
verbose = true;
}
// Añade un elemento a la lista
@@ -26,8 +27,8 @@ std::string Asset::get(std::string text)
{
for (auto f : fileList)
{
const size_t lastIndex = f.file.find_last_of("/")+1;
const std:: string file = f.file.substr(lastIndex, std::string::npos);
const size_t lastIndex = f.file.find_last_of("/") + 1;
const std::string file = f.file.substr(lastIndex, std::string::npos);
if (file == text)
{
@@ -35,7 +36,10 @@ std::string Asset::get(std::string text)
}
}
if (verbose)
{
std::cout << "Warning: file " << text.c_str() << " not found" << std::endl;
}
return "";
}
@@ -44,7 +48,10 @@ bool Asset::check()
{
bool success = true;
if (verbose)
{
std::cout << "\n** Checking files." << std::endl;
}
// Comprueba la lista de ficheros clasificandolos por tipo
for (int type = 0; type < t_maxAssetType; ++type)
@@ -62,8 +69,11 @@ bool Asset::check()
// Si hay ficheros de ese tipo, comprueba si existen
if (any)
{
if (verbose)
{
std::cout << "\n>> " << getTypeName(type).c_str() << " FILES" << std::endl;
}
for (auto f : fileList)
{
@@ -76,6 +86,8 @@ bool Asset::check()
}
// Resultado
if (verbose)
{
if (success)
{
std::cout << "\n** All files OK.\n"
@@ -86,6 +98,7 @@ bool Asset::check()
std::cout << "\n** A file is missing. Exiting.\n"
<< std::endl;
}
}
return success;
}
@@ -107,12 +120,15 @@ bool Asset::checkFile(std::string path)
SDL_RWclose(file);
}
if (verbose)
{
std::cout.setf(std::ios::left, std::ios::adjustfield);
std::cout << "Checking file: ";
std::cout.width(longestName + 2);
std::cout.fill('.');
std::cout << filename + " ";
std::cout << " [" + result + "]" << std::endl;
}
return success;
}
@@ -163,3 +179,9 @@ std::string Asset::getTypeName(int type)
break;
}
}
// Establece si ha de mostrar texto por pantalla
void Asset::setVerbose(bool value)
{
verbose = value;
}

View File

@@ -35,8 +35,9 @@ private:
// Variables
int longestName; // Contiene la longitud del nombre de fichero mas largo
std::vector<item_t> fileList;
std::string executablePath;
std::vector<item_t> fileList; // Listado con todas las rutas a los ficheros
std::string executablePath; // Ruta al ejecutable
bool verbose; // Indica si ha de mostrar información por pantalla
// Comprueba que existe un fichero
bool checkFile(std::string path);
@@ -56,6 +57,9 @@ public:
// Comprueba que existen todos los elementos
bool check();
// Establece si ha de mostrar texto por pantalla
void setVerbose(bool value);
};
#endif

View File

@@ -18,17 +18,19 @@ Input::Input(std::string file)
gcb.active = false;
gameControllerBindings.resize(17, gcb);
verbose = true;
// Comprueba si hay un mando conectado
discoverGameController();
}
// Asigna uno de los posibles inputs a una tecla del teclado
// Asigna inputs a teclas
void Input::bindKey(Uint8 input, SDL_Scancode code)
{
keyBindings.at(input).scancode = code;
}
// Asigna uno de los posibles inputs a un botón del mando
// Asigna inputs a botones del mando
void Input::bindGameControllerButton(Uint8 input, SDL_GameControllerButton button)
{
gameControllerBindings.at(input).button = button;
@@ -41,7 +43,9 @@ bool Input::checkInput(Uint8 input, bool repeat, int device, int index)
bool successGameController = false;
if (device == INPUT_USE_ANY)
{
index = 0;
}
if (device == INPUT_USE_KEYBOARD || device == INPUT_USE_ANY)
{
@@ -182,9 +186,12 @@ bool Input::discoverGameController()
}
if (SDL_GameControllerAddMappingsFromFile(dbPath.c_str()) < 0)
{
if (verbose)
{
std::cout << "Error, could not load " << dbPath.c_str() << " file: " << SDL_GetError() << std::endl;
}
}
const int nJoysticks = SDL_NumJoysticks();
numGamepads = 0;
@@ -198,8 +205,11 @@ bool Input::discoverGameController()
}
}
if (verbose)
{
std::cout << "\nChecking for game controllers...\n";
std::cout << nJoysticks << " joysticks found, " << numGamepads << " are gamepads\n";
}
if (numGamepads > 0)
{
@@ -216,14 +226,20 @@ bool Input::discoverGameController()
std::string name = SDL_GameControllerNameForIndex(i);
name.resize(25);
name = name + separator + std::to_string(i);
if (verbose)
{
std::cout << name << std::endl;
}
controllerNames.push_back(name);
}
else
{
if (verbose)
{
std::cout << "SDL_GetError() = " << SDL_GetError() << std::endl;
}
}
}
SDL_GameControllerEventState(SDL_ENABLE);
}
@@ -262,3 +278,9 @@ int Input::getNumControllers()
{
return numGamepads;
}
// Establece si ha de mostrar mensajes
void Input::setVerbose(bool value)
{
verbose = value;
}

View File

@@ -57,6 +57,7 @@ private:
std::vector<std::string> controllerNames; // Vector con los nombres de los mandos
int numGamepads; // Numero de mandos conectados
std::string dbPath; // Ruta al archivo gamecontrollerdb.txt
bool verbose; // Indica si ha de mostrar mensajes
// Comprueba si hay un mando conectado
bool discoverGameController();
@@ -65,10 +66,10 @@ public:
// Constructor
Input(std::string file);
// Asigna uno de los posibles inputs a una tecla del teclado
// Asigna inputs a teclas
void bindKey(Uint8 input, SDL_Scancode code);
// Asigna uno de los posibles inputs a un botón del mando
// Asigna inputs a botones del mando
void bindGameControllerButton(Uint8 input, SDL_GameControllerButton button);
// Comprueba si un input esta activo
@@ -85,6 +86,9 @@ public:
// Obten el nombre de un mando de juego
std::string getControllerName(int index);
// Establece si ha de mostrar mensajes
void setVerbose(bool value);
};
#endif

View File

@@ -13,9 +13,12 @@ Resource::Resource(SDL_Renderer *renderer, Asset *asset, options_t *options)
void Resource::loadTextures(std::vector<std::string> list)
{
for (auto l : list)
{
if (options->console)
{
std::cout << "\nLOAD TEXTURE: " << l << std::endl;
std::cout << "png: " << asset->get(l) << std::endl;
}
res_texture_t t;
t.name = l;
@@ -33,9 +36,12 @@ void Resource::loadAnimations(std::vector<std::string> list)
const size_t lastIndex = l.find_last_of(".");
const std::string pngFile = l.substr(0, lastIndex) + ".png";
if (options->console)
{
std::cout << "\nLOAD ANIMATION: " << l << std::endl;
std::cout << "png: " << asset->get(pngFile) << std::endl;
std::cout << "ani: " << asset->get(l) << std::endl;
}
res_animation_t as;
as.name = l;
@@ -196,7 +202,10 @@ Texture *Resource::getTexture(std::string name)
}
}
if (options->console)
{
std::cout << "NOT FOUND ON CACHE: " << name << std::endl;
}
return nullptr;
}
@@ -214,7 +223,10 @@ animatedSprite_t *Resource::getAnimation(std::string name)
}
}
if (options->console)
{
std::cout << "NOT FOUND ON CACHE: " << name << std::endl;
}
return nullptr;
}
@@ -230,7 +242,10 @@ textFile_t *Resource::getOffset(std::string name)
}
}
if (options->console)
{
std::cout << "NOT FOUND ON CACHE: " << name << std::endl;
}
return nullptr;
}
@@ -246,7 +261,10 @@ std::vector<int> *Resource::getTileMap(std::string name)
}
}
if (options->console)
{
std::cout << "NOT FOUND ON CACHE: " << name << std::endl;
}
return nullptr;
}
@@ -262,6 +280,9 @@ room_t *Resource::getRoom(std::string name)
}
}
if (options->console)
{
std::cout << "NOT FOUND ON CACHE: " << name << std::endl;
}
return nullptr;
}

View File

@@ -75,6 +75,8 @@ struct options_t
bool borderEnabled; // Indica si ha de mostrar el borde en el modo de ventana
float borderSize; // Porcentaje de borde que se añade a lo ventana
palette_e palette; // Paleta de colores a usar en el juego
bool console; // Indica si ha de mostrar información por la consola de texto
bool infiniteLives; // Indica si el jugador dispone de vidas infinitas
};
// Calcula el cuadrado de la distancia entre dos puntos

View File

@@ -32,17 +32,23 @@ Credits::Credits(SDL_Renderer *renderer, Screen *screen, Resource *resource, Ass
// Crea la textura para el texto que se escribe en pantalla
textTexture = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, GAMECANVAS_WIDTH, GAMECANVAS_HEIGHT);
if (textTexture == nullptr)
{
if (options->console)
{
std::cout << "Error: textTexture could not be created!\nSDL Error: " << SDL_GetError() << std::endl;
}
}
SDL_SetTextureBlendMode(textTexture, SDL_BLENDMODE_BLEND);
// Crea la textura para cubrir el rexto
coverTexture = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, GAMECANVAS_WIDTH, GAMECANVAS_HEIGHT);
if (coverTexture == nullptr)
{
if (options->console)
{
std::cout << "Error: textTexture could not be created!\nSDL Error: " << SDL_GetError() << std::endl;
}
}
SDL_SetTextureBlendMode(coverTexture, SDL_BLENDMODE_BLEND);
// Escribe el texto en la textura

View File

@@ -4,7 +4,7 @@
#include <string>
// Constructor
Director::Director(std::string path)
Director::Director(int argc, char *argv[])
{
section.name = SECTION_PROG_LOGO;
section.subsection = SUBSECTION_LOGO_TO_INTRO;
@@ -12,7 +12,8 @@ Director::Director(std::string path)
section.name = SECTION_PROG_GAME;
// Crea el objeto que controla los ficheros de recursos
asset = new Asset(path.substr(0, path.find_last_of("\\/")));
executablePath = argv[0];
asset = new Asset(executablePath.substr(0, executablePath.find_last_of("\\/")));
// Si falta algún fichero no inicia el programa
if (!setFileList())
@@ -20,6 +21,13 @@ Director::Director(std::string path)
section.name = SECTION_PROG_QUIT;
}
// Crea e inicializa las opciones del programa
iniOptions();
// Comprueba los parametros del programa
checkProgramArguments(argc, argv);
asset->setVerbose(options->console);
// Inicializa variables desde el fichero de configuración
loadConfig();
@@ -59,11 +67,13 @@ Director::~Director()
SDL_Quit();
}
// Carga el fichero de configuración
bool Director::loadConfig()
// Crea e inicializa las opciones del programa
void Director::iniOptions()
{
// Crea el puntero a la estructura de opciones e inicializa valores
// Crea el puntero a la estructura de opciones
options = new options_t;
// Inicializa valores
options->fullScreenMode = 0;
options->windowSize = 3;
options->filter = FILTER_NEAREST;
@@ -74,6 +84,31 @@ bool Director::loadConfig()
options->borderSize = 0.1f;
options->palette = p_zxspectrum;
// Estos valores no se guardan en el fichero de configuraci´ón
options->console = false;
options->infiniteLives = false;
}
// Comprueba los parametros del programa
void Director::checkProgramArguments(int argc, char *argv[])
{
for (int i = 0; i < argc; ++i)
{
if (strcmp(argv[i], "--console") == 0)
{
options->console = true;
}
else if (strcmp(argv[i], "--infiniteLives") == 0)
{
options->infiniteLives = true;
}
}
}
// Carga el fichero de configuración
bool Director::loadConfig()
{
// Indicador de éxito en la carga
bool success = true;
@@ -85,7 +120,10 @@ bool Director::loadConfig()
if (file.good())
{
// Procesa el fichero linea a linea
if (options->console)
{
std::cout << "Reading file config.txt\n";
}
while (std::getline(file, line))
{
// Comprueba que la linea no sea un comentario
@@ -95,16 +133,22 @@ bool Director::loadConfig()
int pos = line.find("=");
// Procesa las dos subcadenas
if (!setOptions(options, line.substr(0, pos), line.substr(pos + 1, line.length())))
{
if (options->console)
{
std::cout << "Warning: file config.txt\n";
std::cout << "unknown parameter " << line.substr(0, pos).c_str() << std::endl;
}
success = false;
}
}
}
// Cierra el fichero
if (options->console)
{
std::cout << "Closing file config.txt\n\n";
}
file.close();
}
@@ -182,7 +226,10 @@ bool Director::saveConfig()
// Carga los recursos
void Director::loadResources(section_t section)
{
if (options->console)
{
std::cout << "** LOAD RESOURCES" << std::endl;
}
if (section.name == SECTION_PROG_LOGO)
{
@@ -503,7 +550,10 @@ void Director::loadResources(section_t section)
resource->loadRooms(roomList);
}
if (options->console)
{
std::cout << "** RESOURCES LOADED" << std::endl;
}
}
// Asigna variables a partir de dos cadenas
@@ -608,6 +658,10 @@ bool Director::setOptions(options_t *options, std::string var, std::string value
// Inicia las variables necesarias para arrancar el programa
void Director::initInput()
{
// Establece si ha de mostrar mensajes
input->setVerbose(options->console);
// Asigna inputs a teclas
input->bindKey(INPUT_UP, SDL_SCANCODE_UP);
input->bindKey(INPUT_DOWN, SDL_SCANCODE_DOWN);
input->bindKey(INPUT_LEFT, SDL_SCANCODE_LEFT);
@@ -644,8 +698,11 @@ bool Director::initSDL()
// Inicializa SDL
if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_GAMECONTROLLER | SDL_INIT_AUDIO) < 0)
{
if (options->console)
{
std::cout << "SDL could not initialize!\nSDL Error: " << SDL_GetError() << std::endl;
}
success = false;
}
else
@@ -655,28 +712,41 @@ bool Director::initSDL()
// Establece el filtro de la textura a nearest
if (!SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, std::to_string(options->filter).c_str()))
{
if (options->console)
{
std::cout << "Warning: Nearest texture filtering not enabled!\n";
}
}
// Crea la ventana
window = SDL_CreateWindow(WINDOW_CAPTION, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, options->screenWidth, options->screenHeight, SDL_WINDOW_SHOWN | SDL_WINDOW_ALLOW_HIGHDPI);
if (window == nullptr)
{
if (options->console)
{
std::cout << "Window could not be created!\nSDL Error: " << SDL_GetError() << std::endl;
}
success = false;
}
else
{
// Crea un renderizador para la ventana. El vsync se activa en funcion de las opciones
if (options->vSync)
{
renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
}
else
{
renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
}
if (renderer == nullptr)
{
if (options->console)
{
std::cout << "Renderer could not be created!\nSDL Error: " << SDL_GetError() << std::endl;
}
success = false;
}
else
@@ -693,7 +763,10 @@ bool Director::initSDL()
}
}
if (options->console)
{
std::cout << std::endl;
}
return success;
}
@@ -1010,7 +1083,10 @@ void Director::setSection(section_t section)
// Ejecuta la seccion de juego con el logo
void Director::runLogo()
{
if (options->console)
{
std::cout << "\n* SECTION: LOGO" << std::endl;
}
loadResources(section);
logo = new Logo(renderer, screen, resource, asset, options, section.subsection);
setSection(logo->run());
@@ -1021,7 +1097,10 @@ void Director::runLogo()
// Ejecuta la seccion de juego de la introducción
void Director::runIntro()
{
if (options->console)
{
std::cout << "\n* SECTION: INTRO" << std::endl;
}
loadResources(section);
intro = new Intro(renderer, screen, resource, asset, options);
setSection(intro->run());
@@ -1032,7 +1111,10 @@ void Director::runIntro()
// Ejecuta la seccion de juego con el titulo y los menus
void Director::runTitle()
{
if (options->console)
{
std::cout << "\n* SECTION: TITLE" << std::endl;
}
if ((JA_GetMusicState() == JA_MUSIC_INVALID) || (JA_GetMusicState() == JA_MUSIC_STOPPED))
{
JA_PlayMusic(music);
@@ -1047,7 +1129,10 @@ void Director::runTitle()
// Ejecuta la seccion de los creditos del juego
void Director::runCredits()
{
if (options->console)
{
std::cout << "\n* SECTION: CREDITS" << std::endl;
}
loadResources(section);
credits = new Credits(renderer, screen, resource, asset, options);
setSection(credits->run());
@@ -1058,7 +1143,10 @@ void Director::runCredits()
// Ejecuta la seccion de la demo, donde se ven pantallas del juego
void Director::runDemo()
{
if (options->console)
{
std::cout << "\n* SECTION: DEMO" << std::endl;
}
loadResources(section);
demo = new Demo(renderer, screen, resource, asset, options, debug);
setSection(demo->run());
@@ -1069,7 +1157,10 @@ void Director::runDemo()
// Ejecuta la seccion de juego donde se juega
void Director::runGame()
{
if (options->console)
{
std::cout << "\n* SECTION: GAME" << std::endl;
}
JA_StopMusic();
loadResources(section);
game = new Game(renderer, screen, resource, asset, options, input, debug);

View File

@@ -37,13 +37,19 @@ private:
Credits *credits; // Objeto para gestionar los creditos del juego
Demo *demo; // Objeto para gestionar el modo demo, en el que se ven pantallas del juego
Debug *debug; // Objeto para getsionar la información de debug
struct options_t *options; // Variable con todas las opciones del programa
// Variables
JA_Music music; // Musica del titulo
struct options_t *options; // Variable con todas las opciones del programa
std::string executablePath; // Path del ejecutable
section_t section; // Sección y subsección actual del programa;
// Crea e inicializa las opciones del programa
void iniOptions();
// Comprueba los parametros del programa
void checkProgramArguments(int argc, char *argv[]);
// Carga el fichero de configuración
bool loadConfig();
@@ -97,7 +103,7 @@ private:
public:
// Constructor
Director(std::string path);
Director(int argc, char *argv[]);
// Destructor
~Director();

View File

@@ -389,7 +389,11 @@ void Game::killPlayer()
return;
}
// board.lives--;
// Resta una vida al jugador
if (!options->infiniteLives)
{
board.lives--;
}
// Destruye la habitacion y el jugador
delete room;
@@ -412,7 +416,10 @@ void Game::killPlayer()
// Recarga todas las texturas
void Game::reLoadTextures()
{
if (options->console)
{
std::cout << "** RELOAD REQUESTED" << std::endl;
}
player->reLoadTexture();
room->reLoadTexture();
scoreboard->reLoadTexture();
@@ -422,7 +429,10 @@ void Game::reLoadTextures()
// Cambia la paleta
void Game::switchPalette()
{
if (options->console)
{
std::cout << "** PALETTE SWITCH REQUESTED" << std::endl;
}
// Modifica la variable
options->palette = (options->palette == p_zxspectrum) ? p_zxarne : p_zxspectrum;

View File

@@ -85,7 +85,7 @@ void Logo::checkEventHandler()
switch (eventHandler->key.keysym.scancode)
{
case SDL_SCANCODE_ESCAPE:
std::cout << "PULSADO ESCAPE" << std::endl;
//std::cout << "PULSADO ESCAPE" << std::endl;
section.name = SECTION_PROG_QUIT;
break;

View File

@@ -8,12 +8,12 @@ Empezado en Castalla el 01/07/2022.
#include "director.h"
#include <iostream>
int main(int argc, char *args[])
int main(int argc, char *argv[])
{
std::cout << "Starting the game...\n\n";
// Crea el objeto Director
Director *director = new Director(args[0]);
Director *director = new Director(argc, argv);
// Bucle principal
director->run();
@@ -22,7 +22,7 @@ int main(int argc, char *args[])
delete director;
director = nullptr;
std::cout << "\nShutting down the game...\n";
std::cout << "\nShutting down the game..." << std::endl;
return 0;
}

View File

@@ -109,9 +109,11 @@ room_t loadRoomFile(std::string file_path)
// Procesa las dos subcadenas
if (!setItem(&item, line.substr(0, pos), line.substr(pos + 1, line.length())))
{
{
std::cout << "Warning: file " << filename.c_str() << "\n, unknown parameter \"" << line.substr(0, pos).c_str() << "\"" << std::endl;
}
}
} while (line != "[/item]");
@@ -126,21 +128,27 @@ room_t loadRoomFile(std::string file_path)
// Procesa las dos subcadenas
if (!setVars(&room, line.substr(0, pos), line.substr(pos + 1, line.length())))
{
{
std::cout << "Warning: file " << filename.c_str() << "\n, unknown parameter \"" << line.substr(0, pos).c_str() << "\"" << std::endl;
}
}
}
}
// Cierra el fichero
{
std::cout << "Room loaded: " << filename.c_str() << std::endl;
}
file.close();
}
// El fichero no se puede abrir
else
{
{
std::cout << "Warning: Unable to open " << filename.c_str() << " file" << std::endl;
}
}
return room;
}
@@ -433,9 +441,12 @@ Room::Room(room_t *room, SDL_Renderer *renderer, Screen *screen, Asset *asset, o
// Crea la textura para el mapa de tiles de la habitación
mapTexture = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, GAMECANVAS_WIDTH, GAMECANVAS_HEIGHT);
if (mapTexture == nullptr)
{
if (options->console)
{
std::cout << "Error: mapTexture could not be created!\nSDL Error: " << SDL_GetError() << std::endl;
}
}
SDL_SetTextureBlendMode(mapTexture, SDL_BLENDMODE_BLEND);
// Pinta el mapa de la habitación en la textura