mes reestructuracio de fitxers de codi

This commit is contained in:
2025-10-26 14:46:19 +01:00
parent 51330db998
commit 2eadd7d8df
24 changed files with 52 additions and 56 deletions

View File

@@ -6,7 +6,7 @@
#include <fstream> // Para basic_ostream, operator<<, basic_ofstream
#include <iostream> // Para cout, cerr
#include "game/gameplay/options.hpp" // Para Options, options
#include "game/options.hpp" // Para Options, options
#include "game/ui/notifier.hpp" // Para Notifier
// [SINGLETON]

View File

@@ -1,77 +0,0 @@
#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 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
// =============================================================================
// 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

@@ -1,228 +0,0 @@
#include "game/gameplay/options.hpp"
#include <SDL3/SDL.h>
#include <algorithm> // Para find_if
#include <cctype> // Para isspace
#include <fstream> // Para basic_ostream, operator<<, basic_ofstream
#include <functional> // Para function
#include <iostream> // Para cout, cerr
#include <sstream> // Para basic_istringstream
#include <string> // Para char_traits, string, operator<<, hash
#include <unordered_map> // Para unordered_map, operator==, _Node_const_i...
#include <utility> // Para pair
#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
bool setOptions(const std::string& var, const std::string& value);
// Crea e inicializa las opciones del programa
void init() {
#ifdef DEBUG
console = true;
#else
console = false;
#endif
}
// Carga las opciones desde un fichero
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 = version;
version = "";
// Variables para manejar el fichero
std::ifstream file(file_path);
// Si el fichero se puede abrir
if (file.good()) {
// Procesa el fichero línea a línea
if (console) {
std::cout << "Reading file config.txt\n";
}
std::string line;
while (std::getline(file, line)) {
// Elimina espacios en blanco iniciales y finales
line = std::string(std::find_if(line.begin(), line.end(), [](int ch) { return !std::isspace(ch); }),
line.end());
line.erase(std::find_if(line.rbegin(), line.rend(), [](int ch) { return !std::isspace(ch); })
.base(),
line.end());
// Ignora líneas vacías o comentarios
if (line.empty() || line[0] == '#') {
continue;
}
// Usa un stringstream para dividir la línea en dos partes
std::istringstream iss(line);
std::string key, value;
if (iss >> key >> value) {
if (!setOptions(key, value)) {
if (console) {
std::cout << "Warning: file config.txt\n";
std::cout << "unknown parameter " << key << std::endl;
}
success = false;
}
}
}
// Cierra el fichero
if (console) {
std::cout << "Closing file config.txt\n\n";
}
file.close();
} else {
// Crea el fichero con los valores por defecto
saveToFile(file_path);
}
// Si la versión de fichero no coincide, crea un fichero nuevo con los valores por defecto
if (configVersion != version) {
init();
saveToFile(file_path);
if (console) {
std::cout << "Wrong config file: initializing \n\n";
}
}
return success;
}
// Guarda las opciones en un fichero
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 (console) {
std::cerr << "Error: Unable to open file " << file_path << " for writing." << std::endl;
}
return false;
}
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 " << version << "\n";
file << "\n## CONTROL\n";
file << "# Esquema de control: 0 = Cursores, 1 = OPQ, 2 = WAD\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 " << window.zoom << "\n";
file << "\n## VIDEO\n";
file << "# Modo de video: 0 = Ventana, 1 = Pantalla completa, 2 = Pantalla completa (escritorio)\n";
file << "video.mode " << video.fullscreen << "\n\n";
file << "# Filtro de pantalla: 0 = Nearest, 1 = Linear\n";
file << "video.filter " << static_cast<int>(video.filter) << "\n\n";
file << "# Shaders: 1 = Activado, 0 = Desactivado\n";
file << "video.shaders " << boolToString(video.shaders) << "\n\n";
file << "# Sincronización vertical: 1 = Activado, 0 = Desactivado\n";
file << "video.vertical_sync " << boolToString(video.vertical_sync) << "\n\n";
file << "# Escalado entero: 1 = Activado, 0 = Desactivado\n";
file << "video.integer_scale " << boolToString(video.integer_scale) << "\n\n";
file << "# Mantener aspecto: 1 = Activado, 0 = Desactivado\n";
file << "video.keep_aspect " << boolToString(video.keep_aspect) << "\n\n";
file << "# Borde: 1 = Activado, 0 = Desactivado\n";
file << "video.border.enabled " << boolToString(video.border.enabled) << "\n\n";
file << "# Ancho del borde\n";
file << "video.border.width " << video.border.width << "\n\n";
file << "# Alto del borde\n";
file << "video.border.height " << video.border.height << "\n\n";
file << "# Paleta\n";
file << "video.palette " << video.palette << "\n";
// Cierra el fichero
file.close();
return success;
}
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) { version = v; }},
{"keys", [](const std::string& v) {
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)) {
keys = static_cast<ControlScheme>(val);
} else {
keys = GameDefaults::CONTROL_SCHEME;
}
}},
{"window.zoom", [](const std::string& v) {
int val = safeStoi(v, GameDefaults::WINDOW_ZOOM);
if (val > 0) {
window.zoom = val;
} else {
window.zoom = GameDefaults::WINDOW_ZOOM;
}
}},
{"video.mode", [](const std::string& v) { video.fullscreen = stringToBool(v); }},
{"video.filter", [](const std::string& v) {
int val = safeStoi(v, static_cast<int>(GameDefaults::VIDEO_FILTER));
if (val == static_cast<int>(ScreenFilter::NEAREST) || val == static_cast<int>(ScreenFilter::LINEAR)) {
video.filter = static_cast<ScreenFilter>(val);
} else {
video.filter = GameDefaults::VIDEO_FILTER;
}
}},
{"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, GameDefaults::BORDER_WIDTH);
if (val > 0) {
video.border.width = val;
} else {
video.border.width = GameDefaults::BORDER_WIDTH;
}
}},
{"video.border.height", [](const std::string& v) {
int val = safeStoi(v, GameDefaults::BORDER_HEIGHT);
if (val > 0) {
video.border.height = val;
} else {
video.border.height = GameDefaults::BORDER_HEIGHT;
}
}},
{"video.palette", [](const std::string& v) {
video.palette = v;
}}};
auto it = optionHandlers.find(var);
if (it != optionHandlers.end()) {
it->second(value);
return true;
}
return false;
}
}

View File

@@ -1,332 +0,0 @@
#pragma once
#include <SDL3/SDL.h>
#include <algorithm>
#include <string> // Para string, basic_string
#include "core/rendering/screen.hpp" // Para ScreenFilter
#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
// Posiciones de las notificaciones
enum class NotificationPosition {
UPPER_LEFT,
UPPER_CENTER,
UPPER_RIGHT,
BOTTOM_LEFT,
BOTTOM_CENTER,
BOTTOM_RIGHT,
TOP,
BOTTOM,
LEFT,
RIGHT,
CENTER,
UNKNOWN,
};
// Tipos de control de teclado
enum class ControlScheme {
CURSOR,
OPQA,
WASD
};
} // 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 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
Notification()
: pos(GameDefaults::NOTIFICATION_POSITION),
sound(GameDefaults::NOTIFICATION_SOUND),
color(GameDefaults::NOTIFICATION_COLOR) {}
// Constructor
Notification(NotificationPosition p, bool s, Uint8 c)
: pos(p),
sound(s),
color(c) {}
// Método que devuelve la posición horizontal
NotificationPosition getHorizontalPosition() const {
switch (pos) {
case NotificationPosition::UPPER_LEFT:
case NotificationPosition::BOTTOM_LEFT:
return NotificationPosition::LEFT;
case NotificationPosition::UPPER_CENTER:
case NotificationPosition::BOTTOM_CENTER:
return NotificationPosition::CENTER;
case NotificationPosition::UPPER_RIGHT:
case NotificationPosition::BOTTOM_RIGHT:
return NotificationPosition::RIGHT;
default:
return NotificationPosition::UNKNOWN;
}
}
// Método que devuelve la posición vertical
NotificationPosition getVerticalPosition() const {
switch (pos) {
case NotificationPosition::UPPER_LEFT:
case NotificationPosition::UPPER_CENTER:
case NotificationPosition::UPPER_RIGHT:
return NotificationPosition::TOP;
case NotificationPosition::BOTTOM_LEFT:
case NotificationPosition::BOTTOM_CENTER:
case NotificationPosition::BOTTOM_RIGHT:
return NotificationPosition::BOTTOM;
default:
return NotificationPosition::UNKNOWN;
}
}
};
// Estructura para albergar trucos
struct Cheat {
enum class State : bool {
DISABLED = false,
ENABLED = true
};
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(State::DISABLED),
invincible(State::DISABLED),
jail_is_open(State::DISABLED),
alternate_skin(State::DISABLED) {}
// Constructor
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 == State::ENABLED ||
invincible == State::ENABLED ||
jail_is_open == State::ENABLED;
}
};
// Estructura para almacenar estadísticas
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
Stats()
: rooms(0),
items(0),
worst_nightmare("") {}
// Constructor
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 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
Window()
: caption("JailDoctor's Dilemma"),
zoom(GameDefaults::WINDOW_ZOOM),
max_zoom(GameDefaults::WINDOW_ZOOM) {}
// Constructor
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
struct Border {
bool enabled; // Indica si se ha de mostrar el borde
float width; // Ancho del borde
float height; // Alto del borde
// Constructor por defecto
Border()
: enabled(GameDefaults::BORDER_ENABLED),
width(GameDefaults::BORDER_WIDTH),
height(GameDefaults::BORDER_HEIGHT) {}
// Constructor
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 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
bool shaders; // Indica si se van a usar shaders o no
bool integer_scale; // Indica si el escalado de la imagen ha de ser entero en el modo a pantalla completa
bool keep_aspect; // Indica si se ha de mantener la relación de aspecto al poner el modo a pantalla completa
Border border; // Borde de la pantalla
std::string palette; // Paleta de colores a usar en el juego
std::string info; // Información sobre el modo de vídeo
// Constructor por defecto
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(GameDefaults::PALETTE_NAME),
info("") {}
// Constructor
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 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
Music()
: enabled(GameDefaults::MUSIC_ENABLED),
volume(VolumeHelpers::convertVolume(GameDefaults::MUSIC_VOLUME)) {}
// Constructor con parámetros
Music(bool is_enabled, int volume_percent)
: enabled(is_enabled),
volume(VolumeHelpers::convertVolume(volume_percent)) {}
// Método para establecer el volumen
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 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
Sound()
: enabled(GameDefaults::SOUND_ENABLED),
volume(VolumeHelpers::convertVolume(GameDefaults::SOUND_VOLUME)) {}
// Constructor con parámetros
Sound(bool is_enabled, int volume_percent)
: enabled(is_enabled),
volume(VolumeHelpers::convertVolume(volume_percent)) {}
// Método para establecer el volumen
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 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
Audio()
: music(Music()),
sound(Sound()),
enabled(GameDefaults::AUDIO_ENABLED),
volume(VolumeHelpers::convertVolume(GameDefaults::AUDIO_VOLUME)) {}
// Constructor
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 Game {
float width; // Ancho de la resolucion del juego
float height; // Alto de la resolucion del juego
// Constructor por defecto
Game()
: width(GameDefaults::GAME_WIDTH),
height(GameDefaults::GAME_HEIGHT) {}
// Constructor
Game(float game_width, float game_height)
: width(game_width),
height(game_height) {}
};
// --- 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
// --- 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
} // namespace Options

View File

@@ -12,7 +12,7 @@
#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/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

View File

@@ -7,7 +7,7 @@
#include "core/rendering/surface_animated_sprite.hpp" // Para SAnimatedSprite
#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 "game/options.hpp" // Para Options, options, Cheat, OptionsGame
#include "utils/defines.hpp" // Para BLOCK
#include "utils/utils.hpp" // Para stringToColor

View File

@@ -3,7 +3,7 @@
#include <fstream> // Para basic_ostream, basic_ifstream, basic_istream
#include <sstream> // Para basic_stringstream
#include "game/gameplay/options.hpp" // Para Options, OptionsStats, options
#include "game/options.hpp" // Para Options, OptionsStats, options
// Constructor
Stats::Stats(const std::string& file, const std::string& buffer)