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

@@ -3,9 +3,9 @@
#include <SDL3/SDL.h>
#include <stdlib.h> // Para rand
#include "core/resources/resource.hpp" // Para Resource
#include "core/rendering/surface_animated_sprite.hpp" // Para SAnimatedSprite
#include "utils/utils.hpp" // Para stringToColor
#include "core/resources/resource.hpp" // Para Resource
#include "utils/utils.hpp" // Para stringToColor
// Constructor
Enemy::Enemy(const EnemyData& enemy)

View File

@@ -1,7 +1,7 @@
#include "game/entities/item.hpp"
#include "core/resources/resource.hpp" // Para Resource
#include "core/rendering/surface_sprite.hpp" // Para SSprite
#include "core/resources/resource.hpp" // Para Resource
// Constructor
Item::Item(ItemData item)

View File

@@ -9,8 +9,8 @@ class SSprite;
struct ItemData {
std::string tile_set_file; // Ruta al fichero con los gráficos del item
float x; // Posición del item en pantalla
float y; // Posición del item en pantalla
float x; // Posición del item en pantalla
float y; // Posición del item en pantalla
int tile; // Número de tile dentro de la textura
int counter; // Contador inicial. Es el que lo hace cambiar de color
Uint8 color1; // Uno de los dos colores que se utiliza para el item

View File

@@ -4,14 +4,14 @@
#include <algorithm> // Para max, min
#include <cmath> // Para ceil, abs
#include "core/system/debug.hpp" // Para Debug
#include "utils/defines.hpp" // Para RoomBorder::BOTTOM, RoomBorder::LEFT, RoomBorder::RIGHT
#include "external/jail_audio.h" // Para JA_PlaySound
#include "core/input/input.hpp" // Para Input, InputAction
#include "game/gameplay/options.hpp" // Para Cheat, Options, options
#include "core/resources/resource.hpp" // Para Resource
#include "game/gameplay/room.hpp" // Para Room, TileType
#include "core/input/input.hpp" // Para Input, InputAction
#include "core/rendering/surface_animated_sprite.hpp" // Para SAnimatedSprite
#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/options.hpp" // Para Cheat, Options, options
#include "game/gameplay/room.hpp" // Para Room, TileType
#include "utils/defines.hpp" // Para RoomBorder::BOTTOM, RoomBorder::LEFT, RoomBorder::RIGHT
// Constructor
Player::Player(const PlayerData& player)
@@ -218,8 +218,8 @@ void Player::applyGravity() {
// Recalcula la posición del jugador y su animación
void Player::move() {
last_position_ = {x_, y_}; // Guarda la posicion actual antes de modificarla
applyGravity(); // Aplica gravedad al jugador
checkState(); // Comprueba el estado del jugador
applyGravity(); // Aplica gravedad al jugador
checkState(); // Comprueba el estado del jugador
#ifdef DEBUG
debug_color_ = static_cast<Uint8>(PaletteColor::GREEN);
@@ -549,9 +549,9 @@ bool Player::checkKillingTiles() {
// Establece el color del jugador
void Player::setColor() {
if (options.cheats.invincible == Cheat::CheatState::ENABLED) {
if (Options::cheats.invincible == Options::Cheat::State::ENABLED) {
color_ = static_cast<Uint8>(PaletteColor::CYAN);
} else if (options.cheats.infinite_lives == Cheat::CheatState::ENABLED) {
} else if (Options::cheats.infinite_lives == Options::Cheat::State::ENABLED) {
color_ = static_cast<Uint8>(PaletteColor::YELLOW);
} else {
color_ = static_cast<Uint8>(PaletteColor::WHITE);

View File

@@ -6,11 +6,11 @@
#include <string> // Para string
#include <vector> // Para vector
#include "utils/defines.hpp" // Para BORDER_TOP, BLOCK
#include "game/gameplay/room.hpp"
#include "core/rendering/surface_animated_sprite.hpp" // Para SAnimatedSprite
#include "utils/utils.hpp" // Para Color
struct JA_Sound_t; // lines 13-13
#include "game/gameplay/room.hpp"
#include "utils/defines.hpp" // Para BORDER_TOP, BLOCK
#include "utils/utils.hpp" // Para Color
struct JA_Sound_t; // lines 13-13
enum class PlayerState {
STANDING,

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);
};

View File

@@ -4,33 +4,33 @@
#include <algorithm> // Para min
#include "utils/defines.hpp" // Para GAME_SPEED, PLAY_AREA_CENTER_X, PLAY_...
#include "utils/global_events.hpp" // Para check
#include "core/input/global_inputs.hpp" // Para check
#include "game/gameplay/options.hpp" // Para Options, options, OptionsGame, Sectio...
#include "core/resources/resource.hpp" // Para Resource
#include "core/rendering/screen.hpp" // Para Screen
#include "core/input/global_inputs.hpp" // Para check
#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, TEXT_CENTER, TEXT_COLOR
#include "utils/utils.hpp" // Para PaletteColor
#include "core/rendering/text.hpp" // Para Text, TEXT_CENTER, TEXT_COLOR
#include "core/resources/resource.hpp" // Para Resource
#include "game/gameplay/options.hpp" // Para Options, options, OptionsGame, Sectio...
#include "utils/defines.hpp" // Para GAME_SPEED, PLAY_AREA_CENTER_X, PLAY_...
#include "utils/global_events.hpp" // Para check
#include "utils/utils.hpp" // Para PaletteColor
// Constructor
Credits::Credits()
: shining_sprite_(std::make_shared<SAnimatedSprite>(Resource::get()->getSurface("shine.gif"), Resource::get()->getAnimations("shine.ani"))) {
// Inicializa variables
options.section.section = Section::CREDITS;
options.section.subsection = Subsection::NONE;
Options::section.section = Options::Scene::CREDITS;
Options::section.subsection = Options::SceneOptions::NONE;
shining_sprite_->setPos({194, 174, 8, 8});
// Cambia el color del borde
Screen::get()->setBorderColor(static_cast<Uint8>(PaletteColor::BLACK));
// Crea la textura para el texto que se escribe en pantalla
text_surface_ = std::make_shared<Surface>(options.game.width, options.game.height);
text_surface_ = std::make_shared<Surface>(Options::game.width, Options::game.height);
// Crea la textura para cubrir el rexto
cover_surface_ = std::make_shared<Surface>(options.game.width, options.game.height);
cover_surface_ = std::make_shared<Surface>(Options::game.width, Options::game.height);
// Escribe el texto en la textura
fillTexture();
@@ -51,17 +51,16 @@ void Credits::checkInput() {
// Inicializa los textos
void Credits::iniTexts() {
#ifndef GAME_CONSOLE
std::string keys = "";
switch (options.keys) {
case ControlScheme::CURSOR:
switch (Options::keys) {
case Options::ControlScheme::CURSOR:
keys = "CURSORS";
break;
case ControlScheme::OPQA:
case Options::ControlScheme::OPQA:
keys = "O,P AND Q";
break;
case ControlScheme::WASD:
case Options::ControlScheme::WASD:
keys = "A,D AND W";
break;
default:
@@ -96,36 +95,6 @@ void Credits::iniTexts() {
texts_.push_back({"I LOVE JAILGAMES! ", static_cast<Uint8>(PaletteColor::WHITE)});
texts_.push_back({"", static_cast<Uint8>(PaletteColor::WHITE)});
#else
texts.clear();
texts.push_back({"", static_cast<Uint8>(PaletteColor::WHITE)});
texts.push_back({"INSTRUCTIONS:", static_cast<Uint8>(PaletteColor::YELLOW)});
texts.push_back({"", static_cast<Uint8>(PaletteColor::WHITE)});
texts.push_back({"HELP JAILDOC TO GET BACK ALL", static_cast<Uint8>(PaletteColor::WHITE)});
texts.push_back({"HIS PROJECTS AND GO TO THE", static_cast<Uint8>(PaletteColor::WHITE)});
texts.push_back({"JAIL TO FINISH THEM", static_cast<Uint8>(PaletteColor::WHITE)});
texts.push_back({"", static_cast<Uint8>(PaletteColor::WHITE)});
texts.push_back({"", static_cast<Uint8>(PaletteColor::WHITE)});
texts.push_back({"KEYS:", static_cast<Uint8>(PaletteColor::YELLOW)});
texts.push_back({"", static_cast<Uint8>(PaletteColor::WHITE)});
texts.push_back({"B TO JUMP", static_cast<Uint8>(PaletteColor::WHITE)});
texts.push_back({"R TO SWITCH THE MUSIC", static_cast<Uint8>(PaletteColor::WHITE)});
texts.push_back({"L TO SWAP THE COLOR PALETTE", static_cast<Uint8>(PaletteColor::WHITE)});
texts.push_back({"START TO PAUSE", static_cast<Uint8>(PaletteColor::WHITE)});
texts.push_back({"SELECT TO EXIT", static_cast<Uint8>(PaletteColor::WHITE)});
texts.push_back({"", static_cast<Uint8>(PaletteColor::WHITE)});
texts.push_back({"", static_cast<Uint8>(PaletteColor::WHITE)});
texts.push_back({"", static_cast<Uint8>(PaletteColor::WHITE)});
texts.push_back({"A GAME BY JAILDESIGNER", static_cast<Uint8>(PaletteColor::YELLOW)});
texts.push_back({"MADE ON SUMMER/FALL 2022", static_cast<Uint8>(PaletteColor::YELLOW)});
texts.push_back({"", static_cast<Uint8>(PaletteColor::WHITE)});
texts.push_back({"", static_cast<Uint8>(PaletteColor::WHITE)});
texts.push_back({"I LOVE JAILGAMES! ", static_cast<Uint8>(PaletteColor::WHITE)});
texts.push_back({"", static_cast<Uint8>(PaletteColor::WHITE)});
#endif
}
// Escribe el texto en la textura
@@ -196,7 +165,7 @@ void Credits::updateCounter() {
// Comprueba si ha terminado la sección
if (counter_ > 1200) {
options.section.section = Section::DEMO;
Options::section.section = Options::Scene::DEMO;
}
}
@@ -249,7 +218,7 @@ void Credits::render() {
// Bucle para el logo del juego
void Credits::run() {
while (options.section.section == Section::CREDITS) {
while (Options::section.section == Options::Scene::CREDITS) {
update();
checkEvents();
render();

View File

@@ -4,17 +4,17 @@
#include <algorithm> // Para min
#include "utils/defines.hpp" // Para GAME_SPEED
#include "external/jail_audio.h" // Para JA_SetVolume, JA_PlayMusic, JA_StopMusic
#include "utils/global_events.hpp" // Para check
#include "core/input/global_inputs.hpp" // Para check
#include "game/gameplay/options.hpp" // Para Options, options, OptionsGame, SectionS...
#include "core/resources/resource.hpp" // Para Resource
#include "core/rendering/screen.hpp" // Para Screen
#include "core/input/global_inputs.hpp" // Para check
#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 "core/rendering/text.hpp" // Para Text, TEXT_STROKE
#include "utils/utils.hpp" // Para PaletteColor
#include "core/rendering/text.hpp" // Para Text, TEXT_STROKE
#include "core/resources/resource.hpp" // Para Resource
#include "external/jail_audio.h" // Para JA_SetVolume, JA_PlayMusic, JA_StopMusic
#include "game/gameplay/options.hpp" // Para Options, options, OptionsGame, SectionS...
#include "utils/defines.hpp" // Para GAME_SPEED
#include "utils/global_events.hpp" // Para check
#include "utils/utils.hpp" // Para PaletteColor
// Constructor
Ending::Ending()
@@ -23,8 +23,8 @@ Ending::Ending()
cover_counter_(0),
ticks_(0),
current_scene_(0) {
options.section.section = Section::ENDING;
options.section.subsection = Subsection::NONE;
Options::section.section = Options::Scene::ENDING;
Options::section.subsection = Options::SceneOptions::NONE;
// Inicializa los textos
iniTexts();
@@ -39,7 +39,7 @@ Ending::Ending()
Screen::get()->setBorderColor(static_cast<Uint8>(PaletteColor::BLACK));
// Crea la textura para cubrir el texto
cover_surface_ = std::make_shared<Surface>(options.game.width, options.game.height + 8);
cover_surface_ = std::make_shared<Surface>(Options::game.width, Options::game.height + 8);
// Rellena la textura para la cortinilla
fillCoverTexture();
@@ -167,7 +167,7 @@ void Ending::iniTexts() {
// Crea el sprite
st.image_sprite = std::make_shared<SSprite>(st.image_surface, 0, 0, st.image_surface->getWidth(), st.image_surface->getHeight());
st.image_sprite->setPosition((options.game.width - st.image_surface->getWidth()) / 2, txt.pos);
st.image_sprite->setPosition((Options::game.width - st.image_surface->getWidth()) / 2, txt.pos);
// Crea la cover_surface
st.cover_surface = std::make_shared<Surface>(WIDTH, HEIGHT + 8);
@@ -195,7 +195,7 @@ void Ending::iniTexts() {
// Crea el sprite
st.cover_sprite = std::make_shared<SSprite>(st.cover_surface, 0, 0, st.cover_surface->getWidth(), st.cover_surface->getHeight() - 8);
st.cover_sprite->setPosition((options.game.width - st.cover_surface->getWidth()) / 2, txt.pos);
st.cover_sprite->setPosition((Options::game.width - st.cover_surface->getWidth()) / 2, txt.pos);
st.cover_sprite->setClip(0, 8, st.cover_surface->getWidth(), st.cover_surface->getHeight());
// Inicializa variables
@@ -232,7 +232,7 @@ void Ending::iniPics() {
// Crea el sprite
sp.image_sprite = std::make_shared<SSprite>(sp.image_surface, 0, 0, WIDTH, HEIGHT);
sp.image_sprite->setPosition((options.game.width - WIDTH) / 2, pic.pos);
sp.image_sprite->setPosition((Options::game.width - WIDTH) / 2, pic.pos);
// Crea la cover_surface
sp.cover_surface = std::make_shared<Surface>(WIDTH, HEIGHT + 8);
@@ -261,7 +261,7 @@ void Ending::iniPics() {
// Crea el sprite
sp.cover_sprite = std::make_shared<SSprite>(sp.cover_surface, 0, 0, sp.cover_surface->getWidth(), sp.cover_surface->getHeight() - 8);
sp.cover_sprite->setPosition((options.game.width - sp.cover_surface->getWidth()) / 2, pic.pos);
sp.cover_sprite->setPosition((Options::game.width - sp.cover_surface->getWidth()) / 2, pic.pos);
sp.cover_sprite->setClip(0, 8, sp.cover_surface->getWidth(), sp.cover_surface->getHeight());
// Inicializa variables
@@ -359,7 +359,7 @@ void Ending::iniScenes() {
void Ending::run() {
JA_PlayMusic(Resource::get()->getMusic("ending1.ogg"));
while (options.section.section == Section::ENDING) {
while (Options::section.section == Options::Scene::ENDING) {
update();
checkEvents();
render();
@@ -423,7 +423,7 @@ void Ending::checkChangeScene() {
cover_counter_ = 0;
if (current_scene_ == 5) {
// Termina el bucle
options.section.section = Section::ENDING2;
Options::section.section = Options::Scene::ENDING2;
// Mantiene los valores anteriores
current_scene_ = 4;
@@ -443,17 +443,17 @@ void Ending::fillCoverTexture() {
const Uint8 color = static_cast<Uint8>(PaletteColor::BLACK);
auto surface = Screen::get()->getRendererSurface();
for (int i = 0; i < 256; i += 2) {
surface->putPixel(i + 0, options.game.height + 0, color);
surface->putPixel(i + 1, options.game.height + 1, color);
surface->putPixel(i + 0, options.game.height + 2, color);
surface->putPixel(i + 1, options.game.height + 3, color);
surface->putPixel(i + 0, Options::game.height + 0, color);
surface->putPixel(i + 1, Options::game.height + 1, color);
surface->putPixel(i + 0, Options::game.height + 2, color);
surface->putPixel(i + 1, Options::game.height + 3, color);
surface->putPixel(i, options.game.height + 4, color);
surface->putPixel(i, options.game.height + 6, color);
surface->putPixel(i, Options::game.height + 4, color);
surface->putPixel(i, Options::game.height + 6, color);
}
// El resto se rellena de color sólido
SDL_FRect rect = {0, 0, 256, options.game.height};
SDL_FRect rect = {0, 0, 256, Options::game.height};
surface->fillRect(&rect, color);
Screen::get()->setRendererSurface(previuos_renderer);

View File

@@ -4,24 +4,24 @@
#include <algorithm> // Para max, replace
#include "utils/defines.hpp" // Para GAMECANVAS_CENTER_X, GAMECANVAS_CENTER_Y
#include "external/jail_audio.h" // Para JA_SetVolume, JA_PlayMusic, JA_StopMusic
#include "utils/global_events.hpp" // Para check
#include "core/input/global_inputs.hpp" // Para check
#include "game/gameplay/options.hpp" // Para Options, options, OptionsGame, Sectio...
#include "core/resources/resource.hpp" // Para Resource
#include "core/rendering/screen.hpp" // Para Screen
#include "core/input/global_inputs.hpp" // Para check
#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_moving_sprite.hpp" // Para SMovingSprite
#include "core/rendering/surface.hpp" // Para Surface
#include "core/rendering/text.hpp" // Para Text
#include "utils/utils.hpp" // Para PaletteColor, stringToColor
#include "core/rendering/text.hpp" // Para Text
#include "core/resources/resource.hpp" // Para Resource
#include "external/jail_audio.h" // Para JA_SetVolume, JA_PlayMusic, JA_StopMusic
#include "game/gameplay/options.hpp" // Para Options, options, OptionsGame, Sectio...
#include "utils/defines.hpp" // Para GAMECANVAS_CENTER_X, GAMECANVAS_CENTER_Y
#include "utils/global_events.hpp" // Para check
#include "utils/utils.hpp" // Para PaletteColor, stringToColor
// Constructor
Ending2::Ending2()
: state_(EndingState::PRE_CREDITS, SDL_GetTicks(), STATE_PRE_CREDITS_DURATION_) {
options.section.section = Section::ENDING2;
options.section.subsection = Subsection::NONE;
Options::section.section = Options::Scene::ENDING2;
Options::section.subsection = Options::SceneOptions::NONE;
// Inicializa el vector de colores
const std::vector<std::string> COLORS = {"white", "yellow", "cyan", "green", "magenta", "red", "blue", "black"};
@@ -146,7 +146,7 @@ void Ending2::checkInput() {
void Ending2::run() {
JA_PlayMusic(Resource::get()->getMusic("ending2.ogg"));
while (options.section.section == Section::ENDING2) {
while (Options::section.section == Options::Scene::ENDING2) {
update();
checkEvents();
render();
@@ -179,8 +179,8 @@ void Ending2::updateState() {
case EndingState::FADING:
if (state_.hasEnded(EndingState::FADING)) {
options.section.section = Section::LOGO;
options.section.subsection = Subsection::LOGO_TO_INTRO;
Options::section.section = Options::Scene::LOGO;
Options::section.subsection = Options::SceneOptions::LOGO_TO_INTRO;
}
break;
@@ -306,7 +306,7 @@ void Ending2::renderSprites() {
const Uint8 colorA = static_cast<Uint8>(PaletteColor::RED);
for (auto sprite : sprites_) {
const bool A = sprite->getRect().y + sprite->getRect().h > 0;
const bool B = sprite->getRect().y < options.game.height;
const bool B = sprite->getRect().y < Options::game.height;
if (A && B) {
sprite->render(1, colorA);
}
@@ -322,7 +322,7 @@ void Ending2::renderSpriteTexts() {
const Uint8 color = static_cast<Uint8>(PaletteColor::WHITE);
for (auto sprite : sprite_texts_) {
const bool A = sprite->getRect().y + sprite->getRect().h > 0;
const bool B = sprite->getRect().y < options.game.height;
const bool B = sprite->getRect().y < Options::game.height;
if (A && B) {
sprite->render(1, color);
}
@@ -333,7 +333,7 @@ void Ending2::renderSpriteTexts() {
void Ending2::renderTexts() {
for (auto sprite : texts_) {
const bool A = sprite->getRect().y + sprite->getRect().h > 0;
const bool B = sprite->getRect().y < options.game.height;
const bool B = sprite->getRect().y < Options::game.height;
if (A && B) {
sprite->render();
}
@@ -344,7 +344,7 @@ void Ending2::renderTexts() {
void Ending2::placeSprites() {
for (int i = 0; i < static_cast<int>(sprites_.size()); ++i) {
const float X = i % 2 == 0 ? FIRST_COL_ : SECOND_COL_;
const float Y = (i / 1) * (sprite_max_height_ + DIST_SPRITE_TEXT_ + Resource::get()->getText("smb2")->getCharacterSize() + DIST_SPRITE_SPRITE_) + options.game.height + 40;
const float Y = (i / 1) * (sprite_max_height_ + DIST_SPRITE_TEXT_ + Resource::get()->getText("smb2")->getCharacterSize() + DIST_SPRITE_SPRITE_) + Options::game.height + 40;
const float W = sprites_.at(i)->getWidth();
const float H = sprites_.at(i)->getHeight();
const float DX = -(W / 2);
@@ -355,7 +355,7 @@ void Ending2::placeSprites() {
}
// Recoloca el sprite del jugador, que es el último de la lista
const float X = (options.game.width - sprites_.back()->getWidth()) / 2;
const float X = (Options::game.width - sprites_.back()->getWidth()) / 2;
const float Y = sprites_.back()->getPosY() + sprite_max_height_ * 2;
sprites_.back()->setPos(X, Y);
sprites_.back()->setCurrentAnimation("walk");
@@ -415,7 +415,7 @@ void Ending2::createTexts() {
const float H = text->getCharacterSize();
const float X = GAMECANVAS_CENTER_X;
const float DX = -(W / 2);
const float Y = options.game.height + (text->getCharacterSize() * (i * 2));
const float Y = Options::game.height + (text->getCharacterSize() * (i * 2));
// Crea la surface
auto surface = std::make_shared<Surface>(W, H);

View File

@@ -6,9 +6,9 @@
#include <string> // Para string
#include <vector> // Para vector
#include "utils/defines.hpp" // Para GAMECANVAS_WIDTH, GAMECANVAS_FIRST_QUAR...
class SAnimatedSprite; // lines 9-9
class SMovingSprite; // lines 10-10
#include "utils/defines.hpp" // Para GAMECANVAS_WIDTH, GAMECANVAS_FIRST_QUAR...
class SAnimatedSprite; // lines 9-9
class SMovingSprite; // lines 10-10
class Ending2 {
private:
@@ -70,8 +70,8 @@ class Ending2 {
Uint32 ticks_ = 0; // Contador de ticks para ajustar la velocidad del programa
std::vector<std::string> sprite_list_; // Lista con todos los sprites a dibujar
std::vector<Uint8> colors_; // Vector con los colores para el fade
float sprite_max_width_ = 0; // El valor de ancho del sprite mas ancho
float sprite_max_height_ = 0; // El valor de alto del sprite mas alto
float sprite_max_width_ = 0; // El valor de ancho del sprite mas ancho
float sprite_max_height_ = 0; // El valor de alto del sprite mas alto
State state_; // Controla el estado de la clase
// Actualiza el objeto

View File

@@ -4,30 +4,30 @@
#include <vector> // Para vector
#include "core/resources/asset.hpp" // Para Asset
#include "game/gameplay/cheevos.hpp" // Para Cheevos
#include "core/system/debug.hpp" // Para Debug
#include "utils/defines.hpp" // Para BLOCK, PLAY_AREA_HEIGHT, RoomBorder::BOTTOM
#include "external/jail_audio.h" // Para JA_PauseMusic, JA_GetMusicState, JA_P...
#include "utils/global_events.hpp" // Para check
#include "core/input/global_inputs.hpp" // Para check
#include "core/input/input.hpp" // Para Input, InputAction, INPUT_DO_NOT_ALLOW_REPEAT
#include "game/gameplay/item_tracker.hpp" // Para ItemTracker
#include "game/gameplay/options.hpp" // Para Options, options, Cheat, SectionState
#include "core/resources/resource.hpp" // Para ResourceRoom, Resource
#include "game/gameplay/room.hpp" // Para Room, RoomData
#include "game/gameplay/room_tracker.hpp" // Para RoomTracker
#include "game/gameplay/scoreboard.hpp" // Para ScoreboardData, Scoreboard
#include "core/rendering/screen.hpp" // Para Screen
#include "game/gameplay/stats.hpp" // Para Stats
#include "core/rendering/surface.hpp" // Para Surface
#include "core/rendering/text.hpp" // Para Text, TEXT_CENTER, TEXT_COLOR
#include "game/ui/notifier.hpp" // Para Notifier, NotificationText, CHEEVO_NO...
#include "utils/utils.hpp" // Para PaletteColor, stringToColor
#include "core/input/global_inputs.hpp" // Para check
#include "core/input/input.hpp" // Para Input, InputAction, INPUT_DO_NOT_ALLOW_REPEAT
#include "core/rendering/screen.hpp" // Para Screen
#include "core/rendering/surface.hpp" // Para Surface
#include "core/rendering/text.hpp" // Para Text, TEXT_CENTER, TEXT_COLOR
#include "core/resources/asset.hpp" // Para Asset
#include "core/resources/resource.hpp" // Para ResourceRoom, Resource
#include "core/system/debug.hpp" // Para Debug
#include "external/jail_audio.h" // Para JA_PauseMusic, JA_GetMusicState, JA_P...
#include "game/gameplay/cheevos.hpp" // Para Cheevos
#include "game/gameplay/item_tracker.hpp" // Para ItemTracker
#include "game/gameplay/options.hpp" // Para Options, options, Cheat, SectionState
#include "game/gameplay/room.hpp" // Para Room, RoomData
#include "game/gameplay/room_tracker.hpp" // Para RoomTracker
#include "game/gameplay/scoreboard.hpp" // Para ScoreboardData, Scoreboard
#include "game/gameplay/stats.hpp" // Para Stats
#include "game/ui/notifier.hpp" // Para Notifier, NotificationText, CHEEVO_NO...
#include "utils/defines.hpp" // Para BLOCK, PLAY_AREA_HEIGHT, RoomBorder::BOTTOM
#include "utils/global_events.hpp" // Para check
#include "utils/utils.hpp" // Para PaletteColor, stringToColor
// Constructor
Game::Game(GameMode mode)
: board_(std::make_shared<ScoreboardData>(0, 9, 0, true, 0, SDL_GetTicks(), options.cheats.jail_is_open == Cheat::CheatState::ENABLED)),
: board_(std::make_shared<ScoreboardData>(0, 9, 0, true, 0, SDL_GetTicks(), Options::cheats.jail_is_open == Options::Cheat::State::ENABLED)),
scoreboard_(std::make_shared<Scoreboard>(board_)),
room_tracker_(std::make_shared<RoomTracker>()),
stats_(std::make_shared<Stats>(Asset::get()->get("stats.csv"), Asset::get()->get("stats_buffer.csv"))),
@@ -55,11 +55,11 @@ Game::Game(GameMode mode)
createRoomNameTexture();
changeRoom(current_room_);
Cheevos::get()->enable(!options.cheats.enabled()); // Deshabilita los logros si hay trucos activados
Cheevos::get()->enable(!Options::cheats.enabled()); // Deshabilita los logros si hay trucos activados
Cheevos::get()->clearUnobtainableState();
options.section.section = (mode_ == GameMode::GAME) ? Section::GAME : Section::DEMO;
options.section.subsection = Subsection::NONE;
Options::section.section = (mode_ == GameMode::GAME) ? Options::Scene::GAME : Options::Scene::DEMO;
Options::section.subsection = Options::SceneOptions::NONE;
}
Game::~Game() {
@@ -100,7 +100,7 @@ void Game::run() {
JA_PauseMusic();
}
while (options.section.section == Section::GAME || options.section.section == Section::DEMO) {
while (Options::section.section == Options::Scene::GAME || Options::section.section == Options::Scene::DEMO) {
update();
checkEvents();
render();
@@ -219,7 +219,7 @@ void Game::checkDebugEvents(const SDL_Event& event) {
switch (event.key.key) {
case SDL_SCANCODE_G:
Debug::get()->toggleEnabled();
options.cheats.invincible = static_cast<Cheat::CheatState>(Debug::get()->getEnabled());
Options::cheats.invincible = static_cast<Options::Cheat::State>(Debug::get()->getEnabled());
board_->music = !Debug::get()->getEnabled();
board_->music ? JA_ResumeMusic() : JA_PauseMusic();
break;
@@ -282,7 +282,7 @@ bool Game::changeRoom(const std::string& room_path) {
if (room_tracker_->addRoom(room_path)) {
// Incrementa el contador de habitaciones visitadas
board_->rooms++;
options.stats.rooms = board_->rooms;
Options::stats.rooms = board_->rooms;
// Actualiza las estadisticas
stats_->addVisit(room_->getName());
@@ -335,18 +335,18 @@ void Game::checkIfPlayerIsAlive() {
// Comprueba si ha terminado la partida
void Game::checkGameOver() {
if (board_->lives < 0 && black_screen_counter_ > 17) {
options.section.section = Section::GAME_OVER;
Options::section.section = Options::Scene::GAME_OVER;
}
}
// Mata al jugador
void Game::killPlayer() {
if (options.cheats.invincible == Cheat::CheatState::ENABLED) {
if (Options::cheats.invincible == Options::Cheat::State::ENABLED) {
return;
}
// Resta una vida al jugador
if (options.cheats.infinite_lives == Cheat::CheatState::DISABLED) {
if (Options::cheats.infinite_lives == Options::Cheat::State::DISABLED) {
--board_->lives;
}
@@ -415,9 +415,9 @@ void Game::setScoreBoardColor() {
// Comprueba si ha finalizado el juego
bool Game::checkEndGame() {
const bool isOnTheRoom = room_->getName() == "THE JAIL"; // Estar en la habitación que toca
const bool haveTheItems = board_->items >= int(total_items_ * 0.9f) || options.cheats.jail_is_open == Cheat::CheatState::ENABLED; // Con mas del 90% de los items recogidos
const bool isOnTheDoor = player_->getRect().x <= 128; // Y en la ubicación que toca (En la puerta)
const bool isOnTheRoom = room_->getName() == "THE JAIL"; // Estar en la habitación que toca
const bool haveTheItems = board_->items >= int(total_items_ * 0.9f) || Options::cheats.jail_is_open == Options::Cheat::State::ENABLED; // Con mas del 90% de los items recogidos
const bool isOnTheDoor = player_->getRect().x <= 128; // Y en la ubicación que toca (En la puerta)
if (haveTheItems) {
board_->jail_is_open = true;
@@ -427,7 +427,7 @@ bool Game::checkEndGame() {
// Comprueba los logros de completar el juego
checkEndGameCheevos();
options.section.section = Section::ENDING;
Options::section.section = Options::Scene::ENDING;
return true;
}
@@ -569,8 +569,8 @@ void Game::checkEndGameCheevos() {
// Inicializa al jugador
void Game::initPlayer(const PlayerSpawn& spawn_point, std::shared_ptr<Room> room) {
std::string player_texture = options.cheats.alternate_skin == Cheat::CheatState::ENABLED ? "player2.gif" : "player.gif";
std::string player_animations = options.cheats.alternate_skin == Cheat::CheatState::ENABLED ? "player2.ani" : "player.ani";
std::string player_texture = Options::cheats.alternate_skin == Options::Cheat::State::ENABLED ? "player2.gif" : "player.gif";
std::string player_animations = Options::cheats.alternate_skin == Options::Cheat::State::ENABLED ? "player2.ani" : "player.ani";
const PlayerData player(spawn_point, player_texture, player_animations, room);
player_ = std::make_shared<Player>(player);
}
@@ -578,10 +578,10 @@ void Game::initPlayer(const PlayerSpawn& spawn_point, std::shared_ptr<Room> room
// Crea la textura para poner el nombre de la habitación
void Game::createRoomNameTexture() {
auto text = Resource::get()->getText("smb2");
room_name_surface_ = std::make_shared<Surface>(options.game.width, text->getCharacterSize() * 2);
room_name_surface_ = std::make_shared<Surface>(Options::game.width, text->getCharacterSize() * 2);
// Establece el destino de la textura
room_name_rect_ = {0.0F, PLAY_AREA_HEIGHT, options.game.width, text->getCharacterSize() * 2.0F};
room_name_rect_ = {0.0F, PLAY_AREA_HEIGHT, Options::game.width, text->getCharacterSize() * 2.0F};
}
// Hace sonar la música
@@ -610,8 +610,8 @@ void Game::DEMO_checkRoomChange() {
demo_.counter = 0;
demo_.room_index++;
if (demo_.room_index == (int)demo_.rooms.size()) {
options.section.section = Section::LOGO;
options.section.subsection = Subsection::LOGO_TO_TITLE;
Options::section.section = Options::Scene::LOGO;
Options::section.subsection = Options::SceneOptions::LOGO_TO_TITLE;
} else {
changeRoom(demo_.rooms[demo_.room_index]);
}

View File

@@ -8,10 +8,10 @@
#include <vector> // Para vector
#include "game/entities/player.hpp" // Para PlayerSpawn
class Room; // lines 12-12
class RoomTracker; // lines 13-13
class Scoreboard; // lines 14-14
class Stats; // lines 15-15
class Room; // lines 12-12
class RoomTracker; // lines 13-13
class Scoreboard; // lines 14-14
class Stats; // lines 15-15
class Surface;
struct ScoreboardData; // lines 16-16

View File

@@ -5,16 +5,16 @@
#include <algorithm> // Para min, max
#include <string> // Para basic_string, operator+, to_string
#include "utils/defines.hpp" // Para GAMECANVAS_CENTER_X, GAME_SPEED
#include "external/jail_audio.h" // Para JA_PlayMusic
#include "utils/global_events.hpp" // Para check
#include "core/input/global_inputs.hpp" // Para check
#include "game/gameplay/options.hpp" // Para Options, options, OptionsStats, Secti...
#include "core/resources/resource.hpp" // Para Resource
#include "core/rendering/screen.hpp" // Para Screen
#include "core/input/global_inputs.hpp" // Para check
#include "core/rendering/screen.hpp" // Para Screen
#include "core/rendering/surface_animated_sprite.hpp" // Para SAnimatedSprite
#include "core/rendering/text.hpp" // Para TEXT_CENTER, TEXT_COLOR, Text
#include "utils/utils.hpp" // Para PaletteColor, stringToColor
#include "core/rendering/text.hpp" // Para TEXT_CENTER, TEXT_COLOR, Text
#include "core/resources/resource.hpp" // Para Resource
#include "external/jail_audio.h" // Para JA_PlayMusic
#include "game/gameplay/options.hpp" // Para Options, options, OptionsStats, Secti...
#include "utils/defines.hpp" // Para GAMECANVAS_CENTER_X, GAME_SPEED
#include "utils/global_events.hpp" // Para check
#include "utils/utils.hpp" // Para PaletteColor, stringToColor
// Constructor
GameOver::GameOver()
@@ -23,8 +23,8 @@ GameOver::GameOver()
pre_counter_(0),
counter_(0),
ticks_(0) {
options.section.section = Section::GAME_OVER;
options.section.subsection = Subsection::NONE;
Options::section.section = Options::Scene::GAME_OVER;
Options::section.subsection = Options::SceneOptions::NONE;
player_sprite_->setPosX(GAMECANVAS_CENTER_X + 10);
player_sprite_->setPosY(30);
@@ -84,14 +84,14 @@ void GameOver::render() {
renderSprites();
// Escribe el texto con las habitaciones y los items
const std::string ITEMS_TEXT = std::to_string(options.stats.items / 100) + std::to_string((options.stats.items % 100) / 10) + std::to_string(options.stats.items % 10);
const std::string ROOMS_TEXT = std::to_string(options.stats.rooms / 100) + std::to_string((options.stats.rooms % 100) / 10) + std::to_string(options.stats.rooms % 10);
const std::string ITEMS_TEXT = std::to_string(Options::stats.items / 100) + std::to_string((Options::stats.items % 100) / 10) + std::to_string(Options::stats.items % 10);
const std::string ROOMS_TEXT = std::to_string(Options::stats.rooms / 100) + std::to_string((Options::stats.rooms % 100) / 10) + std::to_string(Options::stats.rooms % 10);
text->writeDX(TEXT_CENTER | TEXT_COLOR, GAMECANVAS_CENTER_X, Y + 80, "ITEMS: " + ITEMS_TEXT, 1, color_);
text->writeDX(TEXT_CENTER | TEXT_COLOR, GAMECANVAS_CENTER_X, Y + 90, "ROOMS: " + ROOMS_TEXT, 1, color_);
// Escribe el texto con "Tu peor pesadilla"
text->writeDX(TEXT_CENTER | TEXT_COLOR, GAMECANVAS_CENTER_X, Y + 110, "YOUR WORST NIGHTMARE IS", 1, color_);
text->writeDX(TEXT_CENTER | TEXT_COLOR, GAMECANVAS_CENTER_X, Y + 120, options.stats.worst_nightmare, 1, color_);
text->writeDX(TEXT_CENTER | TEXT_COLOR, GAMECANVAS_CENTER_X, Y + 120, Options::stats.worst_nightmare, 1, color_);
// Vuelca el contenido del renderizador en pantalla
Screen::get()->render();
@@ -112,7 +112,7 @@ void GameOver::checkInput() {
// Bucle principal
void GameOver::run() {
while (options.section.section == Section::GAME_OVER) {
while (Options::section.section == Options::Scene::GAME_OVER) {
update();
checkEvents();
render();
@@ -156,7 +156,7 @@ void GameOver::updateCounters() {
// Comprueba si ha terminado la sección
else if (counter_ == COUNTER_SECTION_END_) {
options.section.section = Section::LOGO;
options.section.subsection = Subsection::LOGO_TO_TITLE;
Options::section.section = Options::Scene::LOGO;
Options::section.subsection = Options::SceneOptions::LOGO_TO_TITLE;
}
}

View File

@@ -3,16 +3,16 @@
#include <SDL3/SDL.h>
#include <stdlib.h> // Para rand
#include "utils/defines.hpp" // Para GAME_SPEED
#include "external/jail_audio.h" // Para JA_PlayMusic, JA_SetVolume, JA_StopMusic
#include "utils/global_events.hpp" // Para check
#include "core/input/global_inputs.hpp" // Para check
#include "game/gameplay/options.hpp" // Para Options, options, SectionState, Options...
#include "core/resources/resource.hpp" // Para Resource
#include "core/rendering/screen.hpp" // Para Screen
#include "core/input/global_inputs.hpp" // Para check
#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 stringToColor, PaletteColor
#include "core/resources/resource.hpp" // Para Resource
#include "external/jail_audio.h" // Para JA_PlayMusic, JA_SetVolume, JA_StopMusic
#include "game/gameplay/options.hpp" // Para Options, options, SectionState, Options...
#include "utils/defines.hpp" // Para GAME_SPEED
#include "utils/global_events.hpp" // Para check
#include "utils/utils.hpp" // Para stringToColor, PaletteColor
// Constructor
LoadingScreen::LoadingScreen()
@@ -20,13 +20,13 @@ LoadingScreen::LoadingScreen()
color_loading_screen_surface_(Resource::get()->getSurface("loading_screen_color.gif")),
mono_loading_screen_sprite_(std::make_shared<SSprite>(mono_loading_screen_surface_, 0, 0, mono_loading_screen_surface_->getWidth(), mono_loading_screen_surface_->getHeight())),
color_loading_screen_sprite_(std::make_shared<SSprite>(color_loading_screen_surface_, 0, 0, color_loading_screen_surface_->getWidth(), color_loading_screen_surface_->getHeight())),
screen_surface_(std::make_shared<Surface>(options.game.width, options.game.height)) {
screen_surface_(std::make_shared<Surface>(Options::game.width, Options::game.height)) {
// Configura la superficie donde se van a pintar los sprites
screen_surface_->clear(static_cast<Uint8>(PaletteColor::WHITE));
// Inicializa variables
options.section.section = Section::LOADING_SCREEN;
options.section.subsection = Subsection::NONE;
Options::section.section = Options::Scene::LOADING_SCREEN;
Options::section.subsection = Options::SceneOptions::NONE;
// Establece el orden de las lineas para imitar el direccionamiento de memoria del spectrum
for (int i = 0; i < 192; ++i) {
@@ -96,8 +96,8 @@ void LoadingScreen::updateLoad() {
// Comprueba si ha terminado la intro
if (load_counter_ >= 768) {
options.section.section = Section::TITLE;
options.section.subsection = Subsection::TITLE_WITH_LOADING_SCREEN;
Options::section.section = Options::Scene::TITLE;
Options::section.subsection = Options::SceneOptions::TITLE_WITH_LOADING_SCREEN;
JA_StopMusic();
}
}
@@ -130,8 +130,8 @@ void LoadingScreen::renderBorder() {
// Añade lineas amarillas
const Uint8 COLOR = static_cast<Uint8>(PaletteColor::YELLOW);
const int WIDTH = options.game.width + (options.video.border.width * 2);
const int HEIGHT = options.game.height + (options.video.border.height * 2);
const int WIDTH = Options::game.width + (Options::video.border.width * 2);
const int HEIGHT = Options::game.height + (Options::video.border.height * 2);
bool draw_enabled = rand() % 2 == 0 ? true : false;
int row = 0;
@@ -162,7 +162,7 @@ void LoadingScreen::update() {
// Dibuja en pantalla
void LoadingScreen::render() {
if (options.video.border.enabled) {
if (Options::video.border.enabled) {
// Dibuja el efecto de carga en el borde
renderBorder();
}
@@ -189,7 +189,7 @@ void LoadingScreen::run() {
Screen::get()->clearRenderer();
Screen::get()->render();
while (options.section.section == Section::LOADING_SCREEN) {
while (Options::section.section == Options::Scene::LOADING_SCREEN) {
update();
checkEvents();
render();

View File

@@ -2,15 +2,15 @@
#include <SDL3/SDL.h>
#include "utils/defines.hpp" // Para GAME_SPEED
#include "utils/global_events.hpp" // Para check
#include "core/input/global_inputs.hpp" // Para check
#include "game/gameplay/options.hpp" // Para Options, SectionState, options, Section
#include "core/resources/resource.hpp" // Para Resource
#include "core/rendering/screen.hpp" // Para Screen
#include "core/input/global_inputs.hpp" // Para check
#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 PaletteColor
#include "core/resources/resource.hpp" // Para Resource
#include "game/gameplay/options.hpp" // Para Options, SectionState, options, Section
#include "utils/defines.hpp" // Para GAME_SPEED
#include "utils/global_events.hpp" // Para check
#include "utils/utils.hpp" // Para PaletteColor
// Constructor
Logo::Logo()
@@ -30,7 +30,7 @@ Logo::Logo()
}
// Inicializa variables
options.section.section = Section::LOGO;
Options::section.section = Options::Scene::LOGO;
// Inicializa el vector de colores
const std::vector<Uint8> COLORS = {
@@ -206,7 +206,7 @@ void Logo::render() {
// Bucle para el logo del juego
void Logo::run() {
while (options.section.section == Section::LOGO) {
while (Options::section.section == Options::Scene::LOGO) {
update();
checkEvents();
render();
@@ -215,11 +215,11 @@ void Logo::run() {
// Termina la sección
void Logo::endSection() {
if (options.section.subsection == Subsection::LOGO_TO_TITLE) {
options.section.section = Section::TITLE;
if (Options::section.subsection == Options::SceneOptions::LOGO_TO_TITLE) {
Options::section.section = Options::Scene::TITLE;
}
else if (options.section.subsection == Subsection::LOGO_TO_INTRO) {
options.section.section = Section::LOADING_SCREEN;
else if (Options::section.subsection == Options::SceneOptions::LOGO_TO_INTRO) {
Options::section.section = Options::Scene::LOADING_SCREEN;
}
}

View File

@@ -4,18 +4,18 @@
#include <algorithm> // Para clamp
#include "game/gameplay/cheevos.hpp" // Para Cheevos, Achievement
#include "utils/defines.hpp" // Para PLAY_AREA_CENTER_X, GAMECANVAS_WIDTH
#include "utils/global_events.hpp" // Para check
#include "core/input/global_inputs.hpp" // Para check
#include "core/input/input.hpp" // Para Input, InputAction, INPUT_DO_NOT_ALLOW_REPEAT, REP...
#include "game/gameplay/options.hpp" // Para Options, options, SectionState, Section
#include "core/resources/resource.hpp" // Para Resource
#include "core/rendering/screen.hpp" // Para Screen
#include "core/input/global_inputs.hpp" // Para check
#include "core/input/input.hpp" // Para Input, InputAction, INPUT_DO_NOT_ALLOW_REPEAT, REP...
#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 "core/rendering/text.hpp" // Para Text, TEXT_CENTER, TEXT_COLOR
#include "utils/utils.hpp" // Para stringToColor, PaletteColor, playMusic
#include "core/rendering/text.hpp" // Para Text, TEXT_CENTER, TEXT_COLOR
#include "core/resources/resource.hpp" // Para Resource
#include "game/gameplay/cheevos.hpp" // Para Cheevos, Achievement
#include "game/gameplay/options.hpp" // Para Options, options, SectionState, Section
#include "utils/defines.hpp" // Para PLAY_AREA_CENTER_X, GAMECANVAS_WIDTH
#include "utils/global_events.hpp" // Para check
#include "utils/utils.hpp" // Para stringToColor, PaletteColor, playMusic
// Constructor
Title::Title()
@@ -23,11 +23,11 @@ Title::Title()
title_logo_sprite_(std::make_shared<SSprite>(title_logo_surface_, 29, 9, title_logo_surface_->getWidth(), title_logo_surface_->getHeight())),
loading_screen_surface_(Resource::get()->getSurface("loading_screen_color.gif")),
loading_screen_sprite_(std::make_shared<SSprite>(loading_screen_surface_, 0, 0, loading_screen_surface_->getWidth(), loading_screen_surface_->getHeight())),
bg_surface_(std::make_shared<Surface>(options.game.width, options.game.height)) {
bg_surface_(std::make_shared<Surface>(Options::game.width, Options::game.height)) {
// Inicializa variables
state_ = options.section.subsection == Subsection::TITLE_WITH_LOADING_SCREEN ? TitleState::SHOW_LOADING_SCREEN : TitleState::SHOW_MENU;
options.section.section = Section::TITLE;
options.section.subsection = Subsection::NONE;
state_ = Options::section.subsection == Options::SceneOptions::TITLE_WITH_LOADING_SCREEN ? TitleState::SHOW_LOADING_SCREEN : TitleState::SHOW_MENU;
Options::section.section = Options::Scene::TITLE;
Options::section.subsection = Options::SceneOptions::NONE;
initMarquee();
// Crea y rellena la textura para mostrar los logros
@@ -68,8 +68,8 @@ void Title::checkEvents() {
if (!show_cheevos_) {
switch (event.key.key) {
case SDLK_1:
options.section.section = Section::GAME;
options.section.subsection = Subsection::NONE;
Options::section.section = Options::Scene::GAME;
Options::section.subsection = Options::SceneOptions::NONE;
break;
case SDLK_2:
@@ -180,8 +180,8 @@ void Title::update() {
// Si el contador alcanza cierto valor, termina la seccion
if (counter_ == 2200) {
if (!show_cheevos_) {
options.section.section = Section::CREDITS;
options.section.subsection = Subsection::NONE;
Options::section.section = Options::Scene::CREDITS;
Options::section.subsection = Options::SceneOptions::NONE;
}
}
break;
@@ -228,7 +228,7 @@ void Title::render() {
// Bucle para el logo del juego
void Title::run() {
while (options.section.section == Section::TITLE) {
while (Options::section.section == Options::Scene::TITLE) {
update();
checkEvents();
render();

View File

@@ -7,14 +7,14 @@
#include <string> // Para string, basic_string
#include <vector> // Para vector
#include "external/jail_audio.h" // Para JA_PlaySound
#include "game/gameplay/options.hpp" // Para Options, options, NotificationPosition
#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_sprite.hpp" // Para SSprite
#include "core/rendering/surface.hpp" // Para Surface
#include "core/rendering/text.hpp" // Para Text, TEXT_CENTER, TEXT_COLOR
#include "utils/utils.hpp" // Para PaletteColor
#include "core/rendering/text.hpp" // Para Text, TEXT_CENTER, TEXT_COLOR
#include "core/resources/resource.hpp" // Para Resource
#include "external/jail_audio.h" // Para JA_PlaySound
#include "game/gameplay/options.hpp" // Para Options, options, NotificationPosition
#include "utils/utils.hpp" // Para PaletteColor
// [SINGLETON]
Notifier* Notifier::notifier_ = nullptr;
@@ -38,7 +38,7 @@ Notifier* Notifier::get() {
Notifier::Notifier(const std::string& icon_file, const std::string& text)
: icon_surface_(!icon_file.empty() ? Resource::get()->getSurface(icon_file) : nullptr),
text_(Resource::get()->getText(text)),
bg_color_(options.notifications.color),
bg_color_(Options::notifications.color),
stack_(false),
has_icons_(!icon_file.empty()) {}
@@ -62,7 +62,7 @@ void Notifier::update() {
switch (notification.state) {
case NotificationStatus::RISING: {
const int DIRECTION = (options.notifications.getVerticalPosition() == NotificationPosition::TOP) ? 1 : -1;
const int DIRECTION = (Options::notifications.getVerticalPosition() == Options::NotificationPosition::TOP) ? 1 : -1;
notification.rect.y += DIRECTION;
if (notification.rect.y == notification.y) {
@@ -80,7 +80,7 @@ void Notifier::update() {
}
case NotificationStatus::VANISHING: {
const int DIRECTION = (options.notifications.getVerticalPosition() == NotificationPosition::TOP) ? -1 : 1;
const int DIRECTION = (Options::notifications.getVerticalPosition() == Options::NotificationPosition::TOP) ? -1 : 1;
notification.rect.y += DIRECTION;
if (notification.rect.y == notification.y - notification.travel_dist) {
@@ -140,23 +140,23 @@ void Notifier::show(std::vector<std::string> texts, NotificationText text_is, Ui
const auto PADDING_IN_V = text_size / 2;
const int ICON_SPACE = icon >= 0 ? ICON_SIZE_ + PADDING_IN_H : 0;
text_is = ICON_SPACE > 0 ? NotificationText::LEFT : text_is;
const float WIDTH = options.game.width - (PADDING_OUT_ * 2);
const float WIDTH = Options::game.width - (PADDING_OUT_ * 2);
const float HEIGHT = (text_size * texts.size()) + (PADDING_IN_V * 2);
const auto SHAPE = NotificationShape::SQUARED;
// Posición horizontal
float desp_h = 0;
switch (options.notifications.getHorizontalPosition()) {
case NotificationPosition::LEFT:
switch (Options::notifications.getHorizontalPosition()) {
case Options::NotificationPosition::LEFT:
desp_h = PADDING_OUT_;
break;
case NotificationPosition::CENTER:
desp_h = ((options.game.width / 2) - (WIDTH / 2));
case Options::NotificationPosition::CENTER:
desp_h = ((Options::game.width / 2) - (WIDTH / 2));
break;
case NotificationPosition::RIGHT:
desp_h = options.game.width - WIDTH - PADDING_OUT_;
case Options::NotificationPosition::RIGHT:
desp_h = Options::game.width - WIDTH - PADDING_OUT_;
break;
default:
@@ -165,11 +165,11 @@ void Notifier::show(std::vector<std::string> texts, NotificationText text_is, Ui
}
// Posición vertical
const int DESP_V = (options.notifications.getVerticalPosition() == NotificationPosition::TOP) ? PADDING_OUT_ : options.game.height - HEIGHT - PADDING_OUT_;
const int DESP_V = (Options::notifications.getVerticalPosition() == Options::NotificationPosition::TOP) ? PADDING_OUT_ : Options::game.height - HEIGHT - PADDING_OUT_;
// Offset
const auto TRAVEL_DIST = HEIGHT + PADDING_OUT_;
const int TRAVEL_MOD = (options.notifications.getVerticalPosition() == NotificationPosition::TOP) ? 1 : -1;
const int TRAVEL_MOD = (Options::notifications.getVerticalPosition() == Options::NotificationPosition::TOP) ? 1 : -1;
const int OFFSET = !notifications_.empty() ? notifications_.back().y + TRAVEL_MOD * notifications_.back().travel_dist : DESP_V;
// Crea la notificacion
@@ -183,7 +183,7 @@ void Notifier::show(std::vector<std::string> texts, NotificationText text_is, Ui
n.texts = texts;
n.shape = SHAPE;
n.display_duration = display_duration;
const float Y_POS = OFFSET + ((options.notifications.getVerticalPosition() == NotificationPosition::TOP) ? -TRAVEL_DIST : TRAVEL_DIST);
const float Y_POS = OFFSET + ((Options::notifications.getVerticalPosition() == Options::NotificationPosition::TOP) ? -TRAVEL_DIST : TRAVEL_DIST);
n.rect = {desp_h, Y_POS, WIDTH, HEIGHT};
// Crea la textura