canviat Options de struct a namespace

This commit is contained in:
2025-10-26 14:01:08 +01:00
parent 8f49e442de
commit df4965a84b
59 changed files with 1470 additions and 1533 deletions

View File

@@ -6,8 +6,8 @@
#include <fstream> // Para basic_ostream, operator<<, basic_ofstream
#include <iostream> // Para cout, cerr
#include "game/gameplay/options.hpp" // Para Options, options
#include "game/ui/notifier.hpp" // Para Notifier
#include "game/gameplay/options.hpp" // Para Options, options
#include "game/ui/notifier.hpp" // Para Notifier
// [SINGLETON]
Cheevos* Cheevos::cheevos_ = nullptr;
@@ -102,7 +102,7 @@ void Cheevos::loadFromFile() {
// El fichero no existe
if (!file) {
if (options.console) {
if (Options::console) {
std::cout << "Warning: Unable to open " << file_ << "! Creating new file..." << std::endl;
}
@@ -110,7 +110,7 @@ void Cheevos::loadFromFile() {
std::ofstream newFile(file_, std::ios::binary);
if (newFile) {
if (options.console) {
if (Options::console) {
std::cout << "New " << file_ << " created!" << std::endl;
}
@@ -119,14 +119,14 @@ void Cheevos::loadFromFile() {
newFile.write(reinterpret_cast<const char*>(&cheevo.completed), sizeof(bool));
}
} else {
if (options.console) {
if (Options::console) {
std::cerr << "Error: Unable to create " << file_ << "!" << std::endl;
}
}
}
// El fichero existe
else {
if (options.console) {
if (Options::console) {
std::cout << "Reading " << file_ << std::endl;
}
@@ -150,7 +150,7 @@ void Cheevos::saveToFile() {
// Cierra el fichero
SDL_CloseIO(file);
} else {
if (options.console) {
if (Options::console) {
std::cout << "Error: Unable to save file! " << SDL_GetError() << std::endl;
}
}

View File

@@ -1,83 +1,90 @@
#pragma once
#include <string> // Para string
#include <vector> // Para vector
#include <string> // Para string
#include <vector> // Para vector
// Struct para los logros
struct Achievement
{
int id; // Identificador del logro
std::string caption; // Texto con el nombre del logro
std::string description; // Texto que describe el logro
int icon; // Indice del icono a utilizar en la notificación
bool completed; // Indica si se ha obtenido el logro
bool obtainable; // Indica si se puede obtener el logro
struct Achievement {
int id; // Identificador del logro
std::string caption; // Texto con el nombre del logro
std::string description; // Texto que describe el logro
int icon; // Indice del icono a utilizar en la notificación
bool completed; // Indica si se ha obtenido el logro
bool obtainable; // Indica si se puede obtener el logro
// Constructor vacío
Achievement() : id(0), icon(0), completed(false), obtainable(true) {}
// Constructor vacío
Achievement()
: id(0),
icon(0),
completed(false),
obtainable(true) {}
// Constructor parametrizado
Achievement(int id, const std::string &caption, const std::string &description, int icon, bool completed = false, bool obtainable = true)
: id(id), caption(caption), description(description), icon(icon), completed(completed), obtainable(obtainable) {}
// Constructor parametrizado
Achievement(int id, const std::string& caption, const std::string& description, int icon, bool completed = false, bool obtainable = true)
: id(id),
caption(caption),
description(description),
icon(icon),
completed(completed),
obtainable(obtainable) {}
};
class Cheevos
{
private:
// [SINGLETON] Objeto privado
static Cheevos *cheevos_;
class Cheevos {
private:
// [SINGLETON] Objeto privado
static Cheevos* cheevos_;
// Variables
std::vector<Achievement> cheevos_list_; // Listado de logros
bool enabled_ = true; // Indica si los logros se pueden obtener
std::string file_; // Fichero donde leer/almacenar el estado de los logros
// Variables
std::vector<Achievement> cheevos_list_; // Listado de logros
bool enabled_ = true; // Indica si los logros se pueden obtener
std::string file_; // Fichero donde leer/almacenar el estado de los logros
// Inicializa los logros
void init();
// Inicializa los logros
void init();
// Busca un logro por id y devuelve el índice
int find(int id);
// Busca un logro por id y devuelve el índice
int find(int id);
// Carga el estado de los logros desde un fichero
void loadFromFile();
// Carga el estado de los logros desde un fichero
void loadFromFile();
// Guarda el estado de los logros en un fichero
void saveToFile();
// Guarda el estado de los logros en un fichero
void saveToFile();
// Constructor
explicit Cheevos(const std::string &file);
// Constructor
explicit Cheevos(const std::string& file);
// Destructor
~Cheevos();
// Destructor
~Cheevos();
public:
// [SINGLETON] Crearemos el objeto con esta función estática
static void init(const std::string &file);
public:
// [SINGLETON] Crearemos el objeto con esta función estática
static void init(const std::string& file);
// [SINGLETON] Destruiremos el objeto con esta función estática
static void destroy();
// [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 Cheevos *get();
// [SINGLETON] Con este método obtenemos el objeto y podemos trabajar con él
static Cheevos* get();
// Desbloquea un logro
void unlock(int id);
// Desbloquea un logro
void unlock(int id);
// Invalida un logro
void setUnobtainable(int id);
// Invalida un logro
void setUnobtainable(int id);
// Elimina el estado "no obtenible"
void clearUnobtainableState();
// Elimina el estado "no obtenible"
void clearUnobtainableState();
// Habilita o deshabilita los logros
void enable(bool value) { enabled_ = value; }
// Habilita o deshabilita los logros
void enable(bool value) { enabled_ = value; }
// Lista los logros
const std::vector<Achievement>& list() const { return cheevos_list_; }
// Lista los logros
const std::vector<Achievement>& list() const { return cheevos_list_; }
// Devuelve el número total de logros desbloqueados
int getTotalUnlockedAchievements();
// Devuelve el número total de logros desbloqueados
int getTotalUnlockedAchievements();
// Devuelve el número total de logros
int size() { return cheevos_list_.size(); }
// Devuelve el número total de logros
int size() { return cheevos_list_.size(); }
};

View File

@@ -0,0 +1,85 @@
#pragma once
#include <SDL3/SDL.h>
#include "core/rendering/screen.hpp" // Para ScreenFilter
#include "utils/utils.hpp" // Para PaletteColor
// Forward declarations from Options namespace
namespace Options {
enum class Scene;
enum class SceneOptions;
enum class ControlScheme;
enum class NotificationPosition;
} // namespace Options
namespace GameDefaults {
// =============================================================================
// GAME
// =============================================================================
constexpr int GAME_WIDTH = 256; // Ancho de la ventana por defecto
constexpr int GAME_HEIGHT = 192; // Alto de la ventana por defecto
// =============================================================================
// WINDOW
// =============================================================================
constexpr int WINDOW_ZOOM = 2; // Zoom de la ventana por defecto
// =============================================================================
// VIDEO
// =============================================================================
constexpr bool VIDEO_MODE = false; // Modo de pantalla completa por defecto (false = ventana)
constexpr ScreenFilter VIDEO_FILTER = ScreenFilter::NEAREST; // Filtro por defecto
constexpr bool VIDEO_VERTICAL_SYNC = true; // Vsync activado por defecto
constexpr bool VIDEO_SHADERS = false; // Shaders desactivados por defecto
constexpr bool VIDEO_INTEGER_SCALE = true; // Escalado entero activado por defecto
constexpr bool VIDEO_KEEP_ASPECT = true; // Mantener aspecto activado por defecto
constexpr const char* PALETTE_NAME = "zx-spectrum"; // Paleta por defecto
// =============================================================================
// BORDER
// =============================================================================
constexpr bool BORDER_ENABLED = true; // Borde activado por defecto
constexpr int BORDER_WIDTH = 32; // Ancho del borde por defecto
constexpr int BORDER_HEIGHT = 24; // Alto del borde por defecto
// =============================================================================
// AUDIO
// =============================================================================
constexpr int AUDIO_VOLUME = 100; // Volumen por defecto
constexpr bool AUDIO_ENABLED = true; // Audio por defecto
// MUSIC
constexpr int MUSIC_VOLUME = 80; // Volumen por defecto de la musica
constexpr bool MUSIC_ENABLED = true; // Musica habilitada por defecto
// SOUND
constexpr int SOUND_VOLUME = 100; // Volumen por defecto de los efectos de sonido
constexpr bool SOUND_ENABLED = true; // Sonido habilitado por defecto
// =============================================================================
// NOTIFICATIONS
// =============================================================================
constexpr Options::NotificationPosition NOTIFICATION_POSITION = Options::NotificationPosition::UPPER_LEFT; // Posición de las notificaciones por defecto
constexpr bool NOTIFICATION_SOUND = true; // Sonido de las notificaciones por defecto
const Uint8 NOTIFICATION_COLOR = static_cast<Uint8>(PaletteColor::BLUE); // Color de las notificaciones por defecto
// =============================================================================
// SCENE
// =============================================================================
constexpr Options::Scene SCENE = Options::Scene::LOGO; // Sección por defecto
constexpr Options::SceneOptions SUBSECTION = Options::SceneOptions::LOGO_TO_INTRO; // Subsección por defecto
// =============================================================================
// CONTROL
// =============================================================================
constexpr Options::ControlScheme CONTROL_SCHEME = Options::ControlScheme::CURSOR; // Control por defecto
// =============================================================================
// OTHER
// =============================================================================
constexpr bool CONSOLE = false; // Consola desactivada por defecto
constexpr const char* VERSION = "1.10"; // Versión por defecto
} // namespace GameDefaults

View File

@@ -12,32 +12,44 @@
#include <unordered_map> // Para unordered_map, operator==, _Node_const_i...
#include <utility> // Para pair
// Variables
Options options;
#include "utils/utils.hpp" // Para stringToBool, boolToString, safeStoi
namespace Options {
// --- Variables globales ---
std::string version; // Versión del fichero de configuración. Sirve para saber si las opciones son compatibles
bool console; // Indica si ha de mostrar información por la consola de texto
Cheat cheats; // Contiene trucos y ventajas para el juego
Game game; // Opciones de juego
Video video; // Opciones de video
Stats stats; // Datos con las estadisticas de juego
Notification notifications; // Opciones relativas a las notificaciones;
Window window; // Opciones relativas a la ventana
Audio audio; // Opciones relativas al audio
ControlScheme keys; // Teclas usadas para jugar
SceneState section; // Sección actual del programa
bool setOptions(const std::string& var, const std::string& value);
// Crea e inicializa las opciones del programa
void initOptions() {
options = Options();
void init() {
#ifdef DEBUG
options.section = SectionState(Section::ENDING2, Subsection::LOGO_TO_INTRO);
options.console = true;
section = SceneState(Scene::ENDING2, SceneOptions::LOGO_TO_INTRO);
console = true;
#else
options.section = SectionState(Section::LOGO, Subsection::LOGO_TO_INTRO);
options.console = false;
section = SceneState(Scene::LOGO, SceneOptions::LOGO_TO_INTRO);
console = false;
#endif
}
// Carga las opciones desde un fichero
bool loadOptionsFromFile(const std::string& file_path) {
bool loadFromFile(const std::string& file_path) {
// Indicador de éxito en la carga
bool success = true;
// Versión actual del fichero
const std::string configVersion = options.version;
options.version = "";
const std::string configVersion = version;
version = "";
// Variables para manejar el fichero
std::ifstream file(file_path);
@@ -45,7 +57,7 @@ bool loadOptionsFromFile(const std::string& file_path) {
// Si el fichero se puede abrir
if (file.good()) {
// Procesa el fichero línea a línea
if (options.console) {
if (console) {
std::cout << "Reading file config.txt\n";
}
std::string line;
@@ -68,7 +80,7 @@ bool loadOptionsFromFile(const std::string& file_path) {
if (iss >> key >> value) {
if (!setOptions(key, value)) {
if (options.console) {
if (console) {
std::cout << "Warning: file config.txt\n";
std::cout << "unknown parameter " << key << std::endl;
}
@@ -78,21 +90,21 @@ bool loadOptionsFromFile(const std::string& file_path) {
}
// Cierra el fichero
if (options.console) {
if (console) {
std::cout << "Closing file config.txt\n\n";
}
file.close();
} else {
// Crea el fichero con los valores por defecto
saveOptionsToFile(file_path);
saveToFile(file_path);
}
// Si la versión de fichero no coincide, crea un fichero nuevo con los valores por defecto
if (configVersion != options.version) {
initOptions();
saveOptionsToFile(file_path);
if (options.console) {
std::cout << "Wrong config file: initializing options.\n\n";
if (configVersion != version) {
init();
saveToFile(file_path);
if (console) {
std::cout << "Wrong config file: initializing \n\n";
}
}
@@ -100,56 +112,56 @@ bool loadOptionsFromFile(const std::string& file_path) {
}
// Guarda las opciones en un fichero
bool saveOptionsToFile(const std::string& file_path) {
bool saveToFile(const std::string& file_path) {
// Crea y abre el fichero de texto
std::ofstream file(file_path);
bool success = file.is_open(); // Verifica si el archivo se abrió correctamente
if (!success) // Si no se pudo abrir el archivo, muestra un mensaje de error y devuelve false
{
if (options.console) {
if (console) {
std::cerr << "Error: Unable to open file " << file_path << " for writing." << std::endl;
}
return false;
}
if (options.console) {
if (console) {
std::cout << file_path << " open for writing" << std::endl;
}
// Escribe en el fichero
file << "# Versión de la configuración\n";
file << "version " << options.version << "\n";
file << "version " << version << "\n";
file << "\n## CONTROL\n";
file << "# Esquema de control: 0 = Cursores, 1 = OPQ, 2 = WAD\n";
file << "keys " << static_cast<int>(options.keys) << "\n";
file << "keys " << static_cast<int>(keys) << "\n";
file << "\n## WINDOW\n";
file << "# Zoom de la ventana: 1 = Normal, 2 = Doble, 3 = Triple, ...\n";
file << "window.zoom " << options.window.zoom << "\n";
file << "window.zoom " << window.zoom << "\n";
file << "\n## VIDEO\n";
file << "# Modo de video: 0 = Ventana, 1 = Pantalla completa, 2 = Pantalla completa (escritorio)\n";
file << "video.mode " << options.video.fullscreen << "\n\n";
file << "video.mode " << video.fullscreen << "\n\n";
file << "# Filtro de pantalla: 0 = Nearest, 1 = Linear\n";
file << "video.filter " << static_cast<int>(options.video.filter) << "\n\n";
file << "video.filter " << static_cast<int>(video.filter) << "\n\n";
file << "# Shaders: 1 = Activado, 0 = Desactivado\n";
file << "video.shaders " << boolToString(options.video.shaders) << "\n\n";
file << "video.shaders " << boolToString(video.shaders) << "\n\n";
file << "# Sincronización vertical: 1 = Activado, 0 = Desactivado\n";
file << "video.vertical_sync " << boolToString(options.video.vertical_sync) << "\n\n";
file << "video.vertical_sync " << boolToString(video.vertical_sync) << "\n\n";
file << "# Escalado entero: 1 = Activado, 0 = Desactivado\n";
file << "video.integer_scale " << boolToString(options.video.integer_scale) << "\n\n";
file << "video.integer_scale " << boolToString(video.integer_scale) << "\n\n";
file << "# Mantener aspecto: 1 = Activado, 0 = Desactivado\n";
file << "video.keep_aspect " << boolToString(options.video.keep_aspect) << "\n\n";
file << "video.keep_aspect " << boolToString(video.keep_aspect) << "\n\n";
file << "# Borde: 1 = Activado, 0 = Desactivado\n";
file << "video.border.enabled " << boolToString(options.video.border.enabled) << "\n\n";
file << "video.border.enabled " << boolToString(video.border.enabled) << "\n\n";
file << "# Ancho del borde\n";
file << "video.border.width " << options.video.border.width << "\n\n";
file << "video.border.width " << video.border.width << "\n\n";
file << "# Alto del borde\n";
file << "video.border.height " << options.video.border.height << "\n\n";
file << "video.border.height " << video.border.height << "\n\n";
file << "# Paleta\n";
file << "video.palette " << options.video.palette << "\n";
file << "video.palette " << video.palette << "\n";
// Cierra el fichero
file.close();
@@ -159,55 +171,55 @@ bool saveOptionsToFile(const std::string& file_path) {
bool setOptions(const std::string& var, const std::string& value) {
static const std::unordered_map<std::string, std::function<void(const std::string&)>> optionHandlers = {
{"version", [](const std::string& v) { options.version = v; }},
{"version", [](const std::string& v) { version = v; }},
{"keys", [](const std::string& v) {
int val = safeStoi(v, static_cast<int>(DEFAULT_CONTROL_SCHEME));
int val = safeStoi(v, static_cast<int>(GameDefaults::CONTROL_SCHEME));
if (val == static_cast<int>(ControlScheme::CURSOR) || val == static_cast<int>(ControlScheme::OPQA) || val == static_cast<int>(ControlScheme::WASD)) {
options.keys = static_cast<ControlScheme>(val);
keys = static_cast<ControlScheme>(val);
} else {
options.keys = DEFAULT_CONTROL_SCHEME;
keys = GameDefaults::CONTROL_SCHEME;
}
}},
{"window.zoom", [](const std::string& v) {
int val = safeStoi(v, DEFAULT_WINDOW_ZOOM);
int val = safeStoi(v, GameDefaults::WINDOW_ZOOM);
if (val > 0) {
options.window.zoom = val;
window.zoom = val;
} else {
options.window.zoom = DEFAULT_WINDOW_ZOOM;
window.zoom = GameDefaults::WINDOW_ZOOM;
}
}},
{"video.mode", [](const std::string& v) { options.video.fullscreen = stringToBool(v); }},
{"video.mode", [](const std::string& v) { video.fullscreen = stringToBool(v); }},
{"video.filter", [](const std::string& v) {
int val = safeStoi(v, static_cast<int>(DEFAULT_VIDEO_FILTER));
int val = safeStoi(v, static_cast<int>(GameDefaults::VIDEO_FILTER));
if (val == static_cast<int>(ScreenFilter::NEAREST) || val == static_cast<int>(ScreenFilter::LINEAR)) {
options.video.filter = static_cast<ScreenFilter>(val);
video.filter = static_cast<ScreenFilter>(val);
} else {
options.video.filter = DEFAULT_VIDEO_FILTER;
video.filter = GameDefaults::VIDEO_FILTER;
}
}},
{"video.shaders", [](const std::string& v) { options.video.shaders = stringToBool(v); }},
{"video.vertical_sync", [](const std::string& v) { options.video.vertical_sync = stringToBool(v); }},
{"video.integer_scale", [](const std::string& v) { options.video.integer_scale = stringToBool(v); }},
{"video.keep_aspect", [](const std::string& v) { options.video.keep_aspect = stringToBool(v); }},
{"video.border.enabled", [](const std::string& v) { options.video.border.enabled = stringToBool(v); }},
{"video.shaders", [](const std::string& v) { video.shaders = stringToBool(v); }},
{"video.vertical_sync", [](const std::string& v) { video.vertical_sync = stringToBool(v); }},
{"video.integer_scale", [](const std::string& v) { video.integer_scale = stringToBool(v); }},
{"video.keep_aspect", [](const std::string& v) { video.keep_aspect = stringToBool(v); }},
{"video.border.enabled", [](const std::string& v) { video.border.enabled = stringToBool(v); }},
{"video.border.width", [](const std::string& v) {
int val = safeStoi(v, DEFAULT_BORDER_WIDTH);
int val = safeStoi(v, GameDefaults::BORDER_WIDTH);
if (val > 0) {
options.video.border.width = val;
video.border.width = val;
} else {
options.video.border.width = DEFAULT_BORDER_WIDTH;
video.border.width = GameDefaults::BORDER_WIDTH;
}
}},
{"video.border.height", [](const std::string& v) {
int val = safeStoi(v, DEFAULT_BORDER_HEIGHT);
int val = safeStoi(v, GameDefaults::BORDER_HEIGHT);
if (val > 0) {
options.video.border.height = val;
video.border.height = val;
} else {
options.video.border.height = DEFAULT_BORDER_HEIGHT;
video.border.height = GameDefaults::BORDER_HEIGHT;
}
}},
{"video.palette", [](const std::string& v) {
options.video.palette = v;
video.palette = v;
}}};
auto it = optionHandlers.find(var);
@@ -217,3 +229,4 @@ bool setOptions(const std::string& var, const std::string& value) {
}
return false;
}
}

View File

@@ -6,10 +6,22 @@
#include <string> // Para string, basic_string
#include "core/rendering/screen.hpp" // Para ScreenFilter
#include "utils/utils.hpp" // Para Color, Palette
#include "utils/utils.hpp" // Para Color, Palette
// --- Namespace Options: gestión de configuración y opciones del juego ---
namespace Options {
// =============================================================================
// VOLUME HELPERS - Conversión de volumen 0-100 a 0-128
// =============================================================================
namespace VolumeHelpers {
constexpr int convertVolume(int volume_percent) {
return (volume_percent * 128) / 100;
}
} // namespace VolumeHelpers
// Secciones del programa
enum class Section {
enum class Scene {
LOGO,
LOADING_SCREEN,
TITLE,
@@ -23,7 +35,7 @@ enum class Section {
};
// Subsecciones
enum class Subsection {
enum class SceneOptions {
NONE,
LOGO_TO_INTRO,
LOGO_TO_TITLE,
@@ -54,49 +66,27 @@ enum class ControlScheme {
WASD
};
// Constantes
constexpr int DEFAULT_GAME_WIDTH = 256; // Ancho de la ventana por defecto
constexpr int DEFAULT_GAME_HEIGHT = 192; // Alto de la ventana por defecto
constexpr int DEFAULT_WINDOW_ZOOM = 2; // Zoom de la ventana por defecto
constexpr bool DEFAULT_VIDEO_MODE = false; // Modo de pantalla completa por defecto
constexpr ScreenFilter DEFAULT_VIDEO_FILTER = ScreenFilter::NEAREST; // Filtro por defecto
constexpr bool DEFAULT_VIDEO_VERTICAL_SYNC = true; // Vsync activado por defecto
constexpr bool DEFAULT_VIDEO_SHADERS = false; // Shaders desactivados por defecto
constexpr bool DEFAULT_VIDEO_INTEGER_SCALE = true; // Escalado entero activado por defecto
constexpr bool DEFAULT_VIDEO_KEEP_ASPECT = true; // Mantener aspecto activado por defecto
constexpr bool DEFAULT_BORDER_ENABLED = true; // Borde activado por defecto
constexpr int DEFAULT_BORDER_WIDTH = 32; // Ancho del borde por defecto
constexpr int DEFAULT_BORDER_HEIGHT = 24; // Alto del borde por defecto
constexpr int DEFAULT_SOUND_VOLUME = 100; // Volumen por defecto de los efectos de sonido
constexpr bool DEFAULT_SOUND_ENABLED = true; // Sonido habilitado por defecto
constexpr int DEFAULT_MUSIC_VOLUME = 80; // Volumen por defecto de la musica
constexpr bool DEFAULT_MUSIC_ENABLED = true; // Musica habilitada por defecto
constexpr int DEFAULT_AUDIO_VOLUME = 100; // Volumen por defecto
constexpr bool DEFAULT_AUDIO_ENABLED = true; // Audio por defecto
constexpr const char* DEFAULT_PALETTE = "zx-spectrum"; // Paleta por defecto
constexpr Section DEFAULT_SECTION = Section::LOGO; // Sección por defecto
constexpr Subsection DEFAULT_SUBSECTION = Subsection::LOGO_TO_INTRO; // Subsección por defecto
constexpr ControlScheme DEFAULT_CONTROL_SCHEME = ControlScheme::CURSOR; // Control por defecto
constexpr NotificationPosition DEFAULT_NOTIFICATION_POSITION = NotificationPosition::UPPER_LEFT; // Posición de las notificaciones por defecto
constexpr bool DEFAULT_NOTIFICATION_SOUND = true; // Sonido de las notificaciones por defecto
const Uint8 DEFAULT_NOTIFICATION_COLOR = static_cast<Uint8>(PaletteColor::BLUE); // Color de las notificaciones por defecto
constexpr bool DEFAULT_CONSOLE = false; // Consola desactivada por defecto
constexpr const char* DEFAULT_VERSION = "1.10"; // Versión por defecto
} // namespace Options
// Incluir constantes por defecto después de declarar los enums
#include "game/gameplay/defaults.hpp"
namespace Options {
// Estructura para las opciones de las notificaciones
struct OptionsNotification {
struct Notification {
NotificationPosition pos; // Ubicación de las notificaciones en pantalla
bool sound; // Indica si las notificaciones suenan
Uint8 color; // Color de las notificaciones
// Constructor por defecto
OptionsNotification()
: pos(DEFAULT_NOTIFICATION_POSITION),
sound(DEFAULT_NOTIFICATION_SOUND),
color(DEFAULT_NOTIFICATION_COLOR) {}
Notification()
: pos(GameDefaults::NOTIFICATION_POSITION),
sound(GameDefaults::NOTIFICATION_SOUND),
color(GameDefaults::NOTIFICATION_COLOR) {}
// Constructor
OptionsNotification(NotificationPosition p, bool s, Uint8 c)
Notification(NotificationPosition p, bool s, Uint8 c)
: pos(p),
sound(s),
color(c) {}
@@ -116,7 +106,6 @@ struct OptionsNotification {
default:
return NotificationPosition::UNKNOWN;
}
return NotificationPosition::UNKNOWN;
}
// Método que devuelve la posición vertical
@@ -133,94 +122,95 @@ struct OptionsNotification {
default:
return NotificationPosition::UNKNOWN;
}
return NotificationPosition::UNKNOWN;
}
};
// Estructura para saber la seccion y subseccion del programa
struct SectionState {
Section section;
Subsection subsection;
struct SceneState {
Scene section;
SceneOptions subsection;
// Constructor por defecto
SectionState()
: section(DEFAULT_SECTION),
subsection(DEFAULT_SUBSECTION) {}
SceneState()
: section(GameDefaults::SCENE),
subsection(GameDefaults::SUBSECTION) {}
// Constructor
SectionState(Section s, Subsection ss)
: section(s),
subsection(ss) {}
SceneState(Scene scene, SceneOptions scene_options)
: section(scene),
subsection(scene_options) {}
};
// Estructura para albergar trucos
struct Cheat {
enum class CheatState : bool {
enum class State : bool {
DISABLED = false,
ENABLED = true
};
CheatState infinite_lives; // Indica si el jugador dispone de vidas infinitas
CheatState invincible; // Indica si el jugador puede morir
CheatState jail_is_open; // Indica si la Jail está abierta
CheatState alternate_skin; // Indica si se usa una skin diferente para el jugador
State infinite_lives; // Indica si el jugador dispone de vidas infinitas
State invincible; // Indica si el jugador puede morir
State jail_is_open; // Indica si la Jail está abierta
State alternate_skin; // Indica si se usa una skin diferente para el jugador
// Constructor por defecto
Cheat()
: infinite_lives(CheatState::DISABLED),
invincible(CheatState::DISABLED),
jail_is_open(CheatState::DISABLED),
alternate_skin(CheatState::DISABLED) {}
: infinite_lives(State::DISABLED),
invincible(State::DISABLED),
jail_is_open(State::DISABLED),
alternate_skin(State::DISABLED) {}
// Constructor
Cheat(CheatState il, CheatState i, CheatState je, CheatState as)
: infinite_lives(il),
invincible(i),
jail_is_open(je),
alternate_skin(as) {}
Cheat(State inf_lives, State is_invincible, State jail_enabled, State alt_skin)
: infinite_lives(inf_lives),
invincible(is_invincible),
jail_is_open(jail_enabled),
alternate_skin(alt_skin) {}
// Método para comprobar si alguno de los tres primeros trucos está activo
bool enabled() const {
return infinite_lives == CheatState::ENABLED ||
invincible == CheatState::ENABLED ||
jail_is_open == CheatState::ENABLED;
return infinite_lives == State::ENABLED ||
invincible == State::ENABLED ||
jail_is_open == State::ENABLED;
}
};
// Estructura para almacenar estadísticas
struct OptionsStats {
struct Stats {
int rooms; // Cantidad de habitaciones visitadas
int items; // Cantidad de items obtenidos
std::string worst_nightmare; // Habitación con más muertes acumuladas
// Constructor por defecto
OptionsStats()
Stats()
: rooms(0),
items(0),
worst_nightmare("") {}
// Constructor
OptionsStats(int r, int i, const std::string& wn)
: rooms(r),
items(i),
worst_nightmare(wn) {}
Stats(int room_count, int item_count, const std::string& worst_nightmare_room)
: rooms(room_count),
items(item_count),
worst_nightmare(worst_nightmare_room) {}
};
// Estructura con opciones de la ventana
struct OptionsWindow {
std::string caption = "JailDoctor's Dilemma"; // Texto que aparece en la barra de título de la ventana
int zoom; // Zoom de la ventana
int max_zoom; // Máximo tamaño de zoom para la ventana
struct Window {
std::string caption; // Texto que aparece en la barra de título de la ventana
int zoom; // Zoom de la ventana
int max_zoom; // Máximo tamaño de zoom para la ventana
// Constructor por defecto
OptionsWindow()
: zoom(DEFAULT_WINDOW_ZOOM),
max_zoom(DEFAULT_WINDOW_ZOOM) {}
Window()
: caption("JailDoctor's Dilemma"),
zoom(GameDefaults::WINDOW_ZOOM),
max_zoom(GameDefaults::WINDOW_ZOOM) {}
// Constructor
OptionsWindow(int z, int mz)
: zoom(z),
max_zoom(mz) {}
Window(int window_zoom, int maximum_zoom)
: caption("JailDoctor's Dilemma"),
zoom(window_zoom),
max_zoom(maximum_zoom) {}
};
// Estructura para gestionar el borde de la pantalla
@@ -231,19 +221,19 @@ struct Border {
// Constructor por defecto
Border()
: enabled(DEFAULT_BORDER_ENABLED),
width(DEFAULT_BORDER_WIDTH),
height(DEFAULT_BORDER_HEIGHT) {}
: enabled(GameDefaults::BORDER_ENABLED),
width(GameDefaults::BORDER_WIDTH),
height(GameDefaults::BORDER_HEIGHT) {}
// Constructor
Border(bool e, float w, float h)
: enabled(e),
width(w),
height(h) {}
Border(bool is_enabled, float border_width, float border_height)
: enabled(is_enabled),
width(border_width),
height(border_height) {}
};
// Estructura para las opciones de video
struct OptionsVideo {
struct Video {
bool fullscreen; // Contiene el valor del modo de pantalla completa
ScreenFilter filter; // Filtro usado para el escalado de la imagen
bool vertical_sync; // Indica si se quiere usar vsync o no
@@ -255,170 +245,128 @@ struct OptionsVideo {
std::string info; // Información sobre el modo de vídeo
// Constructor por defecto
OptionsVideo()
: fullscreen(DEFAULT_VIDEO_MODE),
filter(DEFAULT_VIDEO_FILTER),
vertical_sync(DEFAULT_VIDEO_VERTICAL_SYNC),
shaders(DEFAULT_VIDEO_SHADERS),
integer_scale(DEFAULT_VIDEO_INTEGER_SCALE),
keep_aspect(DEFAULT_VIDEO_KEEP_ASPECT),
Video()
: fullscreen(GameDefaults::VIDEO_MODE),
filter(GameDefaults::VIDEO_FILTER),
vertical_sync(GameDefaults::VIDEO_VERTICAL_SYNC),
shaders(GameDefaults::VIDEO_SHADERS),
integer_scale(GameDefaults::VIDEO_INTEGER_SCALE),
keep_aspect(GameDefaults::VIDEO_KEEP_ASPECT),
border(Border()),
palette(DEFAULT_PALETTE) {}
palette(GameDefaults::PALETTE_NAME),
info("") {}
// Constructor
OptionsVideo(Uint32 m, ScreenFilter f, bool vs, bool s, bool is, bool ka, Border b, const std::string& p)
: fullscreen(m),
filter(f),
vertical_sync(vs),
shaders(s),
integer_scale(is),
keep_aspect(ka),
border(b),
palette(p) {}
Video(bool is_fullscreen, ScreenFilter screen_filter, bool vsync, bool use_shaders, bool int_scale, bool keep_aspect_ratio, Border video_border, const std::string& palette_name)
: fullscreen(is_fullscreen),
filter(screen_filter),
vertical_sync(vsync),
shaders(use_shaders),
integer_scale(int_scale),
keep_aspect(keep_aspect_ratio),
border(video_border),
palette(palette_name),
info("") {}
};
// Estructura para las opciones de musica
struct OptionsMusic {
struct Music {
bool enabled; // Indica si la música suena o no
int volume; // Volumen al que suena la música (0 a 128 internamente)
// Constructor por defecto
OptionsMusic()
: enabled(DEFAULT_MUSIC_ENABLED),
volume(convertVolume(DEFAULT_MUSIC_VOLUME)) {} // Usa el método estático para la conversión
Music()
: enabled(GameDefaults::MUSIC_ENABLED),
volume(VolumeHelpers::convertVolume(GameDefaults::MUSIC_VOLUME)) {}
// Constructor con parámetros
OptionsMusic(bool e, int v)
: enabled(e),
volume(convertVolume(v)) {} // Convierte el volumen usando el método estático
Music(bool is_enabled, int volume_percent)
: enabled(is_enabled),
volume(VolumeHelpers::convertVolume(volume_percent)) {}
// Método para establecer el volumen
void setVolume(int v) {
v = std::clamp(v, 0, 100); // Ajusta v al rango [0, 100]
volume = convertVolume(v); // Convierte al rango interno
}
// Método estático para convertir de 0-100 a 0-128
static int convertVolume(int v) {
return (v * 128) / 100;
void setVolume(int volume_percent) {
volume_percent = std::clamp(volume_percent, 0, 100);
volume = VolumeHelpers::convertVolume(volume_percent);
}
};
// Estructura para las opciones de sonido
struct OptionsSound {
struct Sound {
bool enabled; // Indica si los sonidos suenan o no
int volume; // Volumen al que suenan los sonidos (0 a 128 internamente)
// Constructor por defecto
OptionsSound()
: enabled(DEFAULT_SOUND_ENABLED),
volume(convertVolume(DEFAULT_SOUND_VOLUME)) {} // Usa el método estático para la conversión
Sound()
: enabled(GameDefaults::SOUND_ENABLED),
volume(VolumeHelpers::convertVolume(GameDefaults::SOUND_VOLUME)) {}
// Constructor con parámetros
OptionsSound(bool e, int v)
: enabled(e),
volume(convertVolume(v)) {} // También lo integra aquí
Sound(bool is_enabled, int volume_percent)
: enabled(is_enabled),
volume(VolumeHelpers::convertVolume(volume_percent)) {}
// Método para establecer el volumen
void setVolume(int v) {
v = std::clamp(v, 0, 100); // Ajusta v al rango [0, 100]
volume = convertVolume(v); // Convierte al rango interno
}
// Método estático para convertir de 0-100 a 0-128
static int convertVolume(int v) {
return (v * 128) / 100;
void setVolume(int volume_percent) {
volume_percent = std::clamp(volume_percent, 0, 100);
volume = VolumeHelpers::convertVolume(volume_percent);
}
};
// Estructura para las opciones de audio
struct OptionsAudio {
OptionsMusic music; // Opciones para la música
OptionsSound sound; // Opciones para los efectos de sonido
bool enabled; // Indica si el audio está activo o no
int volume; // Volumen al que suenan el audio
struct Audio {
Music music; // Opciones para la música
Sound sound; // Opciones para los efectos de sonido
bool enabled; // Indica si el audio está activo o no
int volume; // Volumen al que suenan el audio (0-128 internamente)
// Constructor por defecto
OptionsAudio()
: music(OptionsMusic()),
sound(OptionsSound()),
enabled(DEFAULT_AUDIO_ENABLED),
volume(DEFAULT_AUDIO_VOLUME) {}
Audio()
: music(Music()),
sound(Sound()),
enabled(GameDefaults::AUDIO_ENABLED),
volume(VolumeHelpers::convertVolume(GameDefaults::AUDIO_VOLUME)) {}
// Constructor
OptionsAudio(OptionsMusic m, OptionsSound s, bool e, int v)
: music(m),
sound(s),
enabled(e),
volume(v) {}
Audio(Music audio_music, Sound audio_sound, bool is_enabled, int volume_percent)
: music(audio_music),
sound(audio_sound),
enabled(is_enabled),
volume(VolumeHelpers::convertVolume(volume_percent)) {}
};
// Estructura para las opciones de juego
struct OptionsGame {
struct Game {
float width; // Ancho de la resolucion del juego
float height; // Alto de la resolucion del juego
// Constructor por defecto
OptionsGame()
: width(DEFAULT_GAME_WIDTH),
height(DEFAULT_GAME_HEIGHT) {}
Game()
: width(GameDefaults::GAME_WIDTH),
height(GameDefaults::GAME_HEIGHT) {}
// Constructor
OptionsGame(float w, float h)
: width(w),
height(h) {}
Game(float game_width, float game_height)
: width(game_width),
height(game_height) {}
};
// Estructura con todas las opciones de configuración del programa
struct Options {
std::string version; // Versión del fichero de configuración. Sirve para saber si las opciones son compatibles
bool console; // Indica si ha de mostrar información por la consola de texto
Cheat cheats; // Contiene trucos y ventajas para el juego
OptionsGame game; // Opciones de juego
OptionsVideo video; // Opciones de video
OptionsStats stats; // Datos con las estadisticas de juego
OptionsNotification notifications; // Opciones relativas a las notificaciones;
OptionsWindow window; // Opciones relativas a la ventana
OptionsAudio audio; // Opciones relativas al audio
ControlScheme keys; // Teclas usadas para jugar
SectionState section; // Sección actual del programa
// --- Variables ---
extern std::string version; // Versión del fichero de configuración. Sirve para saber si las opciones son compatibles
extern bool console; // Indica si ha de mostrar información por la consola de texto
extern Cheat cheats; // Contiene trucos y ventajas para el juego
extern Game game; // Opciones de juego
extern Video video; // Opciones de video
extern Stats stats; // Datos con las estadisticas de juego
extern Notification notifications; // Opciones relativas a las notificaciones;
extern Window window; // Opciones relativas a la ventana
extern Audio audio; // Opciones relativas al audio
extern ControlScheme keys; // Teclas usadas para jugar
extern SceneState section; // Sección actual del programa
// Constructor por defecto
Options()
: version(DEFAULT_VERSION),
console(DEFAULT_CONSOLE),
cheats(Cheat()),
game(OptionsGame()),
video(OptionsVideo()),
stats(OptionsStats()),
notifications(OptionsNotification()),
window(OptionsWindow()),
audio(OptionsAudio()),
keys(DEFAULT_CONTROL_SCHEME),
section(SectionState()) {}
// --- Funciones ---
void init(); // Crea e inicializa las opciones del programa
bool loadFromFile(const std::string& file_path); // Carga las opciones desde un fichero
bool saveToFile(const std::string& file_path); // Guarda las opciones a un fichero
// Constructor
Options(std::string cv, bool c, Cheat ch, OptionsGame g, OptionsVideo v, OptionsStats s, OptionsNotification n, OptionsWindow sw, OptionsAudio a, ControlScheme k, SectionState sec)
: version(cv),
console(c),
cheats(ch),
game(g),
video(v),
stats(s),
notifications(n),
window(sw),
audio(a),
keys(k),
section(sec) {}
};
extern Options options;
// Crea e inicializa las opciones del programa
void initOptions();
// Carga las opciones desde un fichero
bool loadOptionsFromFile(const std::string& file_path);
// Guarda las opciones a un fichero
bool saveOptionsToFile(const std::string& file_path);
} // namespace Options

View File

@@ -5,17 +5,17 @@
#include <iostream> // Para cout, cerr
#include <sstream> // Para basic_stringstream
#include "core/system/debug.hpp" // Para Debug
#include "utils/defines.hpp" // Para BLOCK, PLAY_AREA_HEIGHT, PLAY_AREA_WIDTH
#include "external/jail_audio.h" // Para JA_PlaySound
#include "game/gameplay/item_tracker.hpp" // Para ItemTracker
#include "game/gameplay/options.hpp" // Para Options, OptionsStats, options
#include "core/resources/resource.hpp" // Para Resource
#include "game/gameplay/scoreboard.hpp" // Para ScoreboardData
#include "core/rendering/screen.hpp" // Para Screen
#include "core/rendering/screen.hpp" // Para Screen
#include "core/rendering/surface.hpp" // Para Surface
#include "core/rendering/surface_sprite.hpp" // Para SSprite
#include "core/rendering/surface.hpp" // Para Surface
#include "utils/utils.hpp" // Para LineHorizontal, LineDiagonal, LineVertical
#include "core/resources/resource.hpp" // Para Resource
#include "core/system/debug.hpp" // Para Debug
#include "external/jail_audio.h" // Para JA_PlaySound
#include "game/gameplay/item_tracker.hpp" // Para ItemTracker
#include "game/gameplay/options.hpp" // Para Options, OptionsStats, options
#include "game/gameplay/scoreboard.hpp" // Para ScoreboardData
#include "utils/defines.hpp" // Para BLOCK, PLAY_AREA_HEIGHT, PLAY_AREA_WIDTH
#include "utils/utils.hpp" // Para LineHorizontal, LineDiagonal, LineVertical
// Carga las variables y texturas desde un fichero de mapa de tiles
std::vector<int> loadRoomTileFile(const std::string& file_path, bool verbose) {
@@ -579,7 +579,7 @@ bool Room::itemCollision(SDL_FRect& rect) {
items_.erase(items_.begin() + i);
JA_PlaySound(Resource::get()->getSound("item.wav"));
data_->items++;
options.stats.items = data_->items;
Options::stats.items = data_->items;
return true;
}
}

View File

@@ -6,12 +6,12 @@
#include <string> // Para string
#include <vector> // Para vector
#include "game/entities/enemy.hpp" // Para EnemyData
#include "game/entities/item.hpp" // Para ItemData
#include "utils/utils.hpp" // Para LineHorizontal, LineDiagonal, LineVertical
class SSprite; // lines 12-12
class Surface; // lines 13-13
struct ScoreboardData; // lines 15-15
#include "game/entities/enemy.hpp" // Para EnemyData
#include "game/entities/item.hpp" // Para ItemData
#include "utils/utils.hpp" // Para LineHorizontal, LineDiagonal, LineVertical
class SSprite; // lines 12-12
class Surface; // lines 13-13
struct ScoreboardData; // lines 15-15
enum class TileType {
EMPTY,

View File

@@ -1,12 +1,9 @@
#include "game/gameplay/room_tracker.hpp"
// Comprueba si la habitación ya ha sido visitada
bool RoomTracker::hasBeenVisited(const std::string &name)
{
for (const auto &l : list)
{
if (l == name)
{
bool RoomTracker::hasBeenVisited(const std::string& name) {
for (const auto& l : list) {
if (l == name) {
return true;
}
}
@@ -15,11 +12,9 @@ bool RoomTracker::hasBeenVisited(const std::string &name)
}
// Añade la habitación a la lista
bool RoomTracker::addRoom(const std::string &name)
{
bool RoomTracker::addRoom(const std::string& name) {
// Comprueba si la habitación ya ha sido visitada
if (!hasBeenVisited(name))
{
if (!hasBeenVisited(name)) {
// En caso contrario añádela a la lista
list.push_back(name);
return true;

View File

@@ -1,24 +1,23 @@
#pragma once
#include <string> // Para string
#include <vector> // Para vector
#include <string> // Para string
#include <vector> // Para vector
class RoomTracker
{
private:
// Variables
std::vector<std::string> list; // Lista con las habitaciones visitadas
class RoomTracker {
private:
// Variables
std::vector<std::string> list; // Lista con las habitaciones visitadas
// Comprueba si la habitación ya ha sido visitada
bool hasBeenVisited(const std::string &name);
// Comprueba si la habitación ya ha sido visitada
bool hasBeenVisited(const std::string& name);
public:
// Constructor
RoomTracker() = default;
public:
// Constructor
RoomTracker() = default;
// Destructor
~RoomTracker() = default;
// Destructor
~RoomTracker() = default;
// Añade la habitación a la lista
bool addRoom(const std::string &name);
// Añade la habitación a la lista
bool addRoom(const std::string& name);
};

View File

@@ -2,31 +2,31 @@
#include <SDL3/SDL.h>
#include "utils/defines.hpp" // Para BLOCK
#include "game/gameplay/options.hpp" // Para Options, options, Cheat, OptionsGame
#include "core/resources/resource.hpp" // Para Resource
#include "core/rendering/screen.hpp" // Para Screen
#include "core/rendering/screen.hpp" // Para Screen
#include "core/rendering/surface.hpp" // Para Surface
#include "core/rendering/surface_animated_sprite.hpp" // Para SAnimatedSprite
#include "core/rendering/surface.hpp" // Para Surface
#include "core/rendering/text.hpp" // Para Text
#include "utils/utils.hpp" // Para stringToColor
#include "core/rendering/text.hpp" // Para Text
#include "core/resources/resource.hpp" // Para Resource
#include "game/gameplay/options.hpp" // Para Options, options, Cheat, OptionsGame
#include "utils/defines.hpp" // Para BLOCK
#include "utils/utils.hpp" // Para stringToColor
// Constructor
Scoreboard::Scoreboard(std::shared_ptr<ScoreboardData> data)
: item_surface_(Resource::get()->getSurface("items.gif")),
data_(data),
clock_(ClockData()) {
const float SURFACE_WIDTH_ = options.game.width;
const float SURFACE_WIDTH_ = Options::game.width;
constexpr float SURFACE_HEIGHT_ = 6.0F * BLOCK;
// Reserva memoria para los objetos
auto player_texture = Resource::get()->getSurface(options.cheats.alternate_skin == Cheat::CheatState::ENABLED ? "player2.gif" : "player.gif");
auto player_animations = Resource::get()->getAnimations(options.cheats.alternate_skin == Cheat::CheatState::ENABLED ? "player2.ani" : "player.ani");
auto player_texture = Resource::get()->getSurface(Options::cheats.alternate_skin == Options::Cheat::State::ENABLED ? "player2.gif" : "player.gif");
auto player_animations = Resource::get()->getAnimations(Options::cheats.alternate_skin == Options::Cheat::State::ENABLED ? "player2.ani" : "player.ani");
player_sprite_ = std::make_shared<SAnimatedSprite>(player_texture, player_animations);
player_sprite_->setCurrentAnimation("walk_menu");
surface_ = std::make_shared<Surface>(SURFACE_WIDTH_, SURFACE_HEIGHT_);
surface_dest_ = {0, options.game.height - SURFACE_HEIGHT_, SURFACE_WIDTH_, SURFACE_HEIGHT_};
surface_dest_ = {0, Options::game.height - SURFACE_HEIGHT_, SURFACE_WIDTH_, SURFACE_HEIGHT_};
// Inicializa las variables
counter_ = 0;

View File

@@ -1,16 +1,17 @@
#include "game/gameplay/stats.hpp"
#include <fstream> // Para basic_ostream, basic_ifstream, basic_istream
#include <sstream> // Para basic_stringstream
#include "game/gameplay/options.hpp" // Para Options, OptionsStats, options
#include <fstream> // Para basic_ostream, basic_ifstream, basic_istream
#include <sstream> // Para basic_stringstream
#include "game/gameplay/options.hpp" // Para Options, OptionsStats, options
// Constructor
Stats::Stats(const std::string &file, const std::string &buffer)
Stats::Stats(const std::string& file, const std::string& buffer)
: bufferPath(buffer),
filePath(file) {}
// Destructor
Stats::~Stats()
{
Stats::~Stats() {
// Vuelca los datos del buffer en la lista de estadisticas
updateListFromBuffer();
@@ -38,18 +39,15 @@ void Stats::init()
}
// Añade una muerte a las estadisticas
void Stats::addDeath(const std::string &name)
{
void Stats::addDeath(const std::string& name) {
// Primero busca si ya hay una entrada con ese nombre
const int index = findByName(name, bufferList);
if (index != -1)
{
if (index != -1) {
bufferList[index].died++;
}
// En caso contrario crea la entrada
else
{
else {
StatsData item;
item.name = name;
item.visited = 0;
@@ -59,18 +57,15 @@ void Stats::addDeath(const std::string &name)
}
// Añade una visita a las estadisticas
void Stats::addVisit(const std::string &name)
{
void Stats::addVisit(const std::string& name) {
// Primero busca si ya hay una entrada con ese nombre
const int index = findByName(name, bufferList);
if (index != -1)
{
if (index != -1) {
bufferList[index].visited++;
}
// En caso contrario crea la entrada
else
{
else {
StatsData item;
item.name = name;
item.visited = 1;
@@ -80,14 +75,11 @@ void Stats::addVisit(const std::string &name)
}
// Busca una entrada en la lista por nombre
int Stats::findByName(const std::string &name, const std::vector<StatsData> &list)
{
int Stats::findByName(const std::string& name, const std::vector<StatsData>& list) {
int i = 0;
for (const auto &l : list)
{
if (l.name == name)
{
for (const auto& l : list) {
if (l.name == name) {
return i;
}
i++;
@@ -97,8 +89,7 @@ int Stats::findByName(const std::string &name, const std::vector<StatsData> &lis
}
// Carga las estadisticas desde un fichero
bool Stats::loadFromFile(const std::string &file_path, std::vector<StatsData> &list)
{
bool Stats::loadFromFile(const std::string& file_path, std::vector<StatsData>& list) {
list.clear();
// Indicador de éxito en la carga
@@ -108,15 +99,12 @@ bool Stats::loadFromFile(const std::string &file_path, std::vector<StatsData> &l
std::ifstream file(file_path);
// Si el fichero se puede abrir
if (file.good())
{
if (file.good()) {
std::string line;
// Procesa el fichero linea a linea
while (std::getline(file, line))
{
while (std::getline(file, line)) {
// Comprueba que la linea no sea un comentario
if (line.substr(0, 1) != "#")
{
if (line.substr(0, 1) != "#") {
StatsData stat;
std::stringstream ss(line);
std::string tmp;
@@ -142,8 +130,7 @@ bool Stats::loadFromFile(const std::string &file_path, std::vector<StatsData> &l
}
// El fichero no existe
else
{
else {
// Crea el fichero con los valores por defecto
saveToFile(file_path, list);
}
@@ -152,15 +139,13 @@ bool Stats::loadFromFile(const std::string &file_path, std::vector<StatsData> &l
}
// Guarda las estadisticas en un fichero
void Stats::saveToFile(const std::string &file_path, const std::vector<StatsData> &list)
{
void Stats::saveToFile(const std::string& file_path, const std::vector<StatsData>& list) {
// Crea y abre el fichero de texto
std::ofstream file(file_path);
// Escribe en el fichero
file << "# ROOM NAME;VISITS;DEATHS" << std::endl;
for (const auto &item : list)
{
for (const auto& item : list) {
file << item.name << ";" << item.visited << ";" << item.died << std::endl;
}
@@ -169,40 +154,31 @@ void Stats::saveToFile(const std::string &file_path, const std::vector<StatsData
}
// Calcula cual es la habitación con más muertes
void Stats::checkWorstNightmare()
{
void Stats::checkWorstNightmare() {
int deaths = 0;
for (const auto &item : list)
{
if (item.died > deaths)
{
for (const auto& item : list) {
if (item.died > deaths) {
deaths = item.died;
options.stats.worst_nightmare = item.name;
Options::stats.worst_nightmare = item.name;
}
}
}
// Añade una entrada al diccionario
void Stats::addDictionary(const std::string &number, const std::string &name)
{
void Stats::addDictionary(const std::string& number, const std::string& name) {
dictionary.push_back({number, name});
}
// Vuelca los datos del buffer en la lista de estadisticas
void Stats::updateListFromBuffer()
{
void Stats::updateListFromBuffer() {
// Actualiza list desde bufferList
for (const auto &buffer : bufferList)
{
for (const auto& buffer : bufferList) {
int index = findByName(buffer.name, list);
if (index != -1)
{ // Encontrado. Aumenta sus estadisticas
if (index != -1) { // Encontrado. Aumenta sus estadisticas
list[index].visited += buffer.visited;
list[index].died += buffer.died;
}
else
{ // En caso contrario crea la entrada
} else { // En caso contrario crea la entrada
StatsData item;
item.name = buffer.name;
item.visited = buffer.visited;

View File

@@ -1,63 +1,60 @@
#pragma once
#include <string> // Para string
#include <vector> // Para vector
#include <string> // Para string
#include <vector> // Para vector
class Stats
{
private:
struct StatsData
{
std::string name; // Nombre de la habitación
int visited; // Cuenta las veces que se ha visitado una habitación
int died; // Cuenta las veces que se ha muerto en una habitación
};
class Stats {
private:
struct StatsData {
std::string name; // Nombre de la habitación
int visited; // Cuenta las veces que se ha visitado una habitación
int died; // Cuenta las veces que se ha muerto en una habitación
};
struct StatsDictionary
{
std::string number; // Numero de la habitación
std::string name; // Nombre de la habitación
};
struct StatsDictionary {
std::string number; // Numero de la habitación
std::string name; // Nombre de la habitación
};
// Variables
std::vector<StatsDictionary> dictionary; // Lista con la equivalencia nombre-numero de habitacion
std::vector<StatsData> bufferList; // Lista con las estadisticas temporales por habitación
std::vector<StatsData> list; // Lista con las estadisticas completas por habitación
std::string bufferPath; // Fichero con las estadísticas temporales
std::string filePath; // Fichero con las estadísticas completas
// Variables
std::vector<StatsDictionary> dictionary; // Lista con la equivalencia nombre-numero de habitacion
std::vector<StatsData> bufferList; // Lista con las estadisticas temporales por habitación
std::vector<StatsData> list; // Lista con las estadisticas completas por habitación
std::string bufferPath; // Fichero con las estadísticas temporales
std::string filePath; // Fichero con las estadísticas completas
// Busca una entrada en la lista por nombre
int findByName(const std::string &name, const std::vector<StatsData> &list);
// Busca una entrada en la lista por nombre
int findByName(const std::string& name, const std::vector<StatsData>& list);
// Carga las estadisticas desde un fichero
bool loadFromFile(const std::string &filePath, std::vector<StatsData> &list);
// Carga las estadisticas desde un fichero
bool loadFromFile(const std::string& filePath, std::vector<StatsData>& list);
// Guarda las estadisticas en un fichero
void saveToFile(const std::string &filePath, const std::vector<StatsData> &list);
// Guarda las estadisticas en un fichero
void saveToFile(const std::string& filePath, const std::vector<StatsData>& list);
// Calcula cual es la habitación con más muertes
void checkWorstNightmare();
// Calcula cual es la habitación con más muertes
void checkWorstNightmare();
// Vuelca los datos del buffer en la lista de estadisticas
void updateListFromBuffer();
// Vuelca los datos del buffer en la lista de estadisticas
void updateListFromBuffer();
public:
// Constructor
Stats(const std::string &file, const std::string &buffer);
public:
// Constructor
Stats(const std::string& file, const std::string& buffer);
// Destructor
~Stats();
// Destructor
~Stats();
// Inicializador
// Se debe llamar a este procedimiento una vez se haya creado el diccionario numero-nombre
void init();
// Inicializador
// Se debe llamar a este procedimiento una vez se haya creado el diccionario numero-nombre
void init();
// Añade una muerte a las estadisticas
void addDeath(const std::string &name);
// Añade una muerte a las estadisticas
void addDeath(const std::string& name);
// Añade una visita a las estadisticas
void addVisit(const std::string &name);
// Añade una visita a las estadisticas
void addVisit(const std::string& name);
// Añade una entrada al diccionario
void addDictionary(const std::string &number, const std::string &name);
// Añade una entrada al diccionario
void addDictionary(const std::string& number, const std::string& name);
};