Singletonejant

Borrat menu.cpp que no estava gastantse...mmm.. desde mai
This commit is contained in:
2025-02-22 18:27:23 +01:00
parent e361d295c1
commit fc01676df2
38 changed files with 440 additions and 1751 deletions

View File

@@ -3,113 +3,49 @@
#include <SDL2/SDL_rwops.h> // Para SDL_RWFromFile, SDL_RWclose, SDL_RWwrite #include <SDL2/SDL_rwops.h> // Para SDL_RWFromFile, SDL_RWclose, SDL_RWwrite
#include <stddef.h> // Para NULL #include <stddef.h> // Para NULL
#include <iostream> // Para basic_ostream, operator<<, cout, endl #include <iostream> // Para basic_ostream, operator<<, cout, endl
#include "screen.h" // Para Screen #include "notifier.h" // Para Screen
#include "utils.h" // Para options_t #include "utils.h" // Para options_t
#include "options.h" #include "options.h"
#include <fstream> // Para fstream
// Constructor // Constructor
Cheevos::Cheevos(Screen *screen, std::string file) Cheevos::Cheevos(const std::string &file)
: file_(file)
{ {
// Copia la dirección de los objetos
this->screen = screen;
this->file = file;
// Inicializa los logros
init(); init();
loadFromFile();
// Inicializa variables
enabled = true;
// Carga el estado de los logros
load();
} }
// Destructor // Destructor
Cheevos::~Cheevos() Cheevos::~Cheevos()
{ {
// Guarda el estado de los logros saveToFile();
save();
cheevos.clear();
} }
// Inicializa los logros // Inicializa los logros
void Cheevos::init() void Cheevos::init()
{ {
cheevos.clear(); cheevos_.clear();
cheevos_.emplace_back(1, "SHINY THINGS", "Get 25% of the items", 2);
cheevos_t c; cheevos_.emplace_back(2, "HALF THE WORK", "Get 50% of the items", 2);
c.completed = false; cheevos_.emplace_back(3, "GETTING THERE", "Get 75% of the items", 2);
c.valid = true; cheevos_.emplace_back(4, "THE COLLECTOR", "Get 100% of the items", 2);
c.icon = 2; cheevos_.emplace_back(5, "WANDERING AROUND", "Visit 20 rooms", 2);
cheevos_.emplace_back(6, "I GOT LOST", "Visit 40 rooms", 2);
c.id = 1; cheevos_.emplace_back(7, "I LIKE TO EXPLORE", "Visit all rooms", 2);
c.caption = "SHINY THINGS"; cheevos_.emplace_back(8, "FINISH THE GAME", "Complete the game", 2);
c.description = "Get 25\% of the items"; cheevos_.emplace_back(9, "I WAS SUCKED BY A HOLE", "Complete the game without entering the jail", 2);
cheevos.push_back(c); cheevos_.emplace_back(10, "MY LITTLE PROJECTS", "Complete the game with all items", 2);
cheevos_.emplace_back(11, "I LIKE MY MULTICOLOURED FRIENDS", "Complete the game without dying", 2);
c.id = 2; cheevos_.emplace_back(12, "SHIT PROJECTS DONE FAST", "Complete the game in under 30 minutes", 2);
c.caption = "HALF THE WORK";
c.description = "Get 50\% of the items";
cheevos.push_back(c);
c.id = 3;
c.caption = "GETTING THERE";
c.description = "Get 75\% of the items";
cheevos.push_back(c);
c.id = 4;
c.caption = "THE COLLECTOR";
c.description = "Get 100\% of the items";
cheevos.push_back(c);
c.id = 5;
c.caption = "WANDERING AROUND";
c.description = "Visit 20 rooms";
cheevos.push_back(c);
c.id = 6;
c.caption = "I GOT LOST";
c.description = "Visit 40 rooms";
cheevos.push_back(c);
c.id = 7;
c.caption = "I LIKE TO EXPLORE";
c.description = "Visit all rooms";
cheevos.push_back(c);
c.id = 8;
c.caption = "FINISH THE GAME";
c.description = "Complete the game";
cheevos.push_back(c);
c.id = 9;
c.caption = "I WAS SUCKED BY A HOLE";
c.description = "Complete the game without entering the jail";
cheevos.push_back(c);
c.id = 10;
c.caption = "MY LITTLE PROJECTS";
c.description = "Complete the game with all items";
cheevos.push_back(c);
c.id = 11;
c.caption = "I LIKE MY MULTICOLOURED FRIENDS";
c.description = "Complete the game without dying";
cheevos.push_back(c);
c.id = 12;
c.caption = "SHIT PROJECTS DONE FAST";
c.description = "Complete the game in under 30 minutes";
cheevos.push_back(c);
} }
// Busca un logro por id y devuelve el indice // Busca un logro por id y devuelve el indice
int Cheevos::find(int id) int Cheevos::find(int id)
{ {
for (int i = 0; i < (int)cheevos.size(); ++i) for (int i = 0; i < (int)cheevos_.size(); ++i)
{ {
if (cheevos[i].id == id) if (cheevos_[i].id == id)
{ {
return i; return i;
} }
@@ -123,80 +59,49 @@ void Cheevos::unlock(int id)
{ {
const int index = find(id); const int index = find(id);
if (index == -1) // Si el índice es inválido, el logro no es válido, ya está completado o el sistema de logros no está habilitado, no hacemos nada
if (index == -1 || !cheevos_.at(index).valid || cheevos_.at(index).completed || !enabled_)
{ {
return; return;
} }
if (!cheevos[index].valid) // Marcar el logro como completado
{ cheevos_.at(index).completed = true;
return; // Mostrar notificación en la pantalla
} Notifier::get()->show("ACHIEVEMENT UNLOCKED!", cheevos_.at(index).caption, cheevos_.at(index).icon);
// Guardar el estado de los logros
if (cheevos[index].completed) saveToFile();
{
return;
}
if (!enabled)
{
return;
}
cheevos[index].completed = true;
screen->showNotification("ACHIEVEMENT UNLOCKED!", cheevos[index].caption, cheevos[index].icon);
save();
} }
// Invalida un logro // Invalida un logro
void Cheevos::invalidate(int id) void Cheevos::invalidate(int id)
{ {
const int index = find(id); const int index = find(id);
if (index == -1)
// Si el índice es válido, se invalida el logro
if (index != -1)
{ {
return; cheevos_.at(index).valid = false;
} }
cheevos[index].valid = false;
}
// Habilita o deshabilita los logros
void Cheevos::enable(bool value)
{
enabled = value;
}
// Carga el estado de los logros
void Cheevos::load()
{
// Carga el estado de los logros desde un fichero
loadFromFile();
}
// Guarda el estado de los logros
void Cheevos::save()
{
// Guarda el estado de los logros en un fichero
saveToFile();
} }
// Carga el estado de los logros desde un fichero // Carga el estado de los logros desde un fichero
void Cheevos::loadFromFile() void Cheevos::loadFromFile()
{ {
// Abre el fichero en modo lectura (binario) std::ifstream file(this->file_, std::ios::binary);
SDL_RWops *file = SDL_RWFromFile(this->file.c_str(), "r+b");
// El fichero no existe // El fichero no existe
if (file == NULL) if (!file)
{ {
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! Creating new file..." << std::endl;
} }
// Crea el fichero en modo escritura (binario) // Crea el fichero en modo escritura (binario)
file = SDL_RWFromFile(this->file.c_str(), "w+b"); std::ofstream newFile(this->file_, std::ios::binary);
if (file != NULL) if (newFile)
{ {
if (options.console) if (options.console)
{ {
@@ -204,37 +109,32 @@ void Cheevos::loadFromFile()
} }
// Guarda la información // Guarda la información
for (int i = 0; i < (int)cheevos.size(); ++i) for (const auto &cheevo : cheevos_)
{ {
SDL_RWwrite(file, &cheevos[i].completed, sizeof(bool), 1); newFile.write(reinterpret_cast<const char *>(&cheevo.completed), sizeof(bool));
} }
// Cierra el fichero
SDL_RWclose(file);
} }
else else
{ {
if (options.console) if (options.console)
{ {
std::cout << "Error: Unable to create file! SDL Error: " << SDL_GetError() << std::endl; std::cerr << "Error: Unable to create file!" << std::endl;
} }
} }
} }
// El fichero existe // El fichero existe
else else
{ {
// Carga los datos
if (options.console) if (options.console)
{ {
std::cout << "Reading file...!" << std::endl; std::cout << "Reading file...!" << std::endl;
} }
for (int i = 0; i < (int)cheevos.size(); ++i)
{
SDL_RWread(file, &cheevos[i].completed, sizeof(bool), 1);
}
// Cierra el fichero // Carga los datos
SDL_RWclose(file); for (auto &cheevo : cheevos_)
{
file.read(reinterpret_cast<char *>(&cheevo.completed), sizeof(bool));
}
} }
} }
@@ -242,13 +142,13 @@ void Cheevos::loadFromFile()
void Cheevos::saveToFile() void Cheevos::saveToFile()
{ {
// Abre el fichero en modo escritura (binario) // Abre el fichero en modo escritura (binario)
SDL_RWops *file = SDL_RWFromFile(this->file.c_str(), "w+b"); SDL_RWops *file = SDL_RWFromFile(this->file_.c_str(), "w+b");
if (file != NULL) if (file != NULL)
{ {
// Guarda la información // Guarda la información
for (int i = 0; i < (int)cheevos.size(); ++i) for (int i = 0; i < (int)cheevos_.size(); ++i)
{ {
SDL_RWwrite(file, &cheevos[i].completed, sizeof(bool), 1); SDL_RWwrite(file, &cheevos_[i].completed, sizeof(bool), 1);
} }
// Cierra el fichero // Cierra el fichero
@@ -263,32 +163,16 @@ void Cheevos::saveToFile()
} }
} }
// Lista los logros
std::vector<cheevos_t> Cheevos::list()
{
return cheevos;
}
// Devuelve el número total de logros desbloqueados // Devuelve el número total de logros desbloqueados
int Cheevos::unlocked() int Cheevos::unlocked()
{ {
int count = 0; int count = 0;
for (auto cheevo : cheevos) for (auto cheevo : cheevos_)
{ {
if (cheevo.completed) if (cheevo.completed)
{
count++; count++;
}
} }
return count; return count;
}
// Devuelve el número total de logros
int Cheevos::count()
{
return cheevos.size();
}
// Vuelve a cargar los logros desde el origen
void Cheevos::reload()
{
load();
} }

View File

@@ -1,11 +1,11 @@
#pragma once #pragma once
#include <string> // Para string #include <string> // Para string
#include <vector> // Para vector #include <vector> // Para vector
class Screen; class Screen;
struct options_t; struct options_t;
struct cheevos_t // Struct para los logros
struct Achievement
{ {
int id; // Identificador del logro int id; // Identificador del logro
std::string caption; // Texto con el nombre del logro std::string caption; // Texto con el nombre del logro
@@ -13,31 +13,29 @@ struct cheevos_t
int icon; // Indice del icono a utilizar en la notificación int icon; // Indice del icono a utilizar en la notificación
bool completed; // Indica si se ha obtenido el logro bool completed; // Indica si se ha obtenido el logro
bool valid; // Indica si se puede obtener el logro bool valid; // Indica si se puede obtener el logro
// Constructor vacío
Achievement() : id(0), icon(0), completed(false), valid(true) {}
// Constructor parametrizado
Achievement(int id, const std::string &caption, const std::string &description, int icon, bool completed = false, bool valid = true)
: id(id), caption(caption), description(description), icon(icon), completed(completed), valid(valid) {}
}; };
class Cheevos class Cheevos
{ {
private: private:
// Punteros y objetos
Screen *screen; // Objeto encargado de dibujar en pantalla
// Variables // Variables
std::vector<cheevos_t> cheevos; // Listado de logros std::vector<Achievement> cheevos_; // Listado de logros
bool enabled; // Indica si los logros se pueden obtener bool enabled_ = true; // Indica si los logros se pueden obtener
std::string file; // Fichero done leer/almacenar el estado de los logros std::string file_; // Fichero donde leer/almacenar el estado de los logros
// Inicializa los logros // Inicializa los logros
void init(); void init();
// Busca un logro por id y devuelve el indice // Busca un logro por id y devuelve el índice
int find(int id); int find(int id);
// Carga el estado de los logros
void load();
// Guarda el estado de los logros
void save();
// Carga el estado de los logros desde un fichero // Carga el estado de los logros desde un fichero
void loadFromFile(); void loadFromFile();
@@ -46,7 +44,7 @@ private:
public: public:
// Constructor // Constructor
Cheevos(Screen *screen, std::string file); Cheevos(const std::string &file);
// Destructor // Destructor
~Cheevos(); ~Cheevos();
@@ -58,17 +56,14 @@ public:
void invalidate(int id); void invalidate(int id);
// Habilita o deshabilita los logros // Habilita o deshabilita los logros
void enable(bool value); void enable(bool value) { enabled_ = value; }
// Lista los logros // Lista los logros
std::vector<cheevos_t> list(); std::vector<Achievement> list() { return cheevos_; }
// Devuelve el número total de logros desbloqueados // Devuelve el número total de logros desbloqueados
int unlocked(); int unlocked();
// Devuelve el número total de logros // Devuelve el número total de logros
int count(); int count() { return cheevos_.size(); }
};
// Vuelve a cargar los logros desde el origen
void reload();
};

View File

@@ -17,10 +17,10 @@
class Asset; class Asset;
// Constructor // Constructor
Credits::Credits(Resource *resource) Credits::Credits()
: screen_(Screen::get()), : screen_(Screen::get()),
renderer_(Screen::get()->getRenderer()), renderer_(Screen::get()->getRenderer()),
resource_(resource), resource_(Resource::get()),
asset_(Asset::get()), asset_(Asset::get()),
input_(Input::get()) input_(Input::get())
{ {
@@ -308,8 +308,7 @@ void Credits::update()
// Actualiza el contador // Actualiza el contador
updateCounter(); updateCounter();
// Actualiza las notificaciones screen_->update();
screen_->updateNotifier();
// Actualiza el sprite con el brillo // Actualiza el sprite con el brillo
if (counter_ > 770) if (counter_ > 770)

View File

@@ -68,7 +68,7 @@ private:
public: public:
// Constructor // Constructor
Credits(Resource *resource); Credits();
// Destructor // Destructor
~Credits(); ~Credits();

View File

@@ -7,6 +7,27 @@
#include "screen.h" #include "screen.h"
#include "asset.h" #include "asset.h"
// [SINGLETON]
Debug *Debug::debug_ = nullptr;
// [SINGLETON] Crearemos el objeto con esta función estática
void Debug::init()
{
Debug::debug_ = new Debug();
}
// [SINGLETON] Destruiremos el objeto con esta función estática
void Debug::destroy()
{
delete Debug::debug_;
}
// [SINGLETON] Con este método obtenemos el objeto y podemos trabajar con él
Debug *Debug::get()
{
return Debug::debug_;
}
// Constructor // Constructor
Debug::Debug() Debug::Debug()
// Copia la dirección de los objetos // Copia la dirección de los objetos

View File

@@ -13,6 +13,9 @@ class Texture;
class Debug class Debug
{ {
private: private:
// [SINGLETON] Objeto privado
static Debug *debug_;
// Objetos y punteros // Objetos y punteros
Screen *screen_; // Objeto encargado de dibujar en pantalla Screen *screen_; // Objeto encargado de dibujar en pantalla
SDL_Renderer *renderer_; // El renderizador de la ventana SDL_Renderer *renderer_; // El renderizador de la ventana
@@ -23,17 +26,26 @@ private:
// Variables // Variables
std::vector<std::string> slot_; // Vector con los textos a escribir std::vector<std::string> slot_; // Vector con los textos a escribir
std::vector<std::string> log_; // Vector con los textos a escribir std::vector<std::string> log_; // Vector con los textos a escribir
int x_ = 0; // Posicion donde escribir el texto de debug int x_ = 0; // Posicion donde escribir el texto de debug
int y_ = 0; // Posición donde escribir el texto de debug int y_ = 0; // Posición donde escribir el texto de debug
bool enabled_ = false; // Indica si esta activo el modo debug bool enabled_ = false; // Indica si esta activo el modo debug
public:
// Constructor // Constructor
Debug(); Debug();
// Destructor // Destructor
~Debug(); ~Debug();
public:
// [SINGLETON] Crearemos el objeto con esta función estática
static void init();
// [SINGLETON] Destruiremos el objeto con esta función estática
static void destroy();
// [SINGLETON] Con este método obtenemos el objeto y podemos trabajar con él
static Debug *get();
// Actualiza las variables // Actualiza las variables
void update(); void update();

View File

@@ -12,10 +12,16 @@
#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" #include "options.h"
class Debug; #include "debug.h"
// Constructor // Constructor
Demo::Demo(Resource *resource, Debug *debug) Demo::Demo()
: screen(Screen::get()),
renderer(Screen::get()->getRenderer()),
resource(Resource::get()),
asset(Asset::get()),
input(Input::get()),
debug(Debug::get())
{ {
// Inicia algunas variables // Inicia algunas variables
board.iniClock = SDL_GetTicks(); board.iniClock = SDL_GetTicks();
@@ -31,18 +37,10 @@ Demo::Demo(Resource *resource, Debug *debug)
roomIndex = 0; roomIndex = 0;
currentRoom = rooms[roomIndex]; currentRoom = rooms[roomIndex];
// Copia los punteros
this->resource = resource;
this->screen = Screen::get();
this->renderer = Screen::get()->getRenderer();
this->asset = Asset::get();
this->input = Input::get();
this->debug = debug;
// Crea los objetos // Crea los objetos
itemTracker = new ItemTracker(); itemTracker = new ItemTracker();
scoreboard = new ScoreBoard(renderer, resource, asset, &board); scoreboard = new Scoreboard(&board);
room = new Room(resource->getRoom(currentRoom), renderer, screen, asset, itemTracker, &board.items, false, debug); room = new Room(resource->getRoom(currentRoom), itemTracker, &board.items, false);
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);
@@ -162,8 +160,7 @@ void Demo::update()
screen->updateFX(); screen->updateFX();
checkRoomChange(); checkRoomChange();
// Actualiza las notificaciones screen->update();
screen->updateNotifier();
} }
} }
@@ -242,7 +239,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, itemTracker, &board.items, false, debug); room = new Room(resource->getRoom(file), itemTracker, &board.items, false);
// Pone el color del marcador en función del color del borde de la habitación // Pone el color del marcador en función del color del borde de la habitación
setScoreBoardColor(); setScoreBoardColor();

View File

@@ -21,15 +21,15 @@ class Demo
{ {
private: private:
// Objetos y punteros // Objetos y punteros
Screen *screen; // Objeto encargado de manejar el renderizador
SDL_Renderer *renderer; // El renderizador de la ventana SDL_Renderer *renderer; // El renderizador de la ventana
SDL_Event *eventHandler; // Manejador de eventos SDL_Event *eventHandler; // Manejador de eventos
Screen *screen; // Objeto encargado de manejar el renderizador
Room *room; // Objeto encargado de gestionar cada habitación del juego Room *room; // Objeto encargado de gestionar cada habitación del juego
Resource *resource; // Objeto con los recursos Resource *resource; // Objeto con los recursos
Asset *asset; // Objeto con la ruta a todos los ficheros de recursos Asset *asset; // Objeto con la ruta a todos los ficheros de recursos
Input *input; // Objeto pata gestionar la entrada Input *input; // Objeto pata gestionar la entrada
Text *text; // Objeto para los textos del juego Text *text; // Objeto para los textos del juego
ScoreBoard *scoreboard; // Objeto encargado de gestionar el marcador Scoreboard *scoreboard; // Objeto encargado de gestionar el marcador
ItemTracker *itemTracker; // Lleva el control de los objetos recogidos 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
@@ -75,7 +75,7 @@ private:
public: public:
// Constructor // Constructor
Demo(Resource *resource, Debug *debug); Demo();
// Destructor // Destructor
~Demo(); ~Demo();

View File

@@ -84,11 +84,11 @@ 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);
Resource::init();
Notifier::init(Asset::get()->get("notify.png"), Asset::get()->get("smb2.png"), Asset::get()->get("smb2.txt"), Asset::get()->get("notify.wav")); Notifier::init(Asset::get()->get("notify.png"), Asset::get()->get("smb2.png"), Asset::get()->get("smb2.txt"), Asset::get()->get("notify.wav"));
resource_ = new Resource();
Input::init(Asset::get()->get("gamecontrollerdb.txt")); Input::init(Asset::get()->get("gamecontrollerdb.txt"));
initInput(); initInput();
debug_ = new Debug(); Debug::init();
title_music_ = JA_LoadMusic(Asset::get()->get("title.ogg").c_str()); title_music_ = JA_LoadMusic(Asset::get()->get("title.ogg").c_str());
} }
@@ -97,13 +97,14 @@ Director::~Director()
// Guarda las opciones a un fichero // Guarda las opciones a un fichero
saveOptionsFromFile(Asset::get()->get("config.txt")); saveOptionsFromFile(Asset::get()->get("config.txt"));
// Libera la memoria // Destruye los singletones
Asset::destroy(); Asset::destroy();
Input::destroy(); Input::destroy();
Screen::destroy(); Screen::destroy();
Notifier::destroy(); Notifier::destroy();
delete debug_; Debug::destroy();
delete resource_; Resource::destroy();
JA_DeleteMusic(title_music_); JA_DeleteMusic(title_music_);
SDL_DestroyRenderer(renderer_); SDL_DestroyRenderer(renderer_);
@@ -223,7 +224,7 @@ void Director::loadResources(section_t section)
textureList.push_back("jailgames.png"); textureList.push_back("jailgames.png");
textureList.push_back("since_1998.png"); textureList.push_back("since_1998.png");
resource_->loadTextures(textureList); Resource::get()->loadTextures(textureList);
} }
else if (options.section.name == SECTION_LOADING_SCREEN) else if (options.section.name == SECTION_LOADING_SCREEN)
@@ -234,7 +235,7 @@ void Director::loadResources(section_t section)
textureList.push_back("loading_screen_bn_zxarne.png"); textureList.push_back("loading_screen_bn_zxarne.png");
textureList.push_back("loading_screen_color_zxarne.png"); textureList.push_back("loading_screen_color_zxarne.png");
resource_->loadTextures(textureList); Resource::get()->loadTextures(textureList);
} }
else if (options.section.name == SECTION_TITLE) else if (options.section.name == SECTION_TITLE)
@@ -247,14 +248,14 @@ void Director::loadResources(section_t section)
textureList.push_back("notify.png"); textureList.push_back("notify.png");
textureList.push_back("title_logo.png"); textureList.push_back("title_logo.png");
resource_->loadTextures(textureList); Resource::get()->loadTextures(textureList);
// Offsets // Offsets
std::vector<std::string> offsetsList; std::vector<std::string> offsetsList;
offsetsList.push_back("smb2.txt"); offsetsList.push_back("smb2.txt");
offsetsList.push_back("subatomic.txt"); offsetsList.push_back("subatomic.txt");
resource_->loadOffsets(offsetsList); Resource::get()->loadOffsets(offsetsList);
} }
else if (options.section.name == SECTION_CREDITS) else if (options.section.name == SECTION_CREDITS)
@@ -264,19 +265,19 @@ void Director::loadResources(section_t section)
textureList.push_back("shine.png"); textureList.push_back("shine.png");
textureList.push_back("smb2.png"); textureList.push_back("smb2.png");
resource_->loadTextures(textureList); Resource::get()->loadTextures(textureList);
// Animaciones // Animaciones
std::vector<std::string> animationList; std::vector<std::string> animationList;
animationList.push_back("shine.ani"); animationList.push_back("shine.ani");
resource_->loadAnimations(animationList); Resource::get()->loadAnimations(animationList);
// Offsets // Offsets
std::vector<std::string> offsetsList; std::vector<std::string> offsetsList;
offsetsList.push_back("smb2.txt"); offsetsList.push_back("smb2.txt");
resource_->loadOffsets(offsetsList); Resource::get()->loadOffsets(offsetsList);
} }
else if (options.section.name == SECTION_ENDING) else if (options.section.name == SECTION_ENDING)
@@ -295,13 +296,13 @@ void Director::loadResources(section_t section)
textureList.push_back("ending5_zxarne.png"); textureList.push_back("ending5_zxarne.png");
textureList.push_back("smb2.png"); textureList.push_back("smb2.png");
resource_->loadTextures(textureList); Resource::get()->loadTextures(textureList);
// Offsets // Offsets
std::vector<std::string> offsetsList; std::vector<std::string> offsetsList;
offsetsList.push_back("smb2.txt"); offsetsList.push_back("smb2.txt");
resource_->loadOffsets(offsetsList); Resource::get()->loadOffsets(offsetsList);
} }
else if (options.section.name == SECTION_ENDING2) else if (options.section.name == SECTION_ENDING2)
@@ -370,7 +371,7 @@ void Director::loadResources(section_t section)
// Player // Player
textureList.push_back("player.png"); textureList.push_back("player.png");
resource_->loadTextures(textureList); Resource::get()->loadTextures(textureList);
// Animaciones // Animaciones
std::vector<std::string> animationList; std::vector<std::string> animationList;
@@ -433,13 +434,13 @@ void Director::loadResources(section_t section)
// Player // Player
animationList.push_back("player.ani"); animationList.push_back("player.ani");
resource_->loadAnimations(animationList); Resource::get()->loadAnimations(animationList);
// Offsets // Offsets
std::vector<std::string> offsetsList; std::vector<std::string> offsetsList;
offsetsList.push_back("smb2.txt"); offsetsList.push_back("smb2.txt");
resource_->loadOffsets(offsetsList); Resource::get()->loadOffsets(offsetsList);
} }
else if (options.section.name == SECTION_GAME_OVER) else if (options.section.name == SECTION_GAME_OVER)
@@ -450,20 +451,20 @@ void Director::loadResources(section_t section)
textureList.push_back("player_game_over.png"); textureList.push_back("player_game_over.png");
textureList.push_back("tv.png"); textureList.push_back("tv.png");
resource_->loadTextures(textureList); Resource::get()->loadTextures(textureList);
// Animaciones // Animaciones
std::vector<std::string> animationList; std::vector<std::string> animationList;
animationList.push_back("player_game_over.ani"); animationList.push_back("player_game_over.ani");
animationList.push_back("tv.ani"); animationList.push_back("tv.ani");
resource_->loadAnimations(animationList); Resource::get()->loadAnimations(animationList);
// Offsets // Offsets
std::vector<std::string> offsetsList; std::vector<std::string> offsetsList;
offsetsList.push_back("smb2.txt"); offsetsList.push_back("smb2.txt");
resource_->loadOffsets(offsetsList); Resource::get()->loadOffsets(offsetsList);
} }
else if (options.section.name == SECTION_GAME || options.section.name == SECTION_DEMO) else if (options.section.name == SECTION_GAME || options.section.name == SECTION_DEMO)
@@ -551,7 +552,7 @@ void Director::loadResources(section_t section)
textureList.push_back("smb2.png"); textureList.push_back("smb2.png");
textureList.push_back("debug.png"); textureList.push_back("debug.png");
resource_->loadTextures(textureList); Resource::get()->loadTextures(textureList);
// Animaciones // Animaciones
std::vector<std::string> animationList; std::vector<std::string> animationList;
@@ -625,14 +626,14 @@ void Director::loadResources(section_t section)
animationList.push_back("wave.ani"); animationList.push_back("wave.ani");
animationList.push_back("z80.ani"); animationList.push_back("z80.ani");
resource_->loadAnimations(animationList); Resource::get()->loadAnimations(animationList);
// Offsets // Offsets
std::vector<std::string> offsetsList; std::vector<std::string> offsetsList;
offsetsList.push_back("smb2.txt"); offsetsList.push_back("smb2.txt");
offsetsList.push_back("debug.txt"); offsetsList.push_back("debug.txt");
resource_->loadOffsets(offsetsList); Resource::get()->loadOffsets(offsetsList);
// TileMaps // TileMaps
std::vector<std::string> tileMapList; std::vector<std::string> tileMapList;
@@ -697,7 +698,7 @@ void Director::loadResources(section_t section)
tileMapList.push_back("59.tmx"); tileMapList.push_back("59.tmx");
tileMapList.push_back("60.tmx"); tileMapList.push_back("60.tmx");
resource_->loadTileMaps(tileMapList); Resource::get()->loadTileMaps(tileMapList);
// Habitaciones // Habitaciones
std::vector<std::string> roomList; std::vector<std::string> roomList;
@@ -762,7 +763,7 @@ void Director::loadResources(section_t section)
roomList.push_back("59.room"); roomList.push_back("59.room");
roomList.push_back("60.room"); roomList.push_back("60.room");
resource_->loadRooms(roomList); Resource::get()->loadRooms(roomList);
} }
if (options.console) if (options.console)
@@ -1305,9 +1306,9 @@ void Director::runLogo()
std::cout << "\n* SECTION: LOGO" << std::endl; std::cout << "\n* SECTION: LOGO" << std::endl;
} }
loadResources(options.section); loadResources(options.section);
auto logo = std::make_unique<Logo>(resource_); auto logo = std::make_unique<Logo>();
logo->run(); logo->run();
resource_->free(); Resource::get()->free();
} }
// Ejecuta la seccion de juego de la pantalla de carga // Ejecuta la seccion de juego de la pantalla de carga
@@ -1318,9 +1319,9 @@ void Director::runLoadingScreen()
std::cout << "\n* SECTION: INTRO" << std::endl; std::cout << "\n* SECTION: INTRO" << std::endl;
} }
loadResources(options.section); loadResources(options.section);
auto loadingScreen = std::make_unique<LoadingScreen>(resource_); auto loadingScreen = std::make_unique<LoadingScreen>();
loadingScreen->run(); loadingScreen->run();
resource_->free(); Resource::get()->free();
} }
// Ejecuta la seccion de juego con el titulo y los menus // Ejecuta la seccion de juego con el titulo y los menus
@@ -1335,9 +1336,9 @@ void Director::runTitle()
JA_PlayMusic(title_music_); JA_PlayMusic(title_music_);
} }
loadResources(options.section); loadResources(options.section);
auto title = std::make_unique<Title>(resource_); auto title = std::make_unique<Title>();
title->run(); title->run();
resource_->free(); Resource::get()->free();
} }
// Ejecuta la seccion de los creditos del juego // Ejecuta la seccion de los creditos del juego
@@ -1348,9 +1349,9 @@ void Director::runCredits()
std::cout << "\n* SECTION: CREDITS" << std::endl; std::cout << "\n* SECTION: CREDITS" << std::endl;
} }
loadResources(options.section); loadResources(options.section);
auto credits = std::make_unique<Credits>(resource_); auto credits = std::make_unique<Credits>();
credits->run(); credits->run();
resource_->free(); Resource::get()->free();
} }
// Ejecuta la seccion de la demo, donde se ven pantallas del juego // Ejecuta la seccion de la demo, donde se ven pantallas del juego
@@ -1361,9 +1362,9 @@ void Director::runDemo()
std::cout << "\n* SECTION: DEMO" << std::endl; std::cout << "\n* SECTION: DEMO" << std::endl;
} }
loadResources(options.section); loadResources(options.section);
auto demo = std::make_unique<Demo>(resource_, debug_); auto demo = std::make_unique<Demo>();
demo->run(); demo->run();
resource_->free(); Resource::get()->free();
} }
// Ejecuta la seccion del final del juego // Ejecuta la seccion del final del juego
@@ -1374,9 +1375,9 @@ void Director::runEnding()
std::cout << "\n* SECTION: ENDING" << std::endl; std::cout << "\n* SECTION: ENDING" << std::endl;
} }
loadResources(options.section); loadResources(options.section);
auto ending = std::make_unique<Ending>(resource_); auto ending = std::make_unique<Ending>();
ending->run(); ending->run();
resource_->free(); Resource::get()->free();
} }
// Ejecuta la seccion del final del juego // Ejecuta la seccion del final del juego
@@ -1387,9 +1388,9 @@ void Director::runEnding2()
std::cout << "\n* SECTION: ENDING2" << std::endl; std::cout << "\n* SECTION: ENDING2" << std::endl;
} }
loadResources(options.section); loadResources(options.section);
auto ending2 = std::make_unique<Ending2>(resource_); auto ending2 = std::make_unique<Ending2>();
ending2->run(); ending2->run();
resource_->free(); Resource::get()->free();
} }
// Ejecuta la seccion del final de la partida // Ejecuta la seccion del final de la partida
@@ -1400,9 +1401,9 @@ void Director::runGameOver()
std::cout << "\n* SECTION: GAME OVER" << std::endl; std::cout << "\n* SECTION: GAME OVER" << std::endl;
} }
loadResources(options.section); loadResources(options.section);
auto gameOver = std::make_unique<GameOver>(resource_); auto gameOver = std::make_unique<GameOver>();
gameOver->run(); gameOver->run();
resource_->free(); Resource::get()->free();
} }
// Ejecuta la seccion de juego donde se juega // Ejecuta la seccion de juego donde se juega
@@ -1414,9 +1415,9 @@ void Director::runGame()
} }
JA_StopMusic(); JA_StopMusic();
loadResources(options.section); loadResources(options.section);
auto game = std::make_unique<Game>(resource_, debug_); auto game = std::make_unique<Game>();
game->run(); game->run();
resource_->free(); Resource::get()->free();
} }
int Director::run() int Director::run()

View File

@@ -19,9 +19,6 @@ private:
SDL_Window *window_; // La ventana donde dibujamos SDL_Window *window_; // La ventana donde dibujamos
SDL_Renderer *renderer_; // El renderizador de la ventana SDL_Renderer *renderer_; // El renderizador de la ventana
Resource *resource_; // Objeto con los recursos
Debug *debug_; // Objeto para gestionar la información de debug
// Variables // 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

View File

@@ -19,15 +19,13 @@
#include "options.h" #include "options.h"
// Constructor // Constructor
Ending::Ending(Resource *resource) Ending::Ending()
: screen(Screen::get()),
renderer(Screen::get()->getRenderer()),
resource(Resource::get()),
asset(Asset::get()),
input(Input::get())
{ {
// Copia los punteros
this->screen = Screen::get();
this->renderer = Screen::get()->getRenderer();
this->resource = resource;
this->asset = Asset::get();
this->input = Input::get();
// Reserva memoria para los punteros a objetos // Reserva memoria para los punteros a objetos
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);
@@ -122,8 +120,7 @@ void Ending::update()
// Actualiza el volumen de la musica // Actualiza el volumen de la musica
updateMusicVolume(); updateMusicVolume();
// Actualiza las notificaciones screen->update();
screen->updateNotifier();
} }
} }

View File

@@ -50,8 +50,8 @@ private:
}; };
// Objetos y punteros // Objetos y punteros
SDL_Renderer *renderer; // El renderizador de la ventana
Screen *screen; // Objeto encargado de dibujar en pantalla Screen *screen; // Objeto encargado de dibujar en pantalla
SDL_Renderer *renderer; // El renderizador de la ventana
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
@@ -115,7 +115,7 @@ private:
public: public:
// Constructor // Constructor
Ending(Resource *resource); Ending();
// Destructor // Destructor
~Ending(); ~Ending();

View File

@@ -16,15 +16,13 @@
#include "options.h" #include "options.h"
// Constructor // Constructor
Ending2::Ending2(Resource *resource) Ending2::Ending2()
: screen(Screen::get()),
renderer(Screen::get()->getRenderer()),
resource(Resource::get()),
asset(Asset::get()),
input(Input::get())
{ {
// Copia los punteros
this->screen = Screen::get();
this->renderer = Screen::get()->getRenderer();
this->resource = resource;
this->asset = Asset::get();
this->input = Input::get();
// Reserva memoria para los punteros a objetos // Reserva memoria para los punteros a objetos
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);
@@ -117,8 +115,7 @@ void Ending2::update()
// Actualiza el volumen de la musica // Actualiza el volumen de la musica
updateMusicVolume(); updateMusicVolume();
// Actualiza las notificaciones screen->update();
screen->updateNotifier();
} }
} }

View File

@@ -21,12 +21,12 @@ class Ending2
{ {
private: private:
// Objetos y punteros // Objetos y punteros
Asset *asset; // Objeto con los ficheros de recursos
Resource *resource; // Objeto con los recursos
Screen *screen; // Objeto encargado de dibujar en pantalla Screen *screen; // Objeto encargado de dibujar en pantalla
SDL_Event *eventHandler; // Manejador de eventos
SDL_Renderer *renderer; // El renderizador de la ventana SDL_Renderer *renderer; // El renderizador de la ventana
Resource *resource; // Objeto con los recursos
Asset *asset; // Objeto con los ficheros de recursos
Input *input; // Objeto pata gestionar la entrada Input *input; // Objeto pata gestionar la entrada
SDL_Event *eventHandler; // Manejador de eventos
Text *text; // Objeto para escribir texto en pantalla Text *text; // Objeto para escribir texto en pantalla
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
@@ -118,7 +118,7 @@ private:
public: public:
// Constructor // Constructor
Ending2(Resource *resource); Ending2();
// Destructor // Destructor
~Ending2(); ~Ending2();

View File

@@ -21,15 +21,16 @@
#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" #include "options.h"
#include "notifier.h"
// Constructor // Constructor
Game::Game(Resource *resource, Debug *debug) Game::Game()
: 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::get()),
debug_(debug) debug_(Debug::get())
{ {
// Inicia algunas variables // Inicia algunas variables
board_.iniClock = SDL_GetTicks(); board_.iniClock = SDL_GetTicks();
@@ -38,7 +39,7 @@ Game::Game(Resource *resource, Debug *debug)
const int x = 25; const int x = 25;
const int y = 13; const int y = 13;
spawn_point_ = {x * 8, y * 8, 0, 0, 0, s_standing, SDL_FLIP_HORIZONTAL}; spawn_point_ = {x * 8, y * 8, 0, 0, 0, s_standing, SDL_FLIP_HORIZONTAL};
debug->setEnabled(false); debug_->setEnabled(false);
#else #else
current_room_ = "03.room"; current_room_ = "03.room";
const int x = 25; const int x = 25;
@@ -47,17 +48,17 @@ Game::Game(Resource *resource, Debug *debug)
#endif #endif
// Crea los objetos // Crea los objetos
cheevos_ = new Cheevos(screen_, asset_->get("cheevos.bin")); cheevos_ = new Cheevos(asset_->get("cheevos.bin"));
scoreboard_ = new ScoreBoard(renderer_, resource, asset_, &board_); scoreboard_ = new Scoreboard(&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_, item_tracker_, &board_.items, false, debug); room_ = new Room(resource_->getRoom(current_room_), item_tracker_, &board_.items, false);
const std::string playerPNG = options.cheat.altSkin ? "player2.png" : "player.png"; const std::string 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_, input_, room_, debug}; const player_t player = {spawn_point_, playerPNG, playerANI, room_};
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")); stats_ = new Stats(asset_->get("stats.csv"), asset_->get("stats_buffer.csv"));
@@ -178,19 +179,19 @@ void Game::checkEvents()
break; break;
case SDL_SCANCODE_F6: case SDL_SCANCODE_F6:
screen_->showNotification("ACHIEVEMENT UNLOCKED!", "I LIKE MY MULTICOLOURED FRIENDS", 2); Notifier::get()->show("ACHIEVEMENT UNLOCKED!", "I LIKE MY MULTICOLOURED FRIENDS", 2);
break; break;
case SDL_SCANCODE_F7: case SDL_SCANCODE_F7:
screen_->showNotification("ACHIEVEMENT UNLOCKED!", "I LIKE MY MULTICOLOURED FRIENDS", 3); Notifier::get()->show("ACHIEVEMENT UNLOCKED!", "I LIKE MY MULTICOLOURED FRIENDS", 3);
break; break;
case SDL_SCANCODE_F8: case SDL_SCANCODE_F8:
screen_->showNotification("JAILDESIGNER IS LOGGED IN", "", 4); Notifier::get()->show("JAILDESIGNER IS LOGGED IN", "", 4);
break; break;
case SDL_SCANCODE_F9: case SDL_SCANCODE_F9:
screen_->showNotification("JAILDESIGNER IS LOGGED IN", "", 5); Notifier::get()->show("JAILDESIGNER IS LOGGED IN", "", 5);
break; break;
#endif #endif
default: default:
@@ -305,8 +306,7 @@ void Game::update()
updateBlackScreen(); updateBlackScreen();
// Actualiza las notificaciones screen_->update();
screen_->updateNotifier();
#ifdef DEBUG #ifdef DEBUG
updateDebugInfo(); updateDebugInfo();
@@ -401,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_, item_tracker_, &board_.items, board_.jailEnabled, debug_); room_ = new Room(resource_->getRoom(file), item_tracker_, &board_.items, board_.jailEnabled);
// Pone el nombre de la habitación en la textura // Pone el nombre de la habitación en la textura
fillRoomNameTexture(); fillRoomNameTexture();
@@ -509,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_, item_tracker_, &board_.items, board_.jailEnabled, debug_); room_ = new Room(resource_->getRoom(current_room_),item_tracker_, &board_.items, board_.jailEnabled);
const std::string playerPNG = options.cheat.altSkin ? "player2.png" : "player.png"; const std::string 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_, input_, room_, debug_}; const player_t player = {spawn_point_, playerPNG, playerANI, room_};
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

View File

@@ -37,7 +37,7 @@ private:
Asset *asset_; // Objeto con la ruta a todos los ficheros de recursos Asset *asset_; // Objeto con la ruta a todos los ficheros de recursos
Input *input_; // Objeto pata gestionar la entrada Input *input_; // Objeto pata gestionar la entrada
Text *text_; // Objeto para los textos del juego Text *text_; // Objeto para los textos del juego
ScoreBoard *scoreboard_; // Objeto encargado de gestionar el marcador Scoreboard *scoreboard_; // Objeto encargado de gestionar el marcador
Cheevos *cheevos_; // Objeto encargado de gestionar los logros del juego 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
@@ -149,7 +149,7 @@ private:
public: public:
// Constructor // Constructor
Game(Resource *resource, Debug *debug); Game();
// Destructor // Destructor
~Game(); ~Game();

View File

@@ -14,15 +14,13 @@
#include "options.h" #include "options.h"
// Constructor // Constructor
GameOver::GameOver(Resource *resource) GameOver::GameOver()
: screen(Screen::get()),
renderer(Screen::get()->getRenderer()),
resource(Resource::get()),
asset(Asset::get()),
input(Input::get())
{ {
// Copia los punteros
this->screen = Screen::get();
this->renderer = Screen::get()->getRenderer();
this->resource = resource;
this->asset = Asset::get();
this->input = Input::get();
// Reserva memoria para los punteros a objetos // Reserva memoria para los punteros a objetos
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);
@@ -87,8 +85,7 @@ void GameOver::update()
playerSprite->update(); playerSprite->update();
tvSprite->update(); tvSprite->update();
// Actualiza las notificaciones screen->update();
screen->updateNotifier();
} }
} }

View File

@@ -17,8 +17,8 @@ class GameOver
{ {
private: private:
// Objetos y punteros // Objetos y punteros
SDL_Renderer *renderer; // El renderizador de la ventana
Screen *screen; // Objeto encargado de dibujar en pantalla Screen *screen; // Objeto encargado de dibujar en pantalla
SDL_Renderer *renderer; // El renderizador de la ventana
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
@@ -65,7 +65,7 @@ private:
public: public:
// Constructor // Constructor
GameOver(Resource *resource); GameOver();
// Destructor // Destructor
~GameOver(); ~GameOver();

View File

@@ -13,10 +13,10 @@
#include "options.h" #include "options.h"
// Constructor // Constructor
LoadingScreen::LoadingScreen(Resource *resource) LoadingScreen::LoadingScreen()
: screen_(Screen::get()), : screen_(Screen::get()),
renderer_(Screen::get()->getRenderer()), renderer_(Screen::get()->getRenderer()),
resource_(resource), resource_(Resource::get()),
asset_(Asset::get()), asset_(Asset::get()),
input_(Input::get()) input_(Input::get())
{ {
@@ -24,13 +24,13 @@ LoadingScreen::LoadingScreen(Resource *resource)
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");
} }
mono_loading_screen_sprite_ = new Sprite(0, 0, mono_loading_screen_texture_->getWidth(), mono_loading_screen_texture_->getHeight(), mono_loading_screen_texture_, renderer_); mono_loading_screen_sprite_ = new Sprite(0, 0, mono_loading_screen_texture_->getWidth(), mono_loading_screen_texture_->getHeight(), mono_loading_screen_texture_, renderer_);
color_loading_screen_sprite_ = new Sprite(0, 0, color_loading_screen_texture_->getWidth(), color_loading_screen_texture_->getHeight(), color_loading_screen_texture_, renderer_); color_loading_screen_sprite_ = new Sprite(0, 0, color_loading_screen_texture_->getWidth(), color_loading_screen_texture_->getHeight(), color_loading_screen_texture_, renderer_);
@@ -251,8 +251,7 @@ void LoadingScreen::update()
// Gestiona el contador de carga // Gestiona el contador de carga
updateLoad(); updateLoad();
// Actualiza las notificaciones screen_->update();
screen_->updateNotifier();
} }
} }

View File

@@ -74,7 +74,7 @@ private:
public: public:
// Constructor // Constructor
LoadingScreen(Resource *resource); LoadingScreen();
// Destructor // Destructor
~LoadingScreen(); ~LoadingScreen();

View File

@@ -14,10 +14,10 @@
class Asset; // lines 11-11 class Asset; // lines 11-11
// Constructor // Constructor
Logo::Logo(Resource *resource) Logo::Logo()
: screen_(Screen::get()), : screen_(Screen::get()),
renderer_(Screen::get()->getRenderer()), renderer_(Screen::get()->getRenderer()),
resource_(resource), resource_(Resource::get()),
asset_(Asset::get()), asset_(Asset::get()),
input_(Input::get()) input_(Input::get())
{ {
@@ -268,8 +268,7 @@ void Logo::update()
// Gestiona el color de las texturas // Gestiona el color de las texturas
updateTextureColors(); updateTextureColors();
// Actualiza las notificaciones screen_->update();
screen_->updateNotifier();
// Comprueba si ha terminado el logo // Comprueba si ha terminado el logo
if (counter_ == end_logo_ + post_logo_) if (counter_ == end_logo_ + post_logo_)

View File

@@ -64,7 +64,7 @@ private:
public: public:
// Constructor // Constructor
Logo(Resource *resource); Logo();
// Destructor // Destructor
~Logo(); ~Logo();

View File

@@ -1,990 +0,0 @@
#include "menu.h"
#include <algorithm> // Para max
#include <fstream> // Para char_traits, basic_ostream, operator<<, basi...
#include <iostream> // Para cout
#include <sstream> // Para basic_stringstream
#include "asset.h" // Para Asset
#include "input.h" // Para Input, REPEAT_FALSE, inputs_e
#include "jail_audio.h" // Para JA_LoadSound, JA_PlaySound, JA_DeleteSound
#include "resource.h" // Para Resource
#include "text.h" // Para Text
// Constructor
Menu::Menu(SDL_Renderer *renderer, Resource *resource, Asset *asset, Input *input, std::string file)
{
// Copia punteros
this->renderer = renderer;
this->asset = asset;
this->input = input;
// Inicializa punteros
soundMove = nullptr;
soundAccept = nullptr;
soundCancel = nullptr;
// Inicializa variables
name = "";
selector.index = 0;
itemSelected = MENU_NO_OPTION;
x = 0;
y = 0;
w = 0;
rectBG.rect = {0, 0, 0, 0};
rectBG.color = {0, 0, 0};
rectBG.a = 0;
backgroundType = MENU_BACKGROUND_SOLID;
isCenteredOnX = false;
isCenteredOnY = false;
areElementsCenteredOnX = false;
centerX = 0;
centerY = 0;
widestItem = 0;
colorGreyed = {128, 128, 128};
defaultActionWhenCancel = 0;
font_png = "";
font_txt = "";
// Selector
selector.originY = 0;
selector.targetY = 0;
selector.despY = 0;
selector.originH = 0;
selector.targetH = 0;
selector.incH = 0;
selector.y = 0.0f;
selector.h = 0.0f;
selector.numJumps = 8;
selector.moving = false;
selector.resizing = false;
selector.rect = {0, 0, 0, 0};
selector.color = {0, 0, 0};
selector.itemColor = {0, 0, 0};
selector.a = 255;
// Inicializa las variables desde un fichero
if (file != "")
{
load(file);
}
// Deja el cursor en el primer elemento
reset();
}
Menu::~Menu()
{
renderer = nullptr;
asset = nullptr;
input = nullptr;
if (soundMove)
{
JA_DeleteSound(soundMove);
}
if (soundAccept)
{
JA_DeleteSound(soundAccept);
}
if (soundCancel)
{
JA_DeleteSound(soundCancel);
}
if (text != nullptr)
{
delete text;
}
}
// Carga la configuración del menu desde un archivo de texto
bool Menu::load(std::string file_path)
{
// Indicador de éxito en la carga
bool success = true;
// Indica si se ha creado ya el objeto de texto
bool textAllocated = false;
const std::string filename = file_path.substr(file_path.find_last_of("\\/") + 1);
std::string line;
std::ifstream file(file_path);
// El fichero se puede abrir
if (file.good())
{
// Procesa el fichero linea a linea
std::cout << "Reading file " << filename.c_str() << std::endl;
while (std::getline(file, line))
{
if (line == "[item]")
{
item_t item;
item.label = "";
item.hPaddingDown = 1;
item.selectable = true;
item.greyed = false;
item.linkedDown = false;
do
{
// Lee la siguiente linea
std::getline(file, line);
// Encuentra la posición del caracter '='
int pos = line.find("=");
// Procesa las dos subcadenas
if (!setItem(&item, line.substr(0, pos), line.substr(pos + 1, line.length())))
{
std::cout << "Warning: file " << filename.c_str() << "\n, unknown parameter \"" << line.substr(0, pos).c_str() << "\"" << std::endl;
success = false;
}
} while (line != "[/item]");
addItem(item.label, item.hPaddingDown, item.selectable, item.greyed, item.linkedDown);
}
// En caso contrario se parsea el fichero para buscar las variables y los valores
else
{
// Encuentra la posición del caracter '='
int pos = line.find("=");
// Procesa las dos subcadenas
if (!setVars(line.substr(0, pos), line.substr(pos + 1, line.length())))
{
std::cout << "Warning: file " << filename.c_str() << "\n, unknown parameter \"" << line.substr(0, pos).c_str() << "\"" << std::endl;
success = false;
}
// Crea el objeto text tan pronto como se pueda. Necesario para añadir items
if (font_png != "" && font_txt != "" && !textAllocated)
{
text = new Text(resource->getOffset(font_txt), resource->getTexture(font_png), renderer);
textAllocated = true;
}
}
}
// Cierra el fichero
std::cout << "Closing file " << filename.c_str() << std::endl;
file.close();
}
// El fichero no se puede abrir
else
{
std::cout << "Warning: Unable to open " << filename.c_str() << " file" << std::endl;
success = false;
}
return success;
}
// Asigna variables a partir de dos cadenas
bool Menu::setItem(item_t *item, std::string var, std::string value)
{
// Indicador de éxito en la asignación
bool success = true;
if (var == "text")
{
item->label = value;
}
else if (var == "hPaddingDown")
{
item->hPaddingDown = std::stoi(value);
}
else if (var == "selectable")
{
item->selectable = value == "true" ? true : false;
}
else if (var == "greyed")
{
item->greyed = value == "true" ? true : false;
}
else if (var == "linkedDown")
{
item->linkedDown = value == "true" ? true : false;
}
else if ((var == "") || (var == "[/item]"))
{
}
else
{
success = false;
}
return success;
}
// Asigna variables a partir de dos cadenas
bool Menu::setVars(std::string var, std::string value)
{
// Indicador de éxito en la asignación
bool success = true;
if (var == "font_png")
{
font_png = value;
}
else if (var == "font_txt")
{
font_txt = value;
}
else if (var == "sound_cancel")
{
soundCancel = JA_LoadSound(asset->get(value).c_str());
}
else if (var == "sound_accept")
{
soundAccept = JA_LoadSound(asset->get(value).c_str());
}
else if (var == "sound_move")
{
soundMove = JA_LoadSound(asset->get(value).c_str());
}
else if (var == "name")
{
name = value;
}
else if (var == "x")
{
x = std::stoi(value);
}
else if (var == "centerX")
{
centerX = std::stoi(value);
}
else if (var == "centerY")
{
centerY = std::stoi(value);
}
else if (var == "y")
{
y = std::stoi(value);
}
else if (var == "backgroundType")
{
backgroundType = std::stoi(value);
}
else if (var == "backgroundColor")
{
// Se introducen los valores separados por comas en un vector
std::stringstream ss(value);
std::string tmp;
getline(ss, tmp, ',');
rectBG.color.r = std::stoi(tmp);
getline(ss, tmp, ',');
rectBG.color.g = std::stoi(tmp);
getline(ss, tmp, ',');
rectBG.color.b = std::stoi(tmp);
getline(ss, tmp, ',');
rectBG.a = std::stoi(tmp);
}
else if (var == "selector_color")
{
// Se introducen los valores separados por comas en un vector
std::stringstream ss(value);
std::string tmp;
getline(ss, tmp, ',');
selector.color.r = std::stoi(tmp);
getline(ss, tmp, ',');
selector.color.g = std::stoi(tmp);
getline(ss, tmp, ',');
selector.color.b = std::stoi(tmp);
getline(ss, tmp, ',');
selector.a = std::stoi(tmp);
}
else if (var == "selector_text_color")
{
// Se introducen los valores separados por comas en un vector
std::stringstream ss(value);
std::string tmp;
getline(ss, tmp, ',');
selector.itemColor.r = std::stoi(tmp);
getline(ss, tmp, ',');
selector.itemColor.g = std::stoi(tmp);
getline(ss, tmp, ',');
selector.itemColor.b = std::stoi(tmp);
}
else if (var == "areElementsCenteredOnX")
{
areElementsCenteredOnX = value == "true" ? true : false;
}
else if (var == "isCenteredOnX")
{
isCenteredOnX = value == "true" ? true : false;
}
else if (var == "isCenteredOnY")
{
isCenteredOnY = value == "true" ? true : false;
}
else if (var == "defaultActionWhenCancel")
{
defaultActionWhenCancel = std::stoi(value);
}
else if (var == "")
{
}
else
{
success = false;
}
return success;
}
// Carga los ficheros de audio
void Menu::loadAudioFile(std::string file, int sound)
{
switch (sound)
{
case SOUND_ACCEPT:
soundAccept = JA_LoadSound(file.c_str());
break;
case SOUND_CANCEL:
soundCancel = JA_LoadSound(file.c_str());
break;
case SOUND_MOVE:
soundMove = JA_LoadSound(file.c_str());
break;
default:
break;
}
}
// Obtiene el nombre del menu
std::string Menu::getName()
{
return name;
}
// Obtiene el valor de la variable
int Menu::getItemSelected()
{
// Al llamar a esta funcion, se obtiene el valor y se borra
const int temp = itemSelected;
itemSelected = MENU_NO_OPTION;
return temp;
}
// Actualiza la posicion y el estado del selector
void Menu::updateSelector()
{
if (selector.moving)
{
// Calcula el desplazamiento en Y
selector.y += selector.despY;
if (selector.despY > 0) // Va hacia abajo
{
if (selector.y > selector.targetY) // Ha llegado al destino
{
selector.originY = selector.y = selector.targetY;
selector.moving = false;
}
}
else if (selector.despY < 0) // Va hacia arriba
{
if (selector.y < selector.targetY) // Ha llegado al destino
{
selector.originY = selector.y = selector.targetY;
selector.moving = false;
}
}
selector.rect.y = int(selector.y);
}
else
{
selector.rect.y = int(selector.y);
}
if (selector.resizing)
{
// Calcula el incremento en H
selector.h += selector.incH;
if (selector.incH > 0) // Crece
{
if (selector.h > selector.targetH) // Ha llegado al destino
{
// selector.originH = selector.targetH = selector.rect.h = getSelectorHeight(selector.index);
selector.originH = selector.h = selector.targetH;
selector.resizing = false;
}
}
else if (selector.incH < 0) // Decrece
{
if (selector.h < selector.targetH) // Ha llegado al destino
{
// selector.originH = selector.targetH = selector.rect.h = getSelectorHeight(selector.index);
selector.originH = selector.h = selector.targetH;
selector.resizing = false;
}
}
selector.rect.h = int(selector.h);
}
else
{
selector.rect.h = getSelectorHeight(selector.index);
}
}
// Coloca el selector en una posición específica
void Menu::setSelectorPos(int index)
{
if (index < (int)item.size())
{
selector.index = index;
selector.rect.y = selector.y = selector.originY = selector.targetY = item[selector.index].rect.y;
selector.rect.w = rectBG.rect.w;
selector.rect.x = rectBG.rect.x;
selector.originH = selector.targetH = selector.rect.h = getSelectorHeight(selector.index);
selector.moving = false;
selector.resizing = false;
}
}
// Obtiene la anchura del elemento más ancho del menu
int Menu::getWidestItem()
{
int result = 0;
// Obtenemos la anchura del item mas ancho
for (auto &i : item)
{
result = std::max(result, i.rect.w);
}
return result;
}
// Deja el menu apuntando al primer elemento
void Menu::reset()
{
itemSelected = MENU_NO_OPTION;
selector.index = 0;
selector.originY = selector.targetY = selector.y = item[0].rect.y;
selector.originH = selector.targetH = item[0].rect.h;
selector.moving = false;
selector.resizing = false;
// Si el primer elemento no es seleccionable, incrementa el selector
if (!item[selector.index].selectable)
{
increaseSelectorIndex();
setSelectorPos(selector.index);
}
}
// Actualiza el menu para recolocarlo correctamente y establecer el tamaño
void Menu::reorganize()
{
setRectSize();
if (isCenteredOnX)
{
centerMenuOnX(centerX);
}
if (isCenteredOnY)
{
centerMenuOnY(centerY);
}
if (areElementsCenteredOnX)
{
centerMenuElementsOnX();
}
}
// Deja el menu apuntando al siguiente elemento
bool Menu::increaseSelectorIndex()
{
// Obten las coordenadas del elemento actual
selector.y = selector.originY = item[selector.index].rect.y;
selector.h = selector.originH = getSelectorHeight(selector.index);
// Calcula cual es el siguiente elemento
++selector.index %= item.size();
while (!item[selector.index].selectable)
{
++selector.index %= item.size();
}
// Establece las coordenadas y altura de destino
selector.targetY = item[selector.index].rect.y;
selector.despY = (selector.targetY - selector.originY) / selector.numJumps;
selector.targetH = getSelectorHeight(selector.index);
selector.incH = (selector.targetH - selector.originH) / selector.numJumps;
selector.moving = true;
if (selector.incH != 0)
{
selector.resizing = true;
}
return true;
}
// Deja el menu apuntando al elemento anterior
bool Menu::decreaseSelectorIndex()
{
// Obten las coordenadas del elemento actual
selector.y = selector.originY = item[selector.index].rect.y;
selector.h = selector.originH = getSelectorHeight(selector.index);
// Calcula cual es el siguiente elemento
if (selector.index == 0)
{
selector.index = item.size() - 1;
}
else
{
selector.index--;
}
while (!item[selector.index].selectable)
{
if (selector.index == 0)
{
selector.index = item.size() - 1;
}
else
{
selector.index--;
}
}
// Establece las coordenadas y altura de destino
selector.targetY = item[selector.index].rect.y;
selector.despY = (selector.targetY - selector.originY) / selector.numJumps;
selector.targetH = getSelectorHeight(selector.index);
selector.incH = (selector.targetH - selector.originH) / selector.numJumps;
selector.moving = true;
if (selector.incH != 0)
{
selector.resizing = true;
}
return true;
}
// Actualiza la logica del menu
void Menu::update()
{
checkInput();
updateSelector();
}
// Pinta el menu en pantalla
void Menu::render()
{
// Rendereritza el fondo del menu
if (backgroundType == MENU_BACKGROUND_SOLID)
{
SDL_SetRenderDrawColor(renderer, rectBG.color.r, rectBG.color.g, rectBG.color.b, rectBG.a);
SDL_RenderFillRect(renderer, &rectBG.rect);
}
// Renderiza el rectangulo del selector
const SDL_Rect temp = {selector.rect.x, selector.rect.y - 1, selector.rect.w, selector.rect.h + 1};
SDL_SetRenderDrawColor(renderer, selector.color.r, selector.color.g, selector.color.b, selector.a);
SDL_RenderFillRect(renderer, &temp);
// Renderiza el borde del fondo
if (backgroundType == MENU_BACKGROUND_SOLID)
{
SDL_SetRenderDrawColor(renderer, rectBG.color.r, rectBG.color.g, rectBG.color.b, 255);
SDL_RenderDrawRect(renderer, &rectBG.rect);
}
// Renderiza el texto
for (int i = 0; i < (int)item.size(); ++i)
{
if (i == selector.index)
{
const color_t color = {selector.itemColor.r, selector.itemColor.g, selector.itemColor.b};
text->writeColored(item[i].rect.x, item[i].rect.y, item[i].label, color);
}
else if (item[i].selectable)
{
text->write(item[i].rect.x, item[i].rect.y, item[i].label);
}
else if (item[i].greyed)
{
text->writeColored(item[i].rect.x, item[i].rect.y, item[i].label, colorGreyed);
}
else
{ // No seleccionable
if ((item[i].linkedUp) && (i == selector.index + 1))
{
const color_t color = {selector.itemColor.r, selector.itemColor.g, selector.itemColor.b};
text->writeColored(item[i].rect.x, item[i].rect.y, item[i].label, color);
}
else // No enlazado con el de arriba
{
text->write(item[i].rect.x, item[i].rect.y, item[i].label);
}
}
}
}
// Establece el rectangulo de fondo del menu y el selector
void Menu::setRectSize(int w, int h)
{
// Establece el ancho
if (w == 0)
{ // Si no se pasa un valor, se busca si hay uno prefijado
if (this->w == 0)
{ // Si no hay prefijado, coge el item mas ancho
rectBG.rect.w = findWidth() + text->getCharacterSize();
}
else
{ // Si hay prefijado, coge ese
rectBG.rect.w = this->w;
}
}
else
{ // Si se pasa un valor, se usa y se prefija
rectBG.rect.w = w;
this->w = w;
}
// Establece el alto
if (h == 0)
{ // Si no se pasa un valor, se busca de manera automatica
rectBG.rect.h = findHeight() + text->getCharacterSize();
}
else
{ // Si se pasa un valor, se aplica
rectBG.rect.h = h;
}
// La posición X es la del menú menos medio caracter
if (this->w != 0)
{ // Si el ancho esta prefijado, la x coinccide
rectBG.rect.x = x;
}
else
{ // Si el ancho es automatico, se le da un poco de margen
rectBG.rect.x = x - (text->getCharacterSize() / 2);
}
// La posición Y es la del menu menos la altura de medio caracter
rectBG.rect.y = y - (text->getCharacterSize() / 2);
// Establecemos los valores del rectangulo del selector a partir de los valores del rectangulo de fondo
setSelectorPos(selector.index);
}
// Establece el color del rectangulo de fondo
void Menu::setBackgroundColor(color_t color, int alpha)
{
rectBG.color = color;
rectBG.a = alpha;
}
// Establece el color del rectangulo del selector
void Menu::setSelectorColor(color_t color, int alpha)
{
selector.color = color;
selector.a = alpha;
}
// Establece el color del texto del selector
void Menu::setSelectorTextColor(color_t color)
{
selector.itemColor = color;
}
// Centra el menu respecto un punto en el eje X
void Menu::centerMenuOnX(int value)
{
isCenteredOnX = true;
if (value != 0)
{
centerX = value;
}
else if (centerX == 0)
{
return;
}
// Establece la nueva posición centrada en funcion del elemento más ancho o del ancho fijo del menu
if (w != 0)
{ // Si se ha definido un ancho fijo
x = (centerX) - (w / 2);
}
else
{ // Si se actua en función del elemento más ancho
x = (centerX) - (findWidth() / 2);
}
// Actualiza el rectangulo de fondo y del selector
rectBG.rect.x = x;
selector.rect.x = x;
// Reposiciona los elementos del menu
for (auto &i : item)
{
i.rect.x = x;
}
// Recalcula el rectangulo de fondo
setRectSize();
// Vuelve a centrar los elementos si fuera el caso
if (areElementsCenteredOnX)
{
centerMenuElementsOnX();
}
}
// Centra el menu respecto un punto en el eje Y
void Menu::centerMenuOnY(int value)
{
isCenteredOnY = true;
centerY = value;
// Establece la nueva posición centrada en funcion del elemento más ancho
y = (value) - (findHeight() / 2);
// Reposiciona los elementos del menu
replaceElementsOnY();
// Recalcula el rectangulo de fondo
setRectSize();
}
// Centra los elementos del menu en el eje X
void Menu::centerMenuElementsOnX()
{
areElementsCenteredOnX = true;
for (auto &i : item)
{
i.rect.x = (centerX - (i.rect.w / 2));
}
}
// Añade un item al menu
void Menu::addItem(std::string text, int hPaddingDown, bool selectable, bool greyed, bool linkedDown)
{
item_t temp;
if (item.empty())
{ // Si es el primer item coge la posición en el eje Y del propio menu
temp.rect.y = y;
}
else
{ // En caso contrario, coge la posición en el eje Y a partir del último elemento
temp.rect.y = item.back().rect.y + item.back().rect.h + item.back().hPaddingDown;
}
temp.rect.x = x;
temp.hPaddingDown = hPaddingDown;
temp.selectable = selectable;
temp.greyed = greyed;
temp.linkedDown = linkedDown;
item.push_back(temp);
setItemCaption(item.size() - 1, text);
if (item.size() > 1)
{
if (item[item.size() - 2].linkedDown)
{
item.back().linkedUp = true;
}
}
centerX = x + (findWidth() / 2);
reorganize();
}
// Cambia el texto de un item
void Menu::setItemCaption(int index, std::string text)
{
item[index].label = text;
item[index].rect.w = this->text->lenght(item[index].label);
item[index].rect.h = this->text->getCharacterSize();
reorganize();
}
// Establece el indice del itemm que se usará por defecto al cancelar el menu
void Menu::setDefaultActionWhenCancel(int item)
{
defaultActionWhenCancel = item;
}
// Gestiona la entrada de teclado y mando durante el menu
void Menu::checkInput()
{
if (input->checkInput(input_up, REPEAT_FALSE))
{
if (decreaseSelectorIndex())
{
if (soundMove)
{
JA_PlaySound(soundMove);
}
}
}
if (input->checkInput(input_down, REPEAT_FALSE))
{
if (increaseSelectorIndex())
{
if (soundMove)
{
JA_PlaySound(soundMove);
}
}
}
if (input->checkInput(input_accept, REPEAT_FALSE))
{
itemSelected = selector.index;
if (soundAccept)
{
JA_PlaySound(soundAccept);
}
}
if (input->checkInput(input_cancel, REPEAT_FALSE))
{
itemSelected = defaultActionWhenCancel;
if (soundCancel)
{
JA_PlaySound(soundCancel);
}
}
}
// Calcula el ancho del menu
int Menu::findWidth()
{
return getWidestItem();
}
// Calcula el alto del menu
int Menu::findHeight()
{
int height = 0;
// Obtenemos la altura de la suma de alturas de los items
for (auto &i : item)
{
height += i.rect.h + i.hPaddingDown;
}
return height - item.back().hPaddingDown;
}
// Recoloca los elementos del menu en el eje Y
void Menu::replaceElementsOnY()
{
item[0].rect.y = y;
for (int i = 1; i < (int)item.size(); i++)
{
item[i].rect.y = item[i - 1].rect.y + item[i - 1].rect.h + item[i - 1].hPaddingDown;
}
}
// Establece el estado seleccionable de un item
void Menu::setSelectable(int index, bool value)
{
item[index].selectable = value;
}
// Establece el estado agrisado de un item
void Menu::setGreyed(int index, bool value)
{
item[index].greyed = value;
}
// Establece el estado de enlace de un item
void Menu::setLinkedDown(int index, bool value)
{
item[index].linkedDown = value;
}
// Calcula la altura del selector
int Menu::getSelectorHeight(int value)
{
if (item[value].linkedDown)
{
return item[value].rect.h + item[value].hPaddingDown + item[value + 1].rect.h;
}
else
{
return item[value].rect.h;
}
}
// Establece el nombre del menu
void Menu::setName(std::string name)
{
this->name = name;
}
// Establece la posición del menu
void Menu::setPos(int x, int y)
{
this->x = x;
this->y = y;
}
// Establece el tipo de fondo del menu
void Menu::setBackgroundType(int value)
{
backgroundType = value;
}
// Establece la fuente de texto que se utilizará
void Menu::setText(std::string font_png, std::string font_txt)
{
if (!text)
{
text = new Text(resource->getOffset(font_txt), resource->getTexture(font_png), renderer);
}
}

View File

@@ -1,220 +0,0 @@
#pragma once
#include <SDL2/SDL_rect.h> // Para SDL_Rect
#include <SDL2/SDL_render.h> // Para SDL_Renderer
#include <string> // Para string, basic_string
#include <vector> // Para vector
#include "utils.h" // Para color_t
class Asset;
class Input;
class Resource;
class Text;
struct JA_Sound_t;
// Tipos de fondos para el menú
constexpr int MENU_BACKGROUND_TRANSPARENT = 0;
constexpr int MENU_BACKGROUND_SOLID = 1;
// Tipos de archivos de audio
constexpr int SOUND_ACCEPT = 0;
constexpr int SOUND_MOVE = 1;
constexpr int SOUND_CANCEL = 2;
// Opciones de menú
constexpr int MENU_NO_OPTION = -1;
// Clase Menu
class Menu
{
private:
struct rectangle_t
{
SDL_Rect rect; // Rectangulo
color_t color; // Color
int a; // Transparencia
};
struct item_t
{
std::string label; // Texto
SDL_Rect rect; // Rectangulo que delimita el elemento
int hPaddingDown; // Espaciado bajo el elemento
bool selectable; // Indica si se puede seleccionar
bool greyed; // Indica si ha de aparecer con otro color mas oscuro
bool linkedDown; // Indica si el elemento actual y el siguiente se tratan como uno solo. Afecta al selector
bool linkedUp; // Indica si el elemento actual y el anterior se tratan como uno solo. Afecta al selector
};
struct selector_t
{
float originY; // Coordenada de origen
float targetY; // Coordenada de destino
float despY; // Cantidad de pixeles que se desplaza el selector en cada salto: (target - origin) / numJumps
bool moving; // Indica si el selector está avanzando hacia el destino
float originH; // Altura de origen
float targetH; // Altura de destino
float incH; // Cantidad de pixels que debe incrementar o decrementar el selector en cada salto
bool resizing; // Indica si el selector está cambiando de tamaño
float y; // Coordenada actual, usado para el desplazamiento
float h; // Altura actual, usado para el cambio de tamaño
int numJumps; // Numero de pasos preestablecido para llegar al destino
int index; // Elemento del menu que tiene el foco
SDL_Rect rect; // Rectangulo del selector
color_t color; // Color del selector
color_t itemColor; // Color del item
int a; // Cantidad de transparencia para el rectangulo del selector
};
// Objetos y punteros
SDL_Renderer *renderer; // Puntero al renderizador de la ventana
Resource *resource; // Objeto con los recursos
Asset *asset; // Objeto para gestionar los ficheros de recursos
Text *text; // Texto para poder escribir los items del menu
Input *input; // Gestor de eventos de entrada de teclado o gamepad
// Variables
std::string name; // Nombre del menu
int x; // Posición en el eje X de la primera letra del primer elemento
int y; // Posición en el eje Y de la primera letra del primer elemento
int h; // Altura del menu
int w; // Anchura del menu
int itemSelected; // Índice del item del menu que ha sido seleccionado
int defaultActionWhenCancel; // Indice del item del menu que se selecciona cuando se cancela el menu
int backgroundType; // Tipo de fondo para el menu
int centerX; // Centro del menu en el eje X
int centerY; // Centro del menu en el eje Y
bool isCenteredOnX; // Variable para saber si el menu debe estar centrado respecto a un punto en el eje X
bool isCenteredOnY; // Variable para saber si el menu debe estar centrado respecto a un punto en el eje Y
bool areElementsCenteredOnX; // Variable para saber si los elementos van centrados en el eje X
int widestItem; // Anchura del elemento más ancho
JA_Sound_t *soundAccept; // Sonido al aceptar o elegir una opción del menu
JA_Sound_t *soundCancel; // Sonido al cancelar el menu
JA_Sound_t *soundMove; // Sonido al mover el selector
color_t colorGreyed; // Color para los elementos agrisados
rectangle_t rectBG; // Rectangulo de fondo del menu
std::vector<item_t> item; // Estructura para cada elemento del menu
selector_t selector; // Variables para pintar el selector del menu
std::string font_png;
std::string font_txt;
// Carga la configuración del menu desde un archivo de texto
bool load(std::string file_path);
// Asigna variables a partir de dos cadenas
bool setVars(std::string var, std::string value);
// Asigna variables a partir de dos cadenas
bool setItem(item_t *item, std::string var, std::string value);
// Actualiza el menu para recolocarlo correctamente y establecer el tamaño
void reorganize();
// Deja el menu apuntando al siguiente elemento
bool increaseSelectorIndex();
// Deja el menu apuntando al elemento anterior
bool decreaseSelectorIndex();
// Actualiza la posicion y el estado del selector
void updateSelector();
// Obtiene la anchura del elemento más ancho del menu
int getWidestItem();
// Gestiona la entrada de teclado y mando durante el menu
void checkMenuInput(Menu *menu);
// Calcula el ancho del menu
int findWidth();
// Calcula el alto del menu
int findHeight();
// Recoloca los elementos del menu en el eje Y
void replaceElementsOnY();
// Calcula la altura del selector
int getSelectorHeight(int value);
public:
// Constructor
Menu(SDL_Renderer *renderer, Resource *resource, Asset *asset, Input *input, std::string file = "");
// Destructor
~Menu();
// Carga los ficheros de audio
void loadAudioFile(std::string file, int sound);
// Obtiene el nombre del menu
std::string getName();
// Obtiene el valor de la variable
int getItemSelected();
// Deja el menu apuntando al primer elemento
void reset();
// Gestiona la entrada de teclado y mando durante el menu
void checkInput();
// Actualiza la logica del menu
void update();
// Pinta el menu en pantalla
void render();
// Establece el color del rectangulo de fondo
void setBackgroundColor(color_t color, int alpha);
// Establece el color del rectangulo del selector
void setSelectorColor(color_t color, int alpha);
// Establece el color del texto del selector
void setSelectorTextColor(color_t color);
// Centra el menu respecto a un punto en el eje X
void centerMenuOnX(int value = 0);
// Centra el menu respecto a un punto en el eje Y
void centerMenuOnY(int value);
// Centra los elementos del menu en el eje X
void centerMenuElementsOnX();
// Añade un item al menu
void addItem(std::string text, int hPaddingDown = 1, bool selectable = true, bool greyed = false, bool linkedDown = false);
// Cambia el texto de un item
void setItemCaption(int index, std::string text);
// Establece el indice del item que se usará por defecto al cancelar el menu
void setDefaultActionWhenCancel(int item);
// Coloca el selector en una posición específica
void setSelectorPos(int index);
// Establece el estado seleccionable de un item
void setSelectable(int index, bool value);
// Establece el estado agrisado de un item
void setGreyed(int index, bool value);
// Establece el estado de enlace de un item
void setLinkedDown(int index, bool value);
// Establece el nombre del menu
void setName(std::string name);
// Establece la posición del menu
void setPos(int x, int y);
// Establece el tipo de fondo del menu
void setBackgroundType(int value);
// Establece la fuente de texto que se utilizará
void setText(std::string font_png, std::string font_txt);
// Establece el rectangulo de fondo del menu
void setRectSize(int w = 0, int h = 0);
};

View File

@@ -63,9 +63,12 @@ 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) if (active())
{ {
notifications_[i].sprite->render(); for (auto it = notifications_.rbegin(); it != notifications_.rend(); ++it)
{
it->sprite->render();
}
} }
} }
@@ -172,7 +175,7 @@ void Notifier::clearFinishedNotifications()
} }
// Muestra una notificación de texto por pantalla; // Muestra una notificación de texto por pantalla;
void Notifier::showText(std::string text1, std::string text2, int icon) void Notifier::show(std::string text1, std::string text2, int icon)
{ {
// Inicializa variables // Inicializa variables
const int iconSize = 16; const int iconSize = 16;
@@ -296,15 +299,4 @@ void Notifier::showText(std::string text1, std::string text2, int icon)
// Añade la notificación a la lista // Añade la notificación a la lista
notifications_.push_back(n); notifications_.push_back(n);
}
// Indica si hay notificaciones activas
bool Notifier::active()
{
if ((int)notifications_.size() > 0)
{
return true;
}
return false;
} }

View File

@@ -88,8 +88,8 @@ public:
void update(); void update();
// Muestra una notificación de texto por pantalla; // Muestra una notificación de texto por pantalla;
void showText(std::string text1 = "", std::string text2 = "", int icon = -1); void show(std::string text1 = "", std::string text2 = "", int icon = -1);
// Indica si hay notificaciones activas // Getters
bool active(); bool active() const { return !notifications_.empty(); }
}; };

View File

@@ -13,20 +13,19 @@
#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" #include "options.h"
#include "screen.h"
// Constructor // Constructor
Player::Player(player_t player) Player::Player(player_t player)
: renderer_(Screen::get()->getRenderer()),
input_(Input::get()),
resource_(Resource::get()),
asset_(Asset::get()),
room_(player.room),
debug_(Debug::get())
{ {
// Obten punteros a objetos
this->resource = player.resource;
this->asset = player.asset;
this->renderer = player.renderer;
this->input = player.input;
this->room = player.room;
this->debug = player.debug;
// Crea objetos // Crea objetos
sprite = new AnimatedSprite(renderer, resource->getAnimation(player.animation)); sprite_ = new AnimatedSprite(renderer_, resource_->getAnimation(player.animation));
// Inicializa variables // Inicializa variables
reLoadPalette(); reLoadPalette();
@@ -49,14 +48,14 @@ Player::Player(player_t player)
h = 16; h = 16;
maxVY = 1.2f; maxVY = 1.2f;
sprite->setPosX(player.spawn.x); sprite_->setPosX(player.spawn.x);
sprite->setPosY(player.spawn.y); sprite_->setPosY(player.spawn.y);
sprite->setWidth(8); sprite_->setWidth(8);
sprite->setHeight(16); sprite_->setHeight(16);
sprite->setFlipH(player.spawn.flipH); sprite_->setFlipH(player.spawn.flipH);
sprite->setCurrentAnimation("walk"); sprite_->setCurrentAnimation("walk");
sprite->animate(); sprite_->animate();
lastPosition = getRect(); lastPosition = getRect();
colliderBox = getRect(); colliderBox = getRect();
@@ -64,45 +63,45 @@ Player::Player(player_t player)
colliderPoints.insert(colliderPoints.end(), {p, p, p, p, p, p, p, p}); colliderPoints.insert(colliderPoints.end(), {p, p, p, p, p, p, p, p});
underFeet.insert(underFeet.end(), {p, p}); underFeet.insert(underFeet.end(), {p, p});
feet.insert(feet.end(), {p, p}); feet.insert(feet.end(), {p, p});
jumpSound.push_back(JA_LoadSound(asset->get("jump1.wav").c_str())); jumpSound.push_back(JA_LoadSound(asset_->get("jump1.wav").c_str()));
jumpSound.push_back(JA_LoadSound(asset->get("jump2.wav").c_str())); jumpSound.push_back(JA_LoadSound(asset_->get("jump2.wav").c_str()));
jumpSound.push_back(JA_LoadSound(asset->get("jump3.wav").c_str())); jumpSound.push_back(JA_LoadSound(asset_->get("jump3.wav").c_str()));
jumpSound.push_back(JA_LoadSound(asset->get("jump4.wav").c_str())); jumpSound.push_back(JA_LoadSound(asset_->get("jump4.wav").c_str()));
jumpSound.push_back(JA_LoadSound(asset->get("jump5.wav").c_str())); jumpSound.push_back(JA_LoadSound(asset_->get("jump5.wav").c_str()));
jumpSound.push_back(JA_LoadSound(asset->get("jump6.wav").c_str())); jumpSound.push_back(JA_LoadSound(asset_->get("jump6.wav").c_str()));
jumpSound.push_back(JA_LoadSound(asset->get("jump7.wav").c_str())); jumpSound.push_back(JA_LoadSound(asset_->get("jump7.wav").c_str()));
jumpSound.push_back(JA_LoadSound(asset->get("jump8.wav").c_str())); jumpSound.push_back(JA_LoadSound(asset_->get("jump8.wav").c_str()));
jumpSound.push_back(JA_LoadSound(asset->get("jump9.wav").c_str())); jumpSound.push_back(JA_LoadSound(asset_->get("jump9.wav").c_str()));
jumpSound.push_back(JA_LoadSound(asset->get("jump10.wav").c_str())); jumpSound.push_back(JA_LoadSound(asset_->get("jump10.wav").c_str()));
jumpSound.push_back(JA_LoadSound(asset->get("jump11.wav").c_str())); jumpSound.push_back(JA_LoadSound(asset_->get("jump11.wav").c_str()));
jumpSound.push_back(JA_LoadSound(asset->get("jump12.wav").c_str())); jumpSound.push_back(JA_LoadSound(asset_->get("jump12.wav").c_str()));
jumpSound.push_back(JA_LoadSound(asset->get("jump13.wav").c_str())); jumpSound.push_back(JA_LoadSound(asset_->get("jump13.wav").c_str()));
jumpSound.push_back(JA_LoadSound(asset->get("jump14.wav").c_str())); jumpSound.push_back(JA_LoadSound(asset_->get("jump14.wav").c_str()));
jumpSound.push_back(JA_LoadSound(asset->get("jump15.wav").c_str())); jumpSound.push_back(JA_LoadSound(asset_->get("jump15.wav").c_str()));
jumpSound.push_back(JA_LoadSound(asset->get("jump16.wav").c_str())); jumpSound.push_back(JA_LoadSound(asset_->get("jump16.wav").c_str()));
jumpSound.push_back(JA_LoadSound(asset->get("jump17.wav").c_str())); jumpSound.push_back(JA_LoadSound(asset_->get("jump17.wav").c_str()));
jumpSound.push_back(JA_LoadSound(asset->get("jump18.wav").c_str())); jumpSound.push_back(JA_LoadSound(asset_->get("jump18.wav").c_str()));
jumpSound.push_back(JA_LoadSound(asset->get("jump19.wav").c_str())); jumpSound.push_back(JA_LoadSound(asset_->get("jump19.wav").c_str()));
jumpSound.push_back(JA_LoadSound(asset->get("jump20.wav").c_str())); jumpSound.push_back(JA_LoadSound(asset_->get("jump20.wav").c_str()));
jumpSound.push_back(JA_LoadSound(asset->get("jump21.wav").c_str())); jumpSound.push_back(JA_LoadSound(asset_->get("jump21.wav").c_str()));
jumpSound.push_back(JA_LoadSound(asset->get("jump22.wav").c_str())); jumpSound.push_back(JA_LoadSound(asset_->get("jump22.wav").c_str()));
jumpSound.push_back(JA_LoadSound(asset->get("jump23.wav").c_str())); jumpSound.push_back(JA_LoadSound(asset_->get("jump23.wav").c_str()));
jumpSound.push_back(JA_LoadSound(asset->get("jump24.wav").c_str())); jumpSound.push_back(JA_LoadSound(asset_->get("jump24.wav").c_str()));
fallSound.push_back(JA_LoadSound(asset->get("jump11.wav").c_str())); fallSound.push_back(JA_LoadSound(asset_->get("jump11.wav").c_str()));
fallSound.push_back(JA_LoadSound(asset->get("jump12.wav").c_str())); fallSound.push_back(JA_LoadSound(asset_->get("jump12.wav").c_str()));
fallSound.push_back(JA_LoadSound(asset->get("jump13.wav").c_str())); fallSound.push_back(JA_LoadSound(asset_->get("jump13.wav").c_str()));
fallSound.push_back(JA_LoadSound(asset->get("jump14.wav").c_str())); fallSound.push_back(JA_LoadSound(asset_->get("jump14.wav").c_str()));
fallSound.push_back(JA_LoadSound(asset->get("jump15.wav").c_str())); fallSound.push_back(JA_LoadSound(asset_->get("jump15.wav").c_str()));
fallSound.push_back(JA_LoadSound(asset->get("jump16.wav").c_str())); fallSound.push_back(JA_LoadSound(asset_->get("jump16.wav").c_str()));
fallSound.push_back(JA_LoadSound(asset->get("jump17.wav").c_str())); fallSound.push_back(JA_LoadSound(asset_->get("jump17.wav").c_str()));
fallSound.push_back(JA_LoadSound(asset->get("jump18.wav").c_str())); fallSound.push_back(JA_LoadSound(asset_->get("jump18.wav").c_str()));
fallSound.push_back(JA_LoadSound(asset->get("jump19.wav").c_str())); fallSound.push_back(JA_LoadSound(asset_->get("jump19.wav").c_str()));
fallSound.push_back(JA_LoadSound(asset->get("jump20.wav").c_str())); fallSound.push_back(JA_LoadSound(asset_->get("jump20.wav").c_str()));
fallSound.push_back(JA_LoadSound(asset->get("jump21.wav").c_str())); fallSound.push_back(JA_LoadSound(asset_->get("jump21.wav").c_str()));
fallSound.push_back(JA_LoadSound(asset->get("jump22.wav").c_str())); fallSound.push_back(JA_LoadSound(asset_->get("jump22.wav").c_str()));
fallSound.push_back(JA_LoadSound(asset->get("jump23.wav").c_str())); fallSound.push_back(JA_LoadSound(asset_->get("jump23.wav").c_str()));
fallSound.push_back(JA_LoadSound(asset->get("jump24.wav").c_str())); fallSound.push_back(JA_LoadSound(asset_->get("jump24.wav").c_str()));
jumpCounter = 0; jumpCounter = 0;
fallCounter = 0; fallCounter = 0;
@@ -118,7 +117,7 @@ Player::Player(player_t player)
// Destructor // Destructor
Player::~Player() Player::~Player()
{ {
delete sprite; delete sprite_;
for (auto s : jumpSound) for (auto s : jumpSound)
{ {
@@ -129,38 +128,38 @@ Player::~Player()
// Pinta el jugador en pantalla // Pinta el jugador en pantalla
void Player::render() void Player::render()
{ {
sprite->getTexture()->setColor(color.r, color.g, color.b); sprite_->getTexture()->setColor(color.r, color.g, color.b);
sprite->render(); sprite_->render();
#ifdef DEBUG #ifdef DEBUG
if (debug->getEnabled()) if (debug_->getEnabled())
{ {
// Pinta los underfeet // Pinta los underfeet
SDL_SetRenderDrawColor(renderer, 255, 0, 255, 255); SDL_SetRenderDrawColor(renderer_, 255, 0, 255, 255);
SDL_RenderDrawPoint(renderer, underFeet[0].x, underFeet[0].y); SDL_RenderDrawPoint(renderer_, underFeet[0].x, underFeet[0].y);
SDL_RenderDrawPoint(renderer, underFeet[1].x, underFeet[1].y); SDL_RenderDrawPoint(renderer_, underFeet[1].x, underFeet[1].y);
// Pinta rectangulo del jugador // Pinta rectangulo del jugador
SDL_SetRenderDrawColor(renderer, debugColor.r, debugColor.g, debugColor.b, 192); SDL_SetRenderDrawColor(renderer_, debugColor.r, debugColor.g, debugColor.b, 192);
SDL_Rect rect = getRect(); SDL_Rect rect = getRect();
SDL_RenderFillRect(renderer, &rect); SDL_RenderFillRect(renderer_, &rect);
SDL_SetRenderDrawColor(renderer, 0, 255, 255, 255); SDL_SetRenderDrawColor(renderer_, 0, 255, 255, 255);
SDL_RenderDrawRect(renderer, &rect); SDL_RenderDrawRect(renderer_, &rect);
// Pinta el rectangulo de movimiento // Pinta el rectangulo de movimiento
SDL_SetRenderDrawColor(renderer, 255, 0, 0, 255); SDL_SetRenderDrawColor(renderer_, 255, 0, 0, 255);
if (vx != 0.0f) if (vx != 0.0f)
{ {
SDL_RenderFillRect(renderer, &rx); SDL_RenderFillRect(renderer_, &rx);
} }
if (vy != 0.0f) if (vy != 0.0f)
{ {
SDL_RenderFillRect(renderer, &ry); SDL_RenderFillRect(renderer_, &ry);
} }
// Pinta el punto de debug // Pinta el punto de debug
SDL_SetRenderDrawColor(renderer, rand() % 256, rand() % 256, rand() % 256, 255); SDL_SetRenderDrawColor(renderer_, rand() % 256, rand() % 256, rand() % 256, 255);
SDL_RenderDrawPoint(renderer, debugPoint.x, debugPoint.y); SDL_RenderDrawPoint(renderer_, debugPoint.x, debugPoint.y);
} }
#endif #endif
} }
@@ -192,16 +191,16 @@ void Player::checkInput()
if (!autoMovement) if (!autoMovement)
{ // Comprueba las entradas de desplazamiento lateral solo en el caso de no estar enganchado a una superficie automatica { // Comprueba las entradas de desplazamiento lateral solo en el caso de no estar enganchado a una superficie automatica
if (input->checkInput(input_left)) if (input_->checkInput(input_left))
{ {
vx = -0.6f; vx = -0.6f;
sprite->setFlipH(true); sprite_->setFlipH(true);
} }
else if (input->checkInput(input_right)) else if (input_->checkInput(input_right))
{ {
vx = 0.6f; vx = 0.6f;
sprite->setFlipH(false); sprite_->setFlipH(false);
} }
else else
@@ -215,19 +214,19 @@ void Player::checkInput()
} }
else else
{ // El movimiento lo proporciona la superficie { // El movimiento lo proporciona la superficie
vx = 0.6f * room->getAutoSurfaceDirection(); vx = 0.6f * room_->getAutoSurfaceDirection();
if (vx > 0.0f) if (vx > 0.0f)
{ {
sprite->setFlipH(false); sprite_->setFlipH(false);
} }
else else
{ {
sprite->setFlipH(true); sprite_->setFlipH(true);
} }
} }
if (input->checkInput(input_jump)) if (input_->checkInput(input_jump))
{ {
// Solo puede saltar si ademas de estar (state == s_standing) // Solo puede saltar si ademas de estar (state == s_standing)
// Esta sobre el suelo, rampa o suelo que se mueve // Esta sobre el suelo, rampa o suelo que se mueve
@@ -409,7 +408,7 @@ void Player::move()
#endif #endif
// Comprueba la colisión con las superficies // Comprueba la colisión con las superficies
const int pos = room->checkRightSurfaces(&proj); const int pos = room_->checkRightSurfaces(&proj);
// Calcula la nueva posición // Calcula la nueva posición
if (pos == -1) if (pos == -1)
@@ -425,7 +424,7 @@ void Player::move()
if (state != s_jumping) if (state != s_jumping)
{ {
v_line_t leftSide = {(int)x, (int)y + h - 2, (int)y + h - 1}; // Comprueba solo los dos pixels de abajo v_line_t leftSide = {(int)x, (int)y + h - 2, (int)y + h - 1}; // Comprueba solo los dos pixels de abajo
const int ly = room->checkLeftSlopes(&leftSide); const int ly = room_->checkLeftSlopes(&leftSide);
if (ly > -1) if (ly > -1)
{ {
y = ly - h; y = ly - h;
@@ -454,7 +453,7 @@ void Player::move()
#endif #endif
// Comprueba la colisión // Comprueba la colisión
const int pos = room->checkLeftSurfaces(&proj); const int pos = room_->checkLeftSurfaces(&proj);
// Calcula la nueva posición // Calcula la nueva posición
if (pos == -1) if (pos == -1)
@@ -470,7 +469,7 @@ void Player::move()
if (state != s_jumping) if (state != s_jumping)
{ {
v_line_t rightSide = {(int)x + w - 1, (int)y + h - 2, (int)y + h - 1}; // Comprueba solo los dos pixels de abajo v_line_t rightSide = {(int)x + w - 1, (int)y + h - 2, (int)y + h - 1}; // Comprueba solo los dos pixels de abajo
const int ry = room->checkRightSlopes(&rightSide); const int ry = room_->checkRightSlopes(&rightSide);
if (ry > -1) if (ry > -1)
{ {
y = ry - h; y = ry - h;
@@ -515,7 +514,7 @@ void Player::move()
#endif #endif
// Comprueba la colisión // Comprueba la colisión
const int pos = room->checkBottomSurfaces(&proj); const int pos = room_->checkBottomSurfaces(&proj);
// Calcula la nueva posición // Calcula la nueva posición
if (pos == -1) if (pos == -1)
@@ -544,7 +543,7 @@ void Player::move()
#endif #endif
// Comprueba la colisión con las superficies normales y las automáticas // Comprueba la colisión con las superficies normales y las automáticas
const int pos = std::max(room->checkTopSurfaces(&proj), room->checkAutoSurfaces(&proj)); const int pos = std::max(room_->checkTopSurfaces(&proj), room_->checkAutoSurfaces(&proj));
if (pos > -1) if (pos > -1)
{ // Si hay colisión lo mueve hasta donde no colisiona y pasa a estar sobre la superficie { // Si hay colisión lo mueve hasta donde no colisiona y pasa a estar sobre la superficie
y = pos - h; y = pos - h;
@@ -559,7 +558,7 @@ void Player::move()
{ // Las rampas no se miran si se está saltando { // Las rampas no se miran si se está saltando
v_line_t leftSide = {proj.x, proj.y, proj.y + proj.h - 1}; v_line_t leftSide = {proj.x, proj.y, proj.y + proj.h - 1};
v_line_t rightSide = {proj.x + proj.w - 1, proj.y, proj.y + proj.h - 1}; v_line_t rightSide = {proj.x + proj.w - 1, proj.y, proj.y + proj.h - 1};
const int p = std::max(room->checkRightSlopes(&rightSide), room->checkLeftSlopes(&leftSide)); const int p = std::max(room_->checkRightSlopes(&rightSide), room_->checkLeftSlopes(&leftSide));
if (p > -1) if (p > -1)
{ // No está saltando y hay colisión con una rampa { // No está saltando y hay colisión con una rampa
// Calcula la nueva posición // Calcula la nueva posición
@@ -588,12 +587,12 @@ void Player::move()
} }
// Actualiza la posición del sprite // Actualiza la posición del sprite
sprite->setPosX(x); sprite_->setPosX(x);
sprite->setPosY(y); sprite_->setPosY(y);
#ifdef DEBUG #ifdef DEBUG
debug->add("RECT_X: " + std::to_string(rx.x) + "," + std::to_string(rx.y) + "," + std::to_string(rx.w) + "," + std::to_string(rx.h)); debug_->add("RECT_X: " + std::to_string(rx.x) + "," + std::to_string(rx.y) + "," + std::to_string(rx.w) + "," + std::to_string(rx.h));
debug->add("RECT_Y: " + std::to_string(ry.x) + "," + std::to_string(ry.y) + "," + std::to_string(ry.w) + "," + std::to_string(ry.h)); debug_->add("RECT_Y: " + std::to_string(ry.x) + "," + std::to_string(ry.y) + "," + std::to_string(ry.w) + "," + std::to_string(ry.h));
#endif #endif
} }
@@ -602,7 +601,7 @@ void Player::animate()
{ {
if (vx != 0) if (vx != 0)
{ {
sprite->animate(); sprite_->animate();
} }
} }
@@ -632,7 +631,7 @@ void Player::playJumpSound()
} }
#ifdef DEBUG #ifdef DEBUG
debug->add("JUMP: " + std::to_string(jumpCounter / 4)); debug_->add("JUMP: " + std::to_string(jumpCounter / 4));
#endif #endif
} }
@@ -645,7 +644,7 @@ void Player::playFallSound()
} }
#ifdef DEBUG #ifdef DEBUG
debug->add("FALL: " + std::to_string(fallCounter / 4)); debug_->add("FALL: " + std::to_string(fallCounter / 4));
#endif #endif
} }
@@ -661,28 +660,28 @@ bool Player::isOnFloor()
// Comprueba las superficies // Comprueba las superficies
for (auto f : underFeet) for (auto f : underFeet)
{ {
onFloor |= room->checkTopSurfaces(&f); onFloor |= room_->checkTopSurfaces(&f);
onFloor |= room->checkAutoSurfaces(&f); onFloor |= room_->checkAutoSurfaces(&f);
} }
// Comprueba las rampas // Comprueba las rampas
onSlopeL = room->checkLeftSlopes(&underFeet[0]); onSlopeL = room_->checkLeftSlopes(&underFeet[0]);
onSlopeR = room->checkRightSlopes(&underFeet[1]); onSlopeR = room_->checkRightSlopes(&underFeet[1]);
#ifdef DEBUG #ifdef DEBUG
if (onFloor) if (onFloor)
{ {
debug->add("ON_FLOOR"); debug_->add("ON_FLOOR");
} }
if (onSlopeL) if (onSlopeL)
{ {
debug->add("ON_SLOPE_L: " + std::to_string(underFeet[0].x) + "," + std::to_string(underFeet[0].y)); debug_->add("ON_SLOPE_L: " + std::to_string(underFeet[0].x) + "," + std::to_string(underFeet[0].y));
} }
if (onSlopeR) if (onSlopeR)
{ {
debug->add("ON_SLOPE_R: " + std::to_string(underFeet[1].x) + "," + std::to_string(underFeet[1].y)); debug_->add("ON_SLOPE_R: " + std::to_string(underFeet[1].x) + "," + std::to_string(underFeet[1].y));
} }
#endif #endif
@@ -699,13 +698,13 @@ bool Player::isOnAutoSurface()
// Comprueba las superficies // Comprueba las superficies
for (auto f : underFeet) for (auto f : underFeet)
{ {
onAutoSurface |= room->checkAutoSurfaces(&f); onAutoSurface |= room_->checkAutoSurfaces(&f);
} }
#ifdef DEBUG #ifdef DEBUG
if (onAutoSurface) if (onAutoSurface)
{ {
debug->add("ON_AUTO_SURFACE"); debug_->add("ON_AUTO_SURFACE");
} }
#endif #endif
@@ -725,13 +724,13 @@ bool Player::isOnDownSlope()
underFeet[1].y += 1; underFeet[1].y += 1;
// Comprueba las rampas // Comprueba las rampas
onSlope |= room->checkLeftSlopes(&underFeet[0]); onSlope |= room_->checkLeftSlopes(&underFeet[0]);
onSlope |= room->checkRightSlopes(&underFeet[1]); onSlope |= room_->checkRightSlopes(&underFeet[1]);
#ifdef DEBUG #ifdef DEBUG
if (onSlope) if (onSlope)
{ {
debug->add("ON_DOWN_SLOPE"); debug_->add("ON_DOWN_SLOPE");
} }
#endif #endif
@@ -749,7 +748,7 @@ bool Player::checkKillingTiles()
for (auto c : colliderPoints) for (auto c : colliderPoints)
{ {
check |= (room->getTile(c) == t_kill); check |= (room_->getTile(c) == t_kill);
} }
// Mata al jugador si hay colisión // Mata al jugador si hay colisión
@@ -772,7 +771,7 @@ playerSpawn_t Player::getSpawnParams()
params.vy = vy; params.vy = vy;
params.jumpIni = jumpIni; params.jumpIni = jumpIni;
params.state = state; params.state = state;
params.flipH = sprite->getFlipH(); params.flipH = sprite_->getFlipH();
return params; return params;
} }
@@ -780,7 +779,7 @@ playerSpawn_t Player::getSpawnParams()
// Recarga la textura // Recarga la textura
void Player::reLoadTexture() void Player::reLoadTexture()
{ {
sprite->getTexture()->reLoad(); sprite_->getTexture()->reLoad();
} }
// Recarga la paleta // Recarga la paleta
@@ -800,7 +799,7 @@ void Player::reLoadPalette()
// Establece el valor de la variable // Establece el valor de la variable
void Player::setRoom(Room *room) void Player::setRoom(Room *room)
{ {
this->room = room; this->room_ = room;
} }
// Actualiza los puntos de colisión // Actualiza los puntos de colisión

View File

@@ -36,25 +36,20 @@ struct player_t
playerSpawn_t spawn; playerSpawn_t spawn;
std::string png; std::string png;
std::string animation; std::string animation;
SDL_Renderer *renderer;
Resource *resource;
Asset *asset;
Input *input;
Room *room; Room *room;
Debug *debug;
}; };
class Player class Player
{ {
public: public:
// Objetos y punteros // Objetos y punteros
SDL_Renderer *renderer; // El renderizador de la ventana SDL_Renderer *renderer_; // El renderizador de la ventana
Input *input; // Objeto para gestionar la entrada Input *input_; // Objeto para gestionar la entrada
Resource *resource; // Objeto con los recursos Resource *resource_; // Objeto con los recursos
Asset *asset; // Objeto con la ruta a todos los ficheros de recursos Asset *asset_; // Objeto con la ruta a todos los ficheros de recursos
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 jugador
Debug *debug; // Objeto para gestionar la información de debug Debug *debug_; // Objeto para gestionar la información de debug
// Variables // Variables
float x; // Posición del jugador en el eje X float x; // Posición del jugador en el eje X

View File

@@ -11,6 +11,27 @@
#include "screen.h" #include "screen.h"
#include "options.h" #include "options.h"
// [SINGLETON]
Resource *Resource::resource_ = nullptr;
// [SINGLETON] Crearemos el objeto con esta función estática
void Resource::init()
{
Resource::resource_ = new Resource();
}
// [SINGLETON] Destruiremos el objeto con esta función estática
void Resource::destroy()
{
delete Resource::resource_;
}
// [SINGLETON] Con este método obtenemos el objeto y podemos trabajar con él
Resource *Resource::get()
{
return Resource::resource_;
}
// Carga las texturas de una lista // Carga las texturas de una lista
void Resource::loadTextures(std::vector<std::string> list) void Resource::loadTextures(std::vector<std::string> list)
{ {

View File

@@ -44,6 +44,9 @@ struct res_room_t
class Resource class Resource
{ {
private: private:
// [SINGLETON] Objeto privado
static Resource *resource_;
// 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_;
@@ -51,13 +54,22 @@ private:
std::vector<res_tileMap_t> tile_maps_; std::vector<res_tileMap_t> tile_maps_;
std::vector<res_room_t> rooms_; std::vector<res_room_t> rooms_;
public:
// Constructor // Constructor
Resource() = default; Resource() = default;
// Destructor // Destructor
~Resource() = default; ~Resource() = default;
public:
// [SINGLETON] Crearemos el objeto con esta función estática
static void init();
// [SINGLETON] Destruiremos el objeto con esta función estática
static void destroy();
// [SINGLETON] Con este método obtenemos el objeto y podemos trabajar con él
static Resource *get();
// Carga las texturas de una lista // Carga las texturas de una lista
void loadTextures(std::vector<std::string> list); void loadTextures(std::vector<std::string> list);

View File

@@ -404,16 +404,14 @@ 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, ItemTracker *itemTracker, int *itemsPicked, bool jailEnabled, Debug *debug) Room::Room(room_t *room, ItemTracker *itemTracker, int *itemsPicked, bool jailEnabled)
: screen(Screen::get()),
renderer(Screen::get()->getRenderer()),
asset(Asset::get()),
debug(Debug::get()),
itemTracker(itemTracker),
itemsPicked(itemsPicked)
{ {
// Copia los punteros a objetos
this->renderer = renderer;
this->asset = asset;
this->screen = screen;
this->itemTracker = itemTracker;
this->itemsPicked = itemsPicked;
this->debug = debug;
number = room->number; number = room->number;
name = room->name; name = room->name;
bgColor = room->bgColor; bgColor = room->bgColor;

View File

@@ -73,18 +73,18 @@ class Room
{ {
private: private:
// Objetos y punteros // Objetos y punteros
Screen *screen; // Objeto encargado de dibujar en pantalla
SDL_Renderer *renderer; // El renderizador de la ventana
Asset *asset; // Objeto con la ruta a todos los ficheros de recursos
Debug *debug; // Objeto para gestionar la información de debug
std::vector<Enemy *> enemies; // Listado con los enemigos de la habitación std::vector<Enemy *> enemies; // Listado con los enemigos de la habitación
std::vector<Item *> items; // Listado con los items que hay en la habitación std::vector<Item *> items; // Listado con los items que hay en la habitación
Texture *texture; // Textura con los graficos de la habitación Texture *texture; // Textura con los graficos de la habitación
Texture *textureA; // Textura con los graficos de la habitación Texture *textureA; // Textura con los graficos de la habitación
Texture *textureB; // Textura con los graficos de la habitación Texture *textureB; // Textura con los graficos de la habitación
Asset *asset; // Objeto con la ruta a todos los ficheros de recursos
Screen *screen; // Objeto encargado de dibujar en pantalla
ItemTracker *itemTracker; // Lleva el control de los objetos recogidos ItemTracker *itemTracker; // Lleva el control de los objetos recogidos
SDL_Renderer *renderer; // El renderizador de la ventana
SDL_Texture *mapTexture; // Textura para dibujar el mapa de la habitación 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
// Variables // Variables
std::string number; // Numero de la habitación std::string number; // Numero de la habitación
@@ -159,7 +159,7 @@ private:
public: public:
// Constructor // Constructor
Room(room_t *room, SDL_Renderer *renderer, Screen *screen, Asset *asset, ItemTracker *itemTracker, int *itemsPicked, bool jailEnabled, Debug *debug); Room(room_t *room, ItemTracker *itemTracker, int *itemsPicked, bool jailEnabled);
// Destructor // Destructor
~Room(); ~Room();

View File

@@ -7,17 +7,17 @@
#include "text.h" // Para Text #include "text.h" // Para Text
#include "texture.h" // Para Texture #include "texture.h" // Para Texture
#include "options.h" #include "options.h"
#include "screen.h"
#include "asset.h"
class Asset; class Asset;
// Constructor // Constructor
ScoreBoard::ScoreBoard(SDL_Renderer *renderer, Resource *resource, Asset *asset, board_t *board) Scoreboard::Scoreboard(board_t *board)
: renderer(Screen::get()->getRenderer()),
resource(Resource::get()),
asset(Asset::get()),
board(board)
{ {
// Obten punteros a objetos
this->renderer = renderer;
this->resource = resource;
this->asset = asset;
this->board = board;
// Reserva memoria para los objetos // 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";
@@ -42,14 +42,14 @@ ScoreBoard::ScoreBoard(SDL_Renderer *renderer, Resource *resource, Asset *asset,
} }
// Destructor // Destructor
ScoreBoard::~ScoreBoard() Scoreboard::~Scoreboard()
{ {
delete sprite; delete sprite;
delete text; delete text;
} }
// Pinta el objeto en pantalla // Pinta el objeto en pantalla
void ScoreBoard::render() void Scoreboard::render()
{ {
// Anclas // Anclas
const int line1 = 19 * BLOCK; const int line1 = 19 * BLOCK;
@@ -96,7 +96,7 @@ void ScoreBoard::render()
} }
// Actualiza las variables del objeto // Actualiza las variables del objeto
void ScoreBoard::update() void Scoreboard::update()
{ {
counter++; counter++;
sprite->update(); sprite->update();
@@ -111,7 +111,7 @@ void ScoreBoard::update()
} }
// Obtiene el tiempo transcurrido de partida // Obtiene el tiempo transcurrido de partida
ScoreBoard::clock_t ScoreBoard::getTime() Scoreboard::clock_t Scoreboard::getTime()
{ {
const Uint32 timeElapsed = SDL_GetTicks() - board->iniClock - totalTimePaused; const Uint32 timeElapsed = SDL_GetTicks() - board->iniClock - totalTimePaused;
@@ -125,7 +125,7 @@ ScoreBoard::clock_t ScoreBoard::getTime()
} }
// Recarga la textura // Recarga la textura
void ScoreBoard::reLoadTexture() void Scoreboard::reLoadTexture()
{ {
sprite->getTexture()->reLoad(); sprite->getTexture()->reLoad();
// playerTexture->reLoad(); // playerTexture->reLoad();
@@ -134,7 +134,7 @@ void ScoreBoard::reLoadTexture()
} }
// Recarga la paleta // Recarga la paleta
void ScoreBoard::reLoadPalette() void Scoreboard::reLoadPalette()
{ {
// Reinicia el vector de colores // Reinicia el vector de colores
const std::vector<std::string> vColors = {"blue", "magenta", "green", "cyan", "yellow", "white", "bright_blue", "bright_magenta", "bright_green", "bright_cyan", "bright_yellow", "bright_white"}; const std::vector<std::string> vColors = {"blue", "magenta", "green", "cyan", "yellow", "white", "bright_blue", "bright_magenta", "bright_green", "bright_cyan", "bright_yellow", "bright_white"};
@@ -146,21 +146,21 @@ void ScoreBoard::reLoadPalette()
} }
// Pone el marcador en modo pausa // Pone el marcador en modo pausa
void ScoreBoard::pause() void Scoreboard::pause()
{ {
paused = true; paused = true;
timePaused = SDL_GetTicks(); timePaused = SDL_GetTicks();
} }
// Quita el modo pausa del marcador // Quita el modo pausa del marcador
void ScoreBoard::resume() void Scoreboard::resume()
{ {
paused = false; paused = false;
totalTimePaused += SDL_GetTicks() - timePaused; totalTimePaused += SDL_GetTicks() - timePaused;
} }
// Actualiza el color de la cantidad de items recogidos // Actualiza el color de la cantidad de items recogidos
void ScoreBoard::updateItemsColor() void Scoreboard::updateItemsColor()
{ {
if (!board->jailEnabled) if (!board->jailEnabled)
{ {
@@ -178,7 +178,7 @@ void ScoreBoard::updateItemsColor()
} }
// Devuelve la cantidad de minutos de juego transcurridos // Devuelve la cantidad de minutos de juego transcurridos
int ScoreBoard::getMinutes() int Scoreboard::getMinutes()
{ {
return getTime().minutes; return getTime().minutes;
} }

View File

@@ -22,7 +22,7 @@ struct board_t
bool jailEnabled; // Indica si se puede entrar a la Jail bool jailEnabled; // Indica si se puede entrar a la Jail
}; };
class ScoreBoard class Scoreboard
{ {
private: private:
struct clock_t struct clock_t
@@ -60,10 +60,10 @@ private:
public: public:
// Constructor // Constructor
ScoreBoard(SDL_Renderer *renderer, Resource *resource, Asset *asset, board_t *board); Scoreboard(board_t *board);
// Destructor // Destructor
~ScoreBoard(); ~Scoreboard();
// Pinta el objeto en pantalla // Pinta el objeto en pantalla
void render(); void render();

View File

@@ -435,25 +435,10 @@ void Screen::renderFX()
renderSpectrumFade(); renderSpectrumFade();
} }
// Actualiza el notificador
void Screen::updateNotifier()
{
Notifier::get()->update();
}
// Muestra una notificación de texto por pantalla;
void Screen::showNotification(std::string text1, std::string text2, int icon)
{
Notifier::get()->showText(text1, text2, icon);
}
// Dibuja las notificaciones // Dibuja las notificaciones
void Screen::renderNotifications() void Screen::renderNotifications()
{ {
if (Notifier::get()->active()) Notifier::get()->render();
{
Notifier::get()->render();
}
} }
// Copia el gameCanvas en el borderCanvas // Copia el gameCanvas en el borderCanvas
@@ -498,4 +483,10 @@ void Screen::toggleShaders()
{ {
options.shaders = !options.shaders; options.shaders = !options.shaders;
setVideoMode(options.videoMode); setVideoMode(options.videoMode);
}
// Actualiza la lógica de la clase
void Screen::update()
{
Notifier::get()->update();
} }

View File

@@ -99,6 +99,9 @@ public:
// Vuelca el contenido del renderizador en pantalla // Vuelca el contenido del renderizador en pantalla
void render(); void render();
// Actualiza la lógica de la clase
void update();
// Establece el modo de video // Establece el modo de video
void setVideoMode(int videoMode); void setVideoMode(int videoMode);
@@ -148,12 +151,6 @@ public:
// Dibuja los efectos // Dibuja los efectos
void renderFX(); void renderFX();
// Actualiza el notificador
void updateNotifier();
// Muestra una notificación de texto por pantalla;
void showNotification(std::string text1 = "", std::string text2 = "", int icon = -1);
// Cambia el estado de los shaders // Cambia el estado de los shaders
void toggleShaders(); void toggleShaders();

View File

@@ -18,26 +18,26 @@
#include "options.h" #include "options.h"
// Constructor // Constructor
Title::Title(Resource *resource) Title::Title()
: screen_(Screen::get()), : screen_(Screen::get()),
renderer_(Screen::get()->getRenderer()), renderer_(Screen::get()->getRenderer()),
resource_(resource), resource_(Resource::get()),
input_(Input::get()) input_(Input::get())
{ {
// 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_, Asset::get()->get("cheevos.bin")); cheevos_ = std::make_unique<Cheevos>(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");
} }
sprite_ = new Sprite(0, 0, texture_->getWidth(), texture_->getHeight(), texture_, renderer_); sprite_ = new Sprite(0, 0, texture_->getWidth(), texture_->getHeight(), texture_, renderer_);
text_ = new Text(resource->getOffset("smb2.txt"), resource->getTexture("smb2.png"), renderer_); text_ = new Text(resource_->getOffset("smb2.txt"), resource_->getTexture("smb2.png"), renderer_);
info_text_ = new Text(resource->getOffset("subatomic.txt"), resource->getTexture("subatomic.png"), renderer_); info_text_ = new Text(resource_->getOffset("subatomic.txt"), resource_->getTexture("subatomic.png"), renderer_);
// Crea la textura para los graficos que aparecen en el fondo de la pantalla de titulo // Crea la textura para los graficos que aparecen en el fondo de la pantalla de titulo
bg_texture_ = SDL_CreateTexture(renderer_, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, GAMECANVAS_WIDTH, GAMECANVAS_HEIGHT); bg_texture_ = SDL_CreateTexture(renderer_, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, GAMECANVAS_WIDTH, GAMECANVAS_HEIGHT);
@@ -271,8 +271,7 @@ void Title::update()
// Comprueba las entradas // Comprueba las entradas
checkInput(); checkInput();
// Actualiza las notificaciones screen_->update();
screen_->updateNotifier();
// Incrementa el contador // Incrementa el contador
counter_++; counter_++;
@@ -447,7 +446,7 @@ void Title::fillTexture()
void Title::createCheevosTexture() void Title::createCheevosTexture()
{ {
// Crea la textura con el listado de logros // Crea la textura con el listado de logros
const std::vector<cheevos_t> cheevosList = cheevos_->list(); const auto cheevosList = cheevos_->list();
const int cheevosTextureWidth = 200; const int cheevosTextureWidth = 200;
const int cheevosTextureViewHeight = 110; const int cheevosTextureViewHeight = 110;
const int cheevosTexturePosY = 73; const int cheevosTexturePosY = 73;

View File

@@ -107,7 +107,7 @@ private:
public: public:
// Constructor // Constructor
Title(Resource *resource); Title();
// Destructor // Destructor
~Title(); ~Title();