treball en curs: correccions de tidy
This commit is contained in:
@@ -3,7 +3,6 @@
|
|||||||
#include <cmath> // Para lround
|
#include <cmath> // Para lround
|
||||||
#include <cstdint> // Para int8_t, uint8_t
|
#include <cstdint> // Para int8_t, uint8_t
|
||||||
#include <string> // Para string
|
#include <string> // Para string
|
||||||
#include <utility> // Para move
|
|
||||||
|
|
||||||
// --- Clase Audio: gestor de audio (singleton) ---
|
// --- Clase Audio: gestor de audio (singleton) ---
|
||||||
// Implementació canònica, byte-idèntica entre projectes.
|
// Implementació canònica, byte-idèntica entre projectes.
|
||||||
|
|||||||
@@ -147,17 +147,27 @@ auto Asset::checkFile(const std::string &path) const -> bool {
|
|||||||
// Devuelve el nombre del tipo de recurso
|
// Devuelve el nombre del tipo de recurso
|
||||||
auto Asset::getTypeName(Type type) -> std::string {
|
auto Asset::getTypeName(Type type) -> std::string {
|
||||||
switch (type) {
|
switch (type) {
|
||||||
case Type::BITMAP: return "BITMAP";
|
case Type::BITMAP:
|
||||||
case Type::MUSIC: return "MUSIC";
|
return "BITMAP";
|
||||||
case Type::SOUND: return "SOUND";
|
case Type::MUSIC:
|
||||||
case Type::FONT: return "FONT";
|
return "MUSIC";
|
||||||
case Type::LANG: return "LANG";
|
case Type::SOUND:
|
||||||
case Type::DATA: return "DATA";
|
return "SOUND";
|
||||||
case Type::ROOM: return "ROOM";
|
case Type::FONT:
|
||||||
case Type::ENEMY: return "ENEMY";
|
return "FONT";
|
||||||
case Type::ITEM: return "ITEM";
|
case Type::LANG:
|
||||||
|
return "LANG";
|
||||||
|
case Type::DATA:
|
||||||
|
return "DATA";
|
||||||
|
case Type::ROOM:
|
||||||
|
return "ROOM";
|
||||||
|
case Type::ENEMY:
|
||||||
|
return "ENEMY";
|
||||||
|
case Type::ITEM:
|
||||||
|
return "ITEM";
|
||||||
case Type::COUNT:
|
case Type::COUNT:
|
||||||
default: return "ERROR";
|
default:
|
||||||
|
return "ERROR";
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -9,14 +9,6 @@
|
|||||||
class ResourcePack;
|
class ResourcePack;
|
||||||
|
|
||||||
class ResourceLoader {
|
class ResourceLoader {
|
||||||
private:
|
|
||||||
static std::unique_ptr<ResourceLoader> instance;
|
|
||||||
ResourcePack* resource_pack_{nullptr};
|
|
||||||
std::string pack_path_;
|
|
||||||
bool fallback_to_files_{true};
|
|
||||||
|
|
||||||
ResourceLoader();
|
|
||||||
|
|
||||||
public:
|
public:
|
||||||
static auto getInstance() -> ResourceLoader&;
|
static auto getInstance() -> ResourceLoader&;
|
||||||
~ResourceLoader();
|
~ResourceLoader();
|
||||||
@@ -34,6 +26,13 @@ class ResourceLoader {
|
|||||||
[[nodiscard]] auto getAvailableResources() const -> std::vector<std::string>;
|
[[nodiscard]] auto getAvailableResources() const -> std::vector<std::string>;
|
||||||
|
|
||||||
private:
|
private:
|
||||||
|
ResourceLoader(); // Constructor privado (singleton)
|
||||||
|
|
||||||
static auto loadFromFile(const std::string& filename) -> std::vector<uint8_t>;
|
static auto loadFromFile(const std::string& filename) -> std::vector<uint8_t>;
|
||||||
static auto getDataPath(const std::string& filename) -> std::string;
|
static auto getDataPath(const std::string& filename) -> std::string;
|
||||||
|
|
||||||
|
static std::unique_ptr<ResourceLoader> instance;
|
||||||
|
ResourcePack* resource_pack_{nullptr};
|
||||||
|
std::string pack_path_;
|
||||||
|
bool fallback_to_files_{true};
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -14,15 +14,6 @@ struct ResourceEntry {
|
|||||||
};
|
};
|
||||||
|
|
||||||
class ResourcePack {
|
class ResourcePack {
|
||||||
private:
|
|
||||||
std::unordered_map<std::string, ResourceEntry> resources_;
|
|
||||||
std::vector<uint8_t> data_;
|
|
||||||
bool loaded_{false};
|
|
||||||
|
|
||||||
static auto calculateChecksum(const std::vector<uint8_t>& data) -> uint32_t;
|
|
||||||
static void encryptData(std::vector<uint8_t>& data, const std::string& key);
|
|
||||||
static void decryptData(std::vector<uint8_t>& data, const std::string& key);
|
|
||||||
|
|
||||||
public:
|
public:
|
||||||
ResourcePack();
|
ResourcePack();
|
||||||
~ResourcePack();
|
~ResourcePack();
|
||||||
@@ -41,4 +32,13 @@ class ResourcePack {
|
|||||||
auto getResourceList() const -> std::vector<std::string>;
|
auto getResourceList() const -> std::vector<std::string>;
|
||||||
|
|
||||||
static const std::string DEFAULT_ENCRYPT_KEY;
|
static const std::string DEFAULT_ENCRYPT_KEY;
|
||||||
|
|
||||||
|
private:
|
||||||
|
static auto calculateChecksum(const std::vector<uint8_t>& data) -> uint32_t;
|
||||||
|
static void encryptData(std::vector<uint8_t>& data, const std::string& key);
|
||||||
|
static void decryptData(std::vector<uint8_t>& data, const std::string& key);
|
||||||
|
|
||||||
|
std::unordered_map<std::string, ResourceEntry> resources_;
|
||||||
|
std::vector<uint8_t> data_;
|
||||||
|
bool loaded_{false};
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -41,8 +41,8 @@
|
|||||||
Director::Director(int argc, const char *argv[]) {
|
Director::Director(int argc, const char *argv[]) {
|
||||||
std::cout << "Game start" << '\n';
|
std::cout << "Game start" << '\n';
|
||||||
// Inicializa variables
|
// Inicializa variables
|
||||||
section = new Section();
|
section_ = new Section();
|
||||||
section->name = SECTION_PROG_LOGO;
|
section_->name = SECTION_PROG_LOGO;
|
||||||
|
|
||||||
// Inicializa las opciones del programa (defaults + dispositivos d'entrada)
|
// Inicializa las opciones del programa (defaults + dispositivos d'entrada)
|
||||||
Options::init();
|
Options::init();
|
||||||
@@ -54,7 +54,7 @@ Director::Director(int argc, const char *argv[]) {
|
|||||||
executablePath = "";
|
executablePath = "";
|
||||||
#else
|
#else
|
||||||
const char *base_path = SDL_GetBasePath();
|
const char *base_path = SDL_GetBasePath();
|
||||||
executablePath = (base_path != nullptr) ? base_path : "";
|
executable_path_ = (base_path != nullptr) ? base_path : "";
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
// Comprueba los parametros del programa (pot activar console)
|
// Comprueba los parametros del programa (pot activar console)
|
||||||
@@ -70,13 +70,13 @@ Director::Director(int argc, const char *argv[]) {
|
|||||||
|
|
||||||
// Estableix el fitxer de configuració i carrega les opcions (o crea el
|
// Estableix el fitxer de configuració i carrega les opcions (o crea el
|
||||||
// YAML amb defaults si no existeix).
|
// YAML amb defaults si no existeix).
|
||||||
Options::setConfigFile(systemFolder + "/config.yaml");
|
Options::setConfigFile(system_folder_ + "/config.yaml");
|
||||||
Options::loadFromFile();
|
Options::loadFromFile();
|
||||||
|
|
||||||
// Presets de shaders (creats amb defaults si no existeixen).
|
// Presets de shaders (creats amb defaults si no existeixen).
|
||||||
Options::setPostFXFile(systemFolder + "/postfx.yaml");
|
Options::setPostFXFile(system_folder_ + "/postfx.yaml");
|
||||||
Options::loadPostFXFromFile();
|
Options::loadPostFXFromFile();
|
||||||
Options::setCrtPiFile(systemFolder + "/crtpi.yaml");
|
Options::setCrtPiFile(system_folder_ + "/crtpi.yaml");
|
||||||
Options::loadCrtPiFromFile();
|
Options::loadCrtPiFromFile();
|
||||||
|
|
||||||
// Inicializa el sistema de recursos (pack + fallback).
|
// Inicializa el sistema de recursos (pack + fallback).
|
||||||
@@ -93,7 +93,7 @@ Director::Director(int argc, const char *argv[]) {
|
|||||||
#ifdef MACOS_BUNDLE
|
#ifdef MACOS_BUNDLE
|
||||||
const std::string PACK_PATH = executablePath + "../Resources/resources.pack";
|
const std::string PACK_PATH = executablePath + "../Resources/resources.pack";
|
||||||
#else
|
#else
|
||||||
const std::string PACK_PATH = executablePath + "resources.pack";
|
const std::string PACK_PATH = executable_path_ + "resources.pack";
|
||||||
#endif
|
#endif
|
||||||
if (!ResourceHelper::initializeResourceSystem(PACK_PATH, ENABLE_FALLBACK)) {
|
if (!ResourceHelper::initializeResourceSystem(PACK_PATH, ENABLE_FALLBACK)) {
|
||||||
std::cerr << "Fatal: resource system init failed (missing resources.pack?)" << '\n';
|
std::cerr << "Fatal: resource system init failed (missing resources.pack?)" << '\n';
|
||||||
@@ -102,7 +102,7 @@ Director::Director(int argc, const char *argv[]) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Crea el objeto que controla los ficheros de recursos
|
// Crea el objeto que controla los ficheros de recursos
|
||||||
Asset::init(executablePath);
|
Asset::init(executable_path_);
|
||||||
Asset::get()->setVerbose(Options::settings.console);
|
Asset::get()->setVerbose(Options::settings.console);
|
||||||
|
|
||||||
// Si falta algún fichero no inicia el programa
|
// Si falta algún fichero no inicia el programa
|
||||||
@@ -127,7 +127,7 @@ Director::Director(int argc, const char *argv[]) {
|
|||||||
Input::init("/gamecontrollerdb.txt");
|
Input::init("/gamecontrollerdb.txt");
|
||||||
#else
|
#else
|
||||||
{
|
{
|
||||||
const std::string BIN_DIR = std::filesystem::path(executablePath).parent_path().string();
|
const std::string BIN_DIR = std::filesystem::path(executable_path_).parent_path().string();
|
||||||
#ifdef MACOS_BUNDLE
|
#ifdef MACOS_BUNDLE
|
||||||
Input::init(BIN_DIR + "/../Resources/gamecontrollerdb.txt");
|
Input::init(BIN_DIR + "/../Resources/gamecontrollerdb.txt");
|
||||||
#else
|
#else
|
||||||
@@ -145,7 +145,7 @@ Director::Director(int argc, const char *argv[]) {
|
|||||||
//
|
//
|
||||||
// Por eso el constructor de Screen NO carga notificationText desde
|
// Por eso el constructor de Screen NO carga notificationText desde
|
||||||
// Resource; se enlaza después vía `Screen::get()->initNotifications()`.
|
// Resource; se enlaza después vía `Screen::get()->initNotifications()`.
|
||||||
Screen::init(window, renderer);
|
Screen::init(window_, renderer_);
|
||||||
|
|
||||||
#ifndef NO_SHADERS
|
#ifndef NO_SHADERS
|
||||||
if (Options::video.gpu.acceleration) {
|
if (Options::video.gpu.acceleration) {
|
||||||
@@ -155,13 +155,13 @@ Director::Director(int argc, const char *argv[]) {
|
|||||||
|
|
||||||
// Ahora sí, precarga todos los recursos en memoria (texturas, sonidos,
|
// Ahora sí, precarga todos los recursos en memoria (texturas, sonidos,
|
||||||
// música, ...). Vivirán durante toda la vida de la app.
|
// música, ...). Vivirán durante toda la vida de la app.
|
||||||
Resource::init(renderer);
|
Resource::init(renderer_);
|
||||||
|
|
||||||
// Completa el enlazado de Screen con recursos que necesitan Resource
|
// Completa el enlazado de Screen con recursos que necesitan Resource
|
||||||
// inicializado (actualmente sólo el Text de las notificaciones).
|
// inicializado (actualmente sólo el Text de las notificaciones).
|
||||||
Screen::get()->initNotifications();
|
Screen::get()->initNotifications();
|
||||||
|
|
||||||
activeSection = ActiveSection::None;
|
active_section_ = ActiveSection::NONE;
|
||||||
}
|
}
|
||||||
|
|
||||||
Director::~Director() {
|
Director::~Director() {
|
||||||
@@ -170,10 +170,10 @@ Director::~Director() {
|
|||||||
// Libera las secciones primero: sus destructores tocan audio/render SDL
|
// Libera las secciones primero: sus destructores tocan audio/render SDL
|
||||||
// (p.ej. Intro::~Intro llama a JA_DeleteMusic) y deben ejecutarse antes
|
// (p.ej. Intro::~Intro llama a JA_DeleteMusic) y deben ejecutarse antes
|
||||||
// de SDL_Quit().
|
// de SDL_Quit().
|
||||||
logo.reset();
|
logo_.reset();
|
||||||
intro.reset();
|
intro_.reset();
|
||||||
title.reset();
|
title_.reset();
|
||||||
game.reset();
|
game_.reset();
|
||||||
|
|
||||||
// Screen puede tener referencias a Text propiedad de Resource: destruir
|
// Screen puede tener referencias a Text propiedad de Resource: destruir
|
||||||
// Screen antes que Resource.
|
// Screen antes que Resource.
|
||||||
@@ -185,12 +185,12 @@ Director::~Director() {
|
|||||||
Asset::destroy();
|
Asset::destroy();
|
||||||
Input::destroy();
|
Input::destroy();
|
||||||
Lang::destroy();
|
Lang::destroy();
|
||||||
delete section;
|
delete section_;
|
||||||
|
|
||||||
Audio::destroy();
|
Audio::destroy();
|
||||||
|
|
||||||
SDL_DestroyRenderer(renderer);
|
SDL_DestroyRenderer(renderer_);
|
||||||
SDL_DestroyWindow(window);
|
SDL_DestroyWindow(window_);
|
||||||
|
|
||||||
SDL_Quit();
|
SDL_Quit();
|
||||||
|
|
||||||
@@ -270,23 +270,23 @@ auto Director::initSDL() -> bool {
|
|||||||
std::srand(static_cast<unsigned int>(SDL_GetTicks()));
|
std::srand(static_cast<unsigned int>(SDL_GetTicks()));
|
||||||
|
|
||||||
// Crea la ventana
|
// Crea la ventana
|
||||||
window = SDL_CreateWindow(
|
window_ = SDL_CreateWindow(
|
||||||
Options::window.caption.c_str(),
|
Options::window.caption.c_str(),
|
||||||
GAMECANVAS_WIDTH * Options::window.zoom,
|
GAMECANVAS_WIDTH * Options::window.zoom,
|
||||||
GAMECANVAS_HEIGHT * Options::window.zoom,
|
GAMECANVAS_HEIGHT * Options::window.zoom,
|
||||||
0);
|
0);
|
||||||
if (window == nullptr) {
|
if (window_ == nullptr) {
|
||||||
if (Options::settings.console) {
|
if (Options::settings.console) {
|
||||||
std::cout << "Window could not be created!\nSDL Error: " << SDL_GetError() << '\n';
|
std::cout << "Window could not be created!\nSDL Error: " << SDL_GetError() << '\n';
|
||||||
}
|
}
|
||||||
success = false;
|
success = false;
|
||||||
} else {
|
} else {
|
||||||
SDL_SetWindowPosition(window, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED);
|
SDL_SetWindowPosition(window_, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED);
|
||||||
|
|
||||||
// Crea un renderizador para la ventana
|
// Crea un renderizador para la ventana
|
||||||
renderer = SDL_CreateRenderer(window, nullptr);
|
renderer_ = SDL_CreateRenderer(window_, nullptr);
|
||||||
|
|
||||||
if (renderer == nullptr) {
|
if (renderer_ == nullptr) {
|
||||||
if (Options::settings.console) {
|
if (Options::settings.console) {
|
||||||
std::cout << "Renderer could not be created!\nSDL Error: " << SDL_GetError() << '\n';
|
std::cout << "Renderer could not be created!\nSDL Error: " << SDL_GetError() << '\n';
|
||||||
}
|
}
|
||||||
@@ -294,21 +294,21 @@ auto Director::initSDL() -> bool {
|
|||||||
} else {
|
} else {
|
||||||
// Modo de blending por defecto (consistente con CCAE):
|
// Modo de blending por defecto (consistente con CCAE):
|
||||||
// permite alpha blending para fades y notificaciones.
|
// permite alpha blending para fades y notificaciones.
|
||||||
SDL_SetRenderDrawBlendMode(renderer, SDL_BLENDMODE_BLEND);
|
SDL_SetRenderDrawBlendMode(renderer_, SDL_BLENDMODE_BLEND);
|
||||||
|
|
||||||
// Activa vsync si es necesario
|
// Activa vsync si es necesario
|
||||||
if (Options::video.vsync) {
|
if (Options::video.vsync) {
|
||||||
SDL_SetRenderVSync(renderer, 1);
|
SDL_SetRenderVSync(renderer_, 1);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Inicializa el color de renderizado
|
// Inicializa el color de renderizado
|
||||||
SDL_SetRenderDrawColor(renderer, 0x00, 0x00, 0x00, 0xFF);
|
SDL_SetRenderDrawColor(renderer_, 0x00, 0x00, 0x00, 0xFF);
|
||||||
|
|
||||||
// Establece el tamaño del buffer de renderizado
|
// Establece el tamaño del buffer de renderizado
|
||||||
SDL_SetRenderLogicalPresentation(renderer, GAMECANVAS_WIDTH, GAMECANVAS_HEIGHT, SDL_LOGICAL_PRESENTATION_LETTERBOX);
|
SDL_SetRenderLogicalPresentation(renderer_, GAMECANVAS_WIDTH, GAMECANVAS_HEIGHT, SDL_LOGICAL_PRESENTATION_LETTERBOX);
|
||||||
|
|
||||||
// Establece el modo de mezcla
|
// Establece el modo de mezcla
|
||||||
SDL_SetRenderDrawBlendMode(renderer, SDL_BLENDMODE_BLEND);
|
SDL_SetRenderDrawBlendMode(renderer_, SDL_BLENDMODE_BLEND);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -328,7 +328,7 @@ auto Director::setFileList() -> bool {
|
|||||||
#endif
|
#endif
|
||||||
|
|
||||||
// Ficheros de configuración
|
// Ficheros de configuración
|
||||||
Asset::get()->add(systemFolder + "/score.bin", Asset::Type::DATA, false, true);
|
Asset::get()->add(system_folder_ + "/score.bin", Asset::Type::DATA, false, true);
|
||||||
Asset::get()->add(PREFIX + "/data/demo/demo.bin", Asset::Type::DATA);
|
Asset::get()->add(PREFIX + "/data/demo/demo.bin", Asset::Type::DATA);
|
||||||
|
|
||||||
// Musicas
|
// Musicas
|
||||||
@@ -470,7 +470,7 @@ void Director::createSystemFolder(const std::string &folder) {
|
|||||||
#elif __linux__
|
#elif __linux__
|
||||||
struct passwd *pw = getpwuid(getuid());
|
struct passwd *pw = getpwuid(getuid());
|
||||||
const char *homedir = pw->pw_dir;
|
const char *homedir = pw->pw_dir;
|
||||||
systemFolder = std::string(homedir) + "/.config/" + folder;
|
system_folder_ = std::string(homedir) + "/.config/" + folder;
|
||||||
|
|
||||||
{
|
{
|
||||||
// Intenta crear ".config", per si no existeix
|
// Intenta crear ".config", per si no existeix
|
||||||
@@ -488,12 +488,12 @@ void Director::createSystemFolder(const std::string &folder) {
|
|||||||
(void)folder;
|
(void)folder;
|
||||||
#else
|
#else
|
||||||
struct stat st = {.st_dev = 0};
|
struct stat st = {.st_dev = 0};
|
||||||
if (stat(systemFolder.c_str(), &st) == -1) {
|
if (stat(system_folder_.c_str(), &st) == -1) {
|
||||||
errno = 0;
|
errno = 0;
|
||||||
#ifdef _WIN32
|
#ifdef _WIN32
|
||||||
int ret = mkdir(systemFolder.c_str());
|
int ret = mkdir(systemFolder.c_str());
|
||||||
#else
|
#else
|
||||||
int ret = mkdir(systemFolder.c_str(), S_IRWXU);
|
int ret = mkdir(system_folder_.c_str(), S_IRWXU);
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
if (ret == -1) {
|
if (ret == -1) {
|
||||||
@@ -522,53 +522,53 @@ void Director::createSystemFolder(const std::string &folder) {
|
|||||||
// Gestiona las transiciones entre secciones
|
// Gestiona las transiciones entre secciones
|
||||||
void Director::handleSectionTransition() {
|
void Director::handleSectionTransition() {
|
||||||
// Determina qué sección debería estar activa
|
// Determina qué sección debería estar activa
|
||||||
ActiveSection target_section = ActiveSection::None;
|
ActiveSection target_section = ActiveSection::NONE;
|
||||||
switch (section->name) {
|
switch (section_->name) {
|
||||||
case SECTION_PROG_LOGO:
|
case SECTION_PROG_LOGO:
|
||||||
target_section = ActiveSection::Logo;
|
target_section = ActiveSection::LOGO;
|
||||||
break;
|
break;
|
||||||
case SECTION_PROG_INTRO:
|
case SECTION_PROG_INTRO:
|
||||||
target_section = ActiveSection::Intro;
|
target_section = ActiveSection::INTRO;
|
||||||
break;
|
break;
|
||||||
case SECTION_PROG_TITLE:
|
case SECTION_PROG_TITLE:
|
||||||
target_section = ActiveSection::Title;
|
target_section = ActiveSection::TITLE;
|
||||||
break;
|
break;
|
||||||
case SECTION_PROG_GAME:
|
case SECTION_PROG_GAME:
|
||||||
target_section = ActiveSection::Game;
|
target_section = ActiveSection::GAME;
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Si no ha cambiado, no hay nada que hacer
|
// Si no ha cambiado, no hay nada que hacer
|
||||||
if (target_section == activeSection) {
|
if (target_section == active_section_) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Destruye la sección anterior
|
// Destruye la sección anterior
|
||||||
logo.reset();
|
logo_.reset();
|
||||||
intro.reset();
|
intro_.reset();
|
||||||
title.reset();
|
title_.reset();
|
||||||
game.reset();
|
game_.reset();
|
||||||
|
|
||||||
// Crea la nueva sección
|
// Crea la nueva sección
|
||||||
activeSection = target_section;
|
active_section_ = target_section;
|
||||||
switch (activeSection) {
|
switch (active_section_) {
|
||||||
case ActiveSection::Logo:
|
case ActiveSection::LOGO:
|
||||||
logo = std::make_unique<Logo>(renderer, section);
|
logo_ = std::make_unique<Logo>(renderer_, section_);
|
||||||
break;
|
break;
|
||||||
case ActiveSection::Intro:
|
case ActiveSection::INTRO:
|
||||||
intro = std::make_unique<Intro>(renderer, section);
|
intro_ = std::make_unique<Intro>(renderer_, section_);
|
||||||
break;
|
break;
|
||||||
case ActiveSection::Title:
|
case ActiveSection::TITLE:
|
||||||
title = std::make_unique<Title>(renderer, section);
|
title_ = std::make_unique<Title>(renderer_, section_);
|
||||||
break;
|
break;
|
||||||
case ActiveSection::Game: {
|
case ActiveSection::GAME: {
|
||||||
const int NUM_PLAYERS = section->subsection == SUBSECTION_GAME_PLAY_1P ? 1 : 2;
|
const int NUM_PLAYERS = section_->subsection == SUBSECTION_GAME_PLAY_1P ? 1 : 2;
|
||||||
game = std::make_unique<Game>(NUM_PLAYERS, 0, renderer, false, section);
|
game_ = std::make_unique<Game>(NUM_PLAYERS, 0, renderer_, false, section_);
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
case ActiveSection::None:
|
case ActiveSection::NONE:
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -581,7 +581,7 @@ auto Director::iterate() -> SDL_AppResult {
|
|||||||
section->name = SECTION_PROG_LOGO;
|
section->name = SECTION_PROG_LOGO;
|
||||||
}
|
}
|
||||||
#else
|
#else
|
||||||
if (section->name == SECTION_PROG_QUIT) {
|
if (section_->name == SECTION_PROG_QUIT) {
|
||||||
return SDL_APP_SUCCESS;
|
return SDL_APP_SUCCESS;
|
||||||
}
|
}
|
||||||
#endif
|
#endif
|
||||||
@@ -593,20 +593,20 @@ auto Director::iterate() -> SDL_AppResult {
|
|||||||
handleSectionTransition();
|
handleSectionTransition();
|
||||||
|
|
||||||
// Ejecuta un frame de la sección activa
|
// Ejecuta un frame de la sección activa
|
||||||
switch (activeSection) {
|
switch (active_section_) {
|
||||||
case ActiveSection::Logo:
|
case ActiveSection::LOGO:
|
||||||
logo->iterate();
|
logo_->iterate();
|
||||||
break;
|
break;
|
||||||
case ActiveSection::Intro:
|
case ActiveSection::INTRO:
|
||||||
intro->iterate();
|
intro_->iterate();
|
||||||
break;
|
break;
|
||||||
case ActiveSection::Title:
|
case ActiveSection::TITLE:
|
||||||
title->iterate();
|
title_->iterate();
|
||||||
break;
|
break;
|
||||||
case ActiveSection::Game:
|
case ActiveSection::GAME:
|
||||||
game->iterate();
|
game_->iterate();
|
||||||
break;
|
break;
|
||||||
case ActiveSection::None:
|
case ActiveSection::NONE:
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -618,7 +618,7 @@ auto Director::handleEvent(SDL_Event *event) -> SDL_AppResult {
|
|||||||
#ifndef __EMSCRIPTEN__
|
#ifndef __EMSCRIPTEN__
|
||||||
// Evento de salida de la aplicación
|
// Evento de salida de la aplicación
|
||||||
if (event->type == SDL_EVENT_QUIT) {
|
if (event->type == SDL_EVENT_QUIT) {
|
||||||
section->name = SECTION_PROG_QUIT;
|
section_->name = SECTION_PROG_QUIT;
|
||||||
return SDL_APP_SUCCESS;
|
return SDL_APP_SUCCESS;
|
||||||
}
|
}
|
||||||
#endif
|
#endif
|
||||||
@@ -646,20 +646,20 @@ auto Director::handleEvent(SDL_Event *event) -> SDL_AppResult {
|
|||||||
Mouse::handleEvent(*event, Options::video.fullscreen);
|
Mouse::handleEvent(*event, Options::video.fullscreen);
|
||||||
|
|
||||||
// Reenvía el evento a la sección activa
|
// Reenvía el evento a la sección activa
|
||||||
switch (activeSection) {
|
switch (active_section_) {
|
||||||
case ActiveSection::Logo:
|
case ActiveSection::LOGO:
|
||||||
logo->handleEvent(event);
|
logo_->handleEvent(event);
|
||||||
break;
|
break;
|
||||||
case ActiveSection::Intro:
|
case ActiveSection::INTRO:
|
||||||
intro->handleEvent(event);
|
intro_->handleEvent(event);
|
||||||
break;
|
break;
|
||||||
case ActiveSection::Title:
|
case ActiveSection::TITLE:
|
||||||
title->handleEvent(event);
|
title_->handleEvent(event);
|
||||||
break;
|
break;
|
||||||
case ActiveSection::Game:
|
case ActiveSection::GAME:
|
||||||
game->handleEvent(event);
|
game_->handleEvent(event);
|
||||||
break;
|
break;
|
||||||
case ActiveSection::None:
|
case ActiveSection::NONE:
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -11,65 +11,48 @@ class Logo;
|
|||||||
class Title;
|
class Title;
|
||||||
struct Section;
|
struct Section;
|
||||||
|
|
||||||
// Secciones activas del Director
|
|
||||||
enum class ActiveSection : std::uint8_t { None,
|
|
||||||
Logo,
|
|
||||||
Intro,
|
|
||||||
Title,
|
|
||||||
Game };
|
|
||||||
|
|
||||||
class Director {
|
class Director {
|
||||||
private:
|
|
||||||
// Objetos y punteros
|
|
||||||
SDL_Window *window; // La ventana donde dibujamos
|
|
||||||
SDL_Renderer *renderer; // El renderizador de la ventana
|
|
||||||
Section *section; // Sección y subsección actual del programa;
|
|
||||||
|
|
||||||
// Secciones del juego
|
|
||||||
ActiveSection activeSection;
|
|
||||||
std::unique_ptr<Logo> logo;
|
|
||||||
std::unique_ptr<Intro> intro;
|
|
||||||
std::unique_ptr<Title> title;
|
|
||||||
std::unique_ptr<Game> game;
|
|
||||||
|
|
||||||
// Variables
|
|
||||||
std::string executablePath; // Path del ejecutable
|
|
||||||
std::string systemFolder; // Carpeta del sistema donde guardar datos
|
|
||||||
|
|
||||||
// Inicializa jail_audio
|
|
||||||
static void initJailAudio();
|
|
||||||
|
|
||||||
// Arranca SDL y crea la ventana
|
|
||||||
auto initSDL() -> bool;
|
|
||||||
|
|
||||||
// Inicializa el objeto input
|
|
||||||
static void initInput();
|
|
||||||
|
|
||||||
// Crea el indice de ficheros
|
|
||||||
auto setFileList() -> bool;
|
|
||||||
|
|
||||||
// Comprueba los parametros del programa
|
|
||||||
static void checkProgramArguments(int argc, const char *argv[]);
|
|
||||||
|
|
||||||
// Crea la carpeta del sistema donde guardar datos
|
|
||||||
void createSystemFolder(const std::string &folder);
|
|
||||||
|
|
||||||
// Gestiona las transiciones entre secciones
|
|
||||||
void handleSectionTransition();
|
|
||||||
|
|
||||||
public:
|
public:
|
||||||
// Constructor
|
Director(int argc, const char *argv[]); // Constructor
|
||||||
Director(int argc, const char *argv[]);
|
~Director(); // Destructor
|
||||||
|
|
||||||
// Destructor
|
|
||||||
~Director();
|
|
||||||
|
|
||||||
Director(const Director &) = delete;
|
Director(const Director &) = delete;
|
||||||
auto operator=(const Director &) -> Director & = delete;
|
auto operator=(const Director &) -> Director & = delete;
|
||||||
|
|
||||||
// Ejecuta un frame del juego
|
auto iterate() -> SDL_AppResult; // Ejecuta un frame del juego
|
||||||
auto iterate() -> SDL_AppResult;
|
auto handleEvent(SDL_Event *event) -> SDL_AppResult; // Procesa un evento
|
||||||
|
|
||||||
// Procesa un evento
|
private:
|
||||||
auto handleEvent(SDL_Event *event) -> SDL_AppResult;
|
// Secciones activas del Director
|
||||||
|
enum class ActiveSection : std::uint8_t {
|
||||||
|
NONE,
|
||||||
|
LOGO,
|
||||||
|
INTRO,
|
||||||
|
TITLE,
|
||||||
|
GAME
|
||||||
|
};
|
||||||
|
|
||||||
|
static void initJailAudio(); // Inicializa jail_audio
|
||||||
|
auto initSDL() -> bool; // Arranca SDL y crea la ventana
|
||||||
|
static void initInput(); // Inicializa el objeto input
|
||||||
|
auto setFileList() -> bool; // Crea el indice de ficheros
|
||||||
|
static void checkProgramArguments(int argc, const char *argv[]); // Comprueba los parametros del programa
|
||||||
|
void createSystemFolder(const std::string &folder); // Crea la carpeta del sistema donde guardar datos
|
||||||
|
void handleSectionTransition(); // Gestiona las transiciones entre secciones
|
||||||
|
|
||||||
|
// Objetos y punteros
|
||||||
|
SDL_Window *window_; // La ventana donde dibujamos
|
||||||
|
SDL_Renderer *renderer_; // El renderizador de la ventana
|
||||||
|
Section *section_; // Sección y subsección actual del programa;
|
||||||
|
|
||||||
|
// Secciones del juego
|
||||||
|
ActiveSection active_section_;
|
||||||
|
std::unique_ptr<Logo> logo_;
|
||||||
|
std::unique_ptr<Intro> intro_;
|
||||||
|
std::unique_ptr<Title> title_;
|
||||||
|
std::unique_ptr<Game> game_;
|
||||||
|
|
||||||
|
// Variables
|
||||||
|
std::string executable_path_; // Path del ejecutable
|
||||||
|
std::string system_folder_; // Carpeta del sistema donde guardar datos
|
||||||
};
|
};
|
||||||
|
|||||||
+157
-331
@@ -21,36 +21,47 @@ class Texture;
|
|||||||
struct JA_Music_t;
|
struct JA_Music_t;
|
||||||
struct JA_Sound_t;
|
struct JA_Sound_t;
|
||||||
|
|
||||||
// Cantidad de elementos a escribir en los ficheros de datos
|
|
||||||
constexpr int TOTAL_SCORE_DATA = 3;
|
|
||||||
constexpr int TOTAL_DEMO_DATA = 2000;
|
|
||||||
|
|
||||||
// Contadores
|
|
||||||
constexpr int STAGE_COUNTER = 200;
|
|
||||||
constexpr int SHAKE_COUNTER = 10;
|
|
||||||
constexpr int HELP_COUNTER = 1000;
|
|
||||||
constexpr int GAME_COMPLETED_START_FADE = 500;
|
|
||||||
constexpr int GAME_COMPLETED_END = 700;
|
|
||||||
|
|
||||||
// Formaciones enemigas
|
|
||||||
constexpr int NUMBER_OF_ENEMY_FORMATIONS = 100;
|
|
||||||
constexpr int MAX_NUMBER_OF_ENEMIES_IN_A_FORMATION = 50;
|
|
||||||
|
|
||||||
// Porcentaje de aparición de los objetos
|
|
||||||
constexpr int ITEM_POINTS_1_DISK_ODDS = 10;
|
|
||||||
constexpr int ITEM_POINTS_2_GAVINA_ODDS = 6;
|
|
||||||
constexpr int ITEM_POINTS_3_PACMAR_ODDS = 3;
|
|
||||||
constexpr int ITEM_CLOCK_ODDS = 5;
|
|
||||||
constexpr int ITEM_COFFEE_ODDS = 5;
|
|
||||||
constexpr int ITEM_POWER_BALL_ODDS = 0;
|
|
||||||
constexpr int ITEM_COFFEE_MACHINE_ODDS = 4;
|
|
||||||
|
|
||||||
// Valores para las variables asociadas a los objetos
|
|
||||||
constexpr int TIME_STOPPED_COUNTER = 300;
|
|
||||||
|
|
||||||
// Clase Game
|
// Clase Game
|
||||||
class Game {
|
class Game {
|
||||||
|
public:
|
||||||
|
Game(int num_players, int current_stage, SDL_Renderer *renderer, bool demo, Section *section); // Constructor
|
||||||
|
~Game(); // Destructor
|
||||||
|
|
||||||
|
Game(const Game &) = delete;
|
||||||
|
auto operator=(const Game &) -> Game & = delete;
|
||||||
|
|
||||||
|
void run(); // Bucle para el juego
|
||||||
|
void iterate(); // Ejecuta un frame del juego
|
||||||
|
[[nodiscard]] auto hasFinished() const -> bool; // Indica si el juego ha terminado
|
||||||
|
void handleEvent(const SDL_Event *event); // Procesa un evento
|
||||||
|
|
||||||
private:
|
private:
|
||||||
|
// Cantidad de elementos a escribir en los ficheros de datos
|
||||||
|
static constexpr int TOTAL_SCORE_DATA = 3;
|
||||||
|
static constexpr int TOTAL_DEMO_DATA = 2000;
|
||||||
|
|
||||||
|
// Contadores
|
||||||
|
static constexpr int STAGE_COUNTER = 200;
|
||||||
|
static constexpr int SHAKE_COUNTER = 10;
|
||||||
|
static constexpr int HELP_COUNTER = 1000;
|
||||||
|
static constexpr int GAME_COMPLETED_START_FADE = 500;
|
||||||
|
static constexpr int GAME_COMPLETED_END = 700;
|
||||||
|
|
||||||
|
// Formaciones enemigas
|
||||||
|
static constexpr int NUMBER_OF_ENEMY_FORMATIONS = 100;
|
||||||
|
static constexpr int MAX_NUMBER_OF_ENEMIES_IN_A_FORMATION = 50;
|
||||||
|
|
||||||
|
// Porcentaje de aparición de los objetos
|
||||||
|
static constexpr int ITEM_POINTS_1_DISK_ODDS = 10;
|
||||||
|
static constexpr int ITEM_POINTS_2_GAVINA_ODDS = 6;
|
||||||
|
static constexpr int ITEM_POINTS_3_PACMAR_ODDS = 3;
|
||||||
|
static constexpr int ITEM_CLOCK_ODDS = 5;
|
||||||
|
static constexpr int ITEM_COFFEE_ODDS = 5;
|
||||||
|
static constexpr int ITEM_COFFEE_MACHINE_ODDS = 4;
|
||||||
|
|
||||||
|
// Valores para las variables asociadas a los objetos
|
||||||
|
static constexpr int TIME_STOPPED_COUNTER = 300;
|
||||||
|
|
||||||
struct EnemyInit {
|
struct EnemyInit {
|
||||||
int x; // Posición en el eje X donde crear al enemigo
|
int x; // Posición en el eje X donde crear al enemigo
|
||||||
int y; // Posición en el eje Y donde crear al enemigo
|
int y; // Posición en el eje Y donde crear al enemigo
|
||||||
@@ -128,6 +139,125 @@ class Game {
|
|||||||
DemoKeys data_file[TOTAL_DEMO_DATA]; // Datos del fichero con los movimientos para la demo
|
DemoKeys data_file[TOTAL_DEMO_DATA]; // Datos del fichero con los movimientos para la demo
|
||||||
};
|
};
|
||||||
|
|
||||||
|
void update(); // Actualiza el juego
|
||||||
|
void render(); // Dibuja el juego
|
||||||
|
void init(); // Inicializa las variables necesarias para la sección 'Game'
|
||||||
|
void loadMedia(); // Carga los recursos necesarios para la sección 'Game'
|
||||||
|
|
||||||
|
auto loadScoreFile() -> bool; // Carga el fichero de puntos
|
||||||
|
auto loadDemoFile() -> bool; // Carga el fichero de datos para la demo
|
||||||
|
auto saveScoreFile() -> bool; // Guarda el fichero de puntos
|
||||||
|
auto saveDemoFile() -> bool; // Guarda el fichero de datos para la demo
|
||||||
|
|
||||||
|
void initEnemyFormations(); // Inicializa las formaciones enemigas
|
||||||
|
void initEnemyFormationsZero(); // Helper de initEnemyFormations
|
||||||
|
void initEnemyFormationsLinear(); // Helper de initEnemyFormations
|
||||||
|
void initEnemyFormationsSymmetric(); // Helper de initEnemyFormations
|
||||||
|
void initEnemyFormationsHexagonsAndTest(); // Helper de initEnemyFormations
|
||||||
|
|
||||||
|
void initEnemyPools(); // Inicializa los conjuntos de formaciones
|
||||||
|
void initGameStages(); // Inicializa las fases del juego
|
||||||
|
void deployEnemyFormation(); // Crea una formación de enemigos
|
||||||
|
void increaseStageCurrentPower(Uint8 power); // Aumenta el poder de la fase
|
||||||
|
|
||||||
|
void setHiScore(Uint32 score); // Establece el valor de la variable
|
||||||
|
void updateHiScore(); // Actualiza el valor de HiScore en caso necesario
|
||||||
|
static auto updateScoreText(Uint32 num) -> std::string; // Transforma un valor numérico en una cadena de 6 cifras
|
||||||
|
void renderScoreBoard(); // Pinta el marcador en pantalla usando un objeto texto
|
||||||
|
|
||||||
|
void updatePlayers(); // Actualiza las variables del jugador
|
||||||
|
void renderPlayers(); // Dibuja a los jugadores
|
||||||
|
|
||||||
|
void updateStage(); // Actualiza las variables de la fase
|
||||||
|
void updateDeath(); // Actualiza el estado de muerte
|
||||||
|
void renderDeathFade(int counter); // Renderiza el fade final cuando se acaba la partida
|
||||||
|
|
||||||
|
void updateBalloons(); // Actualiza los globos
|
||||||
|
void renderBalloons(); // Pinta en pantalla todos los globos activos
|
||||||
|
auto createBalloon(float x, float y, Uint8 kind, float velx, float speed, Uint16 creationtimer) -> Uint8; // Crea un globo nuevo en el vector de globos
|
||||||
|
void createPowerBall(); // Crea una PowerBall
|
||||||
|
void setBalloonSpeed(float speed); // Establece la velocidad de los globos
|
||||||
|
void incBalloonSpeed(); // Incrementa la velocidad de los globos
|
||||||
|
void updateBalloonSpeed(); // Actualiza la velocidad de los globos en funcion del poder acumulado de la fase
|
||||||
|
void popBalloon(Balloon *balloon); // Explosiona un globo. Lo destruye y crea otros dos si es el caso
|
||||||
|
void destroyBalloon(Balloon *balloon); // Explosiona un globo. Lo destruye
|
||||||
|
void destroyAllBalloons(); // Destruye todos los globos
|
||||||
|
void stopAllBalloons(Uint16 time); // Detiene todos los globos
|
||||||
|
void startAllBalloons(); // Pone en marcha todos los globos
|
||||||
|
void freeBalloons(); // Vacia el vector de globos
|
||||||
|
|
||||||
|
auto checkPlayerBalloonCollision(Player *player) -> bool; // Comprueba la colisión entre el jugador y los globos activos
|
||||||
|
void checkPlayerItemCollision(Player *player); // Comprueba la colisión entre el jugador y los items
|
||||||
|
void checkBulletBalloonCollision(); // Comprueba la colisión entre las balas y los globos
|
||||||
|
void resolveBulletBalloonHit(Bullet *bullet, Balloon *balloon); // Resuelve un impacto bala-globo (helper de checkBulletBalloonCollision)
|
||||||
|
|
||||||
|
void moveBullets(); // Mueve las balas activas
|
||||||
|
void renderBullets(); // Pinta las balas activas
|
||||||
|
void createBullet(int x, int y, Bullet::Kind kind, bool powered_up, int owner); // Crea un objeto bala
|
||||||
|
void freeBullets(); // Vacia el vector de balas
|
||||||
|
|
||||||
|
void updateItems(); // Actualiza los items
|
||||||
|
void renderItems(); // Pinta los items activos
|
||||||
|
auto dropItem() -> Item::Id; // Devuelve un item en función del azar
|
||||||
|
void createItem(Item::Id kind, float x, float y); // Crea un objeto item
|
||||||
|
void freeItems(); // Vacia el vector de items
|
||||||
|
|
||||||
|
void createItemScoreSprite(int x, int y, const SmartSprite *sprite); // Crea un objeto SmartSprite
|
||||||
|
void freeSmartSprites(); // Vacia el vector de smartsprites
|
||||||
|
|
||||||
|
void renderFlashEffect(); // Dibuja el efecto de flash
|
||||||
|
void updateShakeEffect(); // Actualiza el efecto de agitar la pantalla
|
||||||
|
void throwCoffee(int x, int y); // Crea un SmartSprite para arrojar el item café al recibir un impacto
|
||||||
|
void updateSmartSprites(); // Actualiza los SmartSprites
|
||||||
|
void renderSmartSprites(); // Pinta los SmartSprites activos
|
||||||
|
|
||||||
|
void killPlayer(Player *player); // Acciones a realizar cuando el jugador muere
|
||||||
|
void evaluateAndSetMenace(); // Calcula y establece el valor de amenaza en funcion de los globos activos
|
||||||
|
[[nodiscard]] auto getMenace() const -> Uint8; // Obtiene el valor de la variable
|
||||||
|
|
||||||
|
void setTimeStopped(bool value); // Establece el valor de la variable
|
||||||
|
[[nodiscard]] auto isTimeStopped() const -> bool; // Obtiene el valor de la variable
|
||||||
|
void setTimeStoppedCounter(Uint16 value); // Establece el valor de la variable
|
||||||
|
void incTimeStoppedCounter(Uint16 value); // Incrementa el valor de la variable
|
||||||
|
|
||||||
|
void updateEnemyDeployCounter(); // Actualiza la variable EnemyDeployCounter
|
||||||
|
void updateTimeStoppedCounter(); // Actualiza y comprueba el valor de la variable
|
||||||
|
void updateMenace(); // Gestiona el nivel de amenaza
|
||||||
|
void updateBackground(); // Actualiza el fondo
|
||||||
|
void renderBackground(); // Dibuja el fondo
|
||||||
|
|
||||||
|
void checkGameInput(); // Gestiona la entrada durante el juego
|
||||||
|
void processDemoInput(); // Helper de checkGameInput
|
||||||
|
void processLiveInput(); // Helper de checkGameInput
|
||||||
|
void processPlayerLiveInput(Player *player, int i); // Helper de checkGameInput
|
||||||
|
|
||||||
|
void renderMessages(); // Pinta diferentes mensajes en la pantalla
|
||||||
|
void enableTimeStopItem(); // Habilita el efecto del item de detener el tiempo
|
||||||
|
void disableTimeStopItem(); // Deshabilita el efecto del item de detener el tiempo
|
||||||
|
void shakeScreen(); // Inicia el efecto de agitación intensa de la pantalla
|
||||||
|
void updateDeathShake(); // Actualiza el efecto de agitación intensa
|
||||||
|
[[nodiscard]] auto isDeathShaking() const -> bool; // Indica si el efecto de agitación intensa está activo
|
||||||
|
void updateDeathSequence(); // Actualiza la secuencia de muerte del jugador
|
||||||
|
|
||||||
|
void updatePausedGame(); // Actualiza las variables del menu de pausa del juego
|
||||||
|
void updateLeavingPauseMenu(); // Helper de updatePausedGame
|
||||||
|
void updatePauseMenuUI(); // Helper de updatePausedGame
|
||||||
|
void renderPausedGame(); // Dibuja el menu de pausa del juego
|
||||||
|
void enterPausedGame(); // Inicializa el estado de pausa del juego
|
||||||
|
|
||||||
|
void updateGameOverScreen(); // Actualiza los elementos de la pantalla de game over
|
||||||
|
void renderGameOverScreen(); // Dibuja los elementos de la pantalla de game over
|
||||||
|
void enterGameOverScreen(); // Inicializa el estado de game over
|
||||||
|
|
||||||
|
auto canPowerBallBeCreated() -> bool; // Indica si se puede crear una powerball
|
||||||
|
auto calculateScreenPower() -> int; // Calcula el poder actual de los globos en pantalla
|
||||||
|
void initPaths(); // Inicializa las variables que contienen puntos de ruta para mover objetos
|
||||||
|
void updateGameCompleted(); // Actualiza el tramo final de juego, una vez completado
|
||||||
|
void updateHelper(); // Actualiza las variables de ayuda
|
||||||
|
auto allPlayersAreDead() -> bool; // Comprueba si todos los jugadores han muerto
|
||||||
|
void deleteAllVectorObjects(); // Elimina todos los objetos contenidos en vectores
|
||||||
|
void setHiScore(); // Establece la máxima puntuación desde fichero o desde las puntuaciones online
|
||||||
|
|
||||||
// Objetos y punteros
|
// Objetos y punteros
|
||||||
SDL_Renderer *renderer_; // El renderizador de la ventana
|
SDL_Renderer *renderer_; // El renderizador de la ventana
|
||||||
Section *section_; // Seccion actual dentro del juego
|
Section *section_; // Seccion actual dentro del juego
|
||||||
@@ -255,308 +385,4 @@ class Game {
|
|||||||
#ifdef PAUSE
|
#ifdef PAUSE
|
||||||
bool pause;
|
bool pause;
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
// Actualiza el juego
|
|
||||||
void update();
|
|
||||||
|
|
||||||
// Dibuja el juego
|
|
||||||
void render();
|
|
||||||
|
|
||||||
// Inicializa las variables necesarias para la sección 'Game'
|
|
||||||
void init();
|
|
||||||
|
|
||||||
// Carga los recursos necesarios para la sección 'Game'
|
|
||||||
void loadMedia();
|
|
||||||
|
|
||||||
// Carga el fichero de puntos
|
|
||||||
auto loadScoreFile() -> bool;
|
|
||||||
|
|
||||||
// Carga el fichero de datos para la demo
|
|
||||||
auto loadDemoFile() -> bool;
|
|
||||||
|
|
||||||
// Guarda el fichero de puntos
|
|
||||||
auto saveScoreFile() -> bool;
|
|
||||||
|
|
||||||
// Guarda el fichero de datos para la demo
|
|
||||||
auto saveDemoFile() -> bool;
|
|
||||||
|
|
||||||
// Inicializa las formaciones enemigas
|
|
||||||
void initEnemyFormations();
|
|
||||||
|
|
||||||
// Helpers de initEnemyFormations
|
|
||||||
void initEnemyFormationsZero();
|
|
||||||
void initEnemyFormationsLinear();
|
|
||||||
void initEnemyFormationsSymmetric();
|
|
||||||
void initEnemyFormationsHexagonsAndTest();
|
|
||||||
|
|
||||||
// Inicializa los conjuntos de formaciones
|
|
||||||
void initEnemyPools();
|
|
||||||
|
|
||||||
// Inicializa las fases del juego
|
|
||||||
void initGameStages();
|
|
||||||
|
|
||||||
// Crea una formación de enemigos
|
|
||||||
void deployEnemyFormation();
|
|
||||||
|
|
||||||
// Aumenta el poder de la fase
|
|
||||||
void increaseStageCurrentPower(Uint8 power);
|
|
||||||
|
|
||||||
// Establece el valor de la variable
|
|
||||||
void setHiScore(Uint32 score);
|
|
||||||
|
|
||||||
// Actualiza el valor de HiScore en caso necesario
|
|
||||||
void updateHiScore();
|
|
||||||
|
|
||||||
// Transforma un valor numérico en una cadena de 6 cifras
|
|
||||||
static auto updateScoreText(Uint32 num) -> std::string;
|
|
||||||
|
|
||||||
// Pinta el marcador en pantalla usando un objeto texto
|
|
||||||
void renderScoreBoard();
|
|
||||||
|
|
||||||
// Actualiza las variables del jugador
|
|
||||||
void updatePlayers();
|
|
||||||
|
|
||||||
// Dibuja a los jugadores
|
|
||||||
void renderPlayers();
|
|
||||||
|
|
||||||
// Actualiza las variables de la fase
|
|
||||||
void updateStage();
|
|
||||||
|
|
||||||
// Actualiza el estado de muerte
|
|
||||||
void updateDeath();
|
|
||||||
|
|
||||||
// Renderiza el fade final cuando se acaba la partida
|
|
||||||
void renderDeathFade(int counter);
|
|
||||||
|
|
||||||
// Actualiza los globos
|
|
||||||
void updateBalloons();
|
|
||||||
|
|
||||||
// Pinta en pantalla todos los globos activos
|
|
||||||
void renderBalloons();
|
|
||||||
|
|
||||||
// Crea un globo nuevo en el vector de globos
|
|
||||||
auto createBalloon(float x, float y, Uint8 kind, float velx, float speed, Uint16 creationtimer) -> Uint8;
|
|
||||||
|
|
||||||
// Crea una PowerBall
|
|
||||||
void createPowerBall();
|
|
||||||
|
|
||||||
// Establece la velocidad de los globos
|
|
||||||
void setBalloonSpeed(float speed);
|
|
||||||
|
|
||||||
// Incrementa la velocidad de los globos
|
|
||||||
void incBalloonSpeed();
|
|
||||||
|
|
||||||
// Actualiza la velocidad de los globos en funcion del poder acumulado de la fase
|
|
||||||
void updateBalloonSpeed();
|
|
||||||
|
|
||||||
// Explosiona un globo. Lo destruye y crea otros dos si es el caso
|
|
||||||
void popBalloon(Balloon *balloon);
|
|
||||||
|
|
||||||
// Explosiona un globo. Lo destruye
|
|
||||||
void destroyBalloon(Balloon *balloon);
|
|
||||||
|
|
||||||
// Destruye todos los globos
|
|
||||||
void destroyAllBalloons();
|
|
||||||
|
|
||||||
// Detiene todos los globos
|
|
||||||
void stopAllBalloons(Uint16 time);
|
|
||||||
|
|
||||||
// Pone en marcha todos los globos
|
|
||||||
void startAllBalloons();
|
|
||||||
|
|
||||||
// Vacia el vector de globos
|
|
||||||
void freeBalloons();
|
|
||||||
|
|
||||||
// Comprueba la colisión entre el jugador y los globos activos
|
|
||||||
auto checkPlayerBalloonCollision(Player *player) -> bool;
|
|
||||||
|
|
||||||
// Comprueba la colisión entre el jugador y los items
|
|
||||||
void checkPlayerItemCollision(Player *player);
|
|
||||||
|
|
||||||
// Comprueba la colisión entre las balas y los globos
|
|
||||||
void checkBulletBalloonCollision();
|
|
||||||
|
|
||||||
// Resuelve un impacto bala-globo (helper de checkBulletBalloonCollision)
|
|
||||||
void resolveBulletBalloonHit(Bullet *bullet, Balloon *balloon);
|
|
||||||
|
|
||||||
// Mueve las balas activas
|
|
||||||
void moveBullets();
|
|
||||||
|
|
||||||
// Pinta las balas activas
|
|
||||||
void renderBullets();
|
|
||||||
|
|
||||||
// Crea un objeto bala
|
|
||||||
void createBullet(int x, int y, Bullet::Kind kind, bool powered_up, int owner);
|
|
||||||
|
|
||||||
// Vacia el vector de balas
|
|
||||||
void freeBullets();
|
|
||||||
|
|
||||||
// Actualiza los items
|
|
||||||
void updateItems();
|
|
||||||
|
|
||||||
// Pinta los items activos
|
|
||||||
void renderItems();
|
|
||||||
|
|
||||||
// Devuelve un item en función del azar
|
|
||||||
auto dropItem() -> Item::Id;
|
|
||||||
|
|
||||||
// Crea un objeto item
|
|
||||||
void createItem(Item::Id kind, float x, float y);
|
|
||||||
|
|
||||||
// Vacia el vector de items
|
|
||||||
void freeItems();
|
|
||||||
|
|
||||||
// Crea un objeto SmartSprite
|
|
||||||
void createItemScoreSprite(int x, int y, const SmartSprite *sprite);
|
|
||||||
|
|
||||||
// Vacia el vector de smartsprites
|
|
||||||
void freeSmartSprites();
|
|
||||||
|
|
||||||
// Dibuja el efecto de flash
|
|
||||||
void renderFlashEffect();
|
|
||||||
|
|
||||||
// Actualiza el efecto de agitar la pantalla
|
|
||||||
void updateShakeEffect();
|
|
||||||
|
|
||||||
// Crea un SmartSprite para arrojar el item café al recibir un impacto
|
|
||||||
void throwCoffee(int x, int y);
|
|
||||||
|
|
||||||
// Actualiza los SmartSprites
|
|
||||||
void updateSmartSprites();
|
|
||||||
|
|
||||||
// Pinta los SmartSprites activos
|
|
||||||
void renderSmartSprites();
|
|
||||||
|
|
||||||
// Acciones a realizar cuando el jugador muere
|
|
||||||
void killPlayer(Player *player);
|
|
||||||
|
|
||||||
// Calcula y establece el valor de amenaza en funcion de los globos activos
|
|
||||||
void evaluateAndSetMenace();
|
|
||||||
|
|
||||||
// Obtiene el valor de la variable
|
|
||||||
[[nodiscard]] auto getMenace() const -> Uint8;
|
|
||||||
|
|
||||||
// Establece el valor de la variable
|
|
||||||
void setTimeStopped(bool value);
|
|
||||||
|
|
||||||
// Obtiene el valor de la variable
|
|
||||||
[[nodiscard]] auto isTimeStopped() const -> bool;
|
|
||||||
|
|
||||||
// Establece el valor de la variable
|
|
||||||
void setTimeStoppedCounter(Uint16 value);
|
|
||||||
|
|
||||||
// Incrementa el valor de la variable
|
|
||||||
void incTimeStoppedCounter(Uint16 value);
|
|
||||||
|
|
||||||
// Actualiza la variable EnemyDeployCounter
|
|
||||||
void updateEnemyDeployCounter();
|
|
||||||
|
|
||||||
// Actualiza y comprueba el valor de la variable
|
|
||||||
void updateTimeStoppedCounter();
|
|
||||||
|
|
||||||
// Gestiona el nivel de amenaza
|
|
||||||
void updateMenace();
|
|
||||||
|
|
||||||
// Actualiza el fondo
|
|
||||||
void updateBackground();
|
|
||||||
|
|
||||||
// Dibuja el fondo
|
|
||||||
void renderBackground();
|
|
||||||
|
|
||||||
// Gestiona la entrada durante el juego
|
|
||||||
void checkGameInput();
|
|
||||||
|
|
||||||
// Helpers de checkGameInput
|
|
||||||
void processDemoInput();
|
|
||||||
void processLiveInput();
|
|
||||||
void processPlayerLiveInput(Player *player, int i);
|
|
||||||
|
|
||||||
// Pinta diferentes mensajes en la pantalla
|
|
||||||
void renderMessages();
|
|
||||||
|
|
||||||
// Habilita el efecto del item de detener el tiempo
|
|
||||||
void enableTimeStopItem();
|
|
||||||
|
|
||||||
// Deshabilita el efecto del item de detener el tiempo
|
|
||||||
void disableTimeStopItem();
|
|
||||||
|
|
||||||
// Inicia el efecto de agitación intensa de la pantalla
|
|
||||||
void shakeScreen();
|
|
||||||
|
|
||||||
// Actualiza el efecto de agitación intensa
|
|
||||||
void updateDeathShake();
|
|
||||||
|
|
||||||
// Indica si el efecto de agitación intensa está activo
|
|
||||||
[[nodiscard]] auto isDeathShaking() const -> bool;
|
|
||||||
|
|
||||||
// Actualiza la secuencia de muerte del jugador
|
|
||||||
void updateDeathSequence();
|
|
||||||
|
|
||||||
// Actualiza las variables del menu de pausa del juego
|
|
||||||
void updatePausedGame();
|
|
||||||
|
|
||||||
// Helpers de updatePausedGame
|
|
||||||
void updateLeavingPauseMenu();
|
|
||||||
void updatePauseMenuUI();
|
|
||||||
|
|
||||||
// Dibuja el menu de pausa del juego
|
|
||||||
void renderPausedGame();
|
|
||||||
|
|
||||||
// Inicializa el estado de pausa del juego
|
|
||||||
void enterPausedGame();
|
|
||||||
|
|
||||||
// Actualiza los elementos de la pantalla de game over
|
|
||||||
void updateGameOverScreen();
|
|
||||||
|
|
||||||
// Dibuja los elementos de la pantalla de game over
|
|
||||||
void renderGameOverScreen();
|
|
||||||
|
|
||||||
// Inicializa el estado de game over
|
|
||||||
void enterGameOverScreen();
|
|
||||||
|
|
||||||
// Indica si se puede crear una powerball
|
|
||||||
auto canPowerBallBeCreated() -> bool;
|
|
||||||
|
|
||||||
// Calcula el poder actual de los globos en pantalla
|
|
||||||
auto calculateScreenPower() -> int;
|
|
||||||
|
|
||||||
// Inicializa las variables que contienen puntos de ruta para mover objetos
|
|
||||||
void initPaths();
|
|
||||||
|
|
||||||
// Actualiza el tramo final de juego, una vez completado
|
|
||||||
void updateGameCompleted();
|
|
||||||
|
|
||||||
// Actualiza las variables de ayuda
|
|
||||||
void updateHelper();
|
|
||||||
|
|
||||||
// Comprueba si todos los jugadores han muerto
|
|
||||||
auto allPlayersAreDead() -> bool;
|
|
||||||
|
|
||||||
// Elimina todos los objetos contenidos en vectores
|
|
||||||
void deleteAllVectorObjects();
|
|
||||||
|
|
||||||
// Establece la máxima puntuación desde fichero o desde las puntuaciones online
|
|
||||||
void setHiScore();
|
|
||||||
|
|
||||||
public:
|
|
||||||
// Constructor
|
|
||||||
Game(int num_players, int current_stage, SDL_Renderer *renderer, bool demo, Section *section);
|
|
||||||
|
|
||||||
// Destructor
|
|
||||||
~Game();
|
|
||||||
|
|
||||||
Game(const Game &) = delete;
|
|
||||||
auto operator=(const Game &) -> Game & = delete;
|
|
||||||
|
|
||||||
// Bucle para el juego
|
|
||||||
void run();
|
|
||||||
|
|
||||||
// Ejecuta un frame del juego
|
|
||||||
void iterate();
|
|
||||||
|
|
||||||
// Indica si el juego ha terminado
|
|
||||||
[[nodiscard]] auto hasFinished() const -> bool;
|
|
||||||
|
|
||||||
// Procesa un evento
|
|
||||||
void handleEvent(const SDL_Event *event);
|
|
||||||
};
|
};
|
||||||
|
|||||||
+285
-285
File diff suppressed because it is too large
Load Diff
+104
-182
@@ -24,6 +24,56 @@ constexpr int MENU_NO_OPTION = -1;
|
|||||||
|
|
||||||
// Clase Menu
|
// Clase Menu
|
||||||
class Menu {
|
class Menu {
|
||||||
|
public:
|
||||||
|
explicit Menu(SDL_Renderer *renderer, const std::string &file = ""); // Constructor
|
||||||
|
~Menu(); // Destructor
|
||||||
|
|
||||||
|
auto loadFromBytes(const std::vector<uint8_t> &bytes, const std::string &name_for_logs = "") -> bool; // Carga el menu desde bytes en memoria
|
||||||
|
void loadAudioFile(const std::string &file, int sound); // Carga los ficheros de audio
|
||||||
|
|
||||||
|
[[nodiscard]] auto getName() const -> const std::string &; // Obtiene el nombre del menu
|
||||||
|
auto getItemSelected() -> int; // Obtiene el valor de la variable
|
||||||
|
|
||||||
|
void reset(); // Deja el menu apuntando al primer elemento
|
||||||
|
void checkInput(); // Gestiona la entrada de teclado y mando durante el menu
|
||||||
|
void update(); // Actualiza la logica del menu
|
||||||
|
void render(); // Pinta el menu en pantalla
|
||||||
|
|
||||||
|
void setBackgroundColor(Color color, int alpha); // Establece el color del rectangulo de fondo
|
||||||
|
void setSelectorColor(Color color, int alpha); // Establece el color del rectangulo del selector
|
||||||
|
void setSelectorTextColor(Color color); // Establece el color del texto del selector
|
||||||
|
|
||||||
|
void centerMenuOnX(int value = 0); // Centra el menu respecto a un punto en el eje X
|
||||||
|
void centerMenuOnY(int value); // Centra el menu respecto a un punto en el eje Y
|
||||||
|
void centerMenuElementsOnX(); // Centra los elementos del menu en el eje X
|
||||||
|
|
||||||
|
struct Item {
|
||||||
|
std::string label; // Texto
|
||||||
|
SDL_Rect rect; // Rectangulo que delimita el elemento
|
||||||
|
int h_padding_down; // Espaciado bajo el elemento
|
||||||
|
bool selectable; // Indica si se puede seleccionar
|
||||||
|
bool greyed; // Indica si ha de aparecer con otro color mas oscuro
|
||||||
|
bool linked_down; // Indica si el elemento actual y el siguiente se tratan como uno solo. Afecta al selector
|
||||||
|
bool linked_up; // Indica si el elemento actual y el anterior se tratan como uno solo. Afecta al selector
|
||||||
|
bool visible; // Indica si el elemento es visible
|
||||||
|
bool line; // Indica si el elemento lleva una linea a continuación
|
||||||
|
};
|
||||||
|
|
||||||
|
void addItem(Item new_item); // Añade un item al menu
|
||||||
|
void setItemCaption(int index, const std::string &text); // Cambia el texto de un item
|
||||||
|
void setDefaultActionWhenCancel(int item); // Establece el indice del item que se usará por defecto al cancelar el menu
|
||||||
|
void setSelectorPos(int index); // Coloca el selector en una posición específica
|
||||||
|
void setSelectable(int index, bool value); // Establece el estado seleccionable de un item
|
||||||
|
void setGreyed(int index, bool value); // Establece el estado agrisado de un item
|
||||||
|
void setLinkedDown(int index, bool value); // Establece el estado de enlace de un item
|
||||||
|
void setVisible(int index, bool value); // Establece el estado de visibilidad de un item
|
||||||
|
|
||||||
|
void setName(const std::string &name); // Establece el nombre del menu
|
||||||
|
void setPos(int x, int y); // Establece la posición del menu
|
||||||
|
void setBackgroundType(int value); // Establece el tipo de fondo del menu
|
||||||
|
void setText(const std::string &font_png, const std::string &font_txt); // Establece la fuente de texto que se utilizará
|
||||||
|
void setRectSize(int w = 0, int h = 0); // Establece el rectangulo de fondo del menu
|
||||||
|
|
||||||
private:
|
private:
|
||||||
struct Rectangle {
|
struct Rectangle {
|
||||||
SDL_Rect rect; // Rectangulo
|
SDL_Rect rect; // Rectangulo
|
||||||
@@ -31,200 +81,72 @@ class Menu {
|
|||||||
int a; // Transparencia
|
int a; // Transparencia
|
||||||
};
|
};
|
||||||
|
|
||||||
struct Item {
|
|
||||||
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
|
|
||||||
bool visible; // Indica si el elemento es visible
|
|
||||||
bool line; // Indica si el elemento lleva una linea a continuación
|
|
||||||
};
|
|
||||||
|
|
||||||
struct Selector {
|
struct Selector {
|
||||||
float originY; // Coordenada de origen
|
float origin_y; // Coordenada de origen
|
||||||
float targetY; // Coordenada de destino
|
float target_y; // Coordenada de destino
|
||||||
float despY; // Cantidad de pixeles que se desplaza el selector en cada salto: (target - origin) / numJumps
|
float desp_y; // 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
|
bool moving; // Indica si el selector está avanzando hacia el destino
|
||||||
float originH; // Altura de origen
|
float origin_h; // Altura de origen
|
||||||
float targetH; // Altura de destino
|
float target_h; // Altura de destino
|
||||||
float incH; // Cantidad de pixels que debe incrementar o decrementar el selector en cada salto
|
float inc_h; // Cantidad de pixels que debe incrementar o decrementar el selector en cada salto
|
||||||
bool resizing; // Indica si el selector está cambiando de tamaño
|
bool resizing; // Indica si el selector está cambiando de tamaño
|
||||||
float y; // Coordenada actual, usado para el desplazamiento
|
float y; // Coordenada actual, usado para el desplazamiento
|
||||||
float h; // Altura actual, usado para el cambio de tamaño
|
float h; // Altura actual, usado para el cambio de tamaño
|
||||||
int numJumps; // Numero de pasos preestablecido para llegar al destino
|
int num_jumps; // Numero de pasos preestablecido para llegar al destino
|
||||||
int index; // Elemento del menu que tiene el foco
|
int index; // Elemento del menu que tiene el foco
|
||||||
int previousIndex; // Elemento que tenia el foco previamente
|
int previous_index; // Elemento que tenia el foco previamente
|
||||||
Color previousItemColor; // Color del item nque tenia el foco previamente
|
Color previous_item_color; // Color del item nque tenia el foco previamente
|
||||||
SDL_Rect rect; // Rectangulo del selector
|
SDL_Rect rect; // Rectangulo del selector
|
||||||
Color color; // Color del selector
|
Color color; // Color del selector
|
||||||
Color itemColor; // Color del item
|
Color item_color; // Color del item
|
||||||
Color jumpItemColors[8]; // Transición de colores para el item seleccionado
|
Color jump_item_colors[8]; // Transición de colores para el item seleccionado
|
||||||
int itemColorIndex; // Indice del color de transición para el item seleccionado
|
int item_color_index; // Indice del color de transición para el item seleccionado
|
||||||
int a; // Cantidad de transparencia para el rectangulo del selector
|
int a; // Cantidad de transparencia para el rectangulo del selector
|
||||||
};
|
};
|
||||||
|
|
||||||
|
auto load(const std::string &file_path) -> bool; // Carga la configuración del menu desde un archivo de texto
|
||||||
|
auto parseFromStream(std::istream &file, const std::string &filename) -> bool; // Parser compartido (recibe cualquier istream)
|
||||||
|
auto setVars(const std::string &var, const std::string &value) -> bool; // Asigna variables a partir de dos cadenas
|
||||||
|
static auto setItem(Item *item, const std::string &var, const std::string &value) -> bool; // Asigna variables a partir de dos cadenas
|
||||||
|
|
||||||
|
void reorganize(); // Actualiza el menu para recolocarlo correctamente y establecer el tamaño
|
||||||
|
void increaseSelectorIndex(); // Deja el menu apuntando al siguiente elemento
|
||||||
|
void decreaseSelectorIndex(); // Deja el menu apuntando al elemento anterior
|
||||||
|
void updateSelector(); // Actualiza la posicion y el estado del selector
|
||||||
|
auto getWidestItem() -> int; // Obtiene la anchura del elemento más ancho del menu
|
||||||
|
void checkMenuInput(Menu *menu); // Gestiona la entrada de teclado y mando durante el menu
|
||||||
|
auto findWidth() -> int; // Calcula el ancho del menu
|
||||||
|
auto findHeight() -> int; // Calcula el alto del menu
|
||||||
|
void replaceElementsOnY(); // Recoloca los elementos del menu en el eje Y
|
||||||
|
auto getSelectorHeight(int value) -> int; // Calcula la altura del selector
|
||||||
|
void setSelectorItemColors(); // Calcula los colores del selector para el degradado
|
||||||
|
|
||||||
// Objetos y punteros
|
// Objetos y punteros
|
||||||
SDL_Renderer *renderer; // Puntero al renderizador de la ventana
|
SDL_Renderer *renderer_; // Puntero al renderizador de la ventana
|
||||||
Text *text; // Texto para poder escribir los items del menu
|
Text *text_; // Texto para poder escribir los items del menu
|
||||||
|
|
||||||
// Variables
|
// Variables
|
||||||
std::string name; // Nombre del menu
|
std::string name_; // Nombre del menu
|
||||||
int x; // Posición en el eje X de la primera letra del primer elemento
|
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 y_; // Posición en el eje Y de la primera letra del primer elemento
|
||||||
int h; // Altura del menu
|
int h_; // Altura del menu
|
||||||
int w; // Anchura del menu
|
int w_; // Anchura del menu
|
||||||
int itemSelected; // Índice del item del menu que ha sido seleccionado
|
int item_selected_; // Í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 default_action_when_cancel_; // Indice del item del menu que se selecciona cuando se cancela el menu
|
||||||
int backgroundType; // Tipo de fondo para el menu
|
int background_type_; // Tipo de fondo para el menu
|
||||||
int centerX; // Centro del menu en el eje X
|
int center_x_; // Centro del menu en el eje X
|
||||||
int centerY; // Centro del menu en el eje Y
|
int center_y_; // 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 is_centered_on_x_; // 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 is_centered_on_y_; // 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
|
bool are_elements_centered_on_x_; // Variable para saber si los elementos van centrados en el eje X
|
||||||
int widestItem; // Anchura del elemento más ancho
|
int widest_item_; // Anchura del elemento más ancho
|
||||||
JA_Sound_t *soundAccept; // Sonido al aceptar o elegir una opción del menu
|
JA_Sound_t *sound_accept_; // Sonido al aceptar o elegir una opción del menu
|
||||||
JA_Sound_t *soundCancel; // Sonido al cancelar el menu
|
JA_Sound_t *sound_cancel_; // Sonido al cancelar el menu
|
||||||
JA_Sound_t *soundMove; // Sonido al mover el selector
|
JA_Sound_t *sound_move_; // Sonido al mover el selector
|
||||||
Color colorGreyed; // Color para los elementos agrisados
|
Color color_greyed_; // Color para los elementos agrisados
|
||||||
Rectangle rectBG; // Rectangulo de fondo del menu
|
Rectangle rect_bg_; // Rectangulo de fondo del menu
|
||||||
std::vector<Item> item; // Estructura para cada elemento del menu
|
std::vector<Item> items_; // Estructura para cada elemento del menu
|
||||||
Selector selector; // Variables para pintar el selector del menu
|
Selector selector_; // Variables para pintar el selector del menu
|
||||||
std::string font_png;
|
std::string font_png_;
|
||||||
std::string font_txt;
|
std::string font_txt_;
|
||||||
|
|
||||||
// Carga la configuración del menu desde un archivo de texto
|
|
||||||
auto load(const std::string &file_path) -> bool;
|
|
||||||
|
|
||||||
// Parser compartido (recibe cualquier istream)
|
|
||||||
auto parseFromStream(std::istream &file, const std::string &filename) -> bool;
|
|
||||||
|
|
||||||
// Asigna variables a partir de dos cadenas
|
|
||||||
auto setVars(const std::string &var, const std::string &value) -> bool;
|
|
||||||
|
|
||||||
// Asigna variables a partir de dos cadenas
|
|
||||||
static auto setItem(Item *item, const std::string &var, const std::string &value) -> bool;
|
|
||||||
|
|
||||||
// Actualiza el menu para recolocarlo correctamente y establecer el tamaño
|
|
||||||
void reorganize();
|
|
||||||
|
|
||||||
// Deja el menu apuntando al siguiente elemento
|
|
||||||
void increaseSelectorIndex();
|
|
||||||
|
|
||||||
// Deja el menu apuntando al elemento anterior
|
|
||||||
void decreaseSelectorIndex();
|
|
||||||
|
|
||||||
// Actualiza la posicion y el estado del selector
|
|
||||||
void updateSelector();
|
|
||||||
|
|
||||||
// Obtiene la anchura del elemento más ancho del menu
|
|
||||||
auto getWidestItem() -> int;
|
|
||||||
|
|
||||||
// Gestiona la entrada de teclado y mando durante el menu
|
|
||||||
void checkMenuInput(Menu *menu);
|
|
||||||
|
|
||||||
// Calcula el ancho del menu
|
|
||||||
auto findWidth() -> int;
|
|
||||||
|
|
||||||
// Calcula el alto del menu
|
|
||||||
auto findHeight() -> int;
|
|
||||||
|
|
||||||
// Recoloca los elementos del menu en el eje Y
|
|
||||||
void replaceElementsOnY();
|
|
||||||
|
|
||||||
// Calcula la altura del selector
|
|
||||||
auto getSelectorHeight(int value) -> int;
|
|
||||||
|
|
||||||
// Calcula los colores del selector para el degradado
|
|
||||||
void setSelectorItemColors();
|
|
||||||
|
|
||||||
public:
|
|
||||||
// Constructor
|
|
||||||
explicit Menu(SDL_Renderer *renderer, const std::string &file = "");
|
|
||||||
|
|
||||||
// Destructor
|
|
||||||
~Menu();
|
|
||||||
|
|
||||||
// Carga el menu desde bytes en memoria
|
|
||||||
auto loadFromBytes(const std::vector<uint8_t> &bytes, const std::string &nameForLogs = "") -> bool;
|
|
||||||
|
|
||||||
// Carga los ficheros de audio
|
|
||||||
void loadAudioFile(const std::string &file, int sound);
|
|
||||||
|
|
||||||
// Obtiene el nombre del menu
|
|
||||||
[[nodiscard]] auto getName() const -> const std::string &;
|
|
||||||
|
|
||||||
// Obtiene el valor de la variable
|
|
||||||
auto getItemSelected() -> int;
|
|
||||||
|
|
||||||
// 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 color, int alpha);
|
|
||||||
|
|
||||||
// Establece el color del rectangulo del selector
|
|
||||||
void setSelectorColor(Color color, int alpha);
|
|
||||||
|
|
||||||
// Establece el color del texto del selector
|
|
||||||
void setSelectorTextColor(Color 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(Item new_item);
|
|
||||||
|
|
||||||
// Cambia el texto de un item
|
|
||||||
void setItemCaption(int index, const 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 estado de visibilidad de un item
|
|
||||||
void setVisible(int index, bool value);
|
|
||||||
|
|
||||||
// Establece el nombre del menu
|
|
||||||
void setName(const 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(const std::string &font_png, const std::string &font_txt);
|
|
||||||
|
|
||||||
// Establece el rectangulo de fondo del menu
|
|
||||||
void setRectSize(int w = 0, int h = 0);
|
|
||||||
};
|
};
|
||||||
|
|||||||
Reference in New Issue
Block a user