style: deixant guapetes les capçaleres de les classes
This commit is contained in:
@@ -35,7 +35,7 @@ void handleQuit() {
|
||||
}
|
||||
} else {
|
||||
// Si la notificación de salir no está activa, muestra la notificación
|
||||
Notifier::get()->show({CODE}, NotificationText::CENTER, 2000, -1, true, CODE);
|
||||
Notifier::get()->show({CODE}, Notifier::TextAlign::CENTER, 2000, -1, true, CODE);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -59,50 +59,50 @@ void handleSkipSection() {
|
||||
|
||||
void handleToggleBorder() {
|
||||
Screen::get()->toggleBorder();
|
||||
Notifier::get()->show({"BORDER " + std::string(Options::video.border.enabled ? "ENABLED" : "DISABLED")}, NotificationText::CENTER);
|
||||
Notifier::get()->show({"BORDER " + std::string(Options::video.border.enabled ? "ENABLED" : "DISABLED")}, Notifier::TextAlign::CENTER);
|
||||
}
|
||||
|
||||
void handleToggleVideoMode() {
|
||||
Screen::get()->toggleVideoMode();
|
||||
Notifier::get()->show({"FULLSCREEN " + std::string(static_cast<int>(Options::video.fullscreen) == 0 ? "DISABLED" : "ENABLED")}, NotificationText::CENTER);
|
||||
Notifier::get()->show({"FULLSCREEN " + std::string(static_cast<int>(Options::video.fullscreen) == 0 ? "DISABLED" : "ENABLED")}, Notifier::TextAlign::CENTER);
|
||||
}
|
||||
|
||||
void handleDecWindowZoom() {
|
||||
if (Screen::get()->decWindowZoom()) {
|
||||
Notifier::get()->show({"WINDOW ZOOM x" + std::to_string(Options::window.zoom)}, NotificationText::CENTER);
|
||||
Notifier::get()->show({"WINDOW ZOOM x" + std::to_string(Options::window.zoom)}, Notifier::TextAlign::CENTER);
|
||||
}
|
||||
}
|
||||
|
||||
void handleIncWindowZoom() {
|
||||
if (Screen::get()->incWindowZoom()) {
|
||||
Notifier::get()->show({"WINDOW ZOOM x" + std::to_string(Options::window.zoom)}, NotificationText::CENTER);
|
||||
Notifier::get()->show({"WINDOW ZOOM x" + std::to_string(Options::window.zoom)}, Notifier::TextAlign::CENTER);
|
||||
}
|
||||
}
|
||||
|
||||
void handleToggleShaders() {
|
||||
Screen::get()->toggleShaders();
|
||||
Notifier::get()->show({"SHADERS " + std::string(Options::video.shaders ? "ENABLED" : "DISABLED")}, NotificationText::CENTER);
|
||||
Notifier::get()->show({"SHADERS " + std::string(Options::video.shaders ? "ENABLED" : "DISABLED")}, Notifier::TextAlign::CENTER);
|
||||
}
|
||||
|
||||
void handleNextPalette() {
|
||||
Screen::get()->nextPalette();
|
||||
Notifier::get()->show({"PALETTE " + Options::video.palette}, NotificationText::CENTER);
|
||||
Notifier::get()->show({"PALETTE " + Options::video.palette}, Notifier::TextAlign::CENTER);
|
||||
}
|
||||
|
||||
void handlePreviousPalette() {
|
||||
Screen::get()->previousPalette();
|
||||
Notifier::get()->show({"PALETTE " + Options::video.palette}, NotificationText::CENTER);
|
||||
Notifier::get()->show({"PALETTE " + Options::video.palette}, Notifier::TextAlign::CENTER);
|
||||
}
|
||||
|
||||
void handleToggleIntegerScale() {
|
||||
Screen::get()->toggleIntegerScale();
|
||||
Screen::get()->setVideoMode(Options::video.fullscreen);
|
||||
Notifier::get()->show({"INTEGER SCALE " + std::string(Options::video.integer_scale ? "ENABLED" : "DISABLED")}, NotificationText::CENTER);
|
||||
Notifier::get()->show({"INTEGER SCALE " + std::string(Options::video.integer_scale ? "ENABLED" : "DISABLED")}, Notifier::TextAlign::CENTER);
|
||||
}
|
||||
|
||||
void handleToggleVSync() {
|
||||
Screen::get()->toggleVSync();
|
||||
Notifier::get()->show({"V-SYNC " + std::string(Options::video.vertical_sync ? "ENABLED" : "DISABLED")}, NotificationText::CENTER);
|
||||
Notifier::get()->show({"V-SYNC " + std::string(Options::video.vertical_sync ? "ENABLED" : "DISABLED")}, Notifier::TextAlign::CENTER);
|
||||
}
|
||||
|
||||
#ifdef _DEBUG
|
||||
@@ -112,7 +112,7 @@ void handleShowDebugInfo() {
|
||||
|
||||
void handleToggleDebug() {
|
||||
Debug::get()->toggleEnabled();
|
||||
Notifier::get()->show({"DEBUG " + std::string(Debug::get()->getEnabled() ? "ENABLED" : "DISABLED")}, NotificationText::CENTER);
|
||||
Notifier::get()->show({"DEBUG " + std::string(Debug::get()->getEnabled() ? "ENABLED" : "DISABLED")}, Notifier::TextAlign::CENTER);
|
||||
}
|
||||
#endif
|
||||
|
||||
|
||||
@@ -44,18 +44,18 @@ Cheevos::~Cheevos() {
|
||||
// Inicializa los logros
|
||||
void Cheevos::init() {
|
||||
cheevos_list_.clear();
|
||||
cheevos_list_.emplace_back(1, "SHINY THINGS", "Get 25% of the items", 2);
|
||||
cheevos_list_.emplace_back(2, "HALF THE WORK", "Get 50% of the items", 2);
|
||||
cheevos_list_.emplace_back(3, "GETTING THERE", "Get 75% of the items", 2);
|
||||
cheevos_list_.emplace_back(4, "THE COLLECTOR", "Get 100% of the items", 2);
|
||||
cheevos_list_.emplace_back(5, "WANDERING AROUND", "Visit 20 rooms", 2);
|
||||
cheevos_list_.emplace_back(6, "I GOT LOST", "Visit 40 rooms", 2);
|
||||
cheevos_list_.emplace_back(7, "I LIKE TO EXPLORE", "Visit all rooms", 2);
|
||||
cheevos_list_.emplace_back(8, "FINISH THE GAME", "Complete the game", 2);
|
||||
cheevos_list_.emplace_back(9, "I WAS SUCKED BY A HOLE", "Complete the game without entering the jail", 2);
|
||||
cheevos_list_.emplace_back(10, "MY LITTLE PROJECTS", "Complete the game with all items", 2);
|
||||
cheevos_list_.emplace_back(11, "I LIKE MY MULTICOLOURED FRIENDS", "Complete the game without dying", 2);
|
||||
cheevos_list_.emplace_back(12, "SHIT PROJECTS DONE FAST", "Complete the game in under 30 minutes", 2);
|
||||
cheevos_list_.emplace_back(Achievement{.id = 1, .caption = "SHINY THINGS", .description = "Get 25% of the items", .icon = 2});
|
||||
cheevos_list_.emplace_back(Achievement{.id = 2, .caption = "HALF THE WORK", .description = "Get 50% of the items", .icon = 2});
|
||||
cheevos_list_.emplace_back(Achievement{.id = 3, .caption = "GETTING THERE", .description = "Get 75% of the items", .icon = 2});
|
||||
cheevos_list_.emplace_back(Achievement{.id = 4, .caption = "THE COLLECTOR", .description = "Get 100% of the items", .icon = 2});
|
||||
cheevos_list_.emplace_back(Achievement{.id = 5, .caption = "WANDERING AROUND", .description = "Visit 20 rooms", .icon = 2});
|
||||
cheevos_list_.emplace_back(Achievement{.id = 6, .caption = "I GOT LOST", .description = "Visit 40 rooms", .icon = 2});
|
||||
cheevos_list_.emplace_back(Achievement{.id = 7, .caption = "I LIKE TO EXPLORE", .description = "Visit all rooms", .icon = 2});
|
||||
cheevos_list_.emplace_back(Achievement{.id = 8, .caption = "FINISH THE GAME", .description = "Complete the game", .icon = 2});
|
||||
cheevos_list_.emplace_back(Achievement{.id = 9, .caption = "I WAS SUCKED BY A HOLE", .description = "Complete the game without entering the jail", .icon = 2});
|
||||
cheevos_list_.emplace_back(Achievement{.id = 10, .caption = "MY LITTLE PROJECTS", .description = "Complete the game with all items", .icon = 2});
|
||||
cheevos_list_.emplace_back(Achievement{.id = 11, .caption = "I LIKE MY MULTICOLOURED FRIENDS", .description = "Complete the game without dying", .icon = 2});
|
||||
cheevos_list_.emplace_back(Achievement{.id = 12, .caption = "SHIT PROJECTS DONE FAST", .description = "Complete the game in under 30 minutes", .icon = 2});
|
||||
}
|
||||
|
||||
// Busca un logro por id y devuelve el indice
|
||||
@@ -82,7 +82,7 @@ void Cheevos::unlock(int id) {
|
||||
cheevos_list_.at(INDEX).completed = true;
|
||||
|
||||
// Mostrar notificación en la pantalla
|
||||
Notifier::get()->show({"ACHIEVEMENT UNLOCKED!", cheevos_list_.at(INDEX).caption}, NotificationText::CENTER, CHEEVO_NOTIFICATION_DURATION /*, cheevos_list_.at(INDEX).icon*/);
|
||||
Notifier::get()->show({"ACHIEVEMENT UNLOCKED!", cheevos_list_.at(INDEX).caption}, Notifier::TextAlign::CENTER, Notifier::DURATION_CHEEVO /*, cheevos_list_.at(INDEX).icon*/);
|
||||
|
||||
// Guardar el estado de los logros
|
||||
saveToFile();
|
||||
@@ -160,8 +160,7 @@ void Cheevos::saveToFile() {
|
||||
|
||||
// Devuelve el número total de logros desbloqueados
|
||||
auto Cheevos::getTotalUnlockedAchievements() -> int {
|
||||
return std::count_if(cheevos_list_.begin(), cheevos_list_.end(),
|
||||
[](const auto& cheevo) { return cheevo.completed; });
|
||||
return std::count_if(cheevos_list_.begin(), cheevos_list_.end(), [](const auto& cheevo) { return cheevo.completed; });
|
||||
}
|
||||
|
||||
// Elimina el estado "no obtenible"
|
||||
|
||||
@@ -4,88 +4,52 @@
|
||||
#include <utility>
|
||||
#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
|
||||
|
||||
// Constructor vacío
|
||||
Achievement()
|
||||
: id(0),
|
||||
icon(0),
|
||||
completed(false),
|
||||
obtainable(true) {}
|
||||
|
||||
// Constructor parametrizado
|
||||
Achievement(int id, std::string caption, std::string description, int icon, bool completed = false, bool obtainable = true)
|
||||
: id(id),
|
||||
caption(std::move(caption)),
|
||||
description(std::move(description)),
|
||||
icon(icon),
|
||||
completed(completed),
|
||||
obtainable(obtainable) {}
|
||||
};
|
||||
|
||||
class Cheevos {
|
||||
public:
|
||||
// Tipos anidados (públicos porque se usan en la interfaz)
|
||||
struct Achievement {
|
||||
int id{0}; // Identificador del logro
|
||||
std::string caption{}; // Texto con el nombre del logro
|
||||
std::string description{}; // Texto que describe el logro
|
||||
int icon{0}; // Indice del icono a utilizar en la notificación
|
||||
bool completed{false}; // Indica si se ha obtenido el logro
|
||||
bool obtainable{true}; // Indica si se puede obtener el logro
|
||||
};
|
||||
|
||||
using Achievements = std::vector<Achievement>; // Type alias para vector de logros
|
||||
|
||||
// Gestión singleton
|
||||
static void init(const std::string& file); // Inicialización
|
||||
static void destroy(); // Destrucción
|
||||
static auto get() -> Cheevos*; // Acceso al singleton
|
||||
|
||||
// Gestión de logros
|
||||
void unlock(int id); // Desbloquea un logro
|
||||
void setUnobtainable(int id); // Invalida un logro
|
||||
void clearUnobtainableState(); // Elimina el estado "no obtenible"
|
||||
void enable(bool value) { enabled_ = value; } // Habilita o deshabilita los logros
|
||||
|
||||
// Consultas
|
||||
[[nodiscard]] auto list() const -> const Achievements& { return cheevos_list_; } // Lista los logros
|
||||
auto getTotalUnlockedAchievements() -> int; // Devuelve logros desbloqueados
|
||||
auto size() -> int { return cheevos_list_.size(); } // Devuelve número total de logros
|
||||
|
||||
private:
|
||||
// [SINGLETON] Objeto privado
|
||||
static Cheevos* cheevos;
|
||||
// Constantes singleton
|
||||
static Cheevos* cheevos; // [SINGLETON] Objeto privado
|
||||
|
||||
// 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
|
||||
// Métodos privados
|
||||
void init(); // Inicializa los logros
|
||||
auto find(int id) -> int; // Busca un logro por id y devuelve el índice
|
||||
void loadFromFile(); // Carga el estado de los logros desde un fichero
|
||||
void saveToFile(); // Guarda el estado de los logros en un fichero
|
||||
|
||||
// Inicializa los logros
|
||||
void init();
|
||||
|
||||
// Busca un logro por id y devuelve el índice
|
||||
auto find(int id) -> int;
|
||||
|
||||
// Carga el estado de los logros desde un fichero
|
||||
void loadFromFile();
|
||||
|
||||
// Guarda el estado de los logros en un fichero
|
||||
void saveToFile();
|
||||
|
||||
// Constructor
|
||||
// Constructor y destructor privados [SINGLETON]
|
||||
explicit Cheevos(std::string file);
|
||||
|
||||
// Destructor
|
||||
~Cheevos();
|
||||
|
||||
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] Con este método obtenemos el objeto y podemos trabajar con él
|
||||
static auto get() -> Cheevos*;
|
||||
|
||||
// Desbloquea un logro
|
||||
void unlock(int id);
|
||||
|
||||
// Invalida un logro
|
||||
void setUnobtainable(int id);
|
||||
|
||||
// Elimina el estado "no obtenible"
|
||||
void clearUnobtainableState();
|
||||
|
||||
// Habilita o deshabilita los logros
|
||||
void enable(bool value) { enabled_ = value; }
|
||||
|
||||
// Lista los logros
|
||||
[[nodiscard]] auto list() const -> const std::vector<Achievement>& { return cheevos_list_; }
|
||||
|
||||
// Devuelve el número total de logros desbloqueados
|
||||
auto getTotalUnlockedAchievements() -> int;
|
||||
|
||||
// Devuelve el número total de logros
|
||||
auto size() -> int { return cheevos_list_.size(); }
|
||||
// Variables miembro
|
||||
Achievements 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
|
||||
};
|
||||
|
||||
@@ -21,9 +21,9 @@ auto ItemTracker::get() -> ItemTracker* {
|
||||
// Comprueba si el objeto ya ha sido cogido
|
||||
auto ItemTracker::hasBeenPicked(const std::string& name, SDL_FPoint pos) -> bool {
|
||||
// Primero busca si ya hay una entrada con ese nombre
|
||||
if (const int INDEX = findByName(name); INDEX != -1) {
|
||||
if (const int INDEX = findByName(name); INDEX != NOT_FOUND) {
|
||||
// Luego busca si existe ya una entrada con esa posición
|
||||
if (findByPos(INDEX, pos) != -1) {
|
||||
if (findByPos(INDEX, pos) != NOT_FOUND) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -36,12 +36,12 @@ void ItemTracker::addItem(const std::string& name, SDL_FPoint pos) {
|
||||
// Comprueba si el objeto no ha sido recogido con anterioridad
|
||||
if (!hasBeenPicked(name, pos)) {
|
||||
// Primero busca si ya hay una entrada con ese nombre
|
||||
if (const int INDEX = findByName(name); INDEX != -1) {
|
||||
item_list_.at(INDEX).pos.push_back(pos);
|
||||
if (const int INDEX = findByName(name); INDEX != NOT_FOUND) {
|
||||
items_.at(INDEX).pos.push_back(pos);
|
||||
}
|
||||
// En caso contrario crea la entrada
|
||||
else {
|
||||
item_list_.emplace_back(name, pos);
|
||||
items_.emplace_back(name, pos);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -50,26 +50,26 @@ void ItemTracker::addItem(const std::string& name, SDL_FPoint pos) {
|
||||
auto ItemTracker::findByName(const std::string& name) -> int {
|
||||
int i = 0;
|
||||
|
||||
for (const auto& l : item_list_) {
|
||||
if (l.name == name) {
|
||||
for (const auto& item : items_) {
|
||||
if (item.name == name) {
|
||||
return i;
|
||||
}
|
||||
i++;
|
||||
}
|
||||
|
||||
return -1;
|
||||
return NOT_FOUND;
|
||||
}
|
||||
|
||||
// Busca una entrada en la lista por posición
|
||||
auto ItemTracker::findByPos(int index, SDL_FPoint pos) -> int {
|
||||
int i = 0;
|
||||
|
||||
for (const auto& l : item_list_[index].pos) {
|
||||
if ((l.x == pos.x) && (l.y == pos.y)) {
|
||||
for (const auto& item : items_[index].pos) {
|
||||
if ((item.x == pos.x) && (item.y == pos.y)) {
|
||||
return i;
|
||||
}
|
||||
i++;
|
||||
}
|
||||
|
||||
return -1;
|
||||
return NOT_FOUND;
|
||||
}
|
||||
@@ -6,50 +6,44 @@
|
||||
#include <utility>
|
||||
#include <vector> // Para vector
|
||||
|
||||
struct ItemTrackerData {
|
||||
std::string name; // Nombre de la habitación donde se encuentra el objeto
|
||||
std::vector<SDL_FPoint> pos; // Lista de objetos cogidos de la habitación
|
||||
|
||||
// Constructor
|
||||
ItemTrackerData(std::string name, const SDL_FPoint& position)
|
||||
: name(std::move(name)) {
|
||||
pos.push_back(position);
|
||||
}
|
||||
};
|
||||
|
||||
class ItemTracker {
|
||||
public:
|
||||
// Gestión singleton
|
||||
static void init(); // Inicialización
|
||||
static void destroy(); // Destrucción
|
||||
static auto get() -> ItemTracker*; // Acceso al singleton
|
||||
|
||||
// Gestión de items
|
||||
auto hasBeenPicked(const std::string& name, SDL_FPoint pos) -> bool; // Comprueba si el objeto ya ha sido cogido
|
||||
void addItem(const std::string& name, SDL_FPoint pos); // Añade el objeto a la lista
|
||||
|
||||
private:
|
||||
// [SINGLETON] Objeto privado
|
||||
static ItemTracker* item_tracker;
|
||||
// Tipos anidados privados
|
||||
struct Data {
|
||||
std::string name{}; // Nombre de la habitación donde se encuentra el objeto
|
||||
std::vector<SDL_FPoint> pos{}; // Lista de objetos cogidos de la habitación
|
||||
|
||||
// Variables
|
||||
std::vector<ItemTrackerData> item_list_; // Lista con todos los objetos recogidos
|
||||
// Constructor para facilitar creación con posición inicial
|
||||
Data(std::string name, const SDL_FPoint& position)
|
||||
: name(std::move(name)) {
|
||||
pos.push_back(position);
|
||||
}
|
||||
};
|
||||
|
||||
// Busca una entrada en la lista por nombre
|
||||
auto findByName(const std::string& name) -> int;
|
||||
// Constantes privadas
|
||||
static constexpr int NOT_FOUND = -1; // Valor de retorno cuando no se encuentra un elemento
|
||||
|
||||
// Busca una entrada en la lista por posición
|
||||
auto findByPos(int index, SDL_FPoint pos) -> int;
|
||||
// Constantes singleton
|
||||
static ItemTracker* item_tracker; // [SINGLETON] Objeto privado
|
||||
|
||||
// Constructor
|
||||
// Métodos privados
|
||||
auto findByName(const std::string& name) -> int; // Busca una entrada en la lista por nombre
|
||||
auto findByPos(int index, SDL_FPoint pos) -> int; // Busca una entrada en la lista por posición
|
||||
|
||||
// Constructor y destructor privados [SINGLETON]
|
||||
ItemTracker() = default;
|
||||
|
||||
// Destructor
|
||||
~ItemTracker() = default;
|
||||
|
||||
public:
|
||||
// [SINGLETON] Crearemos el objeto con esta función estática
|
||||
static void init();
|
||||
|
||||
// [SINGLETON] Destruiremos el objeto con esta función estática
|
||||
static void destroy();
|
||||
|
||||
// [SINGLETON] Con este método obtenemos el objeto y podemos trabajar con él
|
||||
static auto get() -> ItemTracker*;
|
||||
|
||||
// Comprueba si el objeto ya ha sido cogido
|
||||
auto hasBeenPicked(const std::string& name, SDL_FPoint pos) -> bool;
|
||||
|
||||
// Añade el objeto a la lista de objetos cogidos
|
||||
void addItem(const std::string& name, SDL_FPoint pos);
|
||||
// Variables miembro
|
||||
std::vector<Data> items_; // Lista con todos los objetos recogidos
|
||||
};
|
||||
@@ -26,23 +26,12 @@ Room::Room(const std::string& room_path, std::shared_ptr<ScoreboardData> data)
|
||||
auto room = Resource::get()->getRoom(room_path);
|
||||
initializeRoom(*room);
|
||||
|
||||
// Abre la Jail si se da el caso
|
||||
openTheJail();
|
||||
|
||||
// Inicializa las superficies de colision
|
||||
initRoomSurfaces();
|
||||
|
||||
// Busca los tiles animados
|
||||
setAnimatedTiles();
|
||||
|
||||
// Crea la textura para el mapa de tiles de la habitación
|
||||
map_surface_ = std::make_shared<Surface>(PLAY_AREA_WIDTH, PLAY_AREA_HEIGHT);
|
||||
|
||||
// Pinta el mapa de la habitación en la textura
|
||||
fillMapTexture();
|
||||
|
||||
// Establece el color del borde
|
||||
Screen::get()->setBorderColor(stringToColor(border_color_));
|
||||
openTheJail(); // Abre la Jail si se da el caso
|
||||
initRoomSurfaces(); // Inicializa las superficies de colision
|
||||
setAnimatedTiles(); // Busca los tiles animados
|
||||
map_surface_ = std::make_shared<Surface>(PLAY_AREA_WIDTH, PLAY_AREA_HEIGHT); // Crea la textura para el mapa de tiles de la habitación
|
||||
fillMapTexture(); // Pinta el mapa de la habitación en la textura
|
||||
Screen::get()->setBorderColor(stringToColor(border_color_)); // Establece el color del borde
|
||||
}
|
||||
|
||||
void Room::initializeRoom(const Data& room) {
|
||||
@@ -867,17 +856,8 @@ auto Room::setEnemy(Enemy::Data* enemy, const std::string& key, const std::strin
|
||||
bool success = true;
|
||||
|
||||
try {
|
||||
/*if (key == "tileSetFile") {
|
||||
enemy->surface_path = value;
|
||||
} else */
|
||||
if (key == "animation") {
|
||||
enemy->animation_path = value;
|
||||
/* [DOC:29/10/2025] w i h ja no fan falta, se pilla del .ANI
|
||||
} else if (key == "width") {
|
||||
enemy->w = std::stoi(value);
|
||||
} else if (key == "height") {
|
||||
enemy->h = std::stoi(value);
|
||||
[/DOC] */
|
||||
} else if (key == "x") {
|
||||
enemy->x = std::stof(value) * TILE_SIZE;
|
||||
} else if (key == "y") {
|
||||
|
||||
@@ -33,31 +33,23 @@ class Room {
|
||||
ANIMATED
|
||||
};
|
||||
|
||||
struct AnimatedTile {
|
||||
std::shared_ptr<SurfaceSprite> sprite; // SurfaceSprite para dibujar el tile
|
||||
int x_orig = 0; // Posición X donde se encuentra el primer tile de la animación en la tilesheet
|
||||
};
|
||||
|
||||
struct Data {
|
||||
std::string number; // Numero de la habitación
|
||||
std::string name; // Nombre de la habitación
|
||||
std::string bg_color; // Color de fondo de la habitación
|
||||
std::string border_color; // Color del borde de la pantalla
|
||||
std::string item_color1; // Color 1 para los items de la habitación
|
||||
std::string item_color2; // Color 2 para los items de la habitación
|
||||
std::string upper_room; // Identificador de la habitación que se encuentra arriba
|
||||
std::string lower_room; // Identificador de la habitación que se encuentra abajo
|
||||
std::string left_room; // Identificador de la habitación que se encuentra a la izquierda
|
||||
std::string right_room; // Identificador de la habitación que se encuentra a la derecha
|
||||
std::string tile_set_file; // Imagen con los gráficos para la habitación
|
||||
std::string tile_map_file; // Fichero con el mapa de índices de tile
|
||||
int conveyor_belt_direction = 0; // Sentido en el que arrastran las superficies automáticas de la habitación
|
||||
std::vector<int> tile_map; // Índice de los tiles a dibujar en la habitación
|
||||
std::vector<Enemy::Data> enemies; // Listado con los enemigos de la habitación
|
||||
std::vector<Item::Data> items; // Listado con los items que hay en la habitación
|
||||
|
||||
// Constructor por defecto
|
||||
Data() = default;
|
||||
std::string number{}; // Numero de la habitación
|
||||
std::string name{}; // Nombre de la habitación
|
||||
std::string bg_color{}; // Color de fondo de la habitación
|
||||
std::string border_color{}; // Color del borde de la pantalla
|
||||
std::string item_color1{}; // Color 1 para los items de la habitación
|
||||
std::string item_color2{}; // Color 2 para los items de la habitación
|
||||
std::string upper_room{}; // Identificador de la habitación que se encuentra arriba
|
||||
std::string lower_room{}; // Identificador de la habitación que se encuentra abajo
|
||||
std::string left_room{}; // Identificador de la habitación que se encuentra a la izquierda
|
||||
std::string right_room{}; // Identificador de la habitación que se encuentra a la derecha
|
||||
std::string tile_set_file{}; // Imagen con los gráficos para la habitación
|
||||
std::string tile_map_file{}; // Fichero con el mapa de índices de tile
|
||||
int conveyor_belt_direction{0}; // Sentido en el que arrastran las superficies automáticas de la habitación
|
||||
std::vector<int> tile_map{}; // Índice de los tiles a dibujar en la habitación
|
||||
std::vector<Enemy::Data> enemies{}; // Listado con los enemigos de la habitación
|
||||
std::vector<Item::Data> items{}; // Listado con los items que hay en la habitación
|
||||
};
|
||||
|
||||
// Constructor y destructor
|
||||
@@ -95,12 +87,19 @@ class Room {
|
||||
static auto loadRoomTileFile(const std::string& file_path, bool verbose = false) -> std::vector<int>; // Carga las variables y texturas desde un fichero de mapa de tiles
|
||||
|
||||
private:
|
||||
// --- Constantes ---
|
||||
// Tipos anidados privados
|
||||
struct AnimatedTile {
|
||||
std::shared_ptr<SurfaceSprite> sprite{nullptr}; // SurfaceSprite para dibujar el tile
|
||||
int x_orig{0}; // Posición X donde se encuentra el primer tile de la animación en la tilesheet
|
||||
};
|
||||
|
||||
// Constantes
|
||||
static constexpr int TILE_SIZE = 8; // Ancho del tile en pixels
|
||||
static constexpr int MAP_WIDTH = 32; // Ancho del mapa en tiles
|
||||
static constexpr int MAP_HEIGHT = 16; // Alto del mapa en tiles
|
||||
static constexpr float CONVEYOR_FRAME_DURATION = 0.05F; // Duración de cada frame de conveyor belt (3 frames @ 60fps)
|
||||
|
||||
// --- Objetos y punteros ---
|
||||
// Objetos y punteros
|
||||
std::vector<std::shared_ptr<Enemy>> enemies_; // Listado con los enemigos de la habitación
|
||||
std::vector<std::shared_ptr<Item>> items_; // Listado con los items que hay en la habitación
|
||||
std::shared_ptr<Surface> surface_; // Textura con los graficos de la habitación
|
||||
@@ -121,21 +120,18 @@ class Room {
|
||||
std::string tile_set_file_; // Imagen con los graficos para la habitación
|
||||
std::string tile_map_file_; // Fichero con el mapa de indices de tile
|
||||
std::vector<int> tile_map_; // Indice de los tiles a dibujar en la habitación
|
||||
int conveyor_belt_direction_ = 0; // Sentido en el que arrastran las superficies automáticas de la habitación
|
||||
int conveyor_belt_direction_{0}; // Sentido en el que arrastran las superficies automáticas de la habitación
|
||||
std::vector<LineHorizontal> bottom_floors_; // Lista con las superficies inferiores de la habitación
|
||||
std::vector<LineHorizontal> top_floors_; // Lista con las superficies superiores de la habitación
|
||||
std::vector<LineVertical> left_walls_; // Lista con las superficies laterales de la parte izquierda de la habitación
|
||||
std::vector<LineVertical> right_walls_; // Lista con las superficies laterales de la parte derecha de la habitación
|
||||
std::vector<LineDiagonal> left_slopes_; // Lista con todas las rampas que suben hacia la izquierda
|
||||
std::vector<LineDiagonal> right_slopes_; // Lista con todas las rampas que suben hacia la derecha
|
||||
float time_accumulator_ = 0.0F; // Acumulador de tiempo para animaciones (time-based)
|
||||
bool is_paused_ = false; // Indica si el mapa esta en modo pausa
|
||||
|
||||
// Constantes de tiempo
|
||||
static constexpr float CONVEYOR_FRAME_DURATION = 0.05F; // Duración de cada frame de conveyor belt (3 frames @ 60fps)
|
||||
std::vector<AnimatedTile> animated_tiles_; // Vector con los indices de tiles animados
|
||||
std::vector<LineHorizontal> conveyor_belt_floors_; // Lista con las superficies automaticas de la habitación
|
||||
int tile_set_width_ = 0; // Ancho del tileset en tiles
|
||||
float time_accumulator_{0.0F}; // Acumulador de tiempo para animaciones (time-based)
|
||||
bool is_paused_{false}; // Indica si el mapa esta en modo pausa
|
||||
std::vector<AnimatedTile> animated_tiles_; // Vector con los indices de tiles animados
|
||||
std::vector<LineHorizontal> conveyor_belt_floors_; // Lista con las superficies automaticas de la habitación
|
||||
int tile_set_width_{0}; // Ancho del tileset en tiles
|
||||
|
||||
// --- Funciones ---
|
||||
void initializeRoom(const Data& room); // Inicializa los valores
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
// Comprueba si la habitación ya ha sido visitada
|
||||
auto RoomTracker::hasBeenVisited(const std::string& name) -> bool {
|
||||
return std::ranges::any_of(list_, [&name](const auto& l) { return l == name; });
|
||||
return std::ranges::any_of(rooms_, [&name](const auto& l) { return l == name; });
|
||||
}
|
||||
|
||||
// Añade la habitación a la lista
|
||||
@@ -12,7 +12,7 @@ auto RoomTracker::addRoom(const std::string& name) -> bool {
|
||||
// Comprueba si la habitación ya ha sido visitada
|
||||
if (!hasBeenVisited(name)) {
|
||||
// En caso contrario añádela a la lista
|
||||
list_.push_back(name);
|
||||
rooms_.push_back(name);
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
@@ -4,20 +4,14 @@
|
||||
#include <vector> // Para vector
|
||||
|
||||
class RoomTracker {
|
||||
private:
|
||||
// Variables
|
||||
std::vector<std::string> list_; // Lista con las habitaciones visitadas
|
||||
|
||||
// Comprueba si la habitación ya ha sido visitada
|
||||
auto hasBeenVisited(const std::string& name) -> bool;
|
||||
|
||||
public:
|
||||
// Constructor
|
||||
RoomTracker() = default;
|
||||
RoomTracker() = default; // Constructor
|
||||
~RoomTracker() = default; // Destructor
|
||||
|
||||
// Destructor
|
||||
~RoomTracker() = default;
|
||||
auto addRoom(const std::string& name) -> bool; // Añade la habitación a la lista
|
||||
|
||||
// Añade la habitación a la lista
|
||||
auto addRoom(const std::string& name) -> bool;
|
||||
private:
|
||||
auto hasBeenVisited(const std::string& name) -> bool; // Comprueba si ya ha sido visitada
|
||||
|
||||
std::vector<std::string> rooms_; // Lista con habitaciones visitadas
|
||||
};
|
||||
|
||||
@@ -21,9 +21,11 @@
|
||||
|
||||
// Constructor
|
||||
Credits::Credits()
|
||||
: shining_sprite_(std::make_shared<SurfaceAnimatedSprite>(Resource::get()->getAnimations("shine.ani"))),
|
||||
: text_surface_(std::make_shared<Surface>(Options::game.width, Options::game.height)),
|
||||
cover_surface_(std::make_shared<Surface>(Options::game.width, Options::game.height)),
|
||||
shining_sprite_(std::make_shared<SurfaceAnimatedSprite>(Resource::get()->getAnimations("shine.ani"))),
|
||||
delta_timer_(std::make_unique<DeltaTimer>()) {
|
||||
// Inicializa variables
|
||||
// Configura la escena
|
||||
SceneManager::current = SceneManager::Scene::CREDITS;
|
||||
SceneManager::options = SceneManager::Options::NONE;
|
||||
shining_sprite_->setPos({194, 174, 8, 8});
|
||||
@@ -31,12 +33,6 @@ Credits::Credits()
|
||||
// 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);
|
||||
|
||||
// Crea la textura para cubrir el rexto
|
||||
cover_surface_ = std::make_shared<Surface>(Options::game.width, Options::game.height);
|
||||
|
||||
// Escribe el texto en la textura
|
||||
fillTexture();
|
||||
}
|
||||
|
||||
@@ -19,7 +19,7 @@ class Credits {
|
||||
void run();
|
||||
|
||||
private:
|
||||
// --- Estados ---
|
||||
// --- Tipos anidados ---
|
||||
enum class State {
|
||||
REVEALING_TEXT,
|
||||
PAUSE_1,
|
||||
@@ -32,6 +32,11 @@ class Credits {
|
||||
EXITING
|
||||
};
|
||||
|
||||
struct Captions {
|
||||
std::string label; // Texto a escribir
|
||||
Uint8 color{0}; // Color del texto
|
||||
};
|
||||
|
||||
// --- Constantes de tiempo (basado en 60 FPS) ---
|
||||
static constexpr float REVEAL_PHASE_1_DURATION = 3.733F; // 224 frames @ 60fps
|
||||
static constexpr float PAUSE_DURATION = 1.667F; // 100 frames @ 60fps
|
||||
@@ -43,25 +48,8 @@ class Credits {
|
||||
static constexpr float SHINE_START_TIME = 12.833F; // 770 frames @ 60fps
|
||||
static constexpr float FADE_OUT_START = 19.167F; // 1150 frames @ 60fps
|
||||
static constexpr float REVEAL_SPEED = 60.0F; // counter equivalente por segundo @ 60fps
|
||||
struct Captions {
|
||||
std::string label; // Texto a escribir
|
||||
Uint8 color; // Color del texto
|
||||
};
|
||||
|
||||
// --- Objetos y punteros ---
|
||||
std::shared_ptr<Surface> text_surface_; // Textura para dibujar el texto
|
||||
std::shared_ptr<Surface> cover_surface_; // Textura para cubrir el texto
|
||||
std::shared_ptr<SurfaceAnimatedSprite> shining_sprite_; // Sprite para el brillo del corazón
|
||||
|
||||
// --- Variables ---
|
||||
std::unique_ptr<DeltaTimer> delta_timer_; // Temporizador delta para time-based update
|
||||
State state_ = State::REVEALING_TEXT; // Estado actual
|
||||
float state_time_ = 0.0F; // Tiempo acumulado en el estado actual
|
||||
float total_time_ = 0.0F; // Tiempo total acumulado
|
||||
float reveal_time_ = 0.0F; // Tiempo acumulado solo durante revelación (se congela en pausas)
|
||||
std::vector<Captions> texts_; // Vector con los textos
|
||||
|
||||
// --- Funciones ---
|
||||
// --- Métodos privados ---
|
||||
void update(); // Actualiza las variables
|
||||
void render(); // Dibuja en pantalla
|
||||
static void handleEvents(); // Comprueba el manejador de eventos
|
||||
@@ -70,4 +58,20 @@ class Credits {
|
||||
void transitionToState(State new_state); // Transición entre estados
|
||||
void iniTexts(); // Inicializa los textos
|
||||
void fillTexture(); // Escribe el texto en la textura
|
||||
|
||||
// --- Variables miembro ---
|
||||
// Recursos gráficos
|
||||
std::shared_ptr<Surface> text_surface_; // Textura para dibujar el texto
|
||||
std::shared_ptr<Surface> cover_surface_; // Textura para cubrir el texto
|
||||
std::shared_ptr<SurfaceAnimatedSprite> shining_sprite_; // Sprite para el brillo del corazón
|
||||
|
||||
// Temporizadores y estado
|
||||
std::unique_ptr<DeltaTimer> delta_timer_; // Temporizador delta para time-based update
|
||||
State state_{State::REVEALING_TEXT}; // Estado actual
|
||||
float state_time_{0.0F}; // Tiempo acumulado en el estado actual
|
||||
float total_time_{0.0F}; // Tiempo total acumulado
|
||||
float reveal_time_{0.0F}; // Tiempo acumulado solo durante revelación (se congela en pausas)
|
||||
|
||||
// Textos
|
||||
std::vector<Captions> texts_; // Vector con los textos
|
||||
};
|
||||
|
||||
@@ -19,7 +19,7 @@ class Ending {
|
||||
void run();
|
||||
|
||||
private:
|
||||
// --- Estados ---
|
||||
// --- Enumeraciones ---
|
||||
enum class State {
|
||||
WARMING_UP,
|
||||
SCENE_0,
|
||||
@@ -30,6 +30,32 @@ class Ending {
|
||||
ENDING
|
||||
};
|
||||
|
||||
// --- Estructuras ---
|
||||
struct EndingSurface {
|
||||
std::shared_ptr<Surface> image_surface; // Surface a mostrar
|
||||
std::shared_ptr<SurfaceSprite> image_sprite; // SSprite para mostrar la textura
|
||||
std::shared_ptr<Surface> cover_surface; // Surface que cubre a la otra textura
|
||||
std::shared_ptr<SurfaceSprite> cover_sprite; // SSprite para mostrar la textura que cubre a la otra textura
|
||||
int cover_clip_desp{0}; // Desplazamiento del spriteClip de la textura de cobertura
|
||||
int cover_clip_height{0}; // Altura del spriteClip de la textura de cobertura
|
||||
};
|
||||
|
||||
struct TextAndPosition {
|
||||
std::string caption; // Texto
|
||||
int pos{0}; // Posición
|
||||
};
|
||||
|
||||
struct TextIndex {
|
||||
int index{0}; // Índice del texto
|
||||
int trigger{0}; // Disparador temporal
|
||||
};
|
||||
|
||||
struct SceneData {
|
||||
std::vector<TextIndex> text_index; // Índices del vector de textos a mostrar y su disparador
|
||||
int picture_index{0}; // Índice del vector de imágenes a mostrar
|
||||
int counter_end{0}; // Valor del contador en el que finaliza la escena
|
||||
};
|
||||
|
||||
// --- Constantes de tiempo (basado en 60 FPS) ---
|
||||
static constexpr float WARMUP_DURATION = 3.333F; // 200 frames @ 60fps
|
||||
static constexpr float FADEOUT_DURATION = 1.667F; // 100 frames @ 60fps
|
||||
@@ -43,56 +69,13 @@ class Ending {
|
||||
static constexpr float TEXT_LAPSE = 1.333F; // 80 frames @ 60fps
|
||||
static constexpr float FADEOUT_START_OFFSET = 1.667F; // Inicio fade-out 100 frames antes del fin
|
||||
|
||||
// --- Estructuras ---
|
||||
struct EndingSurface // Estructura con dos texturas y sprites, uno para mostrar y el otro hace de cortinilla
|
||||
{
|
||||
std::shared_ptr<Surface> image_surface; // Surface a mostrar
|
||||
std::shared_ptr<SurfaceSprite> image_sprite; // SSprite para mostrar la textura
|
||||
std::shared_ptr<Surface> cover_surface; // Surface que cubre a la otra textura
|
||||
std::shared_ptr<SurfaceSprite> cover_sprite; // SSprite para mostrar la textura que cubre a la otra textura
|
||||
int cover_clip_desp; // Desplazamiento del spriteClip de la textura de cobertura
|
||||
int cover_clip_height; // Altura del spriteClip de la textura de cobertura
|
||||
};
|
||||
|
||||
struct TextAndPosition // Estructura con un texto y su posición en el eje Y
|
||||
{
|
||||
std::string caption; // Texto
|
||||
int pos; // Posición
|
||||
};
|
||||
|
||||
struct TextIndex {
|
||||
int index;
|
||||
int trigger;
|
||||
};
|
||||
|
||||
struct SceneData // Estructura para crear cada una de las escenas del final
|
||||
{
|
||||
std::vector<TextIndex> text_index; // Indices del vector de textos a mostrar y su disparador
|
||||
int picture_index; // Indice del vector de imagenes a mostrar
|
||||
int counter_end; // Valor del contador en el que finaliza la escena
|
||||
};
|
||||
|
||||
// --- Objetos y punteros ---
|
||||
std::shared_ptr<Surface> cover_surface_; // Surface para cubrir el texto
|
||||
|
||||
// --- Variables ---
|
||||
std::unique_ptr<DeltaTimer> delta_timer_; // Temporizador delta para time-based update
|
||||
State state_ = State::WARMING_UP; // Estado actual
|
||||
float state_time_ = 0.0F; // Tiempo acumulado en el estado actual
|
||||
float total_time_ = 0.0F; // Tiempo total acumulado desde el inicio
|
||||
float fadeout_time_ = 0.0F; // Tiempo acumulado para el fade-out
|
||||
std::vector<EndingSurface> sprite_texts_; // Vector con los sprites de texto con su cortinilla
|
||||
std::vector<EndingSurface> sprite_pics_; // Vector con los sprites de texto con su cortinilla
|
||||
int current_scene_ = 0; // Escena actual (0-4)
|
||||
std::vector<SceneData> scenes_; // Vector con los textos e imagenes de cada escena
|
||||
|
||||
// --- Funciones ---
|
||||
// --- Métodos ---
|
||||
void update(); // Actualiza el objeto
|
||||
void render(); // Dibuja el final en pantalla
|
||||
static void handleEvents(); // Comprueba el manejador de eventos
|
||||
static void handleInput(); // Comprueba las entradas
|
||||
void iniTexts(); // Inicializa los textos
|
||||
void iniPics(); // Inicializa las imagenes
|
||||
void iniPics(); // Inicializa las imágenes
|
||||
void iniScenes(); // Inicializa las escenas
|
||||
void updateState(float delta_time); // Actualiza la máquina de estados
|
||||
void transitionToState(State new_state); // Transición entre estados
|
||||
@@ -100,5 +83,20 @@ class Ending {
|
||||
void checkChangeScene(); // Comprueba si se ha de cambiar de escena
|
||||
void fillCoverTexture(); // Rellena la textura para la cortinilla
|
||||
void renderCoverTexture(); // Dibuja la cortinilla de cambio de escena
|
||||
void updateMusicVolume() const; // Actualiza el volumen de la musica
|
||||
void updateMusicVolume() const; // Actualiza el volumen de la música
|
||||
|
||||
// --- Variables miembro ---
|
||||
// Objetos y punteros a recursos
|
||||
std::shared_ptr<Surface> cover_surface_; // Surface para cubrir el texto
|
||||
std::unique_ptr<DeltaTimer> delta_timer_; // Timer para time-based update
|
||||
std::vector<EndingSurface> sprite_texts_; // Vector con los sprites de texto con su cortinilla
|
||||
std::vector<EndingSurface> sprite_pics_; // Vector con los sprites de imágenes con su cortinilla
|
||||
std::vector<SceneData> scenes_; // Vector con los textos e imágenes de cada escena
|
||||
|
||||
// Variables de estado
|
||||
State state_{State::WARMING_UP}; // Estado actual
|
||||
float state_time_{0.0F}; // Tiempo acumulado en el estado actual
|
||||
float total_time_{0.0F}; // Tiempo total acumulado desde el inicio
|
||||
float fadeout_time_{0.0F}; // Tiempo acumulado para el fade-out
|
||||
int current_scene_{0}; // Escena actual (0-4)
|
||||
};
|
||||
@@ -23,7 +23,8 @@
|
||||
// Constructor
|
||||
Ending2::Ending2()
|
||||
: delta_timer_(std::make_unique<DeltaTimer>()),
|
||||
state_(EndingState::PRE_CREDITS, STATE_PRE_CREDITS_DURATION) {
|
||||
state_{EndingState::PRE_CREDITS, STATE_PRE_CREDITS_DURATION} {
|
||||
// Establece la escena
|
||||
SceneManager::current = SceneManager::Scene::ENDING2;
|
||||
SceneManager::options = SceneManager::Options::NONE;
|
||||
|
||||
@@ -33,23 +34,13 @@ Ending2::Ending2()
|
||||
colors_.push_back(stringToColor(color));
|
||||
}
|
||||
|
||||
// Cambia el color del borde
|
||||
Screen::get()->setBorderColor(static_cast<Uint8>(PaletteColor::BLACK));
|
||||
|
||||
// Inicializa la lista de sprites
|
||||
iniSpriteList();
|
||||
|
||||
// Carga todos los sprites desde una lista
|
||||
loadSprites();
|
||||
|
||||
// Coloca los sprites en su sito
|
||||
placeSprites();
|
||||
|
||||
// Crea los sprites con las texturas con los textos
|
||||
createSpriteTexts();
|
||||
|
||||
// Crea los sprites con las texturas con los textos del final
|
||||
createTexts();
|
||||
Screen::get()->setBorderColor(static_cast<Uint8>(PaletteColor::BLACK));// Cambia el color del borde
|
||||
iniSpriteList();// Inicializa la lista de sprites
|
||||
loadSprites();// Carga todos los sprites desde una lista
|
||||
placeSprites();// Coloca los sprites en su sito
|
||||
createSpriteTexts();// Crea los sprites con las texturas con los textos
|
||||
createTexts();// Crea los sprites con las texturas con los textos del final
|
||||
}
|
||||
|
||||
// Actualiza el objeto
|
||||
|
||||
@@ -13,7 +13,7 @@ class DeltaTimer;
|
||||
|
||||
class Ending2 {
|
||||
public:
|
||||
// --- Constructor y Destructor --- ---
|
||||
// --- Constructor y Destructor ---
|
||||
Ending2();
|
||||
~Ending2() = default;
|
||||
|
||||
@@ -21,23 +21,18 @@ class Ending2 {
|
||||
void run();
|
||||
|
||||
private:
|
||||
// --- Enum para representar los estados del final ---
|
||||
// --- Enumeraciones ---
|
||||
enum class EndingState : int {
|
||||
PRE_CREDITS, // Estado previo a los créditos
|
||||
CREDITS, // Estado de los créditos
|
||||
POST_CREDITS, // Estado posterior a los créditos
|
||||
FADING, // Estado de fundido de los textos a negrp
|
||||
FADING, // Estado de fundido de los textos a negro
|
||||
};
|
||||
|
||||
// --- Estructura para controlar los estados y su duración ---
|
||||
// --- Estructuras ---
|
||||
struct State {
|
||||
EndingState state; // Estado actual
|
||||
float duration; // Duración en segundos para el estado actual
|
||||
|
||||
// Constructor parametrizado para inicializar la estructura
|
||||
State(EndingState initial_state, float state_duration)
|
||||
: state(initial_state),
|
||||
duration(state_duration) {}
|
||||
EndingState state{EndingState::PRE_CREDITS}; // Estado actual
|
||||
float duration{0.0F}; // Duración en segundos para el estado actual
|
||||
};
|
||||
|
||||
// --- Constantes ---
|
||||
@@ -56,21 +51,7 @@ class Ending2 {
|
||||
static constexpr float STATE_FADE_DURATION = 5.0F; // Duración del fade final en segundos
|
||||
static constexpr int MUSIC_FADE_DURATION = 3000; // Duración del fade de música en milisegundos (para Audio API)
|
||||
|
||||
// --- Objetos y punteros ---
|
||||
std::vector<std::shared_ptr<SurfaceAnimatedSprite>> sprites_; // Vector con todos los sprites a dibujar
|
||||
std::vector<std::shared_ptr<SurfaceMovingSprite>> sprite_texts_; // Vector con los sprites de texto de los sprites
|
||||
std::vector<std::shared_ptr<SurfaceMovingSprite>> texts_; // Vector con los sprites de texto
|
||||
std::unique_ptr<DeltaTimer> delta_timer_; // Temporizador delta para time-based update
|
||||
|
||||
// --- Variables ---
|
||||
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 state_time_ = 0.0F; // Tiempo acumulado en el estado actual
|
||||
State state_; // Controla el estado de la clase
|
||||
|
||||
// --- Fucniones ---
|
||||
// --- Métodos ---
|
||||
void update(); // Actualiza el objeto
|
||||
void render(); // Dibuja el final en pantalla
|
||||
static void handleEvents(); // Comprueba el manejador de eventos
|
||||
@@ -85,8 +66,25 @@ class Ending2 {
|
||||
void renderSprites(); // Dibuja los sprites
|
||||
void renderSpriteTexts(); // Dibuja los sprites con el texto
|
||||
void renderTexts(); // Dibuja los sprites con el texto del final
|
||||
void placeSprites(); // Coloca los sprites en su sito
|
||||
void placeSprites(); // Coloca los sprites en su sitio
|
||||
void createSpriteTexts(); // Crea los sprites con las texturas con los textos
|
||||
void createTexts(); // Crea los sprites con las texturas con los textos del final
|
||||
void updateFinalFade(); // Actualiza el fade final
|
||||
|
||||
// --- Variables miembro ---
|
||||
// Objetos y punteros a recursos
|
||||
std::vector<std::shared_ptr<SurfaceAnimatedSprite>> sprites_; // Vector con todos los sprites a dibujar
|
||||
std::vector<std::shared_ptr<SurfaceMovingSprite>> sprite_texts_; // Vector con los sprites de texto de los sprites
|
||||
std::vector<std::shared_ptr<SurfaceMovingSprite>> texts_; // Vector con los sprites de texto
|
||||
std::unique_ptr<DeltaTimer> delta_timer_; // Timer para time-based update
|
||||
|
||||
// Variables de estado
|
||||
State state_; // Controla el estado de la clase
|
||||
float state_time_{0.0F}; // Tiempo acumulado en el estado actual
|
||||
|
||||
// Variables auxiliares
|
||||
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.0F}; // El valor de ancho del sprite más ancho
|
||||
float sprite_max_height_{0.0F}; // El valor de alto del sprite más alto
|
||||
};
|
||||
|
||||
@@ -85,12 +85,12 @@ void Game::handleInput() {
|
||||
if (Input::get()->checkAction(InputAction::TOGGLE_MUSIC, Input::DO_NOT_ALLOW_REPEAT)) {
|
||||
board_->music = !board_->music;
|
||||
board_->music ? Audio::get()->resumeMusic() : Audio::get()->pauseMusic();
|
||||
Notifier::get()->show({"MUSIC " + std::string(board_->music ? "ENABLED" : "DISABLED")}, NotificationText::CENTER);
|
||||
Notifier::get()->show({"MUSIC " + std::string(board_->music ? "ENABLED" : "DISABLED")}, Notifier::TextAlign::CENTER);
|
||||
}
|
||||
|
||||
else if (Input::get()->checkAction(InputAction::PAUSE, Input::DO_NOT_ALLOW_REPEAT)) {
|
||||
togglePause();
|
||||
Notifier::get()->show({std::string(paused_ ? "GAME PAUSED" : "GAME RUNNING")}, NotificationText::CENTER);
|
||||
Notifier::get()->show({std::string(paused_ ? "GAME PAUSED" : "GAME RUNNING")}, Notifier::TextAlign::CENTER);
|
||||
}
|
||||
|
||||
GlobalInputs::handle();
|
||||
@@ -249,7 +249,7 @@ void Game::handleDebugEvents(const SDL_Event& event) {
|
||||
break;
|
||||
|
||||
case SDL_SCANCODE_7:
|
||||
Notifier::get()->show({"ACHIEVEMENT UNLOCKED!", "I LIKE MY MULTICOLOURED FRIENDS"}, NotificationText::CENTER, CHEEVO_NOTIFICATION_DURATION, -1, false, "F7");
|
||||
Notifier::get()->show({"ACHIEVEMENT UNLOCKED!", "I LIKE MY MULTICOLOURED FRIENDS"}, Notifier::TextAlign::CENTER, Notifier::DURATION_CHEEVO, -1, false, "F7");
|
||||
break;
|
||||
|
||||
default:
|
||||
|
||||
@@ -40,46 +40,12 @@ class Game {
|
||||
|
||||
// --- Estructuras ---
|
||||
struct DemoData {
|
||||
float time_accumulator; // Acumulador de tiempo para el modo demo
|
||||
int room_index; // Índice para el vector de habitaciones
|
||||
std::vector<std::string> rooms; // Listado con los mapas de la demo
|
||||
|
||||
// Constructor por defecto
|
||||
DemoData()
|
||||
: time_accumulator(0.0F),
|
||||
room_index(0),
|
||||
rooms({}) {}
|
||||
|
||||
// Constructor parametrizado
|
||||
DemoData(float time_accumulator, int room_index, const std::vector<std::string>& rooms)
|
||||
: time_accumulator(time_accumulator),
|
||||
room_index(room_index),
|
||||
rooms(rooms) {}
|
||||
float time_accumulator{0.0F}; // Acumulador de tiempo para el modo demo
|
||||
int room_index{0}; // Índice para el vector de habitaciones
|
||||
std::vector<std::string> rooms{}; // Listado con los mapas de la demo
|
||||
};
|
||||
|
||||
// --- Objetos y punteros ---
|
||||
std::shared_ptr<ScoreboardData> board_; // Estructura con los datos del marcador
|
||||
std::shared_ptr<Scoreboard> scoreboard_; // Objeto encargado de gestionar el marcador
|
||||
std::shared_ptr<RoomTracker> room_tracker_; // Lleva el control de las habitaciones visitadas
|
||||
std::shared_ptr<Room> room_; // Objeto encargado de gestionar cada habitación del juego
|
||||
std::shared_ptr<Player> player_; // Objeto con el jugador
|
||||
std::shared_ptr<Stats> stats_; // Objeto encargado de gestionar las estadísticas
|
||||
std::shared_ptr<Surface> room_name_surface_; // Textura para escribir el nombre de la habitación
|
||||
|
||||
// --- Variables ---
|
||||
Mode mode_; // Modo del juego
|
||||
DemoData demo_; // Variables para el modo demo
|
||||
DeltaTimer delta_timer_; // Timer para calcular delta time
|
||||
std::string current_room_; // Fichero de la habitación actual
|
||||
Player::SpawnData spawn_data_; // Lugar de la habitación donde aparece el jugador
|
||||
bool paused_ = false; // Indica si el juego se encuentra en pausa
|
||||
bool black_screen_ = false; // Indica si la pantalla está en negro. Se utiliza para la muerte del jugador
|
||||
float black_screen_time_ = 0.0F; // Tiempo acumulado en pantalla negra en segundos
|
||||
int total_items_; // Cantidad total de items que hay en el mapeado del juego
|
||||
SDL_FRect room_name_rect_; // Rectangulo donde pintar la textura con el nombre de la habitación
|
||||
float jail_restore_time_ = 0.0F; // Tiempo acumulado para restauración de vidas en la Jail
|
||||
|
||||
// --- Funciones ---
|
||||
// --- Métodos ---
|
||||
void update(); // Actualiza el juego, las variables, comprueba la entrada, etc.
|
||||
void render(); // Pinta los objetos en pantalla
|
||||
void handleEvents(); // Comprueba los eventos de la cola
|
||||
@@ -114,4 +80,31 @@ class Game {
|
||||
static void renderDebugInfo(); // Pone la información de debug en pantalla
|
||||
void handleDebugEvents(const SDL_Event& event); // Comprueba los eventos
|
||||
#endif
|
||||
|
||||
// --- Variables miembro ---
|
||||
// Objetos y punteros a recursos
|
||||
std::shared_ptr<ScoreboardData> board_; // Estructura con los datos del marcador
|
||||
std::shared_ptr<Scoreboard> scoreboard_; // Objeto encargado de gestionar el marcador
|
||||
std::shared_ptr<RoomTracker> room_tracker_; // Lleva el control de las habitaciones visitadas
|
||||
std::shared_ptr<Room> room_; // Objeto encargado de gestionar cada habitación del juego
|
||||
std::shared_ptr<Player> player_; // Objeto con el jugador
|
||||
std::shared_ptr<Stats> stats_; // Objeto encargado de gestionar las estadísticas
|
||||
std::shared_ptr<Surface> room_name_surface_; // Textura para escribir el nombre de la habitación
|
||||
|
||||
// Variables de estado del juego
|
||||
Mode mode_; // Modo del juego
|
||||
DeltaTimer delta_timer_; // Timer para calcular delta time
|
||||
std::string current_room_; // Fichero de la habitación actual
|
||||
Player::SpawnData spawn_data_; // Lugar de la habitación donde aparece el jugador
|
||||
int total_items_; // Cantidad total de items que hay en el mapeado del juego
|
||||
bool paused_{false}; // Indica si el juego se encuentra en pausa
|
||||
|
||||
// Variables de demo mode
|
||||
DemoData demo_; // Variables para el modo demo
|
||||
|
||||
// Variables de efectos visuales
|
||||
bool black_screen_{false}; // Indica si la pantalla está en negro. Se utiliza para la muerte del jugador
|
||||
float black_screen_time_{0.0F}; // Tiempo acumulado en pantalla negra en segundos
|
||||
SDL_FRect room_name_rect_; // Rectangulo donde pintar la textura con el nombre de la habitación
|
||||
float jail_restore_time_{0.0F}; // Tiempo acumulado para restauración de vidas en la Jail
|
||||
};
|
||||
@@ -17,7 +17,7 @@ class GameOver {
|
||||
void run();
|
||||
|
||||
private:
|
||||
// --- Estados ---
|
||||
// --- Enumeraciones ---
|
||||
enum class State {
|
||||
WAITING, // Espera inicial antes de empezar
|
||||
FADE_IN, // Fade in de colores desde black
|
||||
@@ -27,14 +27,14 @@ class GameOver {
|
||||
TRANSITION // Cambio a logo
|
||||
};
|
||||
|
||||
// --- Constantes de Duración (segundos) ---
|
||||
// --- Constantes de duración (segundos) ---
|
||||
static constexpr float WAITING_DURATION = 0.8F; // Espera inicial
|
||||
static constexpr float FADE_IN_DURATION = 0.32F; // Duración del fade in
|
||||
static constexpr float DISPLAY_DURATION = 4.64F; // Duración mostrando contenido
|
||||
static constexpr float FADE_OUT_DURATION = 0.32F; // Duración del fade out
|
||||
static constexpr float ENDING_DURATION = 1.12F; // Espera en negro antes de salir
|
||||
|
||||
// --- Constantes de Posición ---
|
||||
// --- Constantes de posición ---
|
||||
static constexpr int TEXT_Y = 32; // Posición Y del texto principal
|
||||
static constexpr int SPRITE_Y_OFFSET = 30; // Offset Y para sprites desde TEXT_Y
|
||||
static constexpr int PLAYER_X_OFFSET = 10; // Offset X del jugador desde el centro
|
||||
@@ -44,23 +44,26 @@ class GameOver {
|
||||
static constexpr int NIGHTMARE_TITLE_Y_OFFSET = 110; // Offset Y del título nightmare desde TEXT_Y
|
||||
static constexpr int NIGHTMARE_TEXT_Y_OFFSET = 120; // Offset Y del texto nightmare desde TEXT_Y
|
||||
|
||||
// --- Objetos y punteros ---
|
||||
std::shared_ptr<SurfaceAnimatedSprite> player_sprite_; // Sprite con el jugador
|
||||
std::shared_ptr<SurfaceAnimatedSprite> tv_sprite_; // Sprite con el televisor
|
||||
std::shared_ptr<DeltaTimer> delta_timer_; // Timer para time-based logic
|
||||
|
||||
// --- Variables ---
|
||||
State state_ = State::WAITING; // Estado actual de la escena
|
||||
float elapsed_time_ = 0.0F; // Tiempo transcurrido en el estado actual
|
||||
std::vector<Uint8> colors_; // Vector con los colores para el fade
|
||||
Uint8 color_; // Color usado para el texto y los sprites
|
||||
|
||||
// --- Funciones ---
|
||||
// --- Métodos ---
|
||||
void update(); // Actualiza el objeto
|
||||
void render(); // Dibuja el final en pantalla
|
||||
static void handleEvents(); // Comprueba el manejador de eventos
|
||||
static void handleInput(); // Comprueba las entradas
|
||||
void updateState(); // Actualiza el estado y transiciones
|
||||
void updateColor(); // Actualiza el color usado para renderizar los textos e imagenes
|
||||
void updateColor(); // Actualiza el color usado para renderizar
|
||||
void renderSprites(); // Dibuja los sprites
|
||||
|
||||
// --- Variables miembro ---
|
||||
// Objetos y punteros a recursos
|
||||
std::shared_ptr<SurfaceAnimatedSprite> player_sprite_; // Sprite con el jugador
|
||||
std::shared_ptr<SurfaceAnimatedSprite> tv_sprite_; // Sprite con el televisor
|
||||
std::shared_ptr<DeltaTimer> delta_timer_; // Timer para time-based logic
|
||||
|
||||
// Variables de estado de la escena
|
||||
State state_{State::WAITING}; // Estado actual de la escena
|
||||
float elapsed_time_{0.0F}; // Tiempo transcurrido en el estado actual
|
||||
|
||||
// Variables de efectos visuales
|
||||
std::vector<Uint8> colors_; // Vector con los colores para el fade
|
||||
Uint8 color_{0}; // Color actual para texto y sprites
|
||||
};
|
||||
@@ -12,6 +12,15 @@ class Surface; // Forward declaration
|
||||
|
||||
class LoadingScreen {
|
||||
public:
|
||||
// --- Constructor y Destructor ---
|
||||
LoadingScreen();
|
||||
~LoadingScreen();
|
||||
|
||||
// --- Bucle principal ---
|
||||
void run();
|
||||
|
||||
private:
|
||||
// --- Enumeraciones ---
|
||||
// Estados de la secuencia de carga
|
||||
enum class State {
|
||||
SILENT1, // Pausa inicial antes de empezar
|
||||
@@ -36,14 +45,6 @@ class LoadingScreen {
|
||||
CYAN
|
||||
};
|
||||
|
||||
// --- Constructor y Destructor ---
|
||||
LoadingScreen();
|
||||
~LoadingScreen();
|
||||
|
||||
// --- Bucle principal ---
|
||||
void run();
|
||||
|
||||
private:
|
||||
// --- Estructuras ---
|
||||
struct Carrier {
|
||||
float offset{0.0F}; // Offset para la carga de cabeceras
|
||||
@@ -77,25 +78,7 @@ class LoadingScreen {
|
||||
static constexpr int COLOR_BLOCK_SPACING = 8; // Espaciado entre bloques
|
||||
static constexpr int HEADER_DATAROW_HEIGHT = 9.0F; // Alto de las barras del borde de la carga de las cabeceras
|
||||
|
||||
// --- Objetos y punteros ---
|
||||
std::shared_ptr<Surface> mono_loading_screen_surface_; // Surface con la pantalla de carga en blanco y negro
|
||||
std::shared_ptr<Surface> color_loading_screen_surface_; // Surface con la pantalla de carga en color
|
||||
std::unique_ptr<SurfaceSprite> mono_loading_screen_sprite_; // SurfaceSprite para manejar la textura mono_loading_screen_surface_
|
||||
std::unique_ptr<SurfaceSprite> color_loading_screen_sprite_; // SurfaceSprite para manejar la textura color_loading_screen_surface_
|
||||
std::unique_ptr<SurfaceSprite> program_sprite_; // SurfaceSprite para manejar la textura con el noimbre del programa
|
||||
std::shared_ptr<Surface> screen_surface_; // Surface para dibujar la pantalla de carga
|
||||
std::unique_ptr<DeltaTimer> delta_timer_; // Timer para delta time
|
||||
|
||||
// --- Variables de estado ---
|
||||
State state_{State::SILENT1}; // Estado actual de la secuencia
|
||||
float state_time_{0.0F}; // Tiempo acumulado en el estado actual
|
||||
Border current_border_type_{Border::NONE}; // Tipo de borde actual
|
||||
std::array<int, MONO_TOTAL_LINES> line_index_; // El orden en el que se procesan las 192 líneas de la pantalla de carga
|
||||
SDL_FRect load_rect_{0.0F, 0.0F, 0.0F, 1.0F}; // Rectángulo para dibujar la pantalla de carga
|
||||
Carrier carrier_; // Estructura para los efectos de la carga de cabeceras
|
||||
Noise noise_; // Variaciones de ruido durante los silencios
|
||||
|
||||
// --- Funciones ---
|
||||
// --- Métodos ---
|
||||
void update(); // Actualiza las variables
|
||||
void render(); // Dibuja en pantalla
|
||||
static void handleEvents(); // Comprueba el manejador de eventos
|
||||
@@ -112,4 +95,25 @@ class LoadingScreen {
|
||||
void printProgramName(); // Escribe el nombre del programa
|
||||
void updateCarrier(float delta_time); // Actualiza la portadora
|
||||
void updateSilent(float delta_time); // Actualiza el ruido durante el tiempo de silencio
|
||||
|
||||
// --- Variables miembro ---
|
||||
// Objetos y punteros a recursos
|
||||
std::shared_ptr<Surface> mono_loading_screen_surface_; // Surface con la pantalla de carga en blanco y negro
|
||||
std::shared_ptr<Surface> color_loading_screen_surface_; // Surface con la pantalla de carga en color
|
||||
std::unique_ptr<SurfaceSprite> mono_loading_screen_sprite_; // SurfaceSprite para manejar la textura mono_loading_screen_surface_
|
||||
std::unique_ptr<SurfaceSprite> color_loading_screen_sprite_; // SurfaceSprite para manejar la textura color_loading_screen_surface_
|
||||
std::unique_ptr<SurfaceSprite> program_sprite_; // SurfaceSprite para manejar la textura con el nombre del programa
|
||||
std::shared_ptr<Surface> screen_surface_; // Surface para dibujar la pantalla de carga
|
||||
std::unique_ptr<DeltaTimer> delta_timer_; // Timer para delta time
|
||||
|
||||
// Variables de estado de la secuencia
|
||||
State state_{State::SILENT1}; // Estado actual de la secuencia
|
||||
float state_time_{0.0F}; // Tiempo acumulado en el estado actual
|
||||
Border current_border_type_{Border::NONE}; // Tipo de borde actual
|
||||
|
||||
// Arrays y estructuras auxiliares
|
||||
std::array<int, MONO_TOTAL_LINES> line_index_; // El orden en el que se procesan las 192 líneas de la pantalla de carga
|
||||
SDL_FRect load_rect_{0.0F, 0.0F, 0.0F, 1.0F}; // Rectángulo para dibujar la pantalla de carga
|
||||
Carrier carrier_; // Estructura para los efectos de la carga de cabeceras
|
||||
Noise noise_; // Variaciones de ruido durante los silencios
|
||||
};
|
||||
@@ -43,23 +43,7 @@ class Logo {
|
||||
static constexpr float JAILGAMES_SLIDE_DURATION = 0.8F; // Duración de la animación de slide-in (segundos)
|
||||
static constexpr int JAILGAMES_DEST_X = 37; // Posición X de destino para JAILGAMES
|
||||
|
||||
// --- Objetos y punteros ---
|
||||
std::shared_ptr<Surface> jailgames_surface_ = nullptr; // Textura con los graficos "JAILGAMES"
|
||||
std::shared_ptr<Surface> since_1998_surface_ = nullptr; // Textura con los graficos "Since 1998"
|
||||
std::vector<std::shared_ptr<SurfaceSprite>> jailgames_sprite_; // Vector con los sprites de cada linea que forman el bitmap JAILGAMES
|
||||
std::vector<int> jailgames_initial_x_; // Posiciones X iniciales de cada línea (para interpolación con easing)
|
||||
std::shared_ptr<SurfaceSprite> since_1998_sprite_ = nullptr; // SSprite para manejar la textura2
|
||||
Uint8 jailgames_color_ = 0; // Color para el sprite de "JAILGAMES"
|
||||
Uint8 since_1998_color_ = 0; // Color para el sprite de "Since 1998"
|
||||
|
||||
// --- Variables de estado ---
|
||||
std::vector<Uint8> color_; // Vector con los colores para el fadeF
|
||||
std::unique_ptr<DeltaTimer> delta_timer_ = nullptr; // Timer para delta time
|
||||
State state_ = State::INITIAL; // Estado actual de la secuencia
|
||||
float state_time_ = 0.0F; // Tiempo acumulado en el estado actual
|
||||
EasingFunction easing_function_; // Función de easing para la animación del logo
|
||||
|
||||
// --- Funciones ---
|
||||
// --- Métodos ---
|
||||
void update(); // Actualiza las variables
|
||||
void render(); // Dibuja en pantalla
|
||||
static void handleEvents(); // Comprueba el manejador de eventos
|
||||
@@ -72,4 +56,23 @@ class Logo {
|
||||
static void endSection(); // Termina la sección
|
||||
void initColors(); // Inicializa el vector de colores
|
||||
void initSprites(); // Crea los sprites de cada linea
|
||||
|
||||
// --- Variables miembro ---
|
||||
// Objetos y punteros a recursos
|
||||
std::shared_ptr<Surface> jailgames_surface_; // Textura con los graficos "JAILGAMES"
|
||||
std::shared_ptr<Surface> since_1998_surface_; // Textura con los graficos "Since 1998"
|
||||
std::vector<std::shared_ptr<SurfaceSprite>> jailgames_sprite_; // Vector con los sprites de cada linea que forman el bitmap JAILGAMES
|
||||
std::vector<int> jailgames_initial_x_; // Posiciones X iniciales de cada línea (para interpolación con easing)
|
||||
std::shared_ptr<SurfaceSprite> since_1998_sprite_; // SSprite para manejar la textura2
|
||||
std::unique_ptr<DeltaTimer> delta_timer_; // Timer para delta time
|
||||
|
||||
// Variables de estado de colores
|
||||
std::vector<Uint8> color_; // Vector con los colores para el fade
|
||||
Uint8 jailgames_color_{0}; // Color para el sprite de "JAILGAMES"
|
||||
Uint8 since_1998_color_{0}; // Color para el sprite de "Since 1998"
|
||||
|
||||
// Variables de estado de la secuencia
|
||||
State state_{State::INITIAL}; // Estado actual de la secuencia
|
||||
float state_time_{0.0F}; // Tiempo acumulado en el estado actual
|
||||
EasingFunction easing_function_; // Función de easing para la animación del logo
|
||||
};
|
||||
@@ -29,35 +29,23 @@ Title::Title()
|
||||
title_surface_(std::make_shared<Surface>(Options::game.width, Options::game.height)),
|
||||
delta_timer_(std::make_unique<DeltaTimer>()),
|
||||
marquee_text_(Resource::get()->getText("gauntlet")),
|
||||
menu_text_(Resource::get()->getText("gauntlet")),
|
||||
first_active_letter_(0),
|
||||
last_active_letter_(0),
|
||||
cheevos_scroll_velocity_(0.0F),
|
||||
state_time_(0.0F),
|
||||
fade_accumulator_(0.0F),
|
||||
exit_scene_(SceneManager::Scene::GAME),
|
||||
is_remapping_keyboard_(false),
|
||||
is_remapping_joystick_(false),
|
||||
remap_step_(0),
|
||||
axis_cooldown_(0.0F),
|
||||
remap_completed_(false) {
|
||||
// Inicializa variables
|
||||
temp_keys_[0] = temp_keys_[1] = temp_keys_[2] = SDL_SCANCODE_UNKNOWN;
|
||||
temp_buttons_[0] = temp_buttons_[1] = temp_buttons_[2] = -1;
|
||||
menu_text_(Resource::get()->getText("gauntlet")) {
|
||||
// Inicializa arrays con valores por defecto
|
||||
temp_keys_.fill(SDL_SCANCODE_UNKNOWN);
|
||||
temp_buttons_.fill(-1);
|
||||
|
||||
// Determina el estado inicial basado en opciones
|
||||
state_ = SceneManager::options == SceneManager::Options::TITLE_WITH_LOADING_SCREEN ? State::SHOW_LOADING_SCREEN : State::MAIN_MENU;
|
||||
|
||||
// Establece SceneManager
|
||||
SceneManager::current = SceneManager::Scene::TITLE;
|
||||
SceneManager::options = SceneManager::Options::NONE;
|
||||
initMarquee();
|
||||
|
||||
// Crea y rellena la textura para mostrar los logros
|
||||
createCheevosTexture();
|
||||
|
||||
// Cambia el color del borde
|
||||
Screen::get()->setBorderColor(static_cast<Uint8>(PaletteColor::BLACK));
|
||||
|
||||
// Inicia la musica
|
||||
playMusic("title.ogg");
|
||||
// Acciones iniciales
|
||||
initMarquee(); // Inicializa la marquesina
|
||||
createCheevosTexture(); // Crea y rellena la textura para mostrar los logros
|
||||
Screen::get()->setBorderColor(static_cast<Uint8>(PaletteColor::BLACK)); // Cambia el color del borde
|
||||
playMusic("title.ogg"); // Inicia la musica
|
||||
}
|
||||
|
||||
// Inicializa la marquesina
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
#include <SDL3/SDL.h>
|
||||
|
||||
#include <array> // Para std::array
|
||||
#include <memory> // Para shared_ptr
|
||||
#include <string> // Para string
|
||||
#include <vector> // Para vector
|
||||
@@ -40,13 +41,13 @@ class Title {
|
||||
};
|
||||
|
||||
// --- Constantes de tiempo (en segundos) ---
|
||||
static constexpr float SHOW_LOADING_DURATION = 5.0F; // Tiempo mostrando loading screen (antes 500 frames)
|
||||
static constexpr float FADE_STEP_INTERVAL = 0.05F; // Intervalo entre pasos de fade (antes cada 4 frames)
|
||||
static constexpr float POST_FADE_DELAY = 1.0F; // Delay después del fade (pantalla en negro)
|
||||
static constexpr float MAIN_MENU_IDLE_TIMEOUT = 20.0F; // Timeout para ir a créditos (antes 2200 frames)
|
||||
static constexpr float KEYBOARD_REMAP_DISPLAY_DELAY = 2.0F; // Tiempo mostrando teclas definidas antes de guardar
|
||||
static constexpr float MARQUEE_SPEED = 100.0F; // Velocidad de marquesina (pixels/segundo)
|
||||
static constexpr float CHEEVOS_SCROLL_MAX_SPEED = 180.0F; // Velocidad máxima de scroll de logros (pixels/segundo)
|
||||
static constexpr float SHOW_LOADING_DURATION = 5.0F; // Tiempo mostrando loading screen (antes 500 frames)
|
||||
static constexpr float FADE_STEP_INTERVAL = 0.05F; // Intervalo entre pasos de fade (antes cada 4 frames)
|
||||
static constexpr float POST_FADE_DELAY = 1.0F; // Delay después del fade (pantalla en negro)
|
||||
static constexpr float MAIN_MENU_IDLE_TIMEOUT = 20.0F; // Timeout para ir a créditos (antes 2200 frames)
|
||||
static constexpr float KEYBOARD_REMAP_DISPLAY_DELAY = 2.0F; // Tiempo mostrando teclas definidas antes de guardar
|
||||
static constexpr float MARQUEE_SPEED = 100.0F; // Velocidad de marquesina (pixels/segundo)
|
||||
static constexpr float CHEEVOS_SCROLL_MAX_SPEED = 180.0F; // Velocidad máxima de scroll de logros (pixels/segundo)
|
||||
static constexpr float CHEEVOS_SCROLL_ACCELERATION = 600.0F; // Aceleración del scroll (pixels/segundo²)
|
||||
static constexpr float CHEEVOS_SCROLL_DECELERATION = 800.0F; // Desaceleración del scroll (pixels/segundo²)
|
||||
|
||||
@@ -56,41 +57,7 @@ class Title {
|
||||
static constexpr float MARQUEE_Y = 184.0F; // Posición Y
|
||||
static constexpr float MARQUEE_LETTER_SPACING = 1.0F; // Espaciado entre letras
|
||||
|
||||
// --- Objetos y punteros ---
|
||||
std::shared_ptr<Surface> game_logo_surface_; // Textura con los graficos
|
||||
std::unique_ptr<SurfaceSprite> game_logo_sprite_; // SSprite para manejar la surface
|
||||
std::shared_ptr<Surface> loading_screen_surface_; // Surface con los gráficos de la pantalla de carga
|
||||
std::unique_ptr<SurfaceSprite> loading_screen_sprite_; // SSprite con los gráficos de la pantalla de carga
|
||||
std::shared_ptr<Surface> cheevos_surface_; // Textura con la lista de logros
|
||||
std::unique_ptr<SurfaceSprite> cheevos_sprite_; // SSprite para manejar la surface con la lista de logros
|
||||
std::shared_ptr<Surface> title_surface_; // Surface donde se dibuja toda la clase
|
||||
std::unique_ptr<DeltaTimer> delta_timer_; // Timer para delta time
|
||||
std::shared_ptr<Text> marquee_text_; // Texto para marquesina
|
||||
std::shared_ptr<Text> menu_text_; // Texto para los menus
|
||||
|
||||
// --- Variables de estado ---
|
||||
std::string long_text_; // Texto que aparece en la parte inferior del titulo
|
||||
std::vector<Glyph> letters_; // Vector con las letras de la marquesina
|
||||
int first_active_letter_; // Primera letra activa (optimización)
|
||||
int last_active_letter_; // Última letra activa (optimización)
|
||||
SDL_FRect cheevos_surface_view_; // Zona visible de la surface con el listado de logros
|
||||
float cheevos_scroll_velocity_; // Velocidad actual del scroll de logros (pixels/segundo)
|
||||
State state_; // Estado en el que se encuentra el bucle principal
|
||||
float state_time_; // Tiempo acumulado en el estado actual
|
||||
float fade_accumulator_; // Acumulador para controlar el fade por tiempo
|
||||
SceneManager::Scene exit_scene_; // Escena de destino al salir del título
|
||||
|
||||
// --- Variables para redefinir controles ---
|
||||
bool is_remapping_keyboard_; // True si estamos redefiniendo teclado
|
||||
bool is_remapping_joystick_; // True si estamos redefiniendo joystick
|
||||
int remap_step_; // Paso actual en la redefinicion (0=LEFT, 1=RIGHT, 2=JUMP)
|
||||
SDL_Scancode temp_keys_[3]; // Almacenamiento temporal de teclas capturadas
|
||||
int temp_buttons_[3]; // Almacenamiento temporal de botones de gamepad capturados
|
||||
std::string remap_error_message_; // Mensaje de error si la tecla/boton es invalido
|
||||
float axis_cooldown_; // Cooldown para evitar múltiples capturas de ejes
|
||||
bool remap_completed_; // True cuando se completa el remap (mostrar antes de guardar)
|
||||
|
||||
// --- Funciones ---
|
||||
// --- Métodos ---
|
||||
void update(); // Actualiza las variables
|
||||
void render(); // Dibuja en pantalla
|
||||
void handleEvents(); // Comprueba el manejador de eventos
|
||||
@@ -118,10 +85,49 @@ class Title {
|
||||
auto isKeyDuplicate(SDL_Scancode scancode, int current_step) -> bool; // Valida si una tecla esta duplicada
|
||||
auto isButtonDuplicate(int button, int current_step) -> bool; // Valida si un boton esta duplicado
|
||||
void applyKeyboardRemap(); // Aplica y guarda las teclas redefinidas
|
||||
void applyJoystickRemap(); // Aplica y guarda los botones del gamepad redestatic finidos
|
||||
static auto getActionName(int step) -> std::string; // Retorna el nombre de la accion (LEFT/RIGHstatic T/JUMP)
|
||||
void applyJoystickRemap(); // Aplica y guarda los botones del gamepad redefinidos
|
||||
static auto getActionName(int step) -> std::string; // Retorna el nombre de la accion (LEFT/RIGHT/JUMP)
|
||||
static auto getButtonName(int button) -> std::string; // Retorna el nombre amigable del boton del gamepad
|
||||
void createCheevosTexture(); // Crea y rellena la surface para mostrar los logros
|
||||
void resetCheevosScroll(); // Resetea el scroll de la lista de logros
|
||||
void fillTitleSurface(); // Dibuja los elementos en la surface
|
||||
|
||||
// --- Variables miembro ---
|
||||
// Objetos y punteros
|
||||
std::shared_ptr<Surface> game_logo_surface_; // Textura con los graficos
|
||||
std::unique_ptr<SurfaceSprite> game_logo_sprite_; // SSprite para manejar la surface
|
||||
std::shared_ptr<Surface> loading_screen_surface_; // Surface con los gráficos de la pantalla de carga
|
||||
std::unique_ptr<SurfaceSprite> loading_screen_sprite_; // SSprite con los gráficos de la pantalla de carga
|
||||
std::shared_ptr<Surface> cheevos_surface_; // Textura con la lista de logros
|
||||
std::unique_ptr<SurfaceSprite> cheevos_sprite_; // SSprite para manejar la surface con la lista de logros
|
||||
std::shared_ptr<Surface> title_surface_; // Surface donde se dibuja toda la clase
|
||||
std::unique_ptr<DeltaTimer> delta_timer_; // Timer para delta time
|
||||
std::shared_ptr<Text> marquee_text_; // Texto para marquesina
|
||||
std::shared_ptr<Text> menu_text_; // Texto para los menus
|
||||
|
||||
// Variables de estado de marquesina
|
||||
std::string long_text_; // Texto que aparece en la parte inferior del titulo
|
||||
std::vector<Glyph> letters_; // Vector con las letras de la marquesina
|
||||
int first_active_letter_{0}; // Primera letra activa (optimización)
|
||||
int last_active_letter_{0}; // Última letra activa (optimización)
|
||||
|
||||
// Variables de estado del menú de logros
|
||||
SDL_FRect cheevos_surface_view_; // Zona visible de la surface con el listado de logros
|
||||
float cheevos_scroll_velocity_{0.0F}; // Velocidad actual del scroll de logros (pixels/segundo)
|
||||
|
||||
// Variables de estado general
|
||||
State state_; // Estado en el que se encuentra el bucle principal
|
||||
float state_time_{0.0F}; // Tiempo acumulado en el estado actual
|
||||
float fade_accumulator_{0.0F}; // Acumulador para controlar el fade por tiempo
|
||||
SceneManager::Scene exit_scene_{SceneManager::Scene::GAME}; // Escena de destino al salir del título
|
||||
|
||||
// Variables para redefinir controles
|
||||
bool is_remapping_keyboard_{false}; // True si estamos redefiniendo teclado
|
||||
bool is_remapping_joystick_{false}; // True si estamos redefiniendo joystick
|
||||
int remap_step_{0}; // Paso actual en la redefinicion (0=LEFT, 1=RIGHT, 2=JUMP)
|
||||
std::array<SDL_Scancode, 3> temp_keys_; // Almacenamiento temporal de teclas capturadas
|
||||
std::array<int, 3> temp_buttons_; // Almacenamiento temporal de botones de gamepad capturados
|
||||
std::string remap_error_message_; // Mensaje de error si la tecla/boton es invalido
|
||||
float axis_cooldown_{0.0F}; // Cooldown para evitar múltiples capturas de ejes
|
||||
bool remap_completed_{false}; // True cuando se completa el remap (mostrar antes de guardar)
|
||||
};
|
||||
@@ -42,7 +42,6 @@ Notifier::Notifier(const std::string& icon_file, const std::string& text)
|
||||
text_(Resource::get()->getText(text)),
|
||||
delta_timer_(std::make_unique<DeltaTimer>()),
|
||||
bg_color_(Options::notifications.color),
|
||||
stack_(false),
|
||||
has_icons_(!icon_file.empty()) {}
|
||||
|
||||
// Dibuja las notificaciones por pantalla
|
||||
@@ -116,7 +115,7 @@ void Notifier::clearFinishedNotifications() {
|
||||
notifications_.erase(result.begin(), result.end());
|
||||
}
|
||||
|
||||
void Notifier::show(std::vector<std::string> texts, NotificationText text_is, Uint32 display_duration, int icon, bool can_be_removed, const std::string& code) {
|
||||
void Notifier::show(std::vector<std::string> texts, TextAlign text_is, Uint32 display_duration, int icon, bool can_be_removed, const std::string& code) {
|
||||
// Si no hay texto, acaba
|
||||
if (texts.empty()) {
|
||||
return;
|
||||
@@ -144,7 +143,7 @@ void Notifier::show(std::vector<std::string> texts, NotificationText text_is, Ui
|
||||
const auto PADDING_IN_H = TEXT_SIZE;
|
||||
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;
|
||||
text_is = ICON_SPACE > 0 ? TextAlign::LEFT : text_is;
|
||||
const float WIDTH = Options::game.width - (PADDING_OUT * 2);
|
||||
const float HEIGHT = (TEXT_SIZE * texts.size()) + (PADDING_IN_V * 2);
|
||||
const auto SHAPE = Shape::SQUARED;
|
||||
@@ -217,10 +216,10 @@ void Notifier::show(std::vector<std::string> texts, NotificationText text_is, Ui
|
||||
int iterator = 0;
|
||||
for (const auto& text : texts) {
|
||||
switch (text_is) {
|
||||
case NotificationText::LEFT:
|
||||
case TextAlign::LEFT:
|
||||
text_->writeColored(PADDING_IN_H + ICON_SPACE, PADDING_IN_V + (iterator * (TEXT_SIZE + 1)), text, COLOR);
|
||||
break;
|
||||
case NotificationText::CENTER:
|
||||
case TextAlign::CENTER:
|
||||
text_->writeDX(TEXT_CENTER | TEXT_COLOR, WIDTH / 2, PADDING_IN_V + (iterator * (TEXT_SIZE + 1)), text, 1, COLOR);
|
||||
break;
|
||||
default:
|
||||
|
||||
@@ -10,26 +10,40 @@ class Surface; // lines 10-10
|
||||
class Text; // lines 9-9
|
||||
class DeltaTimer; // lines 11-11
|
||||
|
||||
// Constantes
|
||||
constexpr Uint32 DEFAULT_NOTIFICATION_DURATION = 2000;
|
||||
constexpr Uint32 CHEEVO_NOTIFICATION_DURATION = 4000;
|
||||
|
||||
// Justificado para las notificaciones
|
||||
enum class NotificationText {
|
||||
LEFT,
|
||||
CENTER,
|
||||
};
|
||||
|
||||
class Notifier {
|
||||
private:
|
||||
public:
|
||||
// Constantes
|
||||
static constexpr float ICON_SIZE = 16.0F;
|
||||
static constexpr float PADDING_OUT = 0.0F;
|
||||
static constexpr float SLIDE_SPEED = 120.0F; // Pixels per second for slide animations
|
||||
static constexpr Uint32 DURATION_DEFAULT = 2000;
|
||||
static constexpr Uint32 DURATION_CHEEVO = 4000;
|
||||
|
||||
// [SINGLETON] Objeto notifier
|
||||
static Notifier* notifier;
|
||||
// Justificado para las notificaciones
|
||||
enum class TextAlign {
|
||||
LEFT,
|
||||
CENTER,
|
||||
};
|
||||
|
||||
// Gestión singleton
|
||||
static void init(const std::string& icon_file, const std::string& text); // Inicialización
|
||||
static void destroy(); // Destrucción
|
||||
static auto get() -> Notifier*; // Acceso al singleton
|
||||
|
||||
// Métodos principales
|
||||
void render(); // Renderizado
|
||||
void update(float delta_time); // Actualización lógica
|
||||
void show(
|
||||
std::vector<std::string> texts,
|
||||
TextAlign text_is = TextAlign::LEFT,
|
||||
Uint32 display_duration = DURATION_DEFAULT,
|
||||
int icon = -1,
|
||||
bool can_be_removed = true,
|
||||
const std::string& code = std::string()); // Mostrar notificación
|
||||
|
||||
// Consultas
|
||||
auto isActive() -> bool; // Indica si hay notificaciones activas
|
||||
auto getCodes() -> std::vector<std::string>; // Obtiene códigos de notificaciones
|
||||
|
||||
private:
|
||||
// Tipos anidados
|
||||
enum class Status {
|
||||
RISING,
|
||||
STAY,
|
||||
@@ -43,71 +57,44 @@ class Notifier {
|
||||
};
|
||||
|
||||
struct Notification {
|
||||
std::shared_ptr<Surface> surface{nullptr}; // Superficie asociada a la notificación
|
||||
std::shared_ptr<SurfaceSprite> sprite{nullptr}; // Sprite asociado para gráficos o animaciones
|
||||
std::vector<std::string> texts; // Lista de textos incluidos en la notificación
|
||||
Status state{Status::RISING}; // Estado actual de la notificación (RISING, SHOWING, etc.)
|
||||
Shape shape{Shape::SQUARED}; // Forma de la notificación (ej. SQUARED o ROUNDED)
|
||||
SDL_FRect rect{0, 0, 0, 0}; // Dimensiones y posición de la notificación en pantalla
|
||||
int y{0}; // Posición actual en el eje Y
|
||||
int travel_dist{0}; // Distancia a recorrer (por ejemplo, en animaciones)
|
||||
std::string code; // Código identificador único para esta notificación
|
||||
bool can_be_removed{true}; // Indica si la notificación puede ser eliminada
|
||||
int height{0}; // Altura de la notificación
|
||||
Uint32 start_time{0}; // Momento en que se creó la notificación
|
||||
Uint32 elapsed_time{0}; // Tiempo transcurrido desde la creación
|
||||
Uint32 display_duration{0}; // Duración total para mostrar la notificación
|
||||
|
||||
// Constructor
|
||||
explicit Notification() = default;
|
||||
std::shared_ptr<Surface> surface{nullptr};
|
||||
std::shared_ptr<SurfaceSprite> sprite{nullptr};
|
||||
std::vector<std::string> texts{};
|
||||
Status state{Status::RISING};
|
||||
Shape shape{Shape::SQUARED};
|
||||
SDL_FRect rect{0.0F, 0.0F, 0.0F, 0.0F};
|
||||
int y{0};
|
||||
int travel_dist{0};
|
||||
std::string code{};
|
||||
bool can_be_removed{true};
|
||||
int height{0};
|
||||
Uint32 start_time{0};
|
||||
Uint32 elapsed_time{0};
|
||||
Uint32 display_duration{0};
|
||||
};
|
||||
|
||||
std::shared_ptr<Surface> icon_surface_; // Textura para los iconos de las notificaciones
|
||||
std::shared_ptr<Text> text_; // Objeto para dibujar texto
|
||||
std::unique_ptr<DeltaTimer> delta_timer_; // Timer for frame-independent animations
|
||||
// Constantes
|
||||
static constexpr float ICON_SIZE = 16.0F;
|
||||
static constexpr float PADDING_OUT = 0.0F;
|
||||
static constexpr float SLIDE_SPEED = 120.0F; // Pixels per second for slide animations
|
||||
|
||||
// Variables
|
||||
Uint8 bg_color_; // Color de fondo de las notificaciones
|
||||
std::vector<Notification> notifications_; // La lista de notificaciones activas
|
||||
bool stack_; // Indica si las notificaciones se apilan
|
||||
bool has_icons_; // Indica si el notificador tiene textura para iconos
|
||||
// [SINGLETON] Objeto notifier
|
||||
static Notifier* notifier;
|
||||
|
||||
// Elimina las notificaciones finalizadas
|
||||
void clearFinishedNotifications();
|
||||
// Métodos privados
|
||||
void clearFinishedNotifications(); // Elimina las notificaciones finalizadas
|
||||
void clearNotifications(); // Finaliza y elimina todas las notificaciones activas
|
||||
|
||||
// Finaliza y elimnina todas las notificaciones activas
|
||||
void clearNotifications();
|
||||
|
||||
// [SINGLETON] Ahora el constructor y el destructor son privados, para no poder crear objetos notifier desde fuera
|
||||
|
||||
// Constructor
|
||||
// Constructor y destructor privados [SINGLETON]
|
||||
Notifier(const std::string& icon_file, const std::string& text);
|
||||
|
||||
// Destructor
|
||||
~Notifier() = default;
|
||||
|
||||
public:
|
||||
// [SINGLETON] Crearemos el objeto con esta función estática
|
||||
static void init(const std::string& icon_file, const std::string& text);
|
||||
|
||||
// [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 auto get() -> Notifier*;
|
||||
|
||||
// Dibuja las notificaciones por pantalla
|
||||
void render();
|
||||
|
||||
// Actualiza el estado de las notificaiones
|
||||
void update(float delta_time);
|
||||
|
||||
// Muestra una notificación de texto por pantalla
|
||||
void show(std::vector<std::string> texts, NotificationText text_is = NotificationText::LEFT, Uint32 display_duration = DEFAULT_NOTIFICATION_DURATION, int icon = -1, bool can_be_removed = true, const std::string& code = std::string());
|
||||
|
||||
// Indica si hay notificaciones activas
|
||||
auto isActive() -> bool;
|
||||
|
||||
// Obtiene los códigos de las notificaciones
|
||||
auto getCodes() -> std::vector<std::string>;
|
||||
// Variables miembro
|
||||
std::shared_ptr<Surface> icon_surface_; // Textura para los iconos
|
||||
std::shared_ptr<Text> text_; // Objeto para dibujar texto
|
||||
std::unique_ptr<DeltaTimer> delta_timer_; // Timer for frame-independent animations
|
||||
Uint8 bg_color_{0}; // Color de fondo de las notificaciones
|
||||
std::vector<Notification> notifications_; // Lista de notificaciones activas
|
||||
bool stack_{false}; // Indica si las notificaciones se apilan
|
||||
bool has_icons_{false}; // Indica si el notificador tiene textura para iconos
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user