JA VA! Nomes s'havia de fer les coses be i no ser un ansias

This commit is contained in:
2025-02-22 00:30:32 +01:00
parent f6098a479b
commit e361d295c1
39 changed files with 1053 additions and 1098 deletions

View File

@@ -5,12 +5,12 @@
#include <iostream> // Para basic_ostream, operator<<, cout, endl #include <iostream> // Para basic_ostream, operator<<, cout, endl
#include "screen.h" // Para Screen #include "screen.h" // Para Screen
#include "utils.h" // Para options_t #include "utils.h" // Para options_t
#include "options.h"
// Constructor // Constructor
Cheevos::Cheevos(Screen *screen, options_t *options, std::string file) Cheevos::Cheevos(Screen *screen, std::string file)
{ {
// Copia la dirección de los objetos // Copia la dirección de los objetos
this->options = options;
this->screen = screen; this->screen = screen;
this->file = file; this->file = file;
@@ -188,7 +188,7 @@ void Cheevos::loadFromFile()
// El fichero no existe // El fichero no existe
if (file == NULL) if (file == NULL)
{ {
if (options->console) if (options.console)
{ {
std::cout << "Warning: Unable to open file! SDL Error: " << SDL_GetError() << std::endl; std::cout << "Warning: Unable to open file! SDL Error: " << SDL_GetError() << std::endl;
} }
@@ -198,7 +198,7 @@ void Cheevos::loadFromFile()
if (file != NULL) if (file != NULL)
{ {
if (options->console) if (options.console)
{ {
std::cout << "New file created!" << std::endl; std::cout << "New file created!" << std::endl;
} }
@@ -214,7 +214,7 @@ void Cheevos::loadFromFile()
} }
else else
{ {
if (options->console) if (options.console)
{ {
std::cout << "Error: Unable to create file! SDL Error: " << SDL_GetError() << std::endl; std::cout << "Error: Unable to create file! SDL Error: " << SDL_GetError() << std::endl;
} }
@@ -224,7 +224,7 @@ void Cheevos::loadFromFile()
else else
{ {
// Carga los datos // Carga los datos
if (options->console) if (options.console)
{ {
std::cout << "Reading file...!" << std::endl; std::cout << "Reading file...!" << std::endl;
} }
@@ -256,7 +256,7 @@ void Cheevos::saveToFile()
} }
else else
{ {
if (options->console) if (options.console)
{ {
std::cout << "Error: Unable to save file! " << SDL_GetError() << std::endl; std::cout << "Error: Unable to save file! " << SDL_GetError() << std::endl;
} }

View File

@@ -20,7 +20,6 @@ class Cheevos
private: private:
// Punteros y objetos // Punteros y objetos
Screen *screen; // Objeto encargado de dibujar en pantalla Screen *screen; // Objeto encargado de dibujar en pantalla
options_t *options; // Puntero a las opciones del juego
// Variables // Variables
std::vector<cheevos_t> cheevos; // Listado de logros std::vector<cheevos_t> cheevos; // Listado de logros
@@ -47,7 +46,7 @@ private:
public: public:
// Constructor // Constructor
Cheevos(Screen *screen, options_t *options, std::string file); Cheevos(Screen *screen, std::string file);
// Destructor // Destructor
~Cheevos(); ~Cheevos();

View File

@@ -13,18 +13,16 @@
#include "screen.h" // Para Screen #include "screen.h" // Para Screen
#include "text.h" // Para Text, TXT_CENTER, TXT_COLOR #include "text.h" // Para Text, TXT_CENTER, TXT_COLOR
#include "asset.h" #include "asset.h"
#include "options.h"
class Asset; class Asset;
// Constructor // Constructor
Credits::Credits(Resource *resource, options_t *options, section_t *section) Credits::Credits(Resource *resource)
: screen_(Screen::get()), : screen_(Screen::get()),
renderer_(Screen::get()->getRenderer()), renderer_(Screen::get()->getRenderer()),
resource_(resource), resource_(resource),
asset_(Asset::get()), asset_(Asset::get()),
input_(Input::get()), input_(Input::get())
options_(options),
section_(section)
{ {
// Reserva memoria para los punteros // Reserva memoria para los punteros
event_handler_ = new SDL_Event(); event_handler_ = new SDL_Event();
@@ -32,18 +30,18 @@ Credits::Credits(Resource *resource, options_t *options, section_t *section)
sprite_ = new AnimatedSprite(renderer_, resource_->getAnimation("shine.ani")); sprite_ = new AnimatedSprite(renderer_, resource_->getAnimation("shine.ani"));
// Inicializa variables // Inicializa variables
section->name = SECTION_CREDITS; options.section.name = SECTION_CREDITS;
section->subsection = 0; options.section.subsection = 0;
sprite_->setRect({194, 174, 8, 8}); sprite_->setRect({194, 174, 8, 8});
// Cambia el color del borde // Cambia el color del borde
screen_->setBorderColor(stringToColor(options->palette, "black")); screen_->setBorderColor(stringToColor(options.palette, "black"));
// Crea la textura para el texto que se escribe en pantalla // Crea la textura para el texto que se escribe en pantalla
text_texture_ = SDL_CreateTexture(renderer_, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, GAMECANVAS_WIDTH, GAMECANVAS_HEIGHT); text_texture_ = SDL_CreateTexture(renderer_, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, GAMECANVAS_WIDTH, GAMECANVAS_HEIGHT);
if (text_texture_ == nullptr) if (text_texture_ == nullptr)
{ {
if (options->console) if (options.console)
{ {
std::cout << "Error: textTexture could not be created!\nSDL Error: " << SDL_GetError() << std::endl; std::cout << "Error: textTexture could not be created!\nSDL Error: " << SDL_GetError() << std::endl;
} }
@@ -54,7 +52,7 @@ Credits::Credits(Resource *resource, options_t *options, section_t *section)
cover_texture_ = SDL_CreateTexture(renderer_, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, GAMECANVAS_WIDTH, GAMECANVAS_HEIGHT); cover_texture_ = SDL_CreateTexture(renderer_, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, GAMECANVAS_WIDTH, GAMECANVAS_HEIGHT);
if (cover_texture_ == nullptr) if (cover_texture_ == nullptr)
{ {
if (options->console) if (options.console)
{ {
std::cout << "Error: textTexture could not be created!\nSDL Error: " << SDL_GetError() << std::endl; std::cout << "Error: textTexture could not be created!\nSDL Error: " << SDL_GetError() << std::endl;
} }
@@ -84,7 +82,7 @@ void Credits::checkEvents()
// Evento de salida de la aplicación // Evento de salida de la aplicación
if (event_handler_->type == SDL_QUIT) if (event_handler_->type == SDL_QUIT)
{ {
section_->name = SECTION_QUIT; options.section.name = SECTION_QUIT;
break; break;
} }
} }
@@ -96,7 +94,7 @@ void Credits::checkInput()
if (input_->checkInput(input_exit, REPEAT_FALSE)) if (input_->checkInput(input_exit, REPEAT_FALSE))
{ {
section_->name = SECTION_QUIT; options.section.name = SECTION_QUIT;
} }
else if (input_->checkInput(input_toggle_border, REPEAT_FALSE)) else if (input_->checkInput(input_toggle_border, REPEAT_FALSE))
@@ -126,8 +124,8 @@ void Credits::checkInput()
else if (input_->checkInput(input_pause, REPEAT_FALSE) || input_->checkInput(input_accept, REPEAT_FALSE) || input_->checkInput(input_jump, REPEAT_FALSE)) else if (input_->checkInput(input_pause, REPEAT_FALSE) || input_->checkInput(input_accept, REPEAT_FALSE) || input_->checkInput(input_jump, REPEAT_FALSE))
{ {
section_->name = SECTION_TITLE; options.section.name = SECTION_TITLE;
section_->subsection = 0; options.section.subsection = 0;
} }
} }
@@ -135,11 +133,11 @@ void Credits::checkInput()
void Credits::iniTexts() void Credits::iniTexts()
{ {
std::string keys = ""; std::string keys = "";
if (options_->keys == ctrl_cursor) if (options.keys == ctrl_cursor)
{ {
keys = "CURSORS"; keys = "CURSORS";
} }
else if (options_->keys == ctrl_opqa) else if (options.keys == ctrl_opqa)
{ {
keys = "O,P AND Q"; keys = "O,P AND Q";
} }
@@ -150,62 +148,62 @@ void Credits::iniTexts()
#ifndef GAME_CONSOLE #ifndef GAME_CONSOLE
texts_.clear(); texts_.clear();
texts_.push_back({"", stringToColor(options_->palette, "white")}); texts_.push_back({"", stringToColor(options.palette, "white")});
texts_.push_back({"INSTRUCTIONS:", stringToColor(options_->palette, "yellow")}); texts_.push_back({"INSTRUCTIONS:", stringToColor(options.palette, "yellow")});
texts_.push_back({"", stringToColor(options_->palette, "white")}); texts_.push_back({"", stringToColor(options.palette, "white")});
texts_.push_back({"HELP JAILDOC TO GET BACK ALL", stringToColor(options_->palette, "white")}); texts_.push_back({"HELP JAILDOC TO GET BACK ALL", stringToColor(options.palette, "white")});
texts_.push_back({"HIS PROJECTS AND GO TO THE", stringToColor(options_->palette, "white")}); texts_.push_back({"HIS PROJECTS AND GO TO THE", stringToColor(options.palette, "white")});
texts_.push_back({"JAIL TO FINISH THEM", stringToColor(options_->palette, "white")}); texts_.push_back({"JAIL TO FINISH THEM", stringToColor(options.palette, "white")});
texts_.push_back({"", stringToColor(options_->palette, "white")}); texts_.push_back({"", stringToColor(options.palette, "white")});
texts_.push_back({"", stringToColor(options_->palette, "white")}); texts_.push_back({"", stringToColor(options.palette, "white")});
texts_.push_back({"KEYS:", stringToColor(options_->palette, "yellow")}); texts_.push_back({"KEYS:", stringToColor(options.palette, "yellow")});
texts_.push_back({"", stringToColor(options_->palette, "white")}); texts_.push_back({"", stringToColor(options.palette, "white")});
texts_.push_back({keys + " TO MOVE AND JUMP", stringToColor(options_->palette, "white")}); texts_.push_back({keys + " TO MOVE AND JUMP", stringToColor(options.palette, "white")});
texts_.push_back({"M TO SWITCH THE MUSIC", stringToColor(options_->palette, "white")}); texts_.push_back({"M TO SWITCH THE MUSIC", stringToColor(options.palette, "white")});
texts_.push_back({"H TO PAUSE THE GAME", stringToColor(options_->palette, "white")}); texts_.push_back({"H TO PAUSE THE GAME", stringToColor(options.palette, "white")});
texts_.push_back({"F1-F2 TO CHANGE WINDOWS SIZE", stringToColor(options_->palette, "white")}); texts_.push_back({"F1-F2 TO CHANGE WINDOWS SIZE", stringToColor(options.palette, "white")});
texts_.push_back({"F3 TO SWITCH TO FULLSCREEN", stringToColor(options_->palette, "white")}); texts_.push_back({"F3 TO SWITCH TO FULLSCREEN", stringToColor(options.palette, "white")});
texts_.push_back({"B TO TOOGLE THE BORDER SCREEN", stringToColor(options_->palette, "white")}); texts_.push_back({"B TO TOOGLE THE BORDER SCREEN", stringToColor(options.palette, "white")});
texts_.push_back({"", stringToColor(options_->palette, "white")}); texts_.push_back({"", stringToColor(options.palette, "white")});
texts_.push_back({"", stringToColor(options_->palette, "white")}); texts_.push_back({"", stringToColor(options.palette, "white")});
texts_.push_back({"A GAME BY JAILDESIGNER", stringToColor(options_->palette, "yellow")}); texts_.push_back({"A GAME BY JAILDESIGNER", stringToColor(options.palette, "yellow")});
texts_.push_back({"MADE ON SUMMER/FALL 2022", stringToColor(options_->palette, "yellow")}); texts_.push_back({"MADE ON SUMMER/FALL 2022", stringToColor(options.palette, "yellow")});
texts_.push_back({"", stringToColor(options_->palette, "white")}); texts_.push_back({"", stringToColor(options.palette, "white")});
texts_.push_back({"", stringToColor(options_->palette, "white")}); texts_.push_back({"", stringToColor(options.palette, "white")});
texts_.push_back({"I LOVE JAILGAMES! ", stringToColor(options_->palette, "white")}); texts_.push_back({"I LOVE JAILGAMES! ", stringToColor(options.palette, "white")});
texts_.push_back({"", stringToColor(options_->palette, "white")}); texts_.push_back({"", stringToColor(options.palette, "white")});
#else #else
texts.clear(); texts.clear();
texts.push_back({"", stringToColor(options->palette, "white")}); texts.push_back({"", stringToColor(options.palette, "white")});
texts.push_back({"INSTRUCTIONS:", stringToColor(options->palette, "yellow")}); texts.push_back({"INSTRUCTIONS:", stringToColor(options.palette, "yellow")});
texts.push_back({"", stringToColor(options->palette, "white")}); texts.push_back({"", stringToColor(options.palette, "white")});
texts.push_back({"HELP JAILDOC TO GET BACK ALL", stringToColor(options->palette, "white")}); texts.push_back({"HELP JAILDOC TO GET BACK ALL", stringToColor(options.palette, "white")});
texts.push_back({"HIS PROJECTS AND GO TO THE", stringToColor(options->palette, "white")}); texts.push_back({"HIS PROJECTS AND GO TO THE", stringToColor(options.palette, "white")});
texts.push_back({"JAIL TO FINISH THEM", stringToColor(options->palette, "white")}); texts.push_back({"JAIL TO FINISH THEM", stringToColor(options.palette, "white")});
texts.push_back({"", stringToColor(options->palette, "white")}); texts.push_back({"", stringToColor(options.palette, "white")});
texts.push_back({"", stringToColor(options->palette, "white")}); texts.push_back({"", stringToColor(options.palette, "white")});
texts.push_back({"KEYS:", stringToColor(options->palette, "yellow")}); texts.push_back({"KEYS:", stringToColor(options.palette, "yellow")});
texts.push_back({"", stringToColor(options->palette, "white")}); texts.push_back({"", stringToColor(options.palette, "white")});
texts.push_back({"B TO JUMP", stringToColor(options->palette, "white")}); texts.push_back({"B TO JUMP", stringToColor(options.palette, "white")});
texts.push_back({"R TO SWITCH THE MUSIC", stringToColor(options->palette, "white")}); texts.push_back({"R TO SWITCH THE MUSIC", stringToColor(options.palette, "white")});
texts.push_back({"L TO SWAP THE COLOR PALETTE", stringToColor(options->palette, "white")}); texts.push_back({"L TO SWAP THE COLOR PALETTE", stringToColor(options.palette, "white")});
texts.push_back({"START TO PAUSE", stringToColor(options->palette, "white")}); texts.push_back({"START TO PAUSE", stringToColor(options.palette, "white")});
texts.push_back({"SELECT TO EXIT", stringToColor(options->palette, "white")}); texts.push_back({"SELECT TO EXIT", stringToColor(options.palette, "white")});
texts.push_back({"", stringToColor(options->palette, "white")}); texts.push_back({"", stringToColor(options.palette, "white")});
texts.push_back({"", stringToColor(options->palette, "white")}); texts.push_back({"", stringToColor(options.palette, "white")});
texts.push_back({"", stringToColor(options->palette, "white")}); texts.push_back({"", stringToColor(options.palette, "white")});
texts.push_back({"A GAME BY JAILDESIGNER", stringToColor(options->palette, "yellow")}); texts.push_back({"A GAME BY JAILDESIGNER", stringToColor(options.palette, "yellow")});
texts.push_back({"MADE ON SUMMER/FALL 2022", stringToColor(options->palette, "yellow")}); texts.push_back({"MADE ON SUMMER/FALL 2022", stringToColor(options.palette, "yellow")});
texts.push_back({"", stringToColor(options->palette, "white")}); texts.push_back({"", stringToColor(options.palette, "white")});
texts.push_back({"", stringToColor(options->palette, "white")}); texts.push_back({"", stringToColor(options.palette, "white")});
texts.push_back({"I LOVE JAILGAMES! ", stringToColor(options->palette, "white")}); texts.push_back({"I LOVE JAILGAMES! ", stringToColor(options.palette, "white")});
texts.push_back({"", stringToColor(options->palette, "white")}); texts.push_back({"", stringToColor(options.palette, "white")});
#endif #endif
} }
@@ -217,7 +215,7 @@ void Credits::fillTexture()
// Rellena la textura de texto // Rellena la textura de texto
SDL_SetRenderTarget(renderer_, text_texture_); SDL_SetRenderTarget(renderer_, text_texture_);
color_t c = stringToColor(options_->palette, "black"); color_t c = stringToColor(options.palette, "black");
SDL_SetRenderDrawColor(renderer_, c.r, c.g, c.b, 0xFF); SDL_SetRenderDrawColor(renderer_, c.r, c.g, c.b, 0xFF);
SDL_RenderClear(renderer_); SDL_RenderClear(renderer_);
@@ -234,7 +232,7 @@ void Credits::fillTexture()
// Escribe el corazón // Escribe el corazón
const int textLenght = text_->lenght(texts_[22].label, 1) - text_->lenght(" ", 1); // Se resta el ultimo caracter que es un espacio const int textLenght = text_->lenght(texts_[22].label, 1) - text_->lenght(" ", 1); // Se resta el ultimo caracter que es un espacio
const int posX = ((PLAY_AREA_WIDTH - textLenght) / 2) + textLenght; const int posX = ((PLAY_AREA_WIDTH - textLenght) / 2) + textLenght;
text_->writeColored(posX, 176, "}", stringToColor(options_->palette, "bright_red")); text_->writeColored(posX, 176, "}", stringToColor(options.palette, "bright_red"));
// Recoloca el sprite del brillo // Recoloca el sprite del brillo
sprite_->setPosX(posX + 2); sprite_->setPosX(posX + 2);
@@ -291,7 +289,7 @@ void Credits::updateCounter()
// Comprueba si ha terminado la sección // Comprueba si ha terminado la sección
if (counter_ > 1200) if (counter_ > 1200)
{ {
section_->name = SECTION_DEMO; options.section.name = SECTION_DEMO;
} }
} }
@@ -352,7 +350,7 @@ void Credits::render()
// Bucle para el logo del juego // Bucle para el logo del juego
void Credits::run() void Credits::run()
{ {
while (section_->name == SECTION_CREDITS) while (options.section.name == SECTION_CREDITS)
{ {
update(); update();
checkEvents(); checkEvents();
@@ -363,6 +361,6 @@ void Credits::run()
// Cambia la paleta // Cambia la paleta
void Credits::switchPalette() void Credits::switchPalette()
{ {
options_->palette = options_->palette == p_zxspectrum ? p_zxarne : p_zxspectrum; options.palette = options.palette == p_zxspectrum ? p_zxarne : p_zxspectrum;
fillTexture(); fillTexture();
} }

View File

@@ -33,8 +33,6 @@ private:
SDL_Texture *text_texture_; // Textura para dibujar el texto SDL_Texture *text_texture_; // Textura para dibujar el texto
SDL_Texture *cover_texture_; // Textura para cubrir el texto SDL_Texture *cover_texture_; // Textura para cubrir el texto
AnimatedSprite *sprite_; // Sprite para el brillo del corazón AnimatedSprite *sprite_; // Sprite para el brillo del corazón
options_t *options_; // Puntero a las opciones del juego
section_t *section_; // Estado del bucle principal para saber si continua o se sale
// Variables // Variables
int counter_ = 0; // Contador int counter_ = 0; // Contador
@@ -70,7 +68,7 @@ private:
public: public:
// Constructor // Constructor
Credits(Resource *resource, options_t *options, section_t *section); Credits(Resource *resource);
// Destructor // Destructor
~Credits(); ~Credits();

View File

@@ -11,10 +11,11 @@
#include "screen.h" // Para Screen #include "screen.h" // Para Screen
#include "text.h" // Para Text, TXT_CENTER, TXT_COLOR #include "text.h" // Para Text, TXT_CENTER, TXT_COLOR
#include "utils.h" // Para color_t, stringToColor, options_t, secti... #include "utils.h" // Para color_t, stringToColor, options_t, secti...
#include "options.h"
class Debug; class Debug;
// Constructor // Constructor
Demo::Demo(Resource *resource, options_t *options, section_t *section, Debug *debug) Demo::Demo(Resource *resource, Debug *debug)
{ {
// Inicia algunas variables // Inicia algunas variables
board.iniClock = SDL_GetTicks(); board.iniClock = SDL_GetTicks();
@@ -36,14 +37,12 @@ Demo::Demo(Resource *resource, options_t *options, section_t *section, Debug *de
this->renderer = Screen::get()->getRenderer(); this->renderer = Screen::get()->getRenderer();
this->asset = Asset::get(); this->asset = Asset::get();
this->input = Input::get(); this->input = Input::get();
this->options = options;
this->section = section;
this->debug = debug; this->debug = debug;
// Crea los objetos // Crea los objetos
itemTracker = new ItemTracker(); itemTracker = new ItemTracker();
scoreboard = new ScoreBoard(renderer, resource, asset, options, &board); scoreboard = new ScoreBoard(renderer, resource, asset, &board);
room = new Room(resource->getRoom(currentRoom), renderer, screen, asset, options, itemTracker, &board.items, false, debug); room = new Room(resource->getRoom(currentRoom), renderer, screen, asset, itemTracker, &board.items, false, debug);
eventHandler = new SDL_Event(); eventHandler = new SDL_Event();
text = new Text(resource->getOffset("smb2.txt"), resource->getTexture("smb2.png"), renderer); text = new Text(resource->getOffset("smb2.txt"), resource->getTexture("smb2.png"), renderer);
@@ -59,8 +58,8 @@ Demo::Demo(Resource *resource, options_t *options, section_t *section, Debug *de
board.music = true; board.music = true;
setScoreBoardColor(); setScoreBoardColor();
section->name = SECTION_DEMO; options.section.name = SECTION_DEMO;
section->subsection = 0; options.section.subsection = 0;
} }
Demo::~Demo() Demo::~Demo()
@@ -82,8 +81,8 @@ void Demo::checkEvents()
// Evento de salida de la aplicación // Evento de salida de la aplicación
if (eventHandler->type == SDL_QUIT) if (eventHandler->type == SDL_QUIT)
{ {
section->name = SECTION_QUIT; options.section.name = SECTION_QUIT;
screen->setBorderColor(stringToColor(options->palette, "black")); screen->setBorderColor(stringToColor(options.palette, "black"));
break; break;
} }
} }
@@ -95,7 +94,7 @@ void Demo::checkInput()
if (input->checkInput(input_exit, REPEAT_FALSE)) if (input->checkInput(input_exit, REPEAT_FALSE))
{ {
section->name = SECTION_QUIT; options.section.name = SECTION_QUIT;
} }
else if (input->checkInput(input_toggle_border, REPEAT_FALSE)) else if (input->checkInput(input_toggle_border, REPEAT_FALSE))
@@ -129,15 +128,15 @@ void Demo::checkInput()
else if (input->checkInput(input_pause, REPEAT_FALSE) || input->checkInput(input_accept, REPEAT_FALSE) || input->checkInput(input_jump, REPEAT_FALSE)) else if (input->checkInput(input_pause, REPEAT_FALSE) || input->checkInput(input_accept, REPEAT_FALSE) || input->checkInput(input_jump, REPEAT_FALSE))
{ {
section->name = SECTION_TITLE; options.section.name = SECTION_TITLE;
section->subsection = 0; options.section.subsection = 0;
} }
} }
// Bucle para el juego // Bucle para el juego
void Demo::run() void Demo::run()
{ {
while (section->name == SECTION_DEMO) while (options.section.name == SECTION_DEMO)
{ {
update(); update();
checkEvents(); checkEvents();
@@ -191,7 +190,7 @@ void Demo::renderRoomName()
{ {
// Texto en el centro de la pantalla // Texto en el centro de la pantalla
SDL_Rect rect = {0, 16 * BLOCK, PLAY_AREA_WIDTH, BLOCK * 2}; SDL_Rect rect = {0, 16 * BLOCK, PLAY_AREA_WIDTH, BLOCK * 2};
color_t color = stringToColor(options->palette, "white"); color_t color = stringToColor(options.palette, "white");
SDL_SetRenderDrawColor(renderer, color.r, color.g, color.b, 0xFF); SDL_SetRenderDrawColor(renderer, color.r, color.g, color.b, 0xFF);
SDL_RenderFillRect(renderer, &rect); SDL_RenderFillRect(renderer, &rect);
@@ -201,7 +200,7 @@ void Demo::renderRoomName()
// Recarga todas las texturas // Recarga todas las texturas
void Demo::reLoadTextures() void Demo::reLoadTextures()
{ {
if (options->console) if (options.console)
{ {
std::cout << "** RELOAD REQUESTED" << std::endl; std::cout << "** RELOAD REQUESTED" << std::endl;
} }
@@ -214,13 +213,13 @@ void Demo::reLoadTextures()
void Demo::switchPalette() void Demo::switchPalette()
{ {
// Modifica la variable // Modifica la variable
if (options->palette == p_zxspectrum) if (options.palette == p_zxspectrum)
{ {
options->palette = p_zxarne; options.palette = p_zxarne;
} }
else else
{ {
options->palette = p_zxspectrum; options.palette = p_zxspectrum;
} }
room->reLoadPalette(); room->reLoadPalette();
@@ -243,7 +242,7 @@ bool Demo::changeRoom(std::string file)
room = nullptr; room = nullptr;
// Crea un objeto habitación nuevo a partir del fichero // Crea un objeto habitación nuevo a partir del fichero
room = new Room(resource->getRoom(file), renderer, screen, asset, options, itemTracker, &board.items, false, debug); room = new Room(resource->getRoom(file), renderer, screen, asset, itemTracker, &board.items, false, debug);
// Pone el color del marcador en función del color del borde de la habitación // Pone el color del marcador en función del color del borde de la habitación
setScoreBoardColor(); setScoreBoardColor();
@@ -264,8 +263,8 @@ void Demo::checkRoomChange()
roomIndex++; roomIndex++;
if (roomIndex == (int)rooms.size()) if (roomIndex == (int)rooms.size())
{ {
section->name = SECTION_LOGO; options.section.name = SECTION_LOGO;
section->subsection = SUBSECTION_LOGO_TO_TITLE; options.section.subsection = SUBSECTION_LOGO_TO_TITLE;
} }
else else
{ {
@@ -281,10 +280,10 @@ void Demo::setScoreBoardColor()
const color_t c = room->getBorderColor(); const color_t c = room->getBorderColor();
// Si el color es negro lo cambia a blanco // Si el color es negro lo cambia a blanco
const color_t cBlack = stringToColor(options->palette, "black"); const color_t cBlack = stringToColor(options.palette, "black");
board.color = colorAreEqual(c, cBlack) ? stringToColor(options->palette, "white") : c; board.color = colorAreEqual(c, cBlack) ? stringToColor(options.palette, "white") : c;
// Si el color es negro brillante lo cambia a blanco // Si el color es negro brillante lo cambia a blanco
const color_t cBrightBlack = stringToColor(options->palette, "bright_black"); const color_t cBrightBlack = stringToColor(options.palette, "bright_black");
board.color = colorAreEqual(c, cBrightBlack) ? stringToColor(options->palette, "white") : c; board.color = colorAreEqual(c, cBrightBlack) ? stringToColor(options.palette, "white") : c;
} }

View File

@@ -32,8 +32,6 @@ private:
ScoreBoard *scoreboard; // Objeto encargado de gestionar el marcador ScoreBoard *scoreboard; // Objeto encargado de gestionar el marcador
ItemTracker *itemTracker; // Lleva el control de los objetos recogidos ItemTracker *itemTracker; // Lleva el control de los objetos recogidos
Debug *debug; // Objeto para gestionar la información de debug Debug *debug; // Objeto para gestionar la información de debug
options_t *options; // Puntero a las opciones del juego
section_t *section; // Seccion actual dentro del juego
// Variables // Variables
Uint32 ticks; // Contador de ticks para ajustar la velocidad del programa Uint32 ticks; // Contador de ticks para ajustar la velocidad del programa
@@ -77,7 +75,7 @@ private:
public: public:
// Constructor // Constructor
Demo(Resource *resource, options_t *options, section_t *section, Debug *debug); Demo(Resource *resource, Debug *debug);
// Destructor // Destructor
~Demo(); ~Demo();

View File

@@ -37,6 +37,7 @@
#include "screen.h" // Para Screen, FILTER_NEAREST, FILTER... #include "screen.h" // Para Screen, FILTER_NEAREST, FILTER...
#include "utils.h" // Para options_t, section_t, op_notif... #include "utils.h" // Para options_t, section_t, op_notif...
#include "notifier.h" #include "notifier.h"
#include "options.h"
#ifndef _WIN32 #ifndef _WIN32
#include <pwd.h> #include <pwd.h>
@@ -47,13 +48,6 @@ Director::Director(int argc, const char *argv[])
{ {
std::cout << "Game start" << std::endl; std::cout << "Game start" << std::endl;
section = new section_t();
section->name = SECTION_LOGO;
section->subsection = SUBSECTION_LOGO_TO_INTRO;
#ifdef DEBUG
section->name = SECTION_TITLE;
#endif
// Crea e inicializa las opciones del programa // Crea e inicializa las opciones del programa
initOptions(); initOptions();
@@ -62,7 +56,7 @@ Director::Director(int argc, const char *argv[])
// Crea el objeto que controla los ficheros de recursos // Crea el objeto que controla los ficheros de recursos
Asset::init(executable_path_); Asset::init(executable_path_);
Asset::get()->setVerbose(options->console); Asset::get()->setVerbose(options.console);
// Crea la carpeta del sistema donde guardar datos // Crea la carpeta del sistema donde guardar datos
createSystemFolder("jailgames"); createSystemFolder("jailgames");
@@ -78,8 +72,8 @@ Director::Director(int argc, const char *argv[])
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
} }
// Inicializa variables desde el fichero de configuración // Carga las opciones desde un fichero
loadConfig(); loadOptionsFromFile(Asset::get()->get("config.txt"));
// Inicializa SDL // Inicializa SDL
initSDL(); initSDL();
@@ -90,8 +84,8 @@ Director::Director(int argc, const char *argv[])
// Crea los objetos // Crea los objetos
Screen::init(window_, renderer_); Screen::init(window_, renderer_);
Screen::get()->setBorderColor(borderColor); Screen::get()->setBorderColor(borderColor);
Notifier::init(Asset::get()->get("notify.png"), Asset::get()->get("smb2.png"), Asset::get()->get("smb2.txt"), Asset::get()->get("notify.wav"), options); Notifier::init(Asset::get()->get("notify.png"), Asset::get()->get("smb2.png"), Asset::get()->get("smb2.txt"), Asset::get()->get("notify.wav"));
resource_ = new Resource(options); resource_ = new Resource();
Input::init(Asset::get()->get("gamecontrollerdb.txt")); Input::init(Asset::get()->get("gamecontrollerdb.txt"));
initInput(); initInput();
debug_ = new Debug(); debug_ = new Debug();
@@ -100,16 +94,14 @@ Director::Director(int argc, const char *argv[])
Director::~Director() Director::~Director()
{ {
// Guarda las opciones de configuración // Guarda las opciones a un fichero
saveConfig(); saveOptionsFromFile(Asset::get()->get("config.txt"));
// Libera la memoria // Libera la memoria
Asset::destroy(); Asset::destroy();
Input::destroy(); Input::destroy();
Screen::destroy(); Screen::destroy();
Notifier::destroy(); Notifier::destroy();
delete section;
delete options;
delete debug_; delete debug_;
delete resource_; delete resource_;
JA_DeleteMusic(title_music_); JA_DeleteMusic(title_music_);
@@ -121,56 +113,6 @@ Director::~Director()
std::cout << "\nBye!" << std::endl; std::cout << "\nBye!" << std::endl;
} }
// Crea e inicializa las opciones del programa
void Director::initOptions()
{
// Crea el puntero a la estructura de opciones
options = new options_t;
// Version del archivo de configuración
options->configVersion = "v1.06.1";
// Opciones de control
options->keys = ctrl_cursor;
// Opciones de video
options->gameWidth = GAMECANVAS_WIDTH;
options->gameHeight = GAMECANVAS_HEIGHT;
options->videoMode = 0;
options->windowSize = 3;
options->filter = FILTER_NEAREST;
options->shaders = false;
options->vSync = true;
options->integerScale = true;
options->keepAspect = true;
options->borderEnabled = true;
options->borderWidth = 32;
options->borderHeight = 24;
options->palette = p_zxspectrum;
#ifdef GAME_CONSOLE
options->windowSize = 2;
#endif
// Estos valores no se guardan en el fichero de configuraci´ón
options->console = false;
#ifdef DEBUG
options->console = true;
#endif
options->cheat.infiniteLives = false;
options->cheat.invincible = false;
options->cheat.jailEnabled = false;
options->cheat.altSkin = false;
options->stats.rooms = 0;
options->stats.items = 0;
// Opciones de las notificaciones
options->notifications.posV = pos_top;
options->notifications.posH = pos_left;
options->notifications.sound = true;
options->notifications.color = {48, 48, 48};
}
// Comprueba los parametros del programa // Comprueba los parametros del programa
void Director::checkProgramArguments(int argc, const char *argv[]) void Director::checkProgramArguments(int argc, const char *argv[])
{ {
@@ -182,236 +124,31 @@ void Director::checkProgramArguments(int argc, const char *argv[])
{ {
if (strcmp(argv[i], "--console") == 0) if (strcmp(argv[i], "--console") == 0)
{ {
options->console = true; options.console = true;
} }
else if (strcmp(argv[i], "--infiniteLives") == 0) else if (strcmp(argv[i], "--infiniteLives") == 0)
{ {
options->cheat.infiniteLives = true; options.cheat.infiniteLives = true;
} }
else if (strcmp(argv[i], "--invincible") == 0) else if (strcmp(argv[i], "--invincible") == 0)
{ {
options->cheat.invincible = true; options.cheat.invincible = true;
} }
else if (strcmp(argv[i], "--jailEnabled") == 0) else if (strcmp(argv[i], "--jailEnabled") == 0)
{ {
options->cheat.jailEnabled = true; options.cheat.jailEnabled = true;
} }
else if (strcmp(argv[i], "--altSkin") == 0) else if (strcmp(argv[i], "--altSkin") == 0)
{ {
options->cheat.altSkin = true; options.cheat.altSkin = true;
} }
} }
} }
// Carga el fichero de configuración
bool Director::loadConfig()
{
// Indicador de éxito en la carga
bool success = true;
// Versión actual del fichero
const std::string configVersion = options->configVersion;
options->configVersion = "";
// Variables para manejar el fichero
std::string line;
std::ifstream file(Asset::get()->get("config.txt"));
// Si el fichero se puede abrir
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
if (line.substr(0, 1) != "#")
{
// Encuentra la posición del caracter '='
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();
}
// El fichero no existe
else
{ // Crea el fichero con los valores por defecto
saveConfig();
}
// Si la versión de fichero no coincide, crea un fichero nuevo con los valores por defecto
if (configVersion != options->configVersion)
{
initOptions();
saveConfig();
}
// Normaliza los valores
const bool a = options->videoMode == 0;
const bool b = options->videoMode == SDL_WINDOW_FULLSCREEN;
const bool c = options->videoMode == SDL_WINDOW_FULLSCREEN_DESKTOP;
if (!(a || b || c))
{
options->videoMode = 0;
}
if (options->windowSize < 1 || options->windowSize > 4)
{
options->windowSize = 3;
}
// Aplica opciones
// if (options->borderEnabled)
//{
// const int incWidth = GAMECANVAS_WIDTH * options->borderSize;
// const int incHeight = GAMECANVAS_HEIGHT * options->borderSize;
// options->gameWidth = GAMECANVAS_WIDTH + incWidth;
// options->gameHeight = GAMECANVAS_HEIGHT + incHeight;
//}
// else
//{
// options->gameWidth = GAMECANVAS_WIDTH;
// options->gameHeight = GAMECANVAS_HEIGHT;
//}
return success;
}
// Guarda el fichero de configuración
bool Director::saveConfig()
{
bool success = true;
// Crea y abre el fichero de texto
std::ofstream file(Asset::get()->get("config.txt"));
if (file.good())
{
if (options->console)
{
std::cout << Asset::get()->get("config.txt") << " open for writing" << std::endl;
}
}
else
{
if (options->console)
{
std::cout << Asset::get()->get("config.txt") << " can't be opened" << std::endl;
}
}
// Escribe en el fichero
file << "## VERSION\n";
file << "configVersion=" + options->configVersion + "\n";
file << "\n## CONTROL OPTIONS\n";
file << "## keys = CURSOR | OPQA | WASD\n";
if (options->keys == ctrl_cursor)
{
file << "keys=CURSOR\n";
}
else if (options->keys == ctrl_opqa)
{
file << "keys=OPQA\n";
}
else if (options->keys == ctrl_wasd)
{
file << "keys=WASD\n";
}
file << "\n## VISUAL OPTIONS\n";
if (options->videoMode == 0)
{
file << "videoMode=0\n";
}
else if (options->videoMode == SDL_WINDOW_FULLSCREEN)
{
file << "videoMode=SDL_WINDOW_FULLSCREEN\n";
}
else if (options->videoMode == SDL_WINDOW_FULLSCREEN_DESKTOP)
{
file << "videoMode=SDL_WINDOW_FULLSCREEN_DESKTOP\n";
}
file << "windowSize=" + std::to_string(options->windowSize) + "\n";
if (options->filter == FILTER_NEAREST)
{
file << "filter=FILTER_NEAREST\n";
}
else
{
file << "filter=FILTER_LINEAR\n";
}
file << "shaders=" + boolToString(options->shaders) + "\n";
file << "vSync=" + boolToString(options->vSync) + "\n";
file << "integerScale=" + boolToString(options->integerScale) + "\n";
file << "keepAspect=" + boolToString(options->keepAspect) + "\n";
file << "borderEnabled=" + boolToString(options->borderEnabled) + "\n";
file << "borderWidth=" + std::to_string(options->borderWidth) + "\n";
file << "borderHeight=" + std::to_string(options->borderHeight) + "\n";
file << "palette=" + std::to_string(options->palette) + "\n";
file << "\n## NOTIFICATION OPTIONS\n";
file << "## notifications.posV = pos_top | pos_bottom\n";
if (options->notifications.posV == pos_top)
{
file << "notifications.posV=pos_top\n";
}
else
{
file << "notifications.posV=pos_bottom\n";
}
file << "## notifications.posH = pos_left | pos_middle | pos_right\n";
if (options->notifications.posH == pos_left)
{
file << "notifications.posH=pos_left\n";
}
else if (options->notifications.posH == pos_middle)
{
file << "notifications.posH=pos_middle\n";
}
else
{
file << "notifications.posH=pos_right\n";
}
file << "notifications.sound=" + boolToString(options->notifications.sound) + "\n";
// Cierra el fichero
file.close();
return success;
}
// Crea la carpeta del sistema donde guardar datos // Crea la carpeta del sistema donde guardar datos
void Director::createSystemFolder(const std::string &folder) void Director::createSystemFolder(const std::string &folder)
{ {
@@ -473,14 +210,14 @@ void Director::createSystemFolder(const std::string &folder)
} }
// Carga los recursos // Carga los recursos
void Director::loadResources(section_t *section) void Director::loadResources(section_t section)
{ {
if (options->console) if (options.console)
{ {
std::cout << "** LOAD RESOURCES" << std::endl; std::cout << "** LOAD RESOURCES" << std::endl;
} }
if (section->name == SECTION_LOGO) if (options.section.name == SECTION_LOGO)
{ {
std::vector<std::string> textureList; std::vector<std::string> textureList;
textureList.push_back("jailgames.png"); textureList.push_back("jailgames.png");
@@ -489,7 +226,7 @@ void Director::loadResources(section_t *section)
resource_->loadTextures(textureList); resource_->loadTextures(textureList);
} }
else if (section->name == SECTION_LOADING_SCREEN) else if (options.section.name == SECTION_LOADING_SCREEN)
{ {
std::vector<std::string> textureList; std::vector<std::string> textureList;
textureList.push_back("loading_screen_bn.png"); textureList.push_back("loading_screen_bn.png");
@@ -500,7 +237,7 @@ void Director::loadResources(section_t *section)
resource_->loadTextures(textureList); resource_->loadTextures(textureList);
} }
else if (section->name == SECTION_TITLE) else if (options.section.name == SECTION_TITLE)
{ {
std::vector<std::string> textureList; std::vector<std::string> textureList;
textureList.push_back("loading_screen_color.png"); textureList.push_back("loading_screen_color.png");
@@ -520,7 +257,7 @@ void Director::loadResources(section_t *section)
resource_->loadOffsets(offsetsList); resource_->loadOffsets(offsetsList);
} }
else if (section->name == SECTION_CREDITS) else if (options.section.name == SECTION_CREDITS)
{ {
// Texturas // Texturas
std::vector<std::string> textureList; std::vector<std::string> textureList;
@@ -542,7 +279,7 @@ void Director::loadResources(section_t *section)
resource_->loadOffsets(offsetsList); resource_->loadOffsets(offsetsList);
} }
else if (section->name == SECTION_ENDING) else if (options.section.name == SECTION_ENDING)
{ {
// Texturas // Texturas
std::vector<std::string> textureList; std::vector<std::string> textureList;
@@ -567,7 +304,7 @@ void Director::loadResources(section_t *section)
resource_->loadOffsets(offsetsList); resource_->loadOffsets(offsetsList);
} }
else if (section->name == SECTION_ENDING2) else if (options.section.name == SECTION_ENDING2)
{ {
// Texturas // Texturas
std::vector<std::string> textureList; std::vector<std::string> textureList;
@@ -705,7 +442,7 @@ void Director::loadResources(section_t *section)
resource_->loadOffsets(offsetsList); resource_->loadOffsets(offsetsList);
} }
else if (section->name == SECTION_GAME_OVER) else if (options.section.name == SECTION_GAME_OVER)
{ {
// Texturas // Texturas
std::vector<std::string> textureList; std::vector<std::string> textureList;
@@ -729,13 +466,13 @@ void Director::loadResources(section_t *section)
resource_->loadOffsets(offsetsList); resource_->loadOffsets(offsetsList);
} }
else if (section->name == SECTION_GAME || section->name == SECTION_DEMO) else if (options.section.name == SECTION_GAME || options.section.name == SECTION_DEMO)
{ {
// Texturas // Texturas
std::vector<std::string> textureList; std::vector<std::string> textureList;
// Jugador // Jugador
if (options->cheat.altSkin) if (options.cheat.altSkin)
{ {
textureList.push_back("player2.png"); textureList.push_back("player2.png");
} }
@@ -820,7 +557,7 @@ void Director::loadResources(section_t *section)
std::vector<std::string> animationList; std::vector<std::string> animationList;
// Jugador // Jugador
if (options->cheat.altSkin) if (options.cheat.altSkin)
{ {
animationList.push_back("player2.ani"); animationList.push_back("player2.ani");
} }
@@ -1028,182 +765,23 @@ void Director::loadResources(section_t *section)
resource_->loadRooms(roomList); resource_->loadRooms(roomList);
} }
if (options->console) if (options.console)
{ {
std::cout << "** RESOURCES LOADED" << std::endl; std::cout << "** RESOURCES LOADED" << std::endl;
} }
} }
// Asigna variables a partir de dos cadenas
bool Director::setOptions(options_t *options, std::string var, std::string value)
{
// Indicador de éxito en la asignación
bool success = true;
if (var == "configVersion")
{
options->configVersion = value;
}
else if (var == "keys")
{
if (value == "OPQA")
{
options->keys = ctrl_opqa;
}
else if (value == "WASD")
{
options->keys = ctrl_wasd;
}
else
{
options->keys = ctrl_cursor;
}
}
else if (var == "videoMode")
{
if (value == "SDL_WINDOW_FULLSCREEN_DESKTOP")
{
options->videoMode = SDL_WINDOW_FULLSCREEN_DESKTOP;
}
else if (value == "SDL_WINDOW_FULLSCREEN")
{
options->videoMode = SDL_WINDOW_FULLSCREEN;
}
else
{
options->videoMode = 0;
}
}
else if (var == "windowSize")
{
options->windowSize = std::stoi(value);
if ((options->windowSize < 1) || (options->windowSize > 4))
{
options->windowSize = 3;
}
}
else if (var == "filter")
{
if (value == "FILTER_LINEAR")
{
options->filter = FILTER_LINEAR;
}
else
{
options->filter = FILTER_NEAREST;
}
}
else if (var == "shaders")
{
options->shaders = stringToBool(value);
}
else if (var == "vSync")
{
options->vSync = stringToBool(value);
}
else if (var == "integerScale")
{
options->integerScale = stringToBool(value);
}
else if (var == "keepAspect")
{
options->keepAspect = stringToBool(value);
}
else if (var == "borderEnabled")
{
options->borderEnabled = stringToBool(value);
}
else if (var == "borderWidth")
{
options->borderWidth = std::stoi(value);
}
else if (var == "borderHeight")
{
options->borderHeight = std::stoi(value);
}
else if (var == "palette")
{
const int pal = std::stoi(value);
if (pal == 0)
{
options->palette = p_zxspectrum;
}
else if (pal == 1)
{
options->palette = p_zxarne;
}
}
else if (var == "notifications.posH")
{
if (value == "pos_left")
{
options->notifications.posH = pos_left;
}
else if (value == "pos_middle")
{
options->notifications.posH = pos_middle;
}
else
{
options->notifications.posH = pos_right;
}
}
else if (var == "notifications.posV")
{
if (value == "pos_top")
{
options->notifications.posV = pos_top;
}
else
{
options->notifications.posV = pos_bottom;
}
}
else if (var == "notifications.sound")
{
options->notifications.sound = stringToBool(value);
}
else if (var == "" || var.substr(0, 1) == "#")
{
}
else
{
success = false;
}
return success;
}
// Inicia las variables necesarias para arrancar el programa // Inicia las variables necesarias para arrancar el programa
void Director::initInput() void Director::initInput()
{ {
// Establece si ha de mostrar mensajes // Establece si ha de mostrar mensajes
Input::get()->setVerbose(options->console); Input::get()->setVerbose(options.console);
// Busca si hay un mando conectado // Busca si hay un mando conectado
Input::get()->discoverGameController(); Input::get()->discoverGameController();
// Teclado - Movimiento // Teclado - Movimiento
if (options->keys == ctrl_cursor) if (options.keys == ctrl_cursor)
{ {
Input::get()->bindKey(input_jump, SDL_SCANCODE_UP); Input::get()->bindKey(input_jump, SDL_SCANCODE_UP);
Input::get()->bindKey(input_left, SDL_SCANCODE_LEFT); Input::get()->bindKey(input_left, SDL_SCANCODE_LEFT);
@@ -1211,7 +789,7 @@ void Director::initInput()
Input::get()->bindKey(input_up, SDL_SCANCODE_UP); Input::get()->bindKey(input_up, SDL_SCANCODE_UP);
Input::get()->bindKey(input_down, SDL_SCANCODE_DOWN); Input::get()->bindKey(input_down, SDL_SCANCODE_DOWN);
} }
else if (options->keys == ctrl_opqa) else if (options.keys == ctrl_opqa)
{ {
Input::get()->bindKey(input_jump, SDL_SCANCODE_Q); Input::get()->bindKey(input_jump, SDL_SCANCODE_Q);
Input::get()->bindKey(input_left, SDL_SCANCODE_O); Input::get()->bindKey(input_left, SDL_SCANCODE_O);
@@ -1219,7 +797,7 @@ void Director::initInput()
Input::get()->bindKey(input_up, SDL_SCANCODE_Q); Input::get()->bindKey(input_up, SDL_SCANCODE_Q);
Input::get()->bindKey(input_down, SDL_SCANCODE_A); Input::get()->bindKey(input_down, SDL_SCANCODE_A);
} }
else if (options->keys == ctrl_wasd) else if (options.keys == ctrl_wasd)
{ {
Input::get()->bindKey(input_jump, SDL_SCANCODE_W); Input::get()->bindKey(input_jump, SDL_SCANCODE_W);
Input::get()->bindKey(input_left, SDL_SCANCODE_A); Input::get()->bindKey(input_left, SDL_SCANCODE_A);
@@ -1276,7 +854,7 @@ bool Director::initSDL()
// Inicializa SDL // Inicializa SDL
if (SDL_Init(SDL_INIT_EVERYTHING) < 0) if (SDL_Init(SDL_INIT_EVERYTHING) < 0)
{ {
if (options->console) if (options.console)
{ {
std::cout << "SDL could not initialize!\nSDL Error: " << SDL_GetError() << std::endl; std::cout << "SDL could not initialize!\nSDL Error: " << SDL_GetError() << std::endl;
} }
@@ -1288,9 +866,9 @@ bool Director::initSDL()
std::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, std::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)
{ {
std::cout << "Warning: Nearest texture filtering not enabled!\n"; std::cout << "Warning: Nearest texture filtering not enabled!\n";
} }
@@ -1305,16 +883,16 @@ bool Director::initSDL()
// Crea la ventana // Crea la ventana
int incW = 0; int incW = 0;
int incH = 0; int incH = 0;
if (options->borderEnabled) if (options.borderEnabled)
{ {
incW = options->borderWidth * 2; incW = options.borderWidth * 2;
incH = options->borderHeight * 2; incH = options.borderHeight * 2;
} }
window_ = SDL_CreateWindow(WINDOW_CAPTION, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, (options->gameWidth + incW) * options->windowSize, (options->gameHeight + incH) * options->windowSize, SDL_WINDOW_HIDDEN); window_ = SDL_CreateWindow(WINDOW_CAPTION, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, (options.gameWidth + incW) * options.windowSize, (options.gameHeight + incH) * options.windowSize, SDL_WINDOW_HIDDEN);
if (window_ == nullptr) if (window_ == nullptr)
{ {
if (options->console) if (options.console)
{ {
std::cout << "Window could not be created!\nSDL Error: " << SDL_GetError() << std::endl; std::cout << "Window could not be created!\nSDL Error: " << SDL_GetError() << std::endl;
} }
@@ -1324,7 +902,7 @@ bool Director::initSDL()
{ {
// Crea un renderizador para la ventana. El vsync se activa en funcion de las opciones // Crea un renderizador para la ventana. El vsync se activa en funcion de las opciones
Uint32 flags = 0; Uint32 flags = 0;
if (options->vSync) if (options.vSync)
{ {
flags = flags | SDL_RENDERER_PRESENTVSYNC; flags = flags | SDL_RENDERER_PRESENTVSYNC;
} }
@@ -1332,7 +910,7 @@ bool Director::initSDL()
if (renderer_ == nullptr) if (renderer_ == nullptr)
{ {
if (options->console) if (options.console)
{ {
std::cout << "Renderer could not be created!\nSDL Error: " << SDL_GetError() << std::endl; std::cout << "Renderer could not be created!\nSDL Error: " << SDL_GetError() << std::endl;
} }
@@ -1344,7 +922,7 @@ bool Director::initSDL()
SDL_SetRenderDrawColor(renderer_, 0x00, 0x00, 0x00, 0xFF); SDL_SetRenderDrawColor(renderer_, 0x00, 0x00, 0x00, 0xFF);
// Establece el tamaño del buffer de renderizado // Establece el tamaño del buffer de renderizado
SDL_RenderSetLogicalSize(renderer_, options->gameWidth, options->gameHeight); SDL_RenderSetLogicalSize(renderer_, options.gameWidth, options.gameHeight);
// Establece el modo de mezcla // Establece el modo de mezcla
SDL_SetRenderDrawBlendMode(renderer_, SDL_BLENDMODE_BLEND); SDL_SetRenderDrawBlendMode(renderer_, SDL_BLENDMODE_BLEND);
@@ -1352,7 +930,7 @@ bool Director::initSDL()
} }
} }
if (options->console) if (options.console)
{ {
std::cout << std::endl; std::cout << std::endl;
} }
@@ -1722,12 +1300,12 @@ bool Director::setFileList()
// Ejecuta la seccion de juego con el logo // Ejecuta la seccion de juego con el logo
void Director::runLogo() void Director::runLogo()
{ {
if (options->console) if (options.console)
{ {
std::cout << "\n* SECTION: LOGO" << std::endl; std::cout << "\n* SECTION: LOGO" << std::endl;
} }
loadResources(section); loadResources(options.section);
auto logo = std::make_unique<Logo>(resource_, options, section); auto logo = std::make_unique<Logo>(resource_);
logo->run(); logo->run();
resource_->free(); resource_->free();
} }
@@ -1735,12 +1313,12 @@ void Director::runLogo()
// Ejecuta la seccion de juego de la pantalla de carga // Ejecuta la seccion de juego de la pantalla de carga
void Director::runLoadingScreen() void Director::runLoadingScreen()
{ {
if (options->console) if (options.console)
{ {
std::cout << "\n* SECTION: INTRO" << std::endl; std::cout << "\n* SECTION: INTRO" << std::endl;
} }
loadResources(section); loadResources(options.section);
auto loadingScreen = std::make_unique<LoadingScreen>(resource_, options, section); auto loadingScreen = std::make_unique<LoadingScreen>(resource_);
loadingScreen->run(); loadingScreen->run();
resource_->free(); resource_->free();
} }
@@ -1748,7 +1326,7 @@ void Director::runLoadingScreen()
// Ejecuta la seccion de juego con el titulo y los menus // Ejecuta la seccion de juego con el titulo y los menus
void Director::runTitle() void Director::runTitle()
{ {
if (options->console) if (options.console)
{ {
std::cout << "\n* SECTION: TITLE" << std::endl; std::cout << "\n* SECTION: TITLE" << std::endl;
} }
@@ -1756,8 +1334,8 @@ void Director::runTitle()
{ {
JA_PlayMusic(title_music_); JA_PlayMusic(title_music_);
} }
loadResources(section); loadResources(options.section);
auto title = std::make_unique<Title>(resource_, options, section); auto title = std::make_unique<Title>(resource_);
title->run(); title->run();
resource_->free(); resource_->free();
} }
@@ -1765,12 +1343,12 @@ void Director::runTitle()
// Ejecuta la seccion de los creditos del juego // Ejecuta la seccion de los creditos del juego
void Director::runCredits() void Director::runCredits()
{ {
if (options->console) if (options.console)
{ {
std::cout << "\n* SECTION: CREDITS" << std::endl; std::cout << "\n* SECTION: CREDITS" << std::endl;
} }
loadResources(section); loadResources(options.section);
auto credits = std::make_unique<Credits>(resource_, options, section); auto credits = std::make_unique<Credits>(resource_);
credits->run(); credits->run();
resource_->free(); resource_->free();
} }
@@ -1778,12 +1356,12 @@ void Director::runCredits()
// Ejecuta la seccion de la demo, donde se ven pantallas del juego // Ejecuta la seccion de la demo, donde se ven pantallas del juego
void Director::runDemo() void Director::runDemo()
{ {
if (options->console) if (options.console)
{ {
std::cout << "\n* SECTION: DEMO" << std::endl; std::cout << "\n* SECTION: DEMO" << std::endl;
} }
loadResources(section); loadResources(options.section);
auto demo = std::make_unique<Demo>(resource_, options, section, debug_); auto demo = std::make_unique<Demo>(resource_, debug_);
demo->run(); demo->run();
resource_->free(); resource_->free();
} }
@@ -1791,12 +1369,12 @@ void Director::runDemo()
// Ejecuta la seccion del final del juego // Ejecuta la seccion del final del juego
void Director::runEnding() void Director::runEnding()
{ {
if (options->console) if (options.console)
{ {
std::cout << "\n* SECTION: ENDING" << std::endl; std::cout << "\n* SECTION: ENDING" << std::endl;
} }
loadResources(section); loadResources(options.section);
auto ending = std::make_unique<Ending>(resource_, options, section); auto ending = std::make_unique<Ending>(resource_);
ending->run(); ending->run();
resource_->free(); resource_->free();
} }
@@ -1804,12 +1382,12 @@ void Director::runEnding()
// Ejecuta la seccion del final del juego // Ejecuta la seccion del final del juego
void Director::runEnding2() void Director::runEnding2()
{ {
if (options->console) if (options.console)
{ {
std::cout << "\n* SECTION: ENDING2" << std::endl; std::cout << "\n* SECTION: ENDING2" << std::endl;
} }
loadResources(section); loadResources(options.section);
auto ending2 = std::make_unique<Ending2>(resource_, options, section); auto ending2 = std::make_unique<Ending2>(resource_);
ending2->run(); ending2->run();
resource_->free(); resource_->free();
} }
@@ -1817,12 +1395,12 @@ void Director::runEnding2()
// Ejecuta la seccion del final de la partida // Ejecuta la seccion del final de la partida
void Director::runGameOver() void Director::runGameOver()
{ {
if (options->console) if (options.console)
{ {
std::cout << "\n* SECTION: GAME OVER" << std::endl; std::cout << "\n* SECTION: GAME OVER" << std::endl;
} }
loadResources(section); loadResources(options.section);
auto gameOver = std::make_unique<GameOver>(resource_, options, section); auto gameOver = std::make_unique<GameOver>(resource_);
gameOver->run(); gameOver->run();
resource_->free(); resource_->free();
} }
@@ -1830,13 +1408,13 @@ void Director::runGameOver()
// Ejecuta la seccion de juego donde se juega // Ejecuta la seccion de juego donde se juega
void Director::runGame() void Director::runGame()
{ {
if (options->console) if (options.console)
{ {
std::cout << "\n* SECTION: GAME" << std::endl; std::cout << "\n* SECTION: GAME" << std::endl;
} }
JA_StopMusic(); JA_StopMusic();
loadResources(section); loadResources(options.section);
auto game = std::make_unique<Game>(resource_, options, section, debug_); auto game = std::make_unique<Game>(resource_, debug_);
game->run(); game->run();
resource_->free(); resource_->free();
} }
@@ -1844,9 +1422,9 @@ void Director::runGame()
int Director::run() int Director::run()
{ {
// Bucle principal // Bucle principal
while (section->name != SECTION_QUIT) while (options.section.name != SECTION_QUIT)
{ {
switch (section->name) switch (options.section.name)
{ {
case SECTION_LOGO: case SECTION_LOGO:
runLogo(); runLogo();

View File

@@ -21,34 +21,20 @@ private:
Resource *resource_; // Objeto con los recursos Resource *resource_; // Objeto con los recursos
Debug *debug_; // Objeto para gestionar la información de debug Debug *debug_; // Objeto para gestionar la información de debug
struct options_t *options; // Variable con todas las opciones del programa
section_t *section; // Sección y subsección actual del programa;
// Variables // Variables
JA_Music_t *title_music_; // Musica del titulo JA_Music_t *title_music_; // Musica del titulo
std::string executable_path_; // Path del ejecutable std::string executable_path_; // Path del ejecutable
std::string system_folder_; // Carpeta del sistema donde guardar datos std::string system_folder_; // Carpeta del sistema donde guardar datos
// Crea e inicializa las opciones del programa
void initOptions();
// Comprueba los parametros del programa // Comprueba los parametros del programa
void checkProgramArguments(int argc, const char *argv[]); void checkProgramArguments(int argc, const char *argv[]);
// Carga el fichero de configuración
bool loadConfig();
// Guarda el fichero de configuración
bool saveConfig();
// Crea la carpeta del sistema donde guardar datos // Crea la carpeta del sistema donde guardar datos
void createSystemFolder(const std::string &folder); void createSystemFolder(const 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
bool setOptions(options_t *options, std::string var, std::string value);
// Inicializa jail_audio // Inicializa jail_audio
void initJailAudio(); void initJailAudio();

View File

@@ -16,9 +16,10 @@
#include "text.h" // Para Text, TXT_STROKE #include "text.h" // Para Text, TXT_STROKE
#include "texture.h" // Para Texture #include "texture.h" // Para Texture
#include "utils.h" // Para color_t, stringToColor, options_t #include "utils.h" // Para color_t, stringToColor, options_t
#include "options.h"
// Constructor // Constructor
Ending::Ending(Resource *resource, options_t *options, section_t *section) Ending::Ending(Resource *resource)
{ {
// Copia los punteros // Copia los punteros
this->screen = Screen::get(); this->screen = Screen::get();
@@ -26,8 +27,6 @@ Ending::Ending(Resource *resource, options_t *options, section_t *section)
this->resource = resource; this->resource = resource;
this->asset = Asset::get(); this->asset = Asset::get();
this->input = Input::get(); this->input = Input::get();
this->options = options;
this->section = section;
// Reserva memoria para los punteros a objetos // Reserva memoria para los punteros a objetos
eventHandler = new SDL_Event(); eventHandler = new SDL_Event();
@@ -38,8 +37,8 @@ Ending::Ending(Resource *resource, options_t *options, section_t *section)
counter = -1; counter = -1;
preCounter = 0; preCounter = 0;
coverCounter = 0; coverCounter = 0;
section->name = SECTION_ENDING; options.section.name = SECTION_ENDING;
section->subsection = 0; options.section.subsection = 0;
ticks = 0; ticks = 0;
ticksSpeed = 15; ticksSpeed = 15;
scene = 0; scene = 0;
@@ -54,13 +53,13 @@ Ending::Ending(Resource *resource, options_t *options, section_t *section)
iniScenes(); iniScenes();
// Cambia el color del borde // Cambia el color del borde
screen->setBorderColor(stringToColor(options->palette, "black")); screen->setBorderColor(stringToColor(options.palette, "black"));
// Crea la textura para cubrir el rexto // Crea la textura para cubrir el rexto
coverTexture = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, GAMECANVAS_WIDTH, GAMECANVAS_HEIGHT + 8); coverTexture = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, GAMECANVAS_WIDTH, GAMECANVAS_HEIGHT + 8);
if (coverTexture == nullptr) if (coverTexture == nullptr)
{ {
if (options->console) if (options.console)
{ {
std::cout << "Error: canvasTexture could not be created!\nSDL Error: " << SDL_GetError() << std::endl; std::cout << "Error: canvasTexture could not be created!\nSDL Error: " << SDL_GetError() << std::endl;
} }
@@ -135,7 +134,7 @@ void Ending::render()
screen->start(); screen->start();
// Limpia la pantalla // Limpia la pantalla
screen->clean(stringToColor(options->palette, "black")); screen->clean(stringToColor(options.palette, "black"));
// Dibuja las imagenes de la escena // Dibuja las imagenes de la escena
spritePics[scene].sprite->render(); spritePics[scene].sprite->render();
@@ -169,7 +168,7 @@ void Ending::checkEvents()
// Evento de salida de la aplicación // Evento de salida de la aplicación
if (eventHandler->type == SDL_QUIT) if (eventHandler->type == SDL_QUIT)
{ {
section->name = SECTION_QUIT; options.section.name = SECTION_QUIT;
break; break;
} }
} }
@@ -181,8 +180,8 @@ void Ending::checkInput()
if (input->checkInput(input_exit, REPEAT_FALSE)) if (input->checkInput(input_exit, REPEAT_FALSE))
{ {
section->name = SECTION_LOGO; options.section.name = SECTION_LOGO;
section->subsection = SUBSECTION_LOGO_TO_INTRO; options.section.subsection = SUBSECTION_LOGO_TO_INTRO;
} }
else if (input->checkInput(input_toggle_border, REPEAT_FALSE)) else if (input->checkInput(input_toggle_border, REPEAT_FALSE))
@@ -261,7 +260,7 @@ void Ending::iniTexts()
endingTexture_t st; endingTexture_t st;
const int width = text->lenght(t.caption, 1) + 2 + 2; const int width = text->lenght(t.caption, 1) + 2 + 2;
const int height = text->getCharacterSize() + 2 + 2; const int height = text->getCharacterSize() + 2 + 2;
color_t c = stringToColor(options->palette, "black"); color_t c = stringToColor(options.palette, "black");
// Crea la texture // Crea la texture
st.texture = new Texture(renderer); st.texture = new Texture(renderer);
@@ -285,7 +284,7 @@ void Ending::iniTexts()
SDL_RenderClear(renderer); SDL_RenderClear(renderer);
// Los primeros 8 pixels crea una malla // Los primeros 8 pixels crea una malla
c = stringToColor(options->palette, "black"); c = stringToColor(options.palette, "black");
SDL_SetRenderDrawColor(renderer, c.r, c.g, c.b, 0xFF); SDL_SetRenderDrawColor(renderer, c.r, c.g, c.b, 0xFF);
for (int i = 0; i < width; i += 2) for (int i = 0; i < width; i += 2)
{ {
@@ -300,7 +299,7 @@ void Ending::iniTexts()
// El resto se rellena de color sólido // El resto se rellena de color sólido
SDL_Rect rect = {0, 8, width, height}; SDL_Rect rect = {0, 8, width, height};
c = stringToColor(options->palette, "black"); c = stringToColor(options.palette, "black");
SDL_SetRenderDrawColor(renderer, c.r, c.g, c.b, 0xFF); SDL_SetRenderDrawColor(renderer, c.r, c.g, c.b, 0xFF);
SDL_RenderFillRect(renderer, &rect); SDL_RenderFillRect(renderer, &rect);
@@ -323,7 +322,7 @@ void Ending::iniPics()
// Vector con las rutas y la posición // Vector con las rutas y la posición
std::vector<textAndPos_t> pics; std::vector<textAndPos_t> pics;
if (options->palette == p_zxspectrum) if (options.palette == p_zxspectrum)
{ {
pics.push_back({"ending1.png", 48}); pics.push_back({"ending1.png", 48});
pics.push_back({"ending2.png", 26}); pics.push_back({"ending2.png", 26});
@@ -373,7 +372,7 @@ void Ending::iniPics()
SDL_RenderClear(renderer); SDL_RenderClear(renderer);
// Los primeros 8 pixels crea una malla // Los primeros 8 pixels crea una malla
color_t c = stringToColor(options->palette, "black"); color_t c = stringToColor(options.palette, "black");
SDL_SetRenderDrawColor(renderer, c.r, c.g, c.b, 0xFF); SDL_SetRenderDrawColor(renderer, c.r, c.g, c.b, 0xFF);
for (int i = 0; i < width; i += 2) for (int i = 0; i < width; i += 2)
{ {
@@ -388,7 +387,7 @@ void Ending::iniPics()
// El resto se rellena de color sólido // El resto se rellena de color sólido
SDL_Rect rect = {0, 8, width, height}; SDL_Rect rect = {0, 8, width, height};
c = stringToColor(options->palette, "black"); c = stringToColor(options.palette, "black");
SDL_SetRenderDrawColor(renderer, c.r, c.g, c.b, 0xFF); SDL_SetRenderDrawColor(renderer, c.r, c.g, c.b, 0xFF);
SDL_RenderFillRect(renderer, &rect); SDL_RenderFillRect(renderer, &rect);
@@ -493,7 +492,7 @@ void Ending::run()
{ {
JA_PlayMusic(music); JA_PlayMusic(music);
while (section->name == SECTION_ENDING) while (options.section.name == SECTION_ENDING)
{ {
update(); update();
checkEvents(); checkEvents();
@@ -577,7 +576,7 @@ void Ending::checkChangeScene()
if (scene == 5) if (scene == 5)
{ {
// Termina el bucle // Termina el bucle
section->name = SECTION_ENDING2; options.section.name = SECTION_ENDING2;
// Mantiene los valores anteriores // Mantiene los valores anteriores
scene = 4; scene = 4;
@@ -595,7 +594,7 @@ void Ending::fillCoverTexture()
SDL_RenderClear(renderer); SDL_RenderClear(renderer);
// Los primeros 8 pixels crea una malla // Los primeros 8 pixels crea una malla
const color_t c = stringToColor(options->palette, "brack"); const color_t c = stringToColor(options.palette, "brack");
SDL_SetRenderDrawColor(renderer, c.r, c.g, c.b, 0xFF); SDL_SetRenderDrawColor(renderer, c.r, c.g, c.b, 0xFF);
for (int i = 0; i < 256; i += 2) for (int i = 0; i < 256; i += 2)
{ {
@@ -641,9 +640,9 @@ void Ending::updateMusicVolume()
// Cambia la paleta // Cambia la paleta
void Ending::switchPalette() void Ending::switchPalette()
{ {
if (options->palette == p_zxspectrum) if (options.palette == p_zxspectrum)
{ {
options->palette = p_zxarne; options.palette = p_zxarne;
spritePics[0].sprite->setTexture(resource->getTexture("ending1_zxarne.png")); spritePics[0].sprite->setTexture(resource->getTexture("ending1_zxarne.png"));
spritePics[1].sprite->setTexture(resource->getTexture("ending2_zxarne.png")); spritePics[1].sprite->setTexture(resource->getTexture("ending2_zxarne.png"));
@@ -653,7 +652,7 @@ void Ending::switchPalette()
} }
else else
{ {
options->palette = p_zxspectrum; options.palette = p_zxspectrum;
spritePics[0].sprite->setTexture(resource->getTexture("ending1.png")); spritePics[0].sprite->setTexture(resource->getTexture("ending1.png"));
spritePics[1].sprite->setTexture(resource->getTexture("ending2.png")); spritePics[1].sprite->setTexture(resource->getTexture("ending2.png"));

View File

@@ -55,11 +55,9 @@ private:
Resource *resource; // Objeto con los recursos Resource *resource; // Objeto con los recursos
Asset *asset; // Objeto con los ficheros de recursos Asset *asset; // Objeto con los ficheros de recursos
Input *input; // Objeto pata gestionar la entrada Input *input; // Objeto pata gestionar la entrada
options_t *options; // Puntero a las opciones del juego
SDL_Event *eventHandler; // Manejador de eventos SDL_Event *eventHandler; // Manejador de eventos
Text *text; // Objeto para escribir texto en pantalla Text *text; // Objeto para escribir texto en pantalla
SDL_Texture *coverTexture; // Textura para cubrir el texto SDL_Texture *coverTexture; // Textura para cubrir el texto
section_t *section; // Estado del bucle principal para saber si continua o se sale
// Variables // Variables
int counter; // Contador int counter; // Contador
@@ -117,7 +115,7 @@ private:
public: public:
// Constructor // Constructor
Ending(Resource *resource, options_t *options, section_t *section); Ending(Resource *resource);
// Destructor // Destructor
~Ending(); ~Ending();

View File

@@ -13,9 +13,10 @@
#include "text.h" // for Text #include "text.h" // for Text
#include "texture.h" // for Texture #include "texture.h" // for Texture
#include "utils.h" // for color_t, stringToColor, options_t #include "utils.h" // for color_t, stringToColor, options_t
#include "options.h"
// Constructor // Constructor
Ending2::Ending2(Resource *resource, options_t *options, section_t *section) Ending2::Ending2(Resource *resource)
{ {
// Copia los punteros // Copia los punteros
this->screen = Screen::get(); this->screen = Screen::get();
@@ -23,8 +24,6 @@ Ending2::Ending2(Resource *resource, options_t *options, section_t *section)
this->resource = resource; this->resource = resource;
this->asset = Asset::get(); this->asset = Asset::get();
this->input = Input::get(); this->input = Input::get();
this->options = options;
this->section = section;
// Reserva memoria para los punteros a objetos // Reserva memoria para los punteros a objetos
eventHandler = new SDL_Event(); eventHandler = new SDL_Event();
@@ -36,8 +35,8 @@ Ending2::Ending2(Resource *resource, options_t *options, section_t *section)
preCounter = 0; preCounter = 0;
postCounter = 0; postCounter = 0;
postCounterEnabled = false; postCounterEnabled = false;
section->name = SECTION_ENDING2; options.section.name = SECTION_ENDING2;
section->subsection = 0; options.section.subsection = 0;
ticks = 0; ticks = 0;
ticksSpeed = 15; ticksSpeed = 15;
distSpriteText = 8; distSpriteText = 8;
@@ -50,11 +49,11 @@ Ending2::Ending2(Resource *resource, options_t *options, section_t *section)
const std::vector<std::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));
} }
// Cambia el color del borde // Cambia el color del borde
screen->setBorderColor(stringToColor(options->palette, "black")); screen->setBorderColor(stringToColor(options.palette, "black"));
// Inicializa la lista de sprites // Inicializa la lista de sprites
iniSpriteList(); iniSpriteList();
@@ -130,7 +129,7 @@ void Ending2::render()
screen->start(); screen->start();
// Limpia la pantalla // Limpia la pantalla
screen->clean(stringToColor(options->palette, "black")); screen->clean(stringToColor(options.palette, "black"));
// Dibuja los sprites // Dibuja los sprites
renderSprites(); renderSprites();
@@ -199,7 +198,7 @@ void Ending2::checkEvents()
// Evento de salida de la aplicación // Evento de salida de la aplicación
if (eventHandler->type == SDL_QUIT) if (eventHandler->type == SDL_QUIT)
{ {
section->name = SECTION_QUIT; options.section.name = SECTION_QUIT;
break; break;
} }
} }
@@ -211,8 +210,8 @@ void Ending2::checkInput()
if (input->checkInput(input_exit, REPEAT_FALSE)) if (input->checkInput(input_exit, REPEAT_FALSE))
{ {
section->name = SECTION_LOGO; options.section.name = SECTION_LOGO;
section->subsection = SUBSECTION_LOGO_TO_INTRO; options.section.subsection = SUBSECTION_LOGO_TO_INTRO;
} }
else if (input->checkInput(input_toggle_border, REPEAT_FALSE)) else if (input->checkInput(input_toggle_border, REPEAT_FALSE))
@@ -246,7 +245,7 @@ void Ending2::run()
{ {
JA_PlayMusic(music); JA_PlayMusic(music);
while (section->name == SECTION_ENDING2) while (options.section.name == SECTION_ENDING2)
{ {
update(); update();
checkEvents(); checkEvents();
@@ -277,8 +276,8 @@ void Ending2::updateCounters()
if (postCounter > 600) if (postCounter > 600)
{ {
section->name = SECTION_LOGO; options.section.name = SECTION_LOGO;
section->subsection = SUBSECTION_LOGO_TO_INTRO; options.section.subsection = SUBSECTION_LOGO_TO_INTRO;
} }
} }
@@ -416,7 +415,7 @@ void Ending2::updateTexts()
// Dibuja los sprites // Dibuja los sprites
void Ending2::renderSprites() void Ending2::renderSprites()
{ {
const color_t color = stringToColor(options->palette, "red"); const color_t color = stringToColor(options.palette, "red");
for (auto sprite : sprites) for (auto sprite : sprites)
{ {
const bool a = sprite->getRect().y + sprite->getRect().h > 0; const bool a = sprite->getRect().y + sprite->getRect().h > 0;
@@ -429,7 +428,7 @@ void Ending2::renderSprites()
} }
// Pinta el ultimo elemento de otro color // Pinta el ultimo elemento de otro color
const color_t c = stringToColor(options->palette, "white"); const color_t c = stringToColor(options.palette, "white");
sprites.back()->getTexture()->setColor(c.r, c.g, c.b); sprites.back()->getTexture()->setColor(c.r, c.g, c.b);
sprites.back()->render(); sprites.back()->render();
} }
@@ -437,7 +436,7 @@ void Ending2::renderSprites()
// Dibuja los sprites con el texto // Dibuja los sprites con el texto
void Ending2::renderSpriteTexts() void Ending2::renderSpriteTexts()
{ {
const color_t color = stringToColor(options->palette, "white"); const color_t color = stringToColor(options.palette, "white");
for (auto sprite : spriteTexts) for (auto sprite : spriteTexts)
{ {
const bool a = sprite->getRect().y + sprite->getRect().h > 0; const bool a = sprite->getRect().y + sprite->getRect().h > 0;
@@ -644,5 +643,5 @@ void Ending2::updateMusicVolume()
// Cambia la paleta // Cambia la paleta
void Ending2::switchPalette() void Ending2::switchPalette()
{ {
options->palette = (options->palette == p_zxspectrum) ? p_zxarne : p_zxspectrum; options.palette = (options.palette == p_zxspectrum) ? p_zxarne : p_zxspectrum;
} }

View File

@@ -28,11 +28,9 @@ private:
SDL_Renderer *renderer; // El renderizador de la ventana SDL_Renderer *renderer; // El renderizador de la ventana
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
std::vector<AnimatedSprite *> sprites; // Vector con todos los sprites a dibujar std::vector<AnimatedSprite *> sprites; // Vector con todos los sprites a dibujar
std::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
std::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
// Variables // Variables
bool counterEnabled; // Indica si está el contador habilitado bool counterEnabled; // Indica si está el contador habilitado
@@ -120,7 +118,7 @@ private:
public: public:
// Constructor // Constructor
Ending2(Resource *resource, options_t *options, section_t *section); Ending2(Resource *resource);
// Destructor // Destructor
~Ending2(); ~Ending2();

View File

@@ -20,17 +20,16 @@
#include "stats.h" // for Stats #include "stats.h" // for Stats
#include "text.h" // for Text, TXT_CENTER, TXT_COLOR #include "text.h" // for Text, TXT_CENTER, TXT_COLOR
#include "utils.h" // for options_t, cheat_t, stringToColor #include "utils.h" // for options_t, cheat_t, stringToColor
#include "options.h"
// Constructor // Constructor
Game::Game(Resource *resource, options_t *options, section_t *section, Debug *debug) Game::Game(Resource *resource, Debug *debug)
: screen_(Screen::get()), : screen_(Screen::get()),
renderer_(Screen::get()->getRenderer()), renderer_(Screen::get()->getRenderer()),
asset_(Asset::get()), asset_(Asset::get()),
input_(Input::get()), input_(Input::get()),
resource_(resource), resource_(resource),
debug_(debug), debug_(debug)
options_(options),
section_(section)
{ {
// Inicia algunas variables // Inicia algunas variables
board_.iniClock = SDL_GetTicks(); board_.iniClock = SDL_GetTicks();
@@ -48,26 +47,26 @@ Game::Game(Resource *resource, options_t *options, section_t *section, Debug *de
#endif #endif
// Crea los objetos // Crea los objetos
cheevos_ = new Cheevos(screen_, options, asset_->get("cheevos.bin")); cheevos_ = new Cheevos(screen_, asset_->get("cheevos.bin"));
scoreboard_ = new ScoreBoard(renderer_, resource, asset_, options, &board_); scoreboard_ = new ScoreBoard(renderer_, resource, asset_, &board_);
item_tracker_ = new ItemTracker(); item_tracker_ = new ItemTracker();
room_tracker_ = new RoomTracker(); room_tracker_ = new RoomTracker();
room_ = new Room(resource->getRoom(current_room_), renderer_, screen_, asset_, options, item_tracker_, &board_.items, false, debug); room_ = new Room(resource->getRoom(current_room_), renderer_, screen_, asset_, item_tracker_, &board_.items, false, debug);
const std::string playerPNG = options->cheat.altSkin ? "player2.png" : "player.png"; const std::string playerPNG = options.cheat.altSkin ? "player2.png" : "player.png";
const std::string playerANI = options->cheat.altSkin ? "player2.ani" : "player.ani"; const std::string playerANI = options.cheat.altSkin ? "player2.ani" : "player.ani";
const player_t player = {spawn_point_, playerPNG, playerANI, renderer_, resource, asset_, options, input_, room_, debug}; const player_t player = {spawn_point_, playerPNG, playerANI, renderer_, resource, asset_, input_, room_, debug};
this->player_ = new Player(player); this->player_ = new Player(player);
event_handler_ = new SDL_Event(); event_handler_ = new SDL_Event();
text_ = new Text(resource->getOffset("smb2.txt"), resource->getTexture("smb2.png"), renderer_); text_ = new Text(resource->getOffset("smb2.txt"), resource->getTexture("smb2.png"), renderer_);
music_ = JA_LoadMusic(asset_->get("game.ogg").c_str()); music_ = JA_LoadMusic(asset_->get("game.ogg").c_str());
death_sound_ = JA_LoadSound(asset_->get("death.wav").c_str()); death_sound_ = JA_LoadSound(asset_->get("death.wav").c_str());
stats_ = new Stats(asset_->get("stats.csv"), asset_->get("stats_buffer.csv"), options); stats_ = new Stats(asset_->get("stats.csv"), asset_->get("stats_buffer.csv"));
// Crea la textura para poner el nombre de la habitación // Crea la textura para poner el nombre de la habitación
room_name_texture_ = SDL_CreateTexture(renderer_, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, GAMECANVAS_WIDTH, text_->getCharacterSize() * 2); room_name_texture_ = SDL_CreateTexture(renderer_, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, GAMECANVAS_WIDTH, text_->getCharacterSize() * 2);
if (room_name_texture_ == nullptr) if (room_name_texture_ == nullptr)
{ {
if (options->console) if (options.console)
{ {
std::cout << "Error: roomNameTexture could not be created!\nSDL Error: " << SDL_GetError() << std::endl; std::cout << "Error: roomNameTexture could not be created!\nSDL Error: " << SDL_GetError() << std::endl;
} }
@@ -92,7 +91,7 @@ Game::Game(Resource *resource, options_t *options, section_t *section, Debug *de
board_.items = 0; board_.items = 0;
board_.rooms = 1; board_.rooms = 1;
board_.music = true; board_.music = true;
board_.jailEnabled = options->cheat.jailEnabled; board_.jailEnabled = options.cheat.jailEnabled;
setScoreBoardColor(); setScoreBoardColor();
room_tracker_->addRoom(current_room_); room_tracker_->addRoom(current_room_);
paused_ = false; paused_ = false;
@@ -101,11 +100,11 @@ Game::Game(Resource *resource, options_t *options, section_t *section, Debug *de
total_items_ = getTotalItems(); total_items_ = getTotalItems();
initStats(); initStats();
stats_->addVisit(room_->getName()); stats_->addVisit(room_->getName());
const bool cheats = options->cheat.infiniteLives || options->cheat.invincible || options->cheat.jailEnabled; const bool cheats = options.cheat.infiniteLives || options.cheat.invincible || options.cheat.jailEnabled;
cheevos_->enable(!cheats); // Deshabilita los logros si hay trucos activados cheevos_->enable(!cheats); // Deshabilita los logros si hay trucos activados
section->name = SECTION_GAME; options.section.name = SECTION_GAME;
section->subsection = 0; options.section.subsection = 0;
} }
Game::~Game() Game::~Game()
@@ -136,8 +135,8 @@ void Game::checkEvents()
// Evento de salida de la aplicación // Evento de salida de la aplicación
if (event_handler_->type == SDL_QUIT) if (event_handler_->type == SDL_QUIT)
{ {
section_->name = SECTION_QUIT; options.section.name = SECTION_QUIT;
screen_->setBorderColor(stringToColor(options_->palette, "black")); screen_->setBorderColor(stringToColor(options.palette, "black"));
break; break;
} }
@@ -153,7 +152,7 @@ void Game::checkEvents()
#ifdef DEBUG #ifdef DEBUG
case SDL_SCANCODE_G: case SDL_SCANCODE_G:
debug_->switchEnabled(); debug_->switchEnabled();
options_->cheat.invincible = debug_->getEnabled(); options.cheat.invincible = debug_->getEnabled();
board_.music = !debug_->getEnabled(); board_.music = !debug_->getEnabled();
board_.music ? JA_ResumeMusic() : JA_PauseMusic(); board_.music ? JA_ResumeMusic() : JA_PauseMusic();
break; break;
@@ -206,7 +205,7 @@ void Game::checkInput()
{ {
if (input_->checkInput(input_exit, REPEAT_FALSE)) if (input_->checkInput(input_exit, REPEAT_FALSE))
{ {
section_->name = SECTION_TITLE; options.section.name = SECTION_TITLE;
} }
else if (input_->checkInput(input_toggle_music, REPEAT_FALSE)) else if (input_->checkInput(input_toggle_music, REPEAT_FALSE))
@@ -264,7 +263,7 @@ void Game::run()
JA_PauseMusic(); JA_PauseMusic();
} }
while (section_->name == SECTION_GAME) while (options.section.name == SECTION_GAME)
{ {
update(); update();
checkEvents(); checkEvents();
@@ -402,7 +401,7 @@ bool Game::changeRoom(std::string file)
room_ = nullptr; room_ = nullptr;
// Crea un objeto habitación nuevo a partir del fichero // Crea un objeto habitación nuevo a partir del fichero
room_ = new Room(resource_->getRoom(file), renderer_, screen_, asset_, options_, item_tracker_, &board_.items, board_.jailEnabled, debug_); room_ = new Room(resource_->getRoom(file), renderer_, screen_, asset_, item_tracker_, &board_.items, board_.jailEnabled, debug_);
// Pone el nombre de la habitación en la textura // Pone el nombre de la habitación en la textura
fillRoomNameTexture(); fillRoomNameTexture();
@@ -414,7 +413,7 @@ bool Game::changeRoom(std::string file)
{ {
// Incrementa el contador de habitaciones visitadas // Incrementa el contador de habitaciones visitadas
board_.rooms++; board_.rooms++;
options_->stats.rooms = board_.rooms; options.stats.rooms = board_.rooms;
// Actualiza las estadisticas // Actualiza las estadisticas
stats_->addVisit(room_->getName()); stats_->addVisit(room_->getName());
@@ -475,20 +474,20 @@ void Game::checkGameOver()
{ {
if (board_.lives < 0 && black_screen_counter_ > 17) if (board_.lives < 0 && black_screen_counter_ > 17)
{ {
section_->name = SECTION_GAME_OVER; options.section.name = SECTION_GAME_OVER;
} }
} }
// Mata al jugador // Mata al jugador
void Game::killPlayer() void Game::killPlayer()
{ {
if (options_->cheat.invincible) if (options.cheat.invincible)
{ {
return; return;
} }
// Resta una vida al jugador // Resta una vida al jugador
if (!options_->cheat.infiniteLives) if (!options.cheat.infiniteLives)
{ {
board_.lives--; board_.lives--;
} }
@@ -510,10 +509,10 @@ void Game::killPlayer()
setBlackScreen(); setBlackScreen();
// Crea la nueva habitación y el nuevo jugador // Crea la nueva habitación y el nuevo jugador
room_ = new Room(resource_->getRoom(current_room_), renderer_, screen_, asset_, options_, item_tracker_, &board_.items, board_.jailEnabled, debug_); room_ = new Room(resource_->getRoom(current_room_), renderer_, screen_, asset_, item_tracker_, &board_.items, board_.jailEnabled, debug_);
const std::string playerPNG = options_->cheat.altSkin ? "player2.png" : "player.png"; const std::string playerPNG = options.cheat.altSkin ? "player2.png" : "player.png";
const std::string playerANI = options_->cheat.altSkin ? "player2.ani" : "player.ani"; const std::string playerANI = options.cheat.altSkin ? "player2.ani" : "player.ani";
const player_t player = {spawn_point_, playerPNG, playerANI, renderer_, resource_, asset_, options_, input_, room_, debug_}; const player_t player = {spawn_point_, playerPNG, playerANI, renderer_, resource_, asset_, input_, room_, debug_};
this->player_ = new Player(player); this->player_ = new Player(player);
// Pone los objetos en pausa mientras esta la habitación en negro // Pone los objetos en pausa mientras esta la habitación en negro
@@ -524,7 +523,7 @@ void Game::killPlayer()
// Recarga todas las texturas // Recarga todas las texturas
void Game::reLoadTextures() void Game::reLoadTextures()
{ {
if (options_->console) if (options.console)
{ {
std::cout << "** RELOAD REQUESTED" << std::endl; std::cout << "** RELOAD REQUESTED" << std::endl;
} }
@@ -537,13 +536,13 @@ void Game::reLoadTextures()
// Cambia la paleta // Cambia la paleta
void Game::switchPalette() void Game::switchPalette()
{ {
if (options_->console) if (options.console)
{ {
std::cout << "** PALETTE SWITCH REQUESTED" << std::endl; std::cout << "** PALETTE SWITCH REQUESTED" << std::endl;
} }
// Modifica la variable // Modifica la variable
options_->palette = (options_->palette == p_zxspectrum) ? p_zxarne : p_zxspectrum; options.palette = (options.palette == p_zxspectrum) ? p_zxarne : p_zxspectrum;
// Recarga las paletas // Recarga las paletas
room_->reLoadPalette(); room_->reLoadPalette();
@@ -584,7 +583,7 @@ void Game::renderBlackScreen()
if (black_screen_) if (black_screen_)
{ {
screen_->clean(); screen_->clean();
screen_->setBorderColor(stringToColor(options_->palette, "black")); screen_->setBorderColor(stringToColor(options.palette, "black"));
} }
} }
@@ -594,18 +593,18 @@ void Game::setScoreBoardColor()
// Obtiene el color del borde // Obtiene el color del borde
const color_t colorBorder = room_->getBorderColor(); const color_t colorBorder = room_->getBorderColor();
const bool isBlack = colorAreEqual(colorBorder, stringToColor(options_->palette, "black")); const bool isBlack = colorAreEqual(colorBorder, stringToColor(options.palette, "black"));
const bool isBrightBlack = colorAreEqual(colorBorder, stringToColor(options_->palette, "bright_black")); const bool isBrightBlack = colorAreEqual(colorBorder, stringToColor(options.palette, "bright_black"));
// Si el color del borde es negro o negro brillante cambia el texto del marcador a blanco // Si el color del borde es negro o negro brillante cambia el texto del marcador a blanco
board_.color = isBlack || isBrightBlack ? stringToColor(options_->palette, "white") : colorBorder; board_.color = isBlack || isBrightBlack ? stringToColor(options.palette, "white") : colorBorder;
} }
// Comprueba si ha finalizado el juego // Comprueba si ha finalizado el juego
bool Game::checkEndGame() bool Game::checkEndGame()
{ {
const bool isOnTheRoom = room_->getName() == "THE JAIL"; // Estar en la habitación que toca const bool isOnTheRoom = room_->getName() == "THE JAIL"; // Estar en la habitación que toca
const bool haveTheItems = board_.items >= int(total_items_ * 0.9f) || options_->cheat.jailEnabled; // Con mas del 90% de los items recogidos const bool haveTheItems = board_.items >= int(total_items_ * 0.9f) || options.cheat.jailEnabled; // Con mas del 90% de los items recogidos
const bool isOnTheDoor = player_->getRect().x <= 128; // Y en la ubicación que toca (En la puerta) const bool isOnTheDoor = player_->getRect().x <= 128; // Y en la ubicación que toca (En la puerta)
if (haveTheItems) if (haveTheItems)
@@ -618,7 +617,7 @@ bool Game::checkEndGame()
// Comprueba los logros de completar el juego // Comprueba los logros de completar el juego
checkEndGameCheevos(); checkEndGameCheevos();
section_->name = SECTION_ENDING; options.section.name = SECTION_ENDING;
return true; return true;
} }
@@ -721,7 +720,7 @@ void Game::fillRoomNameTexture()
SDL_SetRenderTarget(renderer_, room_name_texture_); SDL_SetRenderTarget(renderer_, room_name_texture_);
// Rellena la textura de color // Rellena la textura de color
const color_t color = stringToColor(options_->palette, "white"); const color_t color = stringToColor(options.palette, "white");
SDL_SetRenderDrawColor(renderer_, color.r, color.g, color.b, 0xFF); SDL_SetRenderDrawColor(renderer_, color.r, color.g, color.b, 0xFF);
SDL_RenderClear(renderer_); SDL_RenderClear(renderer_);

View File

@@ -41,10 +41,8 @@ private:
Cheevos *cheevos_; // Objeto encargado de gestionar los logros del juego Cheevos *cheevos_; // Objeto encargado de gestionar los logros del juego
Resource *resource_; // Objeto con los recursos Resource *resource_; // Objeto con los recursos
Debug *debug_; // Objeto para gestionar la información de debug Debug *debug_; // Objeto para gestionar la información de debug
options_t *options_; // Puntero a las opciones del juego
Stats *stats_; // Objeto encargado de gestionar las estadísticas Stats *stats_; // Objeto encargado de gestionar las estadísticas
SDL_Texture *room_name_texture_; // Textura para escribir el nombre de la habitación SDL_Texture *room_name_texture_; // Textura para escribir el nombre de la habitación
section_t *section_; // Seccion actual dentro del juego
// Variables // Variables
JA_Music_t *music_; // Musica que suena durante el juego JA_Music_t *music_; // Musica que suena durante el juego
@@ -151,7 +149,7 @@ private:
public: public:
// Constructor // Constructor
Game(Resource *resource, options_t *options, section_t *section, Debug *debug); Game(Resource *resource, Debug *debug);
// Destructor // Destructor
~Game(); ~Game();

View File

@@ -11,9 +11,10 @@
#include "screen.h" // Para Screen #include "screen.h" // Para Screen
#include "text.h" // Para Text, TXT_CENTER, TXT_COLOR #include "text.h" // Para Text, TXT_CENTER, TXT_COLOR
#include "texture.h" // Para Texture #include "texture.h" // Para Texture
#include "options.h"
// Constructor // Constructor
GameOver::GameOver(Resource *resource, options_t *options, section_t *section) GameOver::GameOver(Resource *resource)
{ {
// Copia los punteros // Copia los punteros
this->screen = Screen::get(); this->screen = Screen::get();
@@ -21,8 +22,6 @@ GameOver::GameOver(Resource *resource, options_t *options, section_t *section)
this->resource = resource; this->resource = resource;
this->asset = Asset::get(); this->asset = Asset::get();
this->input = Input::get(); this->input = Input::get();
this->options = options;
this->section = section;
// Reserva memoria para los punteros a objetos // Reserva memoria para los punteros a objetos
eventHandler = new SDL_Event(); eventHandler = new SDL_Event();
@@ -34,8 +33,8 @@ GameOver::GameOver(Resource *resource, options_t *options, section_t *section)
// Inicializa variables // Inicializa variables
preCounter = 0; preCounter = 0;
counter = 0; counter = 0;
section->name = SECTION_GAME_OVER; options.section.name = SECTION_GAME_OVER;
section->subsection = 0; options.section.subsection = 0;
ticks = 0; ticks = 0;
ticksSpeed = 15; ticksSpeed = 15;
endSection = 400; endSection = 400;
@@ -50,7 +49,7 @@ GameOver::GameOver(Resource *resource, options_t *options, section_t *section)
const std::vector<std::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));
} }
color = colors.back(); color = colors.back();
} }
@@ -113,14 +112,14 @@ void GameOver::render()
renderSprites(); renderSprites();
// Escribe el texto con las habitaciones y los items // Escribe el texto con las habitaciones y los items
const std::string itemsTxt = std::to_string(options->stats.items / 100) + std::to_string((options->stats.items % 100) / 10) + std::to_string(options->stats.items % 10); const std::string itemsTxt = std::to_string(options.stats.items / 100) + std::to_string((options.stats.items % 100) / 10) + std::to_string(options.stats.items % 10);
const std::string roomsTxt = std::to_string(options->stats.rooms / 100) + std::to_string((options->stats.rooms % 100) / 10) + std::to_string(options->stats.rooms % 10); 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);
// Escribe el texto con "Tu peor pesadilla" // Escribe el texto con "Tu peor pesadilla"
text->writeDX(TXT_CENTER | TXT_COLOR, GAMECANVAS_CENTER_X, y + 110, "YOUR WORST NIGHTMARE IS", 1, color); text->writeDX(TXT_CENTER | TXT_COLOR, GAMECANVAS_CENTER_X, y + 110, "YOUR WORST NIGHTMARE IS", 1, color);
text->writeDX(TXT_CENTER | TXT_COLOR, GAMECANVAS_CENTER_X, y + 120, options->stats.worstNightmare, 1, color); text->writeDX(TXT_CENTER | TXT_COLOR, GAMECANVAS_CENTER_X, y + 120, options.stats.worstNightmare, 1, color);
// Vuelca el contenido del renderizador en pantalla // Vuelca el contenido del renderizador en pantalla
screen->render(); screen->render();
@@ -135,8 +134,8 @@ void GameOver::checkEvents()
// Evento de salida de la aplicación // Evento de salida de la aplicación
if (eventHandler->type == SDL_QUIT) if (eventHandler->type == SDL_QUIT)
{ {
section->name = SECTION_QUIT; options.section.name = SECTION_QUIT;
section->subsection = 0; options.section.subsection = 0;
break; break;
} }
} }
@@ -148,7 +147,7 @@ void GameOver::checkInput()
if (input->checkInput(input_exit, REPEAT_FALSE)) if (input->checkInput(input_exit, REPEAT_FALSE))
{ {
section->name = SECTION_QUIT; options.section.name = SECTION_QUIT;
} }
else if (input->checkInput(input_toggle_border, REPEAT_FALSE)) else if (input->checkInput(input_toggle_border, REPEAT_FALSE))
@@ -180,7 +179,7 @@ void GameOver::checkInput()
// Bucle principal // Bucle principal
void GameOver::run() void GameOver::run()
{ {
while (section->name == SECTION_GAME_OVER) while (options.section.name == SECTION_GAME_OVER)
{ {
update(); update();
checkEvents(); checkEvents();
@@ -239,13 +238,13 @@ void GameOver::updateCounters()
// Comprueba si ha terminado la sección // Comprueba si ha terminado la sección
else if (counter == endSection) else if (counter == endSection)
{ {
section->name = SECTION_LOGO; options.section.name = SECTION_LOGO;
section->subsection = SUBSECTION_LOGO_TO_TITLE; options.section.subsection = SUBSECTION_LOGO_TO_TITLE;
} }
} }
// Cambia la paleta // Cambia la paleta
void GameOver::switchPalette() void GameOver::switchPalette()
{ {
options->palette = (options->palette == p_zxspectrum) ? p_zxarne : p_zxspectrum; options.palette = (options.palette == p_zxspectrum) ? p_zxarne : p_zxspectrum;
} }

View File

@@ -22,12 +22,10 @@ private:
Resource *resource; // Objeto con los recursos Resource *resource; // Objeto con los recursos
Asset *asset; // Objeto con los ficheros de recursos Asset *asset; // Objeto con los ficheros de recursos
Input *input; // Objeto pata gestionar la entrada Input *input; // Objeto pata gestionar la entrada
options_t *options; // Puntero a las opciones del juego
SDL_Event *eventHandler; // Manejador de eventos SDL_Event *eventHandler; // Manejador de eventos
Text *text; // Objeto para escribir texto en pantalla Text *text; // Objeto para escribir texto en pantalla
AnimatedSprite *playerSprite; // Sprite con el jugador AnimatedSprite *playerSprite; // Sprite con el jugador
AnimatedSprite *tvSprite; // Sprite con el televisor AnimatedSprite *tvSprite; // Sprite con el televisor
section_t *section; // Estado del bucle principal para saber si continua o se sale
// Variables // Variables
int preCounter; // Contador previo int preCounter; // Contador previo
@@ -67,7 +65,7 @@ private:
public: public:
// Constructor // Constructor
GameOver(Resource *resource, options_t *options, section_t *section); GameOver(Resource *resource);
// Destructor // Destructor
~GameOver(); ~GameOver();

View File

@@ -10,26 +10,24 @@
#include "sprite.h" // for Sprite #include "sprite.h" // for Sprite
#include "texture.h" // for Texture #include "texture.h" // for Texture
#include "utils.h" // for options_t, section_t, color_t, stringToC... #include "utils.h" // for options_t, section_t, color_t, stringToC...
#include "options.h"
// Constructor // Constructor
LoadingScreen::LoadingScreen(Resource *resource, options_t *options, section_t *section) LoadingScreen::LoadingScreen(Resource *resource)
: screen_(Screen::get()), : screen_(Screen::get()),
renderer_(Screen::get()->getRenderer()), renderer_(Screen::get()->getRenderer()),
resource_(resource), resource_(resource),
asset_(Asset::get()), asset_(Asset::get()),
input_(Input::get()), input_(Input::get())
options_(options),
section_(section)
{ {
// Reserva memoria para los punteros // Reserva memoria para los punteros
eventHandler = new SDL_Event(); eventHandler = new SDL_Event();
if (options->palette == p_zxspectrum) if (options.palette == p_zxspectrum)
{ {
mono_loading_screen_texture_ = resource->getTexture("loading_screen_bn.png"); mono_loading_screen_texture_ = resource->getTexture("loading_screen_bn.png");
color_loading_screen_texture_ = resource->getTexture("loading_screen_color.png"); color_loading_screen_texture_ = resource->getTexture("loading_screen_color.png");
} }
else if (options->palette == p_zxarne) else if (options.palette == p_zxarne)
{ {
mono_loading_screen_texture_ = resource->getTexture("loading_screen_bn_zxarne.png"); mono_loading_screen_texture_ = resource->getTexture("loading_screen_bn_zxarne.png");
color_loading_screen_texture_ = resource->getTexture("loading_screen_color_zxarne.png"); color_loading_screen_texture_ = resource->getTexture("loading_screen_color_zxarne.png");
@@ -41,8 +39,8 @@ LoadingScreen::LoadingScreen(Resource *resource, options_t *options, section_t *
loading_sound3_ = JA_LoadMusic(asset_->get("loading_sound3.ogg").c_str()); loading_sound3_ = JA_LoadMusic(asset_->get("loading_sound3.ogg").c_str());
// Inicializa variables // Inicializa variables
section->name = SECTION_LOADING_SCREEN; options.section.name = SECTION_LOADING_SCREEN;
section->subsection = 0; options.section.subsection = 0;
// Establece el orden de las lineas para imitar el direccionamiento de memoria del spectrum // Establece el orden de las lineas para imitar el direccionamiento de memoria del spectrum
for (int i = 0; i < 192; ++i) for (int i = 0; i < 192; ++i)
@@ -64,7 +62,7 @@ LoadingScreen::LoadingScreen(Resource *resource, options_t *options, section_t *
} }
// Cambia el color del borde // Cambia el color del borde
screen_->setBorderColor(stringToColor(options->palette, "black")); screen_->setBorderColor(stringToColor(options.palette, "black"));
} }
// Destructor // Destructor
@@ -87,7 +85,7 @@ void LoadingScreen::checkEvents()
// Evento de salida de la aplicación // Evento de salida de la aplicación
if (eventHandler->type == SDL_QUIT) if (eventHandler->type == SDL_QUIT)
{ {
section_->name = SECTION_QUIT; options.section.name = SECTION_QUIT;
break; break;
} }
} }
@@ -99,7 +97,7 @@ void LoadingScreen::checkInput()
if (input_->checkInput(input_exit, REPEAT_FALSE)) if (input_->checkInput(input_exit, REPEAT_FALSE))
{ {
section_->name = SECTION_QUIT; options.section.name = SECTION_QUIT;
} }
else if (input_->checkInput(input_toggle_border, REPEAT_FALSE)) else if (input_->checkInput(input_toggle_border, REPEAT_FALSE))
@@ -129,8 +127,8 @@ void LoadingScreen::checkInput()
else if (input_->checkInput(input_pause, REPEAT_FALSE) || input_->checkInput(input_accept, REPEAT_FALSE) || input_->checkInput(input_jump, REPEAT_FALSE)) else if (input_->checkInput(input_pause, REPEAT_FALSE) || input_->checkInput(input_accept, REPEAT_FALSE) || input_->checkInput(input_jump, REPEAT_FALSE))
{ {
section_->name = SECTION_TITLE; options.section.name = SECTION_TITLE;
section_->subsection = 0; options.section.subsection = 0;
} }
} }
@@ -175,8 +173,8 @@ void LoadingScreen::updateLoad()
// Comprueba si ha terminado la intro // Comprueba si ha terminado la intro
if (load_counter_ >= 768) if (load_counter_ >= 768)
{ {
section_->name = SECTION_TITLE; options.section.name = SECTION_TITLE;
section_->subsection = SUBSECTION_TITLE_WITH_LOADING_SCREEN; options.section.subsection = SUBSECTION_TITLE_WITH_LOADING_SCREEN;
JA_StopMusic(); JA_StopMusic();
} }
} }
@@ -203,15 +201,15 @@ void LoadingScreen::renderLoad()
void LoadingScreen::renderBorder() void LoadingScreen::renderBorder()
{ {
// Pinta el borde de colro azul // Pinta el borde de colro azul
color_t color = stringToColor(options_->palette, "blue"); color_t color = stringToColor(options.palette, "blue");
SDL_SetRenderDrawColor(renderer_, color.r, color.g, color.b, 0xFF); SDL_SetRenderDrawColor(renderer_, color.r, color.g, color.b, 0xFF);
SDL_RenderClear(renderer_); SDL_RenderClear(renderer_);
// Añade lineas amarillas // Añade lineas amarillas
color = stringToColor(options_->palette, "yellow"); color = stringToColor(options.palette, "yellow");
SDL_SetRenderDrawColor(renderer_, color.r, color.g, color.b, 0xFF); SDL_SetRenderDrawColor(renderer_, color.r, color.g, color.b, 0xFF);
const int width = GAMECANVAS_WIDTH + (options_->borderWidth * 2); const int width = GAMECANVAS_WIDTH + (options.borderWidth * 2);
const int height = GAMECANVAS_HEIGHT + (options_->borderHeight * 2); const int height = GAMECANVAS_HEIGHT + (options.borderHeight * 2);
bool drawEnabled = rand() % 2 == 0 ? true : false; bool drawEnabled = rand() % 2 == 0 ? true : false;
// Para (int i = 0; i < height; ++i) // Para (int i = 0; i < height; ++i)
//{ //{
@@ -261,7 +259,7 @@ void LoadingScreen::update()
// Dibuja en pantalla // Dibuja en pantalla
void LoadingScreen::render() void LoadingScreen::render()
{ {
if (options_->borderEnabled) if (options.borderEnabled)
{ {
// Prepara para empezar a dibujar en la textura del borde // Prepara para empezar a dibujar en la textura del borde
screen_->startDrawOnBorder(); screen_->startDrawOnBorder();
@@ -292,7 +290,7 @@ void LoadingScreen::run()
screen_->clean(); screen_->clean();
screen_->render(); screen_->render();
while (section_->name == SECTION_LOADING_SCREEN) while (options.section.name == SECTION_LOADING_SCREEN)
{ {
update(); update();
checkEvents(); checkEvents();
@@ -305,15 +303,15 @@ void LoadingScreen::run()
// Cambia la paleta // Cambia la paleta
void LoadingScreen::switchPalette() void LoadingScreen::switchPalette()
{ {
if (options_->palette == p_zxspectrum) if (options.palette == p_zxspectrum)
{ {
options_->palette = p_zxarne; options.palette = p_zxarne;
mono_loading_screen_sprite_->setTexture(resource_->getTexture("loading_screen_bn_zxarne.png")); mono_loading_screen_sprite_->setTexture(resource_->getTexture("loading_screen_bn_zxarne.png"));
color_loading_screen_sprite_->setTexture(resource_->getTexture("loading_screen_color_zxarne.png")); color_loading_screen_sprite_->setTexture(resource_->getTexture("loading_screen_color_zxarne.png"));
} }
else else
{ {
options_->palette = p_zxspectrum; options.palette = p_zxspectrum;
mono_loading_screen_sprite_->setTexture(resource_->getTexture("loading_screen_bn.png")); mono_loading_screen_sprite_->setTexture(resource_->getTexture("loading_screen_bn.png"));
color_loading_screen_sprite_->setTexture(resource_->getTexture("loading_screen_color.png")); color_loading_screen_sprite_->setTexture(resource_->getTexture("loading_screen_color.png"));
} }

View File

@@ -28,8 +28,6 @@ private:
SDL_Event *eventHandler; // Manejador de eventos SDL_Event *eventHandler; // Manejador de eventos
Sprite *mono_loading_screen_sprite_; // Sprite para manejar la textura loadingScreenTexture1 Sprite *mono_loading_screen_sprite_; // Sprite para manejar la textura loadingScreenTexture1
Sprite *color_loading_screen_sprite_; // Sprite para manejar la textura loadingScreenTexture2 Sprite *color_loading_screen_sprite_; // Sprite para manejar la textura loadingScreenTexture2
options_t *options_; // Puntero a las opciones del juego
section_t *section_; // Estado del bucle principal para saber si continua o se sale
// Variables // Variables
int pre_counter_ = 0; // Contador previo para realizar una pausa inicial int pre_counter_ = 0; // Contador previo para realizar una pausa inicial
@@ -76,7 +74,7 @@ private:
public: public:
// Constructor // Constructor
LoadingScreen(Resource *resource, options_t *options, section_t *section); LoadingScreen(Resource *resource);
// Destructor // Destructor
~LoadingScreen(); ~LoadingScreen();

View File

@@ -10,17 +10,16 @@
#include "texture.h" // for Texture #include "texture.h" // for Texture
#include "utils.h" // for color_t, section_t, options_t, stringToC... #include "utils.h" // for color_t, section_t, options_t, stringToC...
#include "asset.h" #include "asset.h"
#include "options.h"
class Asset; // lines 11-11 class Asset; // lines 11-11
// Constructor // Constructor
Logo::Logo(Resource *resource, options_t *options, section_t *section) Logo::Logo(Resource *resource)
: screen_(Screen::get()), : screen_(Screen::get()),
renderer_(Screen::get()->getRenderer()), renderer_(Screen::get()->getRenderer()),
resource_(resource), resource_(resource),
asset_(Asset::get()), asset_(Asset::get()),
input_(Input::get()), input_(Input::get())
options_(options),
section_(section)
{ {
// Reserva memoria para los punteros // Reserva memoria para los punteros
event_handler_ = new SDL_Event(); event_handler_ = new SDL_Event();
@@ -47,17 +46,17 @@ Logo::Logo(Resource *resource, options_t *options, section_t *section)
} }
// Inicializa variables // Inicializa variables
section->name = SECTION_LOGO; options.section.name = SECTION_LOGO;
// Inicializa el vector de colores // Inicializa el vector de colores
const std::vector<std::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));
} }
// Cambia el color del borde // Cambia el color del borde
screen_->setBorderColor(stringToColor(options->palette, "black")); screen_->setBorderColor(stringToColor(options.palette, "black"));
} }
// Destructor // Destructor
@@ -81,7 +80,7 @@ void Logo::checkEvents()
// Evento de salida de la aplicación // Evento de salida de la aplicación
if (event_handler_->type == SDL_QUIT) if (event_handler_->type == SDL_QUIT)
{ {
section_->name = SECTION_QUIT; options.section.name = SECTION_QUIT;
break; break;
} }
} }
@@ -92,7 +91,7 @@ void Logo::checkInput()
{ {
if (input_->checkInput(input_exit, REPEAT_FALSE)) if (input_->checkInput(input_exit, REPEAT_FALSE))
{ {
section_->name = SECTION_TITLE; options.section.name = SECTION_TITLE;
} }
else if (input_->checkInput(input_toggle_border, REPEAT_FALSE)) else if (input_->checkInput(input_toggle_border, REPEAT_FALSE))
@@ -122,7 +121,7 @@ void Logo::checkInput()
else if (input_->checkInput(input_pause, REPEAT_FALSE) || input_->checkInput(input_accept, REPEAT_FALSE) || input_->checkInput(input_jump, REPEAT_FALSE)) else if (input_->checkInput(input_pause, REPEAT_FALSE) || input_->checkInput(input_accept, REPEAT_FALSE) || input_->checkInput(input_jump, REPEAT_FALSE))
{ {
section_->subsection = SUBSECTION_LOGO_TO_TITLE; options.section.subsection = SUBSECTION_LOGO_TO_TITLE;
endSection(); endSection();
} }
} }
@@ -306,7 +305,7 @@ void Logo::run()
// Detiene la música // Detiene la música
JA_StopMusic(); JA_StopMusic();
while (section_->name == SECTION_LOGO) while (options.section.name == SECTION_LOGO)
{ {
update(); update();
checkEvents(); checkEvents();
@@ -317,19 +316,19 @@ void Logo::run()
// Cambia la paleta // Cambia la paleta
void Logo::switchPalette() void Logo::switchPalette()
{ {
options_->palette = options_->palette == p_zxspectrum ? p_zxarne : p_zxspectrum; options.palette = options.palette == p_zxspectrum ? p_zxarne : p_zxspectrum;
} }
// Termina la sección // Termina la sección
void Logo::endSection() void Logo::endSection()
{ {
if (section_->subsection == SUBSECTION_LOGO_TO_TITLE) if (options.section.subsection == SUBSECTION_LOGO_TO_TITLE)
{ {
section_->name = SECTION_TITLE; options.section.name = SECTION_TITLE;
} }
else if (section_->subsection == SUBSECTION_LOGO_TO_INTRO) else if (options.section.subsection == SUBSECTION_LOGO_TO_INTRO)
{ {
section_->name = SECTION_LOADING_SCREEN; options.section.name = SECTION_LOADING_SCREEN;
} }
} }

View File

@@ -28,8 +28,6 @@ private:
SDL_Event *event_handler_; // Manejador de eventos SDL_Event *event_handler_; // Manejador de eventos
std::vector<Sprite *> jailgames_sprite_; // Vector con los sprites de cada linea que forman el bitmap JAILGAMES std::vector<Sprite *> jailgames_sprite_; // Vector con los sprites de cada linea que forman el bitmap JAILGAMES
Sprite *since_1998_sprite_; // Sprite para manejar la textura2 Sprite *since_1998_sprite_; // Sprite para manejar la textura2
options_t *options_; // Puntero a las opciones del juego
section_t *section_; // Estado del bucle principal para saber si continua o se sale
// Variables // Variables
std::vector<color_t> color_; // Vector con los colores para el fade std::vector<color_t> color_; // Vector con los colores para el fade
@@ -66,7 +64,7 @@ private:
public: public:
// Constructor // Constructor
Logo(Resource *resource, options_t *options, section_t *section); Logo(Resource *resource);
// Destructor // Destructor
~Logo(); ~Logo();

View File

@@ -6,14 +6,15 @@
#include "text.h" // Para Text #include "text.h" // Para Text
#include "texture.h" // Para Texture #include "texture.h" // Para Texture
#include "screen.h" #include "screen.h"
#include "options.h"
// [SINGLETON] // [SINGLETON]
Notifier *Notifier::notifier_ = nullptr; Notifier *Notifier::notifier_ = nullptr;
// [SINGLETON] Crearemos el objeto con esta función estática // [SINGLETON] Crearemos el objeto con esta función estática
void Notifier::init(std::string iconFile, std::string bitmapFile, std::string textFile, std::string soundFile, options_t *options) void Notifier::init(std::string iconFile, std::string bitmapFile, std::string textFile, std::string soundFile)
{ {
Notifier::notifier_ = new Notifier(iconFile, bitmapFile, textFile, soundFile, options); Notifier::notifier_ = new Notifier(iconFile, bitmapFile, textFile, soundFile);
} }
// [SINGLETON] Destruiremos el objeto con esta función estática // [SINGLETON] Destruiremos el objeto con esta función estática
@@ -29,31 +30,30 @@ Notifier *Notifier::get()
} }
// Constructor // Constructor
Notifier::Notifier(std::string iconFile, std::string bitmapFile, std::string textFile, std::string soundFile, options_t *options) Notifier::Notifier(std::string iconFile, std::string bitmapFile, std::string textFile, std::string soundFile)
{ {
// Inicializa variables // Inicializa variables
this->renderer = Screen::get()->getRenderer(); renderer_ = Screen::get()->getRenderer();
this->options = options; bg_color_ = options.notifications.color;
bgColor = options->notifications.color; wait_time_ = 300;
waitTime = 300;
// Crea objetos // Crea objetos
iconTexture = new Texture(renderer, iconFile); icon_texture_ = new Texture(renderer_, iconFile);
textTexture = new Texture(renderer, bitmapFile); text_texture_ = new Texture(renderer_, bitmapFile);
text = new Text(textFile, textTexture, renderer); text_ = new Text(textFile, text_texture_, renderer_);
sound = JA_LoadSound(soundFile.c_str()); sound_ = JA_LoadSound(soundFile.c_str());
} }
// Destructor // Destructor
Notifier::~Notifier() Notifier::~Notifier()
{ {
// Libera la memoria de los objetos // Libera la memoria de los objetos
delete textTexture; delete text_texture_;
delete iconTexture; delete icon_texture_;
delete text; delete text_;
JA_DeleteSound(sound); JA_DeleteSound(sound_);
for (auto notification : notifications) for (auto notification : notifications_)
{ {
delete notification.sprite; delete notification.sprite;
delete notification.texture; delete notification.texture;
@@ -63,95 +63,95 @@ Notifier::~Notifier()
// Dibuja las notificaciones por pantalla // Dibuja las notificaciones por pantalla
void Notifier::render() void Notifier::render()
{ {
for (int i = (int)notifications.size() - 1; i >= 0; --i) for (int i = (int)notifications_.size() - 1; i >= 0; --i)
{ {
notifications[i].sprite->render(); notifications_[i].sprite->render();
} }
} }
// Actualiza el estado de las notificaiones // Actualiza el estado de las notificaiones
void Notifier::update() void Notifier::update()
{ {
for (int i = 0; i < (int)notifications.size(); ++i) for (int i = 0; i < (int)notifications_.size(); ++i)
{ {
// Si la notificación anterior está "saliendo", no hagas nada // Si la notificación anterior está "saliendo", no hagas nada
if (i > 0) if (i > 0)
{ {
if (notifications[i - 1].state == ns_rising) if (notifications_[i - 1].state == ns_rising)
{ {
break; break;
} }
} }
notifications[i].counter++; notifications_[i].counter++;
// Hace sonar la notificación en el primer frame // Hace sonar la notificación en el primer frame
if (notifications[i].counter == 1) if (notifications_[i].counter == 1)
{ {
if (options->notifications.sound) if (options.notifications.sound)
{ {
if (notifications[i].state == ns_rising) if (notifications_[i].state == ns_rising)
{ // Reproduce el sonido de la notificación { // Reproduce el sonido de la notificación
JA_PlaySound(sound); JA_PlaySound(sound_);
} }
} }
} }
// Comprueba los estados // Comprueba los estados
if (notifications[i].state == ns_rising) if (notifications_[i].state == ns_rising)
{ {
const float step = ((float)notifications[i].counter / notifications[i].travelDist); const float step = ((float)notifications_[i].counter / notifications_[i].travelDist);
const int alpha = 255 * step; const int alpha = 255 * step;
if (options->notifications.posV == pos_top) if (options.notifications.posV == pos_top)
{ {
notifications[i].rect.y++; notifications_[i].rect.y++;
} }
else else
{ {
notifications[i].rect.y--; notifications_[i].rect.y--;
} }
notifications[i].texture->setAlpha(alpha); notifications_[i].texture->setAlpha(alpha);
if (notifications[i].rect.y == notifications[i].y) if (notifications_[i].rect.y == notifications_[i].y)
{ {
notifications[i].state = ns_stay; notifications_[i].state = ns_stay;
notifications[i].texture->setAlpha(255); notifications_[i].texture->setAlpha(255);
notifications[i].counter = 0; notifications_[i].counter = 0;
} }
} }
else if (notifications[i].state == ns_stay) else if (notifications_[i].state == ns_stay)
{ {
if (notifications[i].counter == waitTime) if (notifications_[i].counter == wait_time_)
{ {
notifications[i].state = ns_vanishing; notifications_[i].state = ns_vanishing;
notifications[i].counter = 0; notifications_[i].counter = 0;
} }
} }
else if (notifications[i].state == ns_vanishing) else if (notifications_[i].state == ns_vanishing)
{ {
const float step = (notifications[i].counter / (float)notifications[i].travelDist); const float step = (notifications_[i].counter / (float)notifications_[i].travelDist);
const int alpha = 255 * (1 - step); const int alpha = 255 * (1 - step);
if (options->notifications.posV == pos_top) if (options.notifications.posV == pos_top)
{ {
notifications[i].rect.y--; notifications_[i].rect.y--;
} }
else else
{ {
notifications[i].rect.y++; notifications_[i].rect.y++;
} }
notifications[i].texture->setAlpha(alpha); notifications_[i].texture->setAlpha(alpha);
if (notifications[i].rect.y == notifications[i].y - notifications[i].travelDist) if (notifications_[i].rect.y == notifications_[i].y - notifications_[i].travelDist)
{ {
notifications[i].state = ns_finished; notifications_[i].state = ns_finished;
} }
} }
notifications[i].sprite->setRect(notifications[i].rect); notifications_[i].sprite->setRect(notifications_[i].rect);
} }
clearFinishedNotifications(); clearFinishedNotifications();
@@ -160,13 +160,13 @@ void Notifier::update()
// Elimina las notificaciones finalizadas // Elimina las notificaciones finalizadas
void Notifier::clearFinishedNotifications() void Notifier::clearFinishedNotifications()
{ {
for (int i = (int)notifications.size() - 1; i >= 0; --i) for (int i = (int)notifications_.size() - 1; i >= 0; --i)
{ {
if (notifications[i].state == ns_finished) if (notifications_[i].state == ns_finished)
{ {
delete notifications[i].sprite; delete notifications_[i].sprite;
delete notifications[i].texture; delete notifications_[i].texture;
notifications.erase(notifications.begin() + i); notifications_.erase(notifications_.begin() + i);
} }
} }
} }
@@ -176,49 +176,49 @@ void Notifier::showText(std::string text1, std::string text2, int icon)
{ {
// Inicializa variables // Inicializa variables
const int iconSize = 16; const int iconSize = 16;
const int padding = text->getCharacterSize(); const int padding = text_->getCharacterSize();
const int iconSpace = icon >= 0 ? iconSize + padding : 0; const int iconSpace = icon >= 0 ? iconSize + padding : 0;
const std::string txt = text1.length() > text2.length() ? text1 : text2; const std::string txt = text1.length() > text2.length() ? text1 : text2;
const int width = text->lenght(txt) + (padding * 2) + iconSpace; const int width = text_->lenght(txt) + (padding * 2) + iconSpace;
const int height = (text->getCharacterSize() * 2) + (padding * 2); const int height = (text_->getCharacterSize() * 2) + (padding * 2);
// Posición horizontal // Posición horizontal
int despH = 0; int despH = 0;
if (options->notifications.posH == pos_left) if (options.notifications.posH == pos_left)
{ {
despH = padding; despH = padding;
} }
else if (options->notifications.posH == pos_middle) else if (options.notifications.posH == pos_middle)
{ {
despH = ((options->screen.windowWidth * options->windowSize) / 2 - (width / 2)); despH = ((options.screen.windowWidth * options.windowSize) / 2 - (width / 2));
} }
else else
{ {
despH = (options->screen.windowWidth * options->windowSize) - width - padding; despH = (options.screen.windowWidth * options.windowSize) - width - padding;
} }
// Posición vertical // Posición vertical
int despV = 0; int despV = 0;
if (options->notifications.posV == pos_top) if (options.notifications.posV == pos_top)
{ {
despV = padding; despV = padding;
} }
else else
{ {
despV = (options->screen.windowHeight * options->windowSize) - height - padding; despV = (options.screen.windowHeight * options.windowSize) - height - padding;
} }
const int travelDist = height + padding; const int travelDist = height + padding;
// Offset // Offset
int offset = 0; int offset = 0;
if (options->notifications.posV == pos_top) if (options.notifications.posV == pos_top)
{ {
offset = (int)notifications.size() > 0 ? notifications.back().y + travelDist : despV; offset = (int)notifications_.size() > 0 ? notifications_.back().y + travelDist : despV;
} }
else else
{ {
offset = (int)notifications.size() > 0 ? notifications.back().y - travelDist : despV; offset = (int)notifications_.size() > 0 ? notifications_.back().y - travelDist : despV;
} }
// Crea la notificacion // Crea la notificacion
@@ -231,7 +231,7 @@ void Notifier::showText(std::string text1, std::string text2, int icon)
n.state = ns_rising; n.state = ns_rising;
n.text1 = text1; n.text1 = text1;
n.text2 = text2; n.text2 = text2;
if (options->notifications.posV == pos_top) if (options.notifications.posV == pos_top)
{ {
n.rect = {despH, offset - travelDist, width, height}; n.rect = {despH, offset - travelDist, width, height};
} }
@@ -241,32 +241,32 @@ void Notifier::showText(std::string text1, std::string text2, int icon)
} }
// Crea la textura // Crea la textura
n.texture = new Texture(renderer); n.texture = new Texture(renderer_);
n.texture->createBlank(renderer, width, height, SDL_TEXTUREACCESS_TARGET); n.texture->createBlank(renderer_, width, height, SDL_TEXTUREACCESS_TARGET);
n.texture->setBlendMode(SDL_BLENDMODE_BLEND); n.texture->setBlendMode(SDL_BLENDMODE_BLEND);
// Prepara para dibujar en la textura // Prepara para dibujar en la textura
n.texture->setAsRenderTarget(renderer); n.texture->setAsRenderTarget(renderer_);
// Dibuja el fondo de la notificación // Dibuja el fondo de la notificación
SDL_SetRenderDrawColor(renderer, bgColor.r, bgColor.g, bgColor.b, 255); SDL_SetRenderDrawColor(renderer_, bg_color_.r, bg_color_.g, bg_color_.b, 255);
SDL_Rect rect; SDL_Rect rect;
rect = {4, 0, width - (4 * 2), height}; rect = {4, 0, width - (4 * 2), height};
SDL_RenderFillRect(renderer, &rect); SDL_RenderFillRect(renderer_, &rect);
rect = {4 / 2, 1, width - 4, height - 2}; rect = {4 / 2, 1, width - 4, height - 2};
SDL_RenderFillRect(renderer, &rect); SDL_RenderFillRect(renderer_, &rect);
rect = {1, 4 / 2, width - 2, height - 4}; rect = {1, 4 / 2, width - 2, height - 4};
SDL_RenderFillRect(renderer, &rect); SDL_RenderFillRect(renderer_, &rect);
rect = {0, 4, width, height - (4 * 2)}; rect = {0, 4, width, height - (4 * 2)};
SDL_RenderFillRect(renderer, &rect); SDL_RenderFillRect(renderer_, &rect);
// Dibuja el icono de la notificación // Dibuja el icono de la notificación
if (icon >= 0) if (icon >= 0)
{ {
Sprite *sp = new Sprite({0, 0, iconSize, iconSize}, iconTexture, renderer); Sprite *sp = new Sprite({0, 0, iconSize, iconSize}, icon_texture_, renderer_);
sp->setPos({padding, padding, iconSize, iconSize}); sp->setPos({padding, padding, iconSize, iconSize});
sp->setSpriteClip({iconSize * (icon % 10), iconSize * (icon / 10), iconSize, iconSize}); sp->setSpriteClip({iconSize * (icon % 10), iconSize * (icon / 10), iconSize, iconSize});
sp->render(); sp->render();
@@ -277,31 +277,31 @@ void Notifier::showText(std::string text1, std::string text2, int icon)
color_t color = {255, 255, 255}; color_t color = {255, 255, 255};
if (text2 != "") if (text2 != "")
{ // Dos lineas de texto { // Dos lineas de texto
text->writeColored(padding + iconSpace, padding, text1, color); text_->writeColored(padding + iconSpace, padding, text1, color);
text->writeColored(padding + iconSpace, padding + text->getCharacterSize() + 1, text2, color); text_->writeColored(padding + iconSpace, padding + text_->getCharacterSize() + 1, text2, color);
} }
else else
{ // Una linea de texto { // Una linea de texto
text->writeColored(padding + iconSpace, (height / 2) - (text->getCharacterSize() / 2), text1, color); text_->writeColored(padding + iconSpace, (height / 2) - (text_->getCharacterSize() / 2), text1, color);
} }
// Deja de dibujar en la textura // Deja de dibujar en la textura
SDL_SetRenderTarget(renderer, nullptr); SDL_SetRenderTarget(renderer_, nullptr);
// Crea el sprite de la notificación // Crea el sprite de la notificación
n.sprite = new Sprite(n.rect, n.texture, renderer); n.sprite = new Sprite(n.rect, n.texture, renderer_);
// Deja la notificación invisible // Deja la notificación invisible
n.texture->setAlpha(0); n.texture->setAlpha(0);
// Añade la notificación a la lista // Añade la notificación a la lista
notifications.push_back(n); notifications_.push_back(n);
} }
// Indica si hay notificaciones activas // Indica si hay notificaciones activas
bool Notifier::active() bool Notifier::active()
{ {
if ((int)notifications.size() > 0) if ((int)notifications_.size() > 0)
{ {
return true; return true;
} }

View File

@@ -51,30 +51,29 @@ private:
}; };
// Objetos y punteros // Objetos y punteros
SDL_Renderer *renderer; // El renderizador de la ventana SDL_Renderer *renderer_; // El renderizador de la ventana
Texture *textTexture; // Textura para la fuente de las notificaciones Texture *text_texture_; // Textura para la fuente de las notificaciones
Texture *iconTexture; // Textura para los iconos de las notificaciones Texture *icon_texture_; // Textura para los iconos de las notificaciones
Text *text; // Objeto para dibujar texto Text *text_; // Objeto para dibujar texto
options_t *options; // Variable con todas las opciones del programa
// Variables // Variables
color_t bgColor; // Color de fondo de las notificaciones color_t bg_color_; // Color de fondo de las notificaciones
int waitTime; // Tiempo que se ve la notificación int wait_time_; // Tiempo que se ve la notificación
std::vector<notification_t> notifications; // La lista de notificaciones activas std::vector<notification_t> notifications_; // La lista de notificaciones activas
JA_Sound_t *sound; // Sonido a reproducir cuando suena la notificación JA_Sound_t *sound_; // Sonido a reproducir cuando suena la notificación
// Elimina las notificaciones finalizadas // Elimina las notificaciones finalizadas
void clearFinishedNotifications(); void clearFinishedNotifications();
// Constructor // Constructor
Notifier(std::string iconFile, std::string bitmapFile, std::string textFile, std::string soundFile, options_t *options); Notifier(std::string iconFile, std::string bitmapFile, std::string textFile, std::string soundFile);
// Destructor // Destructor
~Notifier(); ~Notifier();
public: public:
// [SINGLETON] Crearemos el objeto con esta función estática // [SINGLETON] Crearemos el objeto con esta función estática
static void init(std::string iconFile, std::string bitmapFile, std::string textFile, std::string soundFile, options_t *options); static void init(std::string iconFile, std::string bitmapFile, std::string textFile, std::string soundFile);
// [SINGLETON] Destruiremos el objeto con esta función estática // [SINGLETON] Destruiremos el objeto con esta función estática
static void destroy(); static void destroy();

411
source/options.cpp Normal file
View File

@@ -0,0 +1,411 @@
#include "options.h"
#include "const.h"
#include "screen.h"
#include <fstream> // Para basic_ofstream, basic_ifstream
#include <iostream> // Para basic_ostream, operator<<, cout
// Variables
options_t options;
bool setOptions(std::string var, std::string value);
void initOptions()
{
// Version del archivo de configuración
options.configVersion = "v1.06.1";
// Opciones de control
options.keys = ctrl_cursor;
// Opciones de video
options.gameWidth = GAMECANVAS_WIDTH;
options.gameHeight = GAMECANVAS_HEIGHT;
options.videoMode = 0;
options.windowSize = 3;
options.filter = FILTER_NEAREST;
options.shaders = false;
options.vSync = true;
options.integerScale = true;
options.keepAspect = true;
options.borderEnabled = true;
options.borderWidth = 32;
options.borderHeight = 24;
options.palette = p_zxspectrum;
#ifdef GAME_CONSOLE
options.windowSize = 2;
#endif
// Estos valores no se guardan en el fichero de configuración
options.console = false;
#ifdef DEBUG
options.console = true;
#endif
options.cheat.infiniteLives = false;
options.cheat.invincible = false;
options.cheat.jailEnabled = false;
options.cheat.altSkin = false;
options.stats.rooms = 0;
options.stats.items = 0;
// Opciones de las notificaciones
options.notifications.posV = pos_top;
options.notifications.posH = pos_left;
options.notifications.sound = true;
options.notifications.color = {48, 48, 48};
#ifdef DEBUG
options.section.name = SECTION_TITLE;
options.section.subsection = SUBSECTION_LOGO_TO_INTRO;
#else
options.section.name = SECTION_LOGO;
options.section.subsection = SUBSECTION_LOGO_TO_INTRO;
#endif
}
bool loadOptionsFromFile(const std::string &file_path)
{
// Indicador de éxito en la carga
bool success = true;
// Versión actual del fichero
const std::string configVersion = options.configVersion;
options.configVersion = "";
// Variables para manejar el fichero
std::string line;
std::ifstream file(file_path);
// Si el fichero se puede abrir
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
if (line.substr(0, 1) != "#")
{
// Encuentra la posición del caracter '='
int pos = line.find("=");
// Procesa las dos subcadenas
if (!setOptions(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();
}
// El fichero no existe
else
{ // Crea el fichero con los valores por defecto
saveOptionsFromFile(file_path);
}
// Si la versión de fichero no coincide, crea un fichero nuevo con los valores por defecto
if (configVersion != options.configVersion)
{
initOptions();
saveOptionsFromFile(file_path);
}
// Normaliza los valores
const bool a = options.videoMode == 0;
const bool b = options.videoMode == SDL_WINDOW_FULLSCREEN;
const bool c = options.videoMode == SDL_WINDOW_FULLSCREEN_DESKTOP;
if (!(a || b || c))
{
options.videoMode = 0;
}
if (options.windowSize < 1 || options.windowSize > 4)
{
options.windowSize = 3;
}
return success;
}
bool saveOptionsFromFile(const std::string &file_path)
{
bool success = true;
// Crea y abre el fichero de texto
std::ofstream file(file_path);
if (file.good())
{
if (options.console)
{
std::cout << file_path << " open for writing" << std::endl;
}
}
else
{
if (options.console)
{
std::cout << file_path << " can't be opened" << std::endl;
}
}
// Escribe en el fichero
file << "## VERSION\n";
file << "configVersion=" + options.configVersion + "\n";
file << "\n## CONTROL OPTIONS\n";
file << "## keys = CURSOR | OPQA | WASD\n";
if (options.keys == ctrl_cursor)
{
file << "keys=CURSOR\n";
}
else if (options.keys == ctrl_opqa)
{
file << "keys=OPQA\n";
}
else if (options.keys == ctrl_wasd)
{
file << "keys=WASD\n";
}
file << "\n## VISUAL OPTIONS\n";
if (options.videoMode == 0)
{
file << "videoMode=0\n";
}
else if (options.videoMode == SDL_WINDOW_FULLSCREEN)
{
file << "videoMode=SDL_WINDOW_FULLSCREEN\n";
}
else if (options.videoMode == SDL_WINDOW_FULLSCREEN_DESKTOP)
{
file << "videoMode=SDL_WINDOW_FULLSCREEN_DESKTOP\n";
}
file << "windowSize=" + std::to_string(options.windowSize) + "\n";
if (options.filter == FILTER_NEAREST)
{
file << "filter=FILTER_NEAREST\n";
}
else
{
file << "filter=FILTER_LINEAR\n";
}
file << "shaders=" + boolToString(options.shaders) + "\n";
file << "vSync=" + boolToString(options.vSync) + "\n";
file << "integerScale=" + boolToString(options.integerScale) + "\n";
file << "keepAspect=" + boolToString(options.keepAspect) + "\n";
file << "borderEnabled=" + boolToString(options.borderEnabled) + "\n";
file << "borderWidth=" + std::to_string(options.borderWidth) + "\n";
file << "borderHeight=" + std::to_string(options.borderHeight) + "\n";
file << "palette=" + std::to_string(options.palette) + "\n";
file << "\n## NOTIFICATION OPTIONS\n";
file << "## notifications.posV = pos_top | pos_bottom\n";
if (options.notifications.posV == pos_top)
{
file << "notifications.posV=pos_top\n";
}
else
{
file << "notifications.posV=pos_bottom\n";
}
file << "## notifications.posH = pos_left | pos_middle | pos_right\n";
if (options.notifications.posH == pos_left)
{
file << "notifications.posH=pos_left\n";
}
else if (options.notifications.posH == pos_middle)
{
file << "notifications.posH=pos_middle\n";
}
else
{
file << "notifications.posH=pos_right\n";
}
file << "notifications.sound=" + boolToString(options.notifications.sound) + "\n";
// Cierra el fichero
file.close();
return success;
}
bool setOptions(std::string var, std::string value)
{
// Indicador de éxito en la asignación
bool success = true;
if (var == "configVersion")
{
options.configVersion = value;
}
else if (var == "keys")
{
if (value == "OPQA")
{
options.keys = ctrl_opqa;
}
else if (value == "WASD")
{
options.keys = ctrl_wasd;
}
else
{
options.keys = ctrl_cursor;
}
}
else if (var == "videoMode")
{
if (value == "SDL_WINDOW_FULLSCREEN_DESKTOP")
{
options.videoMode = SDL_WINDOW_FULLSCREEN_DESKTOP;
}
else if (value == "SDL_WINDOW_FULLSCREEN")
{
options.videoMode = SDL_WINDOW_FULLSCREEN;
}
else
{
options.videoMode = 0;
}
}
else if (var == "windowSize")
{
options.windowSize = std::stoi(value);
if ((options.windowSize < 1) || (options.windowSize > 4))
{
options.windowSize = 3;
}
}
else if (var == "filter")
{
if (value == "FILTER_LINEAR")
{
options.filter = FILTER_LINEAR;
}
else
{
options.filter = FILTER_NEAREST;
}
}
else if (var == "shaders")
{
options.shaders = stringToBool(value);
}
else if (var == "vSync")
{
options.vSync = stringToBool(value);
}
else if (var == "integerScale")
{
options.integerScale = stringToBool(value);
}
else if (var == "keepAspect")
{
options.keepAspect = stringToBool(value);
}
else if (var == "borderEnabled")
{
options.borderEnabled = stringToBool(value);
}
else if (var == "borderWidth")
{
options.borderWidth = std::stoi(value);
}
else if (var == "borderHeight")
{
options.borderHeight = std::stoi(value);
}
else if (var == "palette")
{
const int pal = std::stoi(value);
if (pal == 0)
{
options.palette = p_zxspectrum;
}
else if (pal == 1)
{
options.palette = p_zxarne;
}
}
else if (var == "notifications.posH")
{
if (value == "pos_left")
{
options.notifications.posH = pos_left;
}
else if (value == "pos_middle")
{
options.notifications.posH = pos_middle;
}
else
{
options.notifications.posH = pos_right;
}
}
else if (var == "notifications.posV")
{
if (value == "pos_top")
{
options.notifications.posV = pos_top;
}
else
{
options.notifications.posV = pos_bottom;
}
}
else if (var == "notifications.sound")
{
options.notifications.sound = stringToBool(value);
}
else if (var == "" || var.substr(0, 1) == "#")
{
}
else
{
success = false;
}
return success;
}

101
source/options.h Normal file
View File

@@ -0,0 +1,101 @@
#pragma once
#include <SDL2/SDL_rect.h> // Para SDL_Rect, SDL_Point
#include <SDL2/SDL_stdinc.h> // Para Uint8, Uint32
#include <string> // Para string, basic_string
#include "utils.h"
// Posiciones de las notificaciones
enum not_pos_e
{
pos_top,
pos_bottom,
pos_left,
pos_middle,
pos_right
};
// Tipos de control de teclado
enum ctrl_schem_e
{
ctrl_cursor,
ctrl_opqa,
ctrl_wasd
};
// Estructura para las opciones de las notificaciones
struct op_notification_t
{
not_pos_e posH; // Ubicación de las notificaciones en pantalla
not_pos_e posV; // Ubicación de las notificaciones en pantalla
bool sound; // Indica si las notificaciones suenan
color_t color; // Color de las notificaciones
};
// Estructura para saber la seccion y subseccion del programa
struct section_t
{
Uint8 name;
Uint8 subsection;
};
// Estructura para albergar trucos
struct cheat_t
{
bool infiniteLives; // Indica si el jugador dispone de vidas infinitas
bool invincible; // Indica si el jugador puede morir
bool jailEnabled; // Indica si la Jail está abierta
bool altSkin; // Indicxa si se usa una skin diferente para el jugador
};
// Estructura para almacenar estadísticas
struct op_stats_t
{
int rooms; // Cantidad de habitaciones visitadas
int items; // Cantidad de items obtenidos
std::string worstNightmare; // Habitación con más muertes acumuladas
};
// Estructura con opciones de la pantalla
struct op_screen_t
{
int windowWidth; // Ancho de la ventana
int windowHeight; // Alto de la ventana
};
// Estructura con todas las opciones de configuración del programa
struct options_t
{
std::string configVersion; // Versión del programa. Sirve para saber si las opciones son compatibles
Uint32 videoMode; // Contiene el valor del modo de pantalla completa
int windowSize; // Contiene el valor por el que se multiplica el tamaño de la ventana
Uint32 filter; // Filtro usado para el escalado de la imagen
bool vSync; // Indica si se quiere usar vsync o no
bool shaders; // Indica si se van a usar shaders o no
int gameWidth; // Ancho de la resolucion nativa del juego
int gameHeight; // Alto de la resolucion nativa del juego
bool integerScale; // Indica si el escalado de la imagen ha de ser entero en el modo a pantalla completa
bool keepAspect; // Indica si se ha de mantener la relación de aspecto al poner el modo a pantalla completa
bool borderEnabled; // Indica si ha de mostrar el borde en el modo de ventana
int borderWidth; // Cantidad de pixels que se añade en el borde de la ventana
int borderHeight; // Cantidad de pixels que se añade en el borde de la 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
cheat_t cheat; // Contiene trucos y ventajas para el juego
op_stats_t stats; // Datos con las estadisticas de juego
op_notification_t notifications; // Opciones relativas a las notificaciones;
op_screen_t screen; // Opciones relativas a la clase screen
ctrl_schem_e keys; // Teclas usadas para jugar
section_t section; // Sección actual del programa
};
extern options_t options;
// Crea e inicializa las opciones del programa
void initOptions();
// Carga las opciones desde un fichero
bool loadOptionsFromFile(const std::string &file_path);
// Guarda las opciones a un fichero
bool saveOptionsFromFile(const std::string &file_path);

View File

@@ -12,6 +12,7 @@
#include "resource.h" // Para Resource #include "resource.h" // Para Resource
#include "room.h" // Para Room, tile_e #include "room.h" // Para Room, tile_e
#include "texture.h" // Para Texture #include "texture.h" // Para Texture
#include "options.h"
// Constructor // Constructor
Player::Player(player_t player) Player::Player(player_t player)
@@ -23,7 +24,6 @@ Player::Player(player_t player)
this->input = player.input; this->input = player.input;
this->room = player.room; this->room = player.room;
this->debug = player.debug; this->debug = player.debug;
this->options = player.options;
// Crea objetos // Crea objetos
sprite = new AnimatedSprite(renderer, resource->getAnimation(player.animation)); sprite = new AnimatedSprite(renderer, resource->getAnimation(player.animation));
@@ -786,14 +786,14 @@ void Player::reLoadTexture()
// Recarga la paleta // Recarga la paleta
void Player::reLoadPalette() void Player::reLoadPalette()
{ {
color = stringToColor(options->palette, "white"); color = stringToColor(options.palette, "white");
if (options->cheat.infiniteLives) if (options.cheat.infiniteLives)
{ {
color = stringToColor(options->palette, "yellow"); color = stringToColor(options.palette, "yellow");
} }
if (options->cheat.invincible) if (options.cheat.invincible)
{ {
color = stringToColor(options->palette, "cyan"); color = stringToColor(options.palette, "cyan");
} }
} }

View File

@@ -39,7 +39,6 @@ struct player_t
SDL_Renderer *renderer; SDL_Renderer *renderer;
Resource *resource; Resource *resource;
Asset *asset; Asset *asset;
options_t *options;
Input *input; Input *input;
Room *room; Room *room;
Debug *debug; Debug *debug;
@@ -56,7 +55,6 @@ public:
Room *room; // Objeto encargado de gestionar cada habitación del juego Room *room; // Objeto encargado de gestionar cada habitación del juego
AnimatedSprite *sprite; // Sprite del enemigo AnimatedSprite *sprite; // Sprite del enemigo
Debug *debug; // Objeto para gestionar la información de debug Debug *debug; // Objeto para gestionar la información de debug
options_t *options; // Puntero a las opciones del juego
// Variables // Variables
float x; // Posición del jugador en el eje X float x; // Posición del jugador en el eje X

View File

@@ -9,13 +9,14 @@
#include "texture.h" // Para Texture #include "texture.h" // Para Texture
#include "utils.h" // Para options_t #include "utils.h" // Para options_t
#include "screen.h" #include "screen.h"
#include "options.h"
// Carga las texturas de una lista // Carga las texturas de una lista
void Resource::loadTextures(std::vector<std::string> list) void Resource::loadTextures(std::vector<std::string> list)
{ {
for (auto l : list) for (auto l : list)
{ {
if (options_->console) if (options.console)
{ {
std::cout << "\nLOAD TEXTURE: " << l << std::endl; std::cout << "\nLOAD TEXTURE: " << l << std::endl;
std::cout << "png: " << Asset::get()->get(l) << std::endl; std::cout << "png: " << Asset::get()->get(l) << std::endl;
@@ -23,7 +24,7 @@ void Resource::loadTextures(std::vector<std::string> list)
res_texture_t t; res_texture_t t;
t.name = l; t.name = l;
t.texture = new Texture(Screen::get()->getRenderer(), Asset::get()->get(t.name), options_->console); t.texture = new Texture(Screen::get()->getRenderer(), Asset::get()->get(t.name), options.console);
textures_.push_back(t); textures_.push_back(t);
} }
} }
@@ -45,7 +46,7 @@ void Resource::loadAnimations(std::vector<std::string> list)
// Extrae el nombre del fichero sin la extension para crear el nombre del fichero de la textura // Extrae el nombre del fichero sin la extension para crear el nombre del fichero de la textura
const std::string pngFile = l.substr(0, l.find_last_of(".")) + ".png"; const std::string pngFile = l.substr(0, l.find_last_of(".")) + ".png";
if (options_->console) if (options.console)
{ {
std::cout << "\nLOAD ANIMATION: " << l << std::endl; std::cout << "\nLOAD ANIMATION: " << l << std::endl;
std::cout << "png: " << Asset::get()->get(pngFile) << std::endl; std::cout << "png: " << Asset::get()->get(pngFile) << std::endl;
@@ -54,7 +55,7 @@ void Resource::loadAnimations(std::vector<std::string> list)
res_animation_t as; res_animation_t as;
as.name = l; as.name = l;
as.animation = new animatedSprite_t(loadAnimationFromFile(getTexture(pngFile), Asset::get()->get(as.name), options_->console)); as.animation = new animatedSprite_t(loadAnimationFromFile(getTexture(pngFile), Asset::get()->get(as.name), options.console));
animations_.push_back(as); animations_.push_back(as);
} }
} }
@@ -69,7 +70,7 @@ void Resource::reLoadAnimations()
// Extrae el nombre del fichero sin la extension para crear el nombre del fichero de la textura // Extrae el nombre del fichero sin la extension para crear el nombre del fichero de la textura
const std::string pngFile = a.name.substr(0, a.name.find_last_of(".")) + ".png"; const std::string pngFile = a.name.substr(0, a.name.find_last_of(".")) + ".png";
delete a.animation; delete a.animation;
a.animation = new animatedSprite_t(loadAnimationFromFile(getTexture(pngFile), Asset::get()->get(a.name), options_->console)); a.animation = new animatedSprite_t(loadAnimationFromFile(getTexture(pngFile), Asset::get()->get(a.name), options.console));
} }
} }
@@ -80,7 +81,7 @@ void Resource::loadOffsets(std::vector<std::string> list)
{ {
res_textOffset_t to; res_textOffset_t to;
to.name = l; to.name = l;
to.textFile = new textFile_t(LoadTextFile(Asset::get()->get(l), options_->console)); to.textFile = new textFile_t(LoadTextFile(Asset::get()->get(l), options.console));
offsets_.push_back(to); offsets_.push_back(to);
} }
} }
@@ -91,7 +92,7 @@ void Resource::reLoadOffsets()
for (auto &o : offsets_) for (auto &o : offsets_)
{ {
delete o.textFile; delete o.textFile;
o.textFile = new textFile_t(LoadTextFile(Asset::get()->get(o.name), options_->console)); o.textFile = new textFile_t(LoadTextFile(Asset::get()->get(o.name), options.console));
} }
} }
@@ -102,7 +103,7 @@ void Resource::loadTileMaps(std::vector<std::string> list)
{ {
res_tileMap_t tm; res_tileMap_t tm;
tm.name = l; tm.name = l;
tm.tileMap = new std::vector<int>(loadRoomTileFile(Asset::get()->get(l), options_->console)); tm.tileMap = new std::vector<int>(loadRoomTileFile(Asset::get()->get(l), options.console));
tile_maps_.push_back(tm); tile_maps_.push_back(tm);
} }
} }
@@ -113,7 +114,7 @@ void Resource::reLoadTileMaps()
for (auto &tm : tile_maps_) for (auto &tm : tile_maps_)
{ {
delete tm.tileMap; delete tm.tileMap;
tm.tileMap = new std::vector<int>(loadRoomTileFile(Asset::get()->get(tm.name), options_->console)); tm.tileMap = new std::vector<int>(loadRoomTileFile(Asset::get()->get(tm.name), options.console));
} }
} }
@@ -124,7 +125,7 @@ void Resource::loadRooms(std::vector<std::string> list)
{ {
res_room_t r; res_room_t r;
r.name = l; r.name = l;
r.room = new room_t(loadRoomFile(Asset::get()->get(l), options_->console)); r.room = new room_t(loadRoomFile(Asset::get()->get(l), options.console));
r.room->tileMap = getTileMap(r.room->tileMapFile); r.room->tileMap = getTileMap(r.room->tileMapFile);
for (auto &e : r.room->enemies) for (auto &e : r.room->enemies)
{ {
@@ -246,7 +247,7 @@ Texture *Resource::getTexture(std::string name)
} }
} }
if (options_->console) if (options.console)
{ {
std::cout << "NOT FOUND ON CACHE: " << name << std::endl; std::cout << "NOT FOUND ON CACHE: " << name << std::endl;
} }
@@ -267,7 +268,7 @@ animatedSprite_t *Resource::getAnimation(std::string name)
} }
} }
if (options_->console) if (options.console)
{ {
std::cout << "NOT FOUND ON CACHE: " << name << std::endl; std::cout << "NOT FOUND ON CACHE: " << name << std::endl;
} }
@@ -286,7 +287,7 @@ textFile_t *Resource::getOffset(std::string name)
} }
} }
if (options_->console) if (options.console)
{ {
std::cout << "NOT FOUND ON CACHE: " << name << std::endl; std::cout << "NOT FOUND ON CACHE: " << name << std::endl;
} }
@@ -305,7 +306,7 @@ std::vector<int> *Resource::getTileMap(std::string name)
} }
} }
if (options_->console) if (options.console)
{ {
std::cout << "NOT FOUND ON CACHE: " << name << std::endl; std::cout << "NOT FOUND ON CACHE: " << name << std::endl;
} }
@@ -324,7 +325,7 @@ room_t *Resource::getRoom(std::string name)
} }
} }
if (options_->console) if (options.console)
{ {
std::cout << "NOT FOUND ON CACHE: " << name << std::endl; std::cout << "NOT FOUND ON CACHE: " << name << std::endl;
} }

View File

@@ -44,9 +44,6 @@ struct res_room_t
class Resource class Resource
{ {
private: private:
// Objetos y punteros
options_t *options_; // Puntero a las opciones del juego
// Variables // Variables
std::vector<res_texture_t> textures_; std::vector<res_texture_t> textures_;
std::vector<res_animation_t> animations_; std::vector<res_animation_t> animations_;
@@ -56,8 +53,10 @@ private:
public: public:
// Constructor // Constructor
Resource(options_t *options) Resource() = default;
: options_(options) {}
// Destructor
~Resource() = default;
// Carga las texturas de una lista // Carga las texturas de una lista
void loadTextures(std::vector<std::string> list); void loadTextures(std::vector<std::string> list);

View File

@@ -14,6 +14,7 @@
#include "screen.h" // Para Screen #include "screen.h" // Para Screen
#include "sprite.h" // Para Sprite #include "sprite.h" // Para Sprite
#include "texture.h" // Para Texture #include "texture.h" // Para Texture
#include "options.h"
// Carga las variables y texturas desde un fichero de mapa de tiles // Carga las variables y texturas desde un fichero de mapa de tiles
std::vector<int> loadRoomTileFile(std::string file_path, bool verbose) std::vector<int> loadRoomTileFile(std::string file_path, bool verbose)
@@ -403,7 +404,7 @@ bool setItem(item_t *item, std::string var, std::string value)
} }
// Constructor // Constructor
Room::Room(room_t *room, SDL_Renderer *renderer, Screen *screen, Asset *asset, options_t *options, ItemTracker *itemTracker, int *itemsPicked, bool jailEnabled, Debug *debug) Room::Room(room_t *room, SDL_Renderer *renderer, Screen *screen, Asset *asset, ItemTracker *itemTracker, int *itemsPicked, bool jailEnabled, Debug *debug)
{ {
// Copia los punteros a objetos // Copia los punteros a objetos
this->renderer = renderer; this->renderer = renderer;
@@ -412,7 +413,6 @@ Room::Room(room_t *room, SDL_Renderer *renderer, Screen *screen, Asset *asset, o
this->itemTracker = itemTracker; this->itemTracker = itemTracker;
this->itemsPicked = itemsPicked; this->itemsPicked = itemsPicked;
this->debug = debug; this->debug = debug;
this->options = options;
number = room->number; number = room->number;
name = room->name; name = room->name;
@@ -430,7 +430,7 @@ Room::Room(room_t *room, SDL_Renderer *renderer, Screen *screen, Asset *asset, o
textureA = room->textureA; textureA = room->textureA;
textureB = room->textureB; textureB = room->textureB;
tileMap = *room->tileMap; tileMap = *room->tileMap;
texture = (options->palette == p_zxspectrum) ? textureA : textureB; texture = (options.palette == p_zxspectrum) ? textureA : textureB;
this->jailEnabled = jailEnabled; this->jailEnabled = jailEnabled;
// Inicializa variables // Inicializa variables
@@ -445,7 +445,7 @@ Room::Room(room_t *room, SDL_Renderer *renderer, Screen *screen, Asset *asset, o
for (auto &enemy : room->enemies) for (auto &enemy : room->enemies)
{ {
enemy.renderer = renderer; enemy.renderer = renderer;
enemy.palette = options->palette; enemy.palette = options.palette;
enemies.push_back(new Enemy(enemy)); enemies.push_back(new Enemy(enemy));
} }
@@ -457,8 +457,8 @@ Room::Room(room_t *room, SDL_Renderer *renderer, Screen *screen, Asset *asset, o
if (!itemTracker->hasBeenPicked(room->name, itemPos)) if (!itemTracker->hasBeenPicked(room->name, itemPos))
{ {
item.renderer = renderer; item.renderer = renderer;
item.color1 = stringToColor(options->palette, itemColor1); item.color1 = stringToColor(options.palette, itemColor1);
item.color2 = stringToColor(options->palette, itemColor2); item.color2 = stringToColor(options.palette, itemColor2);
items.push_back(new Item(item)); items.push_back(new Item(item));
} }
} }
@@ -488,7 +488,7 @@ Room::Room(room_t *room, SDL_Renderer *renderer, Screen *screen, Asset *asset, o
mapTexture = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, PLAY_AREA_WIDTH, PLAY_AREA_HEIGHT); mapTexture = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, PLAY_AREA_WIDTH, PLAY_AREA_HEIGHT);
if (mapTexture == nullptr) if (mapTexture == nullptr)
{ {
if (options->console) if (options.console)
{ {
std::cout << "Error: mapTexture could not be created!\nSDL Error: " << SDL_GetError() << std::endl; std::cout << "Error: mapTexture could not be created!\nSDL Error: " << SDL_GetError() << std::endl;
} }
@@ -499,7 +499,7 @@ Room::Room(room_t *room, SDL_Renderer *renderer, Screen *screen, Asset *asset, o
fillMapTexture(); fillMapTexture();
// Establece el color del borde // Establece el color del borde
screen->setBorderColor(stringToColor(options->palette, room->borderColor)); screen->setBorderColor(stringToColor(options.palette, room->borderColor));
} }
// Destructor // Destructor
@@ -534,19 +534,19 @@ std::string Room::getName()
// Devuelve el color de la habitación // Devuelve el color de la habitación
color_t Room::getBGColor() color_t Room::getBGColor()
{ {
return stringToColor(options->palette, bgColor); return stringToColor(options.palette, bgColor);
} }
// Devuelve el color del borde // Devuelve el color del borde
color_t Room::getBorderColor() color_t Room::getBorderColor()
{ {
return stringToColor(options->palette, borderColor); return stringToColor(options.palette, borderColor);
} }
// Crea la textura con el mapeado de la habitación // Crea la textura con el mapeado de la habitación
void Room::fillMapTexture() void Room::fillMapTexture()
{ {
const color_t color = stringToColor(options->palette, bgColor); const color_t color = stringToColor(options.palette, bgColor);
SDL_SetRenderTarget(renderer, mapTexture); SDL_SetRenderTarget(renderer, mapTexture);
SDL_SetRenderDrawColor(renderer, color.r, color.g, color.b, 0xFF); SDL_SetRenderDrawColor(renderer, color.r, color.g, color.b, 0xFF);
SDL_RenderClear(renderer); SDL_RenderClear(renderer);
@@ -841,7 +841,7 @@ bool Room::itemCollision(SDL_Rect &rect)
items.erase(items.begin() + i); items.erase(items.begin() + i);
JA_PlaySound(itemSound); JA_PlaySound(itemSound);
*itemsPicked = *itemsPicked + 1; *itemsPicked = *itemsPicked + 1;
options->stats.items = *itemsPicked; options.stats.items = *itemsPicked;
return true; return true;
} }
} }
@@ -872,20 +872,20 @@ void Room::reLoadPalette()
// Cambia el color de los items // Cambia el color de los items
for (auto item : items) for (auto item : items)
{ {
item->setColors(stringToColor(options->palette, itemColor1), stringToColor(options->palette, itemColor2)); item->setColors(stringToColor(options.palette, itemColor1), stringToColor(options.palette, itemColor2));
} }
// Cambia el color de los enemigos // Cambia el color de los enemigos
for (auto enemy : enemies) for (auto enemy : enemies)
{ {
enemy->setPalette(options->palette); enemy->setPalette(options.palette);
} }
// Establece el color del borde // Establece el color del borde
screen->setBorderColor(stringToColor(options->palette, borderColor)); screen->setBorderColor(stringToColor(options.palette, borderColor));
// Cambia la textura // Cambia la textura
texture = (options->palette == p_zxspectrum) ? textureA : textureB; texture = (options.palette == p_zxspectrum) ? textureA : textureB;
// Pone la nueva textura a los tiles animados // Pone la nueva textura a los tiles animados
for (auto tile : aTile) for (auto tile : aTile)

View File

@@ -85,7 +85,6 @@ private:
SDL_Texture *mapTexture; // Textura para dibujar el mapa de la habitación SDL_Texture *mapTexture; // Textura para dibujar el mapa de la habitación
int *itemsPicked; // Puntero a la cantidad de items recogidos que lleva el juego int *itemsPicked; // Puntero a la cantidad de items recogidos que lleva el juego
Debug *debug; // Objeto para gestionar la información de debug Debug *debug; // Objeto para gestionar la información de debug
options_t *options; // Puntero a las opciones del juego
// Variables // Variables
std::string number; // Numero de la habitación std::string number; // Numero de la habitación
@@ -160,7 +159,7 @@ private:
public: public:
// Constructor // Constructor
Room(room_t *room, SDL_Renderer *renderer, Screen *screen, Asset *asset, options_t *options, ItemTracker *itemTracker, int *itemsPicked, bool jailEnabled, Debug *debug); Room(room_t *room, SDL_Renderer *renderer, Screen *screen, Asset *asset, ItemTracker *itemTracker, int *itemsPicked, bool jailEnabled, Debug *debug);
// Destructor // Destructor
~Room(); ~Room();

View File

@@ -6,21 +6,21 @@
#include "resource.h" // Para Resource #include "resource.h" // Para Resource
#include "text.h" // Para Text #include "text.h" // Para Text
#include "texture.h" // Para Texture #include "texture.h" // Para Texture
#include "options.h"
class Asset; class Asset;
// Constructor // Constructor
ScoreBoard::ScoreBoard(SDL_Renderer *renderer, Resource *resource, Asset *asset, options_t *options, board_t *board) ScoreBoard::ScoreBoard(SDL_Renderer *renderer, Resource *resource, Asset *asset, board_t *board)
{ {
// Obten punteros a objetos // Obten punteros a objetos
this->renderer = renderer; this->renderer = renderer;
this->resource = resource; this->resource = resource;
this->asset = asset; this->asset = asset;
this->options = options;
this->board = board; this->board = board;
// Reserva memoria para los objetos // Reserva memoria para los objetos
itemTexture = resource->getTexture("items.png"); itemTexture = resource->getTexture("items.png");
const std::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);
@@ -31,13 +31,13 @@ ScoreBoard::ScoreBoard(SDL_Renderer *renderer, Resource *resource, Asset *asset,
paused = false; paused = false;
timePaused = 0; timePaused = 0;
totalTimePaused = 0; totalTimePaused = 0;
itemsColor = stringToColor(options->palette, "white"); itemsColor = stringToColor(options.palette, "white");
// Inicializa el vector de colores // Inicializa el vector de colores
const std::vector<std::string> vColors = {"blue", "magenta", "green", "cyan", "yellow", "white", "bright_blue", "bright_magenta", "bright_green", "bright_cyan", "bright_yellow", "bright_white"}; 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));
} }
} }
@@ -88,11 +88,11 @@ void ScoreBoard::render()
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 std::string roomsTxt = std::to_string(board->rooms / 100) + std::to_string((board->rooms % 100) / 10) + std::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"));
} }
// Actualiza las variables del objeto // Actualiza las variables del objeto
@@ -141,7 +141,7 @@ void ScoreBoard::reLoadPalette()
color.clear(); color.clear();
for (auto v : vColors) for (auto v : vColors)
{ {
color.push_back(stringToColor(options->palette, v)); color.push_back(stringToColor(options.palette, v));
} }
} }
@@ -169,11 +169,11 @@ void ScoreBoard::updateItemsColor()
if (counter % 20 < 10) if (counter % 20 < 10)
{ {
itemsColor = stringToColor(options->palette, "white"); itemsColor = stringToColor(options.palette, "white");
} }
else else
{ {
itemsColor = stringToColor(options->palette, "magenta"); itemsColor = stringToColor(options.palette, "magenta");
} }
} }

View File

@@ -41,7 +41,6 @@ private:
Text *text; // Objeto para escribir texto Text *text; // Objeto para escribir texto
Texture *itemTexture; // Textura con los graficos para las vidas Texture *itemTexture; // Textura con los graficos para las vidas
board_t *board; // Contiene las variables a mostrar en el marcador board_t *board; // Contiene las variables a mostrar en el marcador
options_t *options; // Puntero a las opciones del juego
// Variables // Variables
std::vector<color_t> color; // Vector con los colores del objeto std::vector<color_t> color; // Vector con los colores del objeto
@@ -61,7 +60,7 @@ private:
public: public:
// Constructor // Constructor
ScoreBoard(SDL_Renderer *renderer, Resource *resource, Asset *asset, options_t *options, board_t *board); ScoreBoard(SDL_Renderer *renderer, Resource *resource, Asset *asset, board_t *board);
// Destructor // Destructor
~ScoreBoard(); ~ScoreBoard();

View File

@@ -11,6 +11,7 @@
#include "asset.h" // Para Asset #include "asset.h" // Para Asset
#include "jail_shader.h" // Para init, render #include "jail_shader.h" // Para init, render
#include "notifier.h" // Para Notify #include "notifier.h" // Para Notify
#include "options.h"
// [SINGLETON] // [SINGLETON]
Screen *Screen::screen_ = nullptr; Screen *Screen::screen_ = nullptr;
@@ -38,8 +39,8 @@ Screen::Screen(SDL_Window *window, SDL_Renderer *renderer)
: window_(window), : window_(window),
renderer_(renderer) renderer_(renderer)
{ {
game_canvas_width_ = options_->gameWidth; game_canvas_width_ = options.gameWidth;
game_canvas_height_ = options_->gameHeight; game_canvas_height_ = options.gameHeight;
notification_logical_width_ = game_canvas_width_; notification_logical_width_ = game_canvas_width_;
notification_logical_height_ = game_canvas_height_; notification_logical_height_ = game_canvas_height_;
@@ -53,17 +54,17 @@ Screen::Screen(SDL_Window *window, SDL_Renderer *renderer)
game_canvas_ = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, game_canvas_width_, game_canvas_height_); game_canvas_ = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, game_canvas_width_, game_canvas_height_);
if (game_canvas_ == nullptr) if (game_canvas_ == nullptr)
{ {
if (options_->console) if (options.console)
{ {
std::cout << "gameCanvas could not be created!\nSDL Error: " << SDL_GetError() << std::endl; std::cout << "gameCanvas could not be created!\nSDL Error: " << SDL_GetError() << std::endl;
} }
} }
// Crea la textura donde se dibuja el borde que rodea el area de juego // Crea la textura donde se dibuja el borde que rodea el area de juego
border_canvas_ = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, game_canvas_width_ + options_->borderWidth * 2, game_canvas_height_ + options_->borderHeight * 2); border_canvas_ = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, game_canvas_width_ + options.borderWidth * 2, game_canvas_height_ + options.borderHeight * 2);
if (border_canvas_ == nullptr) if (border_canvas_ == nullptr)
{ {
if (options_->console) if (options.console)
{ {
std::cout << "borderCanvas could not be created!\nSDL Error: " << SDL_GetError() << std::endl; std::cout << "borderCanvas could not be created!\nSDL Error: " << SDL_GetError() << std::endl;
} }
@@ -71,7 +72,7 @@ Screen::Screen(SDL_Window *window, SDL_Renderer *renderer)
setBorderColor(border_color_); setBorderColor(border_color_);
// Establece el modo de video // Establece el modo de video
setVideoMode(options_->videoMode); setVideoMode(options.videoMode);
// Muestra la ventana // Muestra la ventana
SDL_ShowWindow(window); SDL_ShowWindow(window);
@@ -110,7 +111,7 @@ void Screen::render()
renderNotifications(); renderNotifications();
// Si está el borde activo, vuelca gameCanvas sobre borderCanvas // Si está el borde activo, vuelca gameCanvas sobre borderCanvas
if (options_->borderEnabled) if (options.borderEnabled)
{ {
gameCanvasToBorderCanvas(); gameCanvasToBorderCanvas();
} }
@@ -132,11 +133,11 @@ void Screen::setVideoMode(int videoMode)
SDL_ShowCursor(SDL_ENABLE); SDL_ShowCursor(SDL_ENABLE);
// Modifica el tamaño de la ventana en función del borde // Modifica el tamaño de la ventana en función del borde
if (options_->borderEnabled) if (options.borderEnabled)
{ {
window_width_ = game_canvas_width_ + options_->borderWidth * 2; window_width_ = game_canvas_width_ + options.borderWidth * 2;
window_height_ = game_canvas_height_ + options_->borderHeight * 2; window_height_ = game_canvas_height_ + options.borderHeight * 2;
dest_ = {options_->borderWidth, options_->borderHeight, game_canvas_width_, game_canvas_height_}; dest_ = {options.borderWidth, options.borderHeight, game_canvas_width_, game_canvas_height_};
} }
else else
@@ -147,7 +148,7 @@ void Screen::setVideoMode(int videoMode)
} }
// Modifica el tamaño de la ventana // Modifica el tamaño de la ventana
SDL_SetWindowSize(window_, window_width_ * options_->windowSize, window_height_ * options_->windowSize); SDL_SetWindowSize(window_, window_width_ * options.windowSize, window_height_ * options.windowSize);
SDL_SetWindowPosition(window_, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED); SDL_SetWindowPosition(window_, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED);
} }
@@ -161,7 +162,7 @@ void Screen::setVideoMode(int videoMode)
SDL_GetWindowSize(window_, &window_width_, &window_height_); SDL_GetWindowSize(window_, &window_width_, &window_height_);
// Aplica el escalado al rectangulo donde se pinta la textura del juego // Aplica el escalado al rectangulo donde se pinta la textura del juego
if (options_->integerScale) if (options.integerScale)
{ {
// Calcula el tamaño de la escala máxima // Calcula el tamaño de la escala máxima
int scale = 0; int scale = 0;
@@ -175,7 +176,7 @@ void Screen::setVideoMode(int videoMode)
dest_.x = (window_width_ - dest_.w) / 2; dest_.x = (window_width_ - dest_.w) / 2;
dest_.y = (window_height_ - dest_.h) / 2; dest_.y = (window_height_ - dest_.h) / 2;
} }
else if (options_->keepAspect) else if (options.keepAspect)
{ {
float ratio = (float)game_canvas_width_ / (float)game_canvas_height_; float ratio = (float)game_canvas_width_ / (float)game_canvas_height_;
if ((window_width_ - game_canvas_width_) >= (window_height_ - game_canvas_height_)) if ((window_width_ - game_canvas_width_) >= (window_height_ - game_canvas_height_))
@@ -205,18 +206,18 @@ void Screen::setVideoMode(int videoMode)
SDL_RenderSetLogicalSize(renderer_, window_width_, window_height_); SDL_RenderSetLogicalSize(renderer_, window_width_, window_height_);
// Actualiza las opciones // Actualiza las opciones
options_->videoMode = videoMode; options.videoMode = videoMode;
options_->screen.windowWidth = window_width_; options.screen.windowWidth = window_width_;
options_->screen.windowHeight = window_height_; options.screen.windowHeight = window_height_;
// Reinicia los shaders // Reinicia los shaders
if (options_->shaders) if (options.shaders)
{ {
const std::string glsl_file = options_->screen.windowHeight == 192 ? "crtpi_192.glsl" : "crtpi_240.glsl"; const std::string glsl_file = options.screen.windowHeight == 192 ? "crtpi_192.glsl" : "crtpi_240.glsl";
std::ifstream f(Asset::get()->get(glsl_file).c_str()); std::ifstream f(Asset::get()->get(glsl_file).c_str());
std::string source((std::istreambuf_iterator<char>(f)), std::istreambuf_iterator<char>()); std::string source((std::istreambuf_iterator<char>(f)), std::istreambuf_iterator<char>());
if (options_->borderEnabled) if (options.borderEnabled)
{ {
shader::init(window_, border_canvas_, source.c_str()); shader::init(window_, border_canvas_, source.c_str());
} }
@@ -230,30 +231,30 @@ void Screen::setVideoMode(int videoMode)
// Camibia entre pantalla completa y ventana // Camibia entre pantalla completa y ventana
void Screen::toggleVideoMode() void Screen::toggleVideoMode()
{ {
options_->videoMode = (options_->videoMode == 0) ? SDL_WINDOW_FULLSCREEN_DESKTOP : 0; options.videoMode = (options.videoMode == 0) ? SDL_WINDOW_FULLSCREEN_DESKTOP : 0;
setVideoMode(options_->videoMode); setVideoMode(options.videoMode);
} }
// Cambia el tamaño de la ventana // Cambia el tamaño de la ventana
void Screen::setWindowSize(int size) void Screen::setWindowSize(int size)
{ {
options_->windowSize = size; options.windowSize = size;
setVideoMode(0); setVideoMode(0);
} }
// Reduce el tamaño de la ventana // Reduce el tamaño de la ventana
void Screen::decWindowSize() void Screen::decWindowSize()
{ {
--options_->windowSize; --options.windowSize;
options_->windowSize = std::max(options_->windowSize, 1); options.windowSize = std::max(options.windowSize, 1);
setVideoMode(0); setVideoMode(0);
} }
// Aumenta el tamaño de la ventana // Aumenta el tamaño de la ventana
void Screen::incWindowSize() void Screen::incWindowSize()
{ {
++options_->windowSize; ++options.windowSize;
options_->windowSize = std::min(options_->windowSize, 4); options.windowSize = std::min(options.windowSize, 4);
setVideoMode(0); setVideoMode(0);
} }
@@ -277,25 +278,25 @@ void Screen::setBlendMode(SDL_BlendMode blendMode)
// Establece el tamaño del borde // Establece el tamaño del borde
void Screen::setBorderWidth(int s) void Screen::setBorderWidth(int s)
{ {
options_->borderWidth = s; options.borderWidth = s;
} }
// Establece el tamaño del borde // Establece el tamaño del borde
void Screen::setBorderHeight(int s) void Screen::setBorderHeight(int s)
{ {
options_->borderHeight = s; options.borderHeight = s;
} }
// Establece si se ha de ver el borde en el modo ventana // Establece si se ha de ver el borde en el modo ventana
void Screen::setBorderEnabled(bool value) void Screen::setBorderEnabled(bool value)
{ {
options_->borderEnabled = value; options.borderEnabled = value;
} }
// Cambia entre borde visible y no visible // Cambia entre borde visible y no visible
void Screen::toggleBorder() void Screen::toggleBorder()
{ {
options_->borderEnabled = !options_->borderEnabled; options.borderEnabled = !options.borderEnabled;
setVideoMode(0); setVideoMode(0);
} }
@@ -385,7 +386,7 @@ void Screen::iniSpectrumFade()
const std::vector<std::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)
{ {
spectrum_color_.push_back(stringToColor(options_->palette, v)); spectrum_color_.push_back(stringToColor(options.palette, v));
} }
} }
@@ -473,14 +474,14 @@ void Screen::renderPresent()
SDL_SetRenderDrawColor(renderer_, border_color_.r, border_color_.g, border_color_.b, 0xFF); SDL_SetRenderDrawColor(renderer_, border_color_.r, border_color_.g, border_color_.b, 0xFF);
SDL_RenderClear(renderer_); SDL_RenderClear(renderer_);
if (options_->shaders) if (options.shaders)
{ {
// Aplica shaders y renderiza el contenido // Aplica shaders y renderiza el contenido
shader::render(); shader::render();
} }
else else
{ {
if (options_->borderEnabled) if (options.borderEnabled)
{ {
SDL_RenderCopy(renderer_, border_canvas_, nullptr, nullptr); SDL_RenderCopy(renderer_, border_canvas_, nullptr, nullptr);
} }
@@ -495,6 +496,6 @@ void Screen::renderPresent()
// Cambia el estado de los shaders // Cambia el estado de los shaders
void Screen::toggleShaders() void Screen::toggleShaders()
{ {
options_->shaders = !options_->shaders; options.shaders = !options.shaders;
setVideoMode(options_->videoMode); setVideoMode(options.videoMode);
} }

View File

@@ -24,7 +24,6 @@ private:
SDL_Renderer *renderer_; // El renderizador de la ventana SDL_Renderer *renderer_; // El renderizador de la ventana
SDL_Texture *game_canvas_; // Textura donde se dibuja el juego SDL_Texture *game_canvas_; // Textura donde se dibuja el juego
SDL_Texture *border_canvas_; // Textura donde se dibuja el borde del juego SDL_Texture *border_canvas_; // Textura donde se dibuja el borde del juego
options_t *options_; // Variable con todas las opciones del programa
// Variables // Variables
int window_width_; // Ancho de la pantalla o ventana int window_width_; // Ancho de la pantalla o ventana

View File

@@ -2,11 +2,11 @@
#include <fstream> // Para basic_ostream, basic_ifstream, basic_istream, ope... #include <fstream> // Para basic_ostream, basic_ifstream, basic_istream, ope...
#include <sstream> // Para basic_stringstream #include <sstream> // Para basic_stringstream
#include "utils.h" // Para op_stats_t, options_t #include "utils.h" // Para op_stats_t, options_t
#include "options.h"
// Constructor // Constructor
Stats::Stats(std::string file, std::string buffer, options_t *options) Stats::Stats(std::string file, std::string buffer)
{ {
this->options = options;
bufferPath = buffer; bufferPath = buffer;
filePath = file; filePath = file;
bufferList.clear(); bufferList.clear();
@@ -183,7 +183,7 @@ void Stats::checkWorstNightmare()
if (item.died > deaths) if (item.died > deaths)
{ {
deaths = item.died; deaths = item.died;
options->stats.worstNightmare = item.name; options.stats.worstNightmare = item.name;
} }
} }
} }

View File

@@ -20,9 +20,6 @@ private:
std::string name; // Nombre de la habitación std::string name; // Nombre de la habitación
}; };
// Punteros y objetos
options_t *options; // Puntero a la variable con todas las opciones del programa
// Variables // Variables
std::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
std::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
@@ -53,7 +50,7 @@ private:
public: public:
// Constructor // Constructor
Stats(std::string file, std::string buffer, options_t *options); Stats(std::string file, std::string buffer);
// Destructor // Destructor
~Stats(); ~Stats();

View File

@@ -15,24 +15,23 @@
#include "text.h" // Para Text, TXT_CENTER, TXT_COLOR #include "text.h" // Para Text, TXT_CENTER, TXT_COLOR
#include "texture.h" // Para Texture #include "texture.h" // Para Texture
#include "utils.h" // Para color_t, stringToColor, options_t #include "utils.h" // Para color_t, stringToColor, options_t
#include "options.h"
// Constructor // Constructor
Title::Title(Resource *resource, options_t *options, section_t *section) Title::Title(Resource *resource)
: screen_(Screen::get()), : screen_(Screen::get()),
renderer_(Screen::get()->getRenderer()), renderer_(Screen::get()->getRenderer()),
resource_(resource), resource_(resource),
input_(Input::get()), input_(Input::get())
options_(options),
section_(section)
{ {
// Reserva memoria para los punteros // Reserva memoria para los punteros
event_handler_ = new SDL_Event(); event_handler_ = new SDL_Event();
cheevos_ = std::make_unique<Cheevos>(screen_, options, Asset::get()->get("cheevos.bin")); cheevos_ = std::make_unique<Cheevos>(screen_, Asset::get()->get("cheevos.bin"));
if (options->palette == p_zxspectrum) if (options.palette == p_zxspectrum)
{ {
texture_ = resource->getTexture("title_logo.png"); texture_ = resource->getTexture("title_logo.png");
} }
else if (options->palette == p_zxarne) else if (options.palette == p_zxarne)
{ {
texture_ = resource->getTexture("title_logo.png"); texture_ = resource->getTexture("title_logo.png");
} }
@@ -44,7 +43,7 @@ Title::Title(Resource *resource, options_t *options, section_t *section)
bg_texture_ = SDL_CreateTexture(renderer_, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, GAMECANVAS_WIDTH, GAMECANVAS_HEIGHT); bg_texture_ = SDL_CreateTexture(renderer_, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, GAMECANVAS_WIDTH, GAMECANVAS_HEIGHT);
if (bg_texture_ == nullptr) if (bg_texture_ == nullptr)
{ {
if (options->console) if (options.console)
{ {
std::cout << "Error: bgTexture could not be created!\nSDL Error: " << SDL_GetError() << std::endl; std::cout << "Error: bgTexture could not be created!\nSDL Error: " << SDL_GetError() << std::endl;
} }
@@ -58,16 +57,16 @@ Title::Title(Resource *resource, options_t *options, section_t *section)
pSetSource(loading_screen_); pSetSource(loading_screen_);
// Inicializa variables // Inicializa variables
state_ = section_->subsection == SUBSECTION_TITLE_WITH_LOADING_SCREEN ? show_loading_screen : show_menu; state_ = options.section.subsection == SUBSECTION_TITLE_WITH_LOADING_SCREEN ? show_loading_screen : show_menu;
section_->name = SECTION_TITLE; options.section.name = SECTION_TITLE;
section_->subsection = 0; options.section.subsection = 0;
initMarquee(); initMarquee();
// Crea y rellena la textura para mostrar los logros // Crea y rellena la textura para mostrar los logros
createCheevosTexture(); createCheevosTexture();
// Cambia el color del borde // Cambia el color del borde
screen_->setBorderColor(stringToColor(options->palette, "black")); screen_->setBorderColor(stringToColor(options.palette, "black"));
// Rellena la textura de fondo con todos los gráficos // Rellena la textura de fondo con todos los gráficos
fillTexture(); fillTexture();
@@ -111,7 +110,7 @@ void Title::checkEvents()
// Evento de salida de la aplicación // Evento de salida de la aplicación
if (event_handler_->type == SDL_QUIT) if (event_handler_->type == SDL_QUIT)
{ {
section_->name = SECTION_QUIT; options.section.name = SECTION_QUIT;
break; break;
} }
@@ -123,8 +122,8 @@ void Title::checkEvents()
switch (event_handler_->key.keysym.scancode) switch (event_handler_->key.keysym.scancode)
{ {
case SDL_SCANCODE_1: case SDL_SCANCODE_1:
section_->name = SECTION_GAME; options.section.name = SECTION_GAME;
section_->subsection = 0; options.section.subsection = 0;
break; break;
case SDL_SCANCODE_2: case SDL_SCANCODE_2:
@@ -163,7 +162,7 @@ void Title::checkInput()
} }
else else
{ {
section_->name = SECTION_QUIT; options.section.name = SECTION_QUIT;
} }
} }
@@ -247,7 +246,7 @@ void Title::renderMarquee()
{ {
if (l.enabled) if (l.enabled)
{ {
text_->writeColored(l.x, 184, l.letter, stringToColor(options_->palette, "white")); text_->writeColored(l.x, 184, l.letter, stringToColor(options.palette, "white"));
} }
} }
} }
@@ -306,8 +305,8 @@ void Title::update()
{ {
if (!show_cheevos_) if (!show_cheevos_)
{ {
section_->name = SECTION_CREDITS; options.section.name = SECTION_CREDITS;
section_->subsection = 0; options.section.subsection = 0;
} }
} }
break; break;
@@ -323,7 +322,7 @@ void Title::render()
{ {
// Prepara para empezar a dibujar en la textura de juego // Prepara para empezar a dibujar en la textura de juego
screen_->start(); screen_->start();
screen_->clean(stringToColor(options_->palette, "black")); screen_->clean(stringToColor(options.palette, "black"));
if (state_ == show_menu) if (state_ == show_menu)
{ {
@@ -357,7 +356,7 @@ void Title::render()
// Bucle para el logo del juego // Bucle para el logo del juego
void Title::run() void Title::run()
{ {
while (section_->name == SECTION_TITLE) while (options.section.name == SECTION_TITLE)
{ {
update(); update();
checkEvents(); checkEvents();
@@ -369,11 +368,11 @@ void Title::run()
void Title::reLoadTextures() void Title::reLoadTextures()
{ {
// Carga la textura adecuada // Carga la textura adecuada
if (options_->palette == p_zxspectrum) if (options.palette == p_zxspectrum)
{ {
texture_ = resource_->getTexture("loading_screen_color.png"); texture_ = resource_->getTexture("loading_screen_color.png");
} }
else if (options_->palette == p_zxarne) else if (options.palette == p_zxarne)
{ {
texture_ = resource_->getTexture("loading_screen_color_zxarne.png"); texture_ = resource_->getTexture("loading_screen_color_zxarne.png");
} }
@@ -384,19 +383,19 @@ void Title::reLoadTextures()
// Cambia la paleta // Cambia la paleta
void Title::switchPalette() void Title::switchPalette()
{ {
if (options_->palette == p_zxspectrum) if (options.palette == p_zxspectrum)
{ {
options_->palette = p_zxarne; options.palette = p_zxarne;
sprite_->setTexture(resource_->getTexture("loading_screen_color_zxarne.png")); sprite_->setTexture(resource_->getTexture("loading_screen_color_zxarne.png"));
} }
else else
{ {
options_->palette = p_zxspectrum; options.palette = p_zxspectrum;
sprite_->setTexture(resource_->getTexture("loading_screen_color.png")); sprite_->setTexture(resource_->getTexture("loading_screen_color.png"));
} }
// Cambia el color del borde // Cambia el color del borde
screen_->setBorderColor(stringToColor(options_->palette, "bright_blue")); screen_->setBorderColor(stringToColor(options.palette, "bright_blue"));
} }
// Desplaza la lista de logros // Desplaza la lista de logros
@@ -425,7 +424,7 @@ void Title::fillTexture()
SDL_SetRenderTarget(renderer_, bg_texture_); SDL_SetRenderTarget(renderer_, bg_texture_);
// Rellena la textura de color // Rellena la textura de color
const color_t c = stringToColor(options_->palette, "black"); const color_t c = stringToColor(options.palette, "black");
SDL_SetRenderDrawColor(renderer_, c.r, c.g, c.b, 0xFF); SDL_SetRenderDrawColor(renderer_, c.r, c.g, c.b, 0xFF);
SDL_RenderClear(renderer_); SDL_RenderClear(renderer_);
@@ -433,7 +432,7 @@ void Title::fillTexture()
sprite_->render(); sprite_->render();
// Escribe el texto en la textura // Escribe el texto en la textura
const color_t textColor = stringToColor(options_->palette, "green"); const color_t textColor = stringToColor(options.palette, "green");
const int textSize = text_->getCharacterSize(); const int textSize = text_->getCharacterSize();
text_->writeDX(TXT_CENTER | TXT_COLOR, PLAY_AREA_CENTER_X, 11 * textSize, "1.PLAY", 1, textColor); text_->writeDX(TXT_CENTER | TXT_COLOR, PLAY_AREA_CENTER_X, 11 * textSize, "1.PLAY", 1, textColor);
text_->writeDX(TXT_CENTER | TXT_COLOR, PLAY_AREA_CENTER_X, 13 * textSize, "2.ACHIEVEMENTS", 1, textColor); text_->writeDX(TXT_CENTER | TXT_COLOR, PLAY_AREA_CENTER_X, 13 * textSize, "2.ACHIEVEMENTS", 1, textColor);
@@ -461,7 +460,7 @@ void Title::createCheevosTexture()
cheevos_texture_->setBlendMode(SDL_BLENDMODE_BLEND); cheevos_texture_->setBlendMode(SDL_BLENDMODE_BLEND);
// Rellena la textura con color sólido // Rellena la textura con color sólido
const color_t cheevosBGColor = stringToColor(options_->palette, "black"); const color_t cheevosBGColor = stringToColor(options.palette, "black");
SDL_SetRenderDrawColor(renderer_, cheevosBGColor.r, cheevosBGColor.g, cheevosBGColor.b, 0xFF); SDL_SetRenderDrawColor(renderer_, cheevosBGColor.r, cheevosBGColor.g, cheevosBGColor.b, 0xFF);
SDL_RenderClear(renderer_); SDL_RenderClear(renderer_);
@@ -469,10 +468,10 @@ void Title::createCheevosTexture()
const std::string cheevosOwner = "LOCAL ACHIEVEMENTS"; const std::string cheevosOwner = "LOCAL ACHIEVEMENTS";
const std::string cheevosListCaption = cheevosOwner + " (" + std::to_string(cheevos_->unlocked()) + " / " + std::to_string(cheevos_->count()) + ")"; const std::string cheevosListCaption = cheevosOwner + " (" + std::to_string(cheevos_->unlocked()) + " / " + std::to_string(cheevos_->count()) + ")";
int pos = 2; int pos = 2;
info_text_->writeDX(TXT_CENTER | TXT_COLOR, cheevos_texture_->getWidth() / 2, pos, cheevosListCaption, 1, stringToColor(options_->palette, "bright_green")); info_text_->writeDX(TXT_CENTER | TXT_COLOR, cheevos_texture_->getWidth() / 2, pos, cheevosListCaption, 1, stringToColor(options.palette, "bright_green"));
pos += info_text_->getCharacterSize(); pos += info_text_->getCharacterSize();
const color_t cheevoLockedColor = stringToColor(options_->palette, "white"); const color_t cheevoLockedColor = stringToColor(options.palette, "white");
const color_t cheevoUnlockedColor = stringToColor(options_->palette, "bright_green"); const color_t cheevoUnlockedColor = stringToColor(options.palette, "bright_green");
color_t cheevoColor; color_t cheevoColor;
SDL_SetRenderDrawColor(renderer_, cheevoLockedColor.r, cheevoLockedColor.g, cheevoLockedColor.b, 0xFF); SDL_SetRenderDrawColor(renderer_, cheevoLockedColor.r, cheevoLockedColor.g, cheevoLockedColor.b, 0xFF);
const int lineX1 = (cheevosTextureWidth / 7) * 3; const int lineX1 = (cheevosTextureWidth / 7) * 3;

View File

@@ -47,11 +47,9 @@ private:
SDL_Texture *bg_texture_; // Textura para dibujar el fondo de la pantalla SDL_Texture *bg_texture_; // Textura para dibujar el fondo de la pantalla
Text *text_; // Objeto para escribir texto en pantalla Text *text_; // Objeto para escribir texto en pantalla
Text *info_text_; // Objeto para escribir texto en pantalla Text *info_text_; // Objeto para escribir texto en pantalla
options_t *options_; // Puntero a las opciones del juego
Texture *cheevos_texture_; // Textura con la lista de logros Texture *cheevos_texture_; // Textura con la lista de logros
Sprite *cheevos_sprite_; // Sprite para manejar la textura con la lista de logros Sprite *cheevos_sprite_; // Sprite para manejar la textura con la lista de logros
std::unique_ptr<Cheevos> cheevos_; // Objeto encargado de gestionar los logros del juego std::unique_ptr<Cheevos> cheevos_; // Objeto encargado de gestionar los logros del juego
section_t *section_; // Estado del bucle principal para saber si continua o se sale
// Variables // Variables
int counter_ = 0; // Contador int counter_ = 0; // Contador
@@ -109,7 +107,7 @@ private:
public: public:
// Constructor // Constructor
Title(Resource *resource, options_t *options, section_t *section); Title(Resource *resource);
// Destructor // Destructor
~Title(); ~Title();

View File

@@ -36,6 +36,13 @@ struct line_t
int x1, y1, x2, y2; int x1, y1, x2, y2;
}; };
// Tipos de paleta
enum palette_e
{
p_zxspectrum,
p_zxarne
};
// Estructura para definir un color // Estructura para definir un color
struct color_t struct color_t
{ {
@@ -51,96 +58,6 @@ struct color_t
: r(red), g(green), b(blue) {} : r(red), g(green), b(blue) {}
}; };
// Tipos de paleta
enum palette_e
{
p_zxspectrum,
p_zxarne
};
// Posiciones de las notificaciones
enum not_pos_e
{
pos_top,
pos_bottom,
pos_left,
pos_middle,
pos_right
};
// Tipos de control de teclado
enum ctrl_schem_e
{
ctrl_cursor,
ctrl_opqa,
ctrl_wasd
};
// Estructura para las opciones de las notificaciones
struct op_notification_t
{
not_pos_e posH; // Ubicación de las notificaciones en pantalla
not_pos_e posV; // Ubicación de las notificaciones en pantalla
bool sound; // Indica si las notificaciones suenan
color_t color; // Color de las notificaciones
};
// Estructura para saber la seccion y subseccion del programa
struct section_t
{
Uint8 name;
Uint8 subsection;
};
// Estructura para albergar trucos
struct cheat_t
{
bool infiniteLives; // Indica si el jugador dispone de vidas infinitas
bool invincible; // Indica si el jugador puede morir
bool jailEnabled; // Indica si la Jail está abierta
bool altSkin; // Indicxa si se usa una skin diferente para el jugador
};
// Estructura para almacenar estadísticas
struct op_stats_t
{
int rooms; // Cantidad de habitaciones visitadas
int items; // Cantidad de items obtenidos
std::string worstNightmare; // Habitación con más muertes acumuladas
};
// Estructura con opciones de la pantalla
struct op_screen_t
{
int windowWidth; // Ancho de la ventana
int windowHeight; // Alto de la ventana
};
// Estructura con todas las opciones de configuración del programa
struct options_t
{
std::string configVersion; // Versión del programa. Sirve para saber si las opciones son compatibles
Uint32 videoMode; // Contiene el valor del modo de pantalla completa
int windowSize; // Contiene el valor por el que se multiplica el tamaño de la ventana
Uint32 filter; // Filtro usado para el escalado de la imagen
bool vSync; // Indica si se quiere usar vsync o no
bool shaders; // Indica si se van a usar shaders o no
int gameWidth; // Ancho de la resolucion nativa del juego
int gameHeight; // Alto de la resolucion nativa del juego
bool integerScale; // Indica si el escalado de la imagen ha de ser entero en el modo a pantalla completa
bool keepAspect; // Indica si se ha de mantener la relación de aspecto al poner el modo a pantalla completa
bool borderEnabled; // Indica si ha de mostrar el borde en el modo de ventana
int borderWidth; // Cantidad de pixels que se añade en el borde de la ventana
int borderHeight; // Cantidad de pixels que se añade en el borde de la 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
cheat_t cheat; // Contiene trucos y ventajas para el juego
op_stats_t stats; // Datos con las estadisticas de juego
op_notification_t notifications; // Opciones relativas a las notificaciones;
op_screen_t screen; // Opciones relativas a la clase screen
ctrl_schem_e keys; // Teclas usadas para jugar
};
// Calcula el cuadrado de la distancia entre dos puntos // Calcula el cuadrado de la distancia entre dos puntos
double distanceSquared(int x1, int y1, int x2, int y2); double distanceSquared(int x1, int y1, int x2, int y2);