clang-tidy readability-function-cognitive-complexity
clang-format
This commit is contained in:
@@ -13,7 +13,7 @@
|
||||
#include "utils.h" // Para printWithDots
|
||||
|
||||
// Carga las animaciones en un vector(Animations) desde un fichero
|
||||
auto loadAnimationsFromFile(const std::string &file_path) -> AnimationsFileBuffer {
|
||||
auto loadAnimationsFromFile(const std::string& file_path) -> AnimationsFileBuffer {
|
||||
std::ifstream file(file_path);
|
||||
if (!file) {
|
||||
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: Fichero no encontrado %s", file_path.c_str());
|
||||
@@ -34,7 +34,7 @@ auto loadAnimationsFromFile(const std::string &file_path) -> AnimationsFileBuffe
|
||||
}
|
||||
|
||||
// Constructor
|
||||
AnimatedSprite::AnimatedSprite(std::shared_ptr<Texture> texture, const std::string &file_path)
|
||||
AnimatedSprite::AnimatedSprite(std::shared_ptr<Texture> texture, const std::string& file_path)
|
||||
: MovingSprite(texture) {
|
||||
// Carga las animaciones
|
||||
if (!file_path.empty()) {
|
||||
@@ -44,7 +44,7 @@ AnimatedSprite::AnimatedSprite(std::shared_ptr<Texture> texture, const std::stri
|
||||
}
|
||||
|
||||
// Constructor
|
||||
AnimatedSprite::AnimatedSprite(std::shared_ptr<Texture> texture, const AnimationsFileBuffer &animations)
|
||||
AnimatedSprite::AnimatedSprite(std::shared_ptr<Texture> texture, const AnimationsFileBuffer& animations)
|
||||
: MovingSprite(texture) {
|
||||
if (!animations.empty()) {
|
||||
loadFromAnimationsFileBuffer(animations);
|
||||
@@ -52,7 +52,7 @@ AnimatedSprite::AnimatedSprite(std::shared_ptr<Texture> texture, const Animation
|
||||
}
|
||||
|
||||
// Obtiene el índice de la animación a partir del nombre
|
||||
auto AnimatedSprite::getIndex(const std::string &name) -> int {
|
||||
auto AnimatedSprite::getIndex(const std::string& name) -> int {
|
||||
auto iterator = animation_indices_.find(name);
|
||||
if (iterator != animation_indices_.end()) {
|
||||
// Si se encuentra la animación en el mapa, devuelve su índice
|
||||
@@ -100,7 +100,7 @@ auto AnimatedSprite::animationIsCompleted() -> bool {
|
||||
}
|
||||
|
||||
// Establece la animacion actual
|
||||
void AnimatedSprite::setCurrentAnimation(const std::string &name, bool reset) {
|
||||
void AnimatedSprite::setCurrentAnimation(const std::string& name, bool reset) {
|
||||
const auto NEW_ANIMATION = getIndex(name);
|
||||
if (current_animation_ != NEW_ANIMATION) {
|
||||
const auto OLD_ANIMATION = current_animation_;
|
||||
@@ -149,7 +149,7 @@ void AnimatedSprite::resetAnimation() {
|
||||
}
|
||||
|
||||
// Carga la animación desde un vector de cadenas
|
||||
void AnimatedSprite::loadFromAnimationsFileBuffer(const AnimationsFileBuffer &source) {
|
||||
void AnimatedSprite::loadFromAnimationsFileBuffer(const AnimationsFileBuffer& source) {
|
||||
AnimationConfig config;
|
||||
|
||||
size_t index = 0;
|
||||
@@ -202,7 +202,7 @@ void AnimatedSprite::updateFrameCalculations(AnimationConfig& config) {
|
||||
// Procesa un bloque completo de animación
|
||||
auto AnimatedSprite::processAnimationBlock(const AnimationsFileBuffer& source, size_t start_index, const AnimationConfig& config) -> size_t {
|
||||
Animation animation;
|
||||
size_t index = start_index + 1; // Salta la línea "[animation]"
|
||||
size_t index = start_index + 1; // Salta la línea "[animation]"
|
||||
|
||||
while (index < source.size()) {
|
||||
const std::string& line = source.at(index);
|
||||
|
||||
@@ -15,24 +15,24 @@ class Texture;
|
||||
|
||||
// Estructura de Animación
|
||||
struct Animation {
|
||||
static constexpr int DEFAULT_SPEED = 5;
|
||||
static constexpr int DEFAULT_SPEED = 5;
|
||||
|
||||
std::string name; // Nombre de la animación
|
||||
std::vector<SDL_FRect> frames; // Frames que componen la animación
|
||||
int speed{DEFAULT_SPEED}; // Velocidad de reproducción
|
||||
int loop{0}; // Frame de vuelta al terminar (-1 para no repetir)
|
||||
bool completed{false}; // Indica si la animación ha finalizado
|
||||
size_t current_frame{0}; // Frame actual en reproducción
|
||||
int counter{0}; // Contador para la animación
|
||||
std::string name; // Nombre de la animación
|
||||
std::vector<SDL_FRect> frames; // Frames que componen la animación
|
||||
int speed{DEFAULT_SPEED}; // Velocidad de reproducción
|
||||
int loop{0}; // Frame de vuelta al terminar (-1 para no repetir)
|
||||
bool completed{false}; // Indica si la animación ha finalizado
|
||||
size_t current_frame{0}; // Frame actual en reproducción
|
||||
int counter{0}; // Contador para la animación
|
||||
|
||||
Animation() = default;
|
||||
Animation() = default;
|
||||
};
|
||||
|
||||
struct AnimationConfig {
|
||||
float frame_width = 1.0F;
|
||||
float frame_height = 1.0F;
|
||||
int frames_per_row = 1;
|
||||
int max_tiles = 1;
|
||||
float frame_width = 1.0F;
|
||||
float frame_height = 1.0F;
|
||||
int frames_per_row = 1;
|
||||
int max_tiles = 1;
|
||||
};
|
||||
|
||||
// Alias de tipo para buffer de animaciones
|
||||
@@ -43,41 +43,41 @@ auto loadAnimationsFromFile(const std::string& file_path) -> AnimationsFileBuffe
|
||||
|
||||
// Clase AnimatedSprite: Sprite animado que hereda de MovingSprite
|
||||
class AnimatedSprite : public MovingSprite {
|
||||
public:
|
||||
// --- Constructores y destructor ---
|
||||
AnimatedSprite(std::shared_ptr<Texture> texture, const std::string& file_path);
|
||||
AnimatedSprite(std::shared_ptr<Texture> texture, const AnimationsFileBuffer& animations);
|
||||
explicit AnimatedSprite(std::shared_ptr<Texture> texture) : MovingSprite(texture) {}
|
||||
~AnimatedSprite() override = default;
|
||||
public:
|
||||
// --- Constructores y destructor ---
|
||||
AnimatedSprite(std::shared_ptr<Texture> texture, const std::string& file_path);
|
||||
AnimatedSprite(std::shared_ptr<Texture> texture, const AnimationsFileBuffer& animations);
|
||||
explicit AnimatedSprite(std::shared_ptr<Texture> texture) : MovingSprite(texture) {}
|
||||
~AnimatedSprite() override = default;
|
||||
|
||||
// --- Métodos principales ---
|
||||
void update() override; // Actualiza la animación
|
||||
// --- Métodos principales ---
|
||||
void update() override; // Actualiza la animación
|
||||
|
||||
// --- Control de animaciones ---
|
||||
void setCurrentAnimation(const std::string& name = "default", bool reset = true); // Establece la animación por nombre
|
||||
void setCurrentAnimation(int index = 0, bool reset = true); // Establece la animación por índice
|
||||
void resetAnimation(); // Reinicia la animación actual
|
||||
void setAnimationSpeed(size_t value); // Establece la velocidad de la animación
|
||||
auto getAnimationSpeed() const -> size_t { return animations_[current_animation_].speed; } // Obtiene la velocidad de la animación actual
|
||||
// --- Control de animaciones ---
|
||||
void setCurrentAnimation(const std::string& name = "default", bool reset = true); // Establece la animación por nombre
|
||||
void setCurrentAnimation(int index = 0, bool reset = true); // Establece la animación por índice
|
||||
void resetAnimation(); // Reinicia la animación actual
|
||||
void setAnimationSpeed(size_t value); // Establece la velocidad de la animación
|
||||
auto getAnimationSpeed() const -> size_t { return animations_[current_animation_].speed; } // Obtiene la velocidad de la animación actual
|
||||
|
||||
// --- Consultas ---
|
||||
auto animationIsCompleted() -> bool; // Comprueba si la animación ha terminado
|
||||
auto getIndex(const std::string& name) -> int; // Obtiene el índice de una animación por nombre
|
||||
// --- Consultas ---
|
||||
auto animationIsCompleted() -> bool; // Comprueba si la animación ha terminado
|
||||
auto getIndex(const std::string& name) -> int; // Obtiene el índice de una animación por nombre
|
||||
|
||||
protected:
|
||||
// --- Datos de animación ---
|
||||
std::vector<Animation> animations_; // Vector de animaciones disponibles
|
||||
int current_animation_ = 0; // Índice de la animación activa
|
||||
protected:
|
||||
// --- Datos de animación ---
|
||||
std::vector<Animation> animations_; // Vector de animaciones disponibles
|
||||
int current_animation_ = 0; // Índice de la animación activa
|
||||
|
||||
// --- Mapa para búsqueda rápida de animaciones por nombre ---
|
||||
std::unordered_map<std::string, int> animation_indices_;
|
||||
// --- Mapa para búsqueda rápida de animaciones por nombre ---
|
||||
std::unordered_map<std::string, int> animation_indices_;
|
||||
|
||||
// --- Métodos internos ---
|
||||
void animate(); // Calcula el frame correspondiente a la animación
|
||||
void loadFromAnimationsFileBuffer(const AnimationsFileBuffer& source); // Carga la animación desde un vector de cadenas
|
||||
void processConfigLine(const std::string& line, AnimationConfig& config); // Procesa una línea de configuración
|
||||
void updateFrameCalculations(AnimationConfig& config); // Actualiza los cálculos basados en las dimensiones del frame
|
||||
auto processAnimationBlock(const AnimationsFileBuffer& source, size_t start_index, const AnimationConfig& config) -> size_t; // Procesa un bloque completo de animación
|
||||
static void processAnimationParameter(const std::string& line, Animation& animation, const AnimationConfig& config); // Procesa un parámetro individual de animación
|
||||
static void parseFramesParameter(const std::string& frames_str, Animation& animation, const AnimationConfig& config); // Parsea el parámetro de frames (lista separada por comas)
|
||||
// --- Métodos internos ---
|
||||
void animate(); // Calcula el frame correspondiente a la animación
|
||||
void loadFromAnimationsFileBuffer(const AnimationsFileBuffer& source); // Carga la animación desde un vector de cadenas
|
||||
void processConfigLine(const std::string& line, AnimationConfig& config); // Procesa una línea de configuración
|
||||
void updateFrameCalculations(AnimationConfig& config); // Actualiza los cálculos basados en las dimensiones del frame
|
||||
auto processAnimationBlock(const AnimationsFileBuffer& source, size_t start_index, const AnimationConfig& config) -> size_t; // Procesa un bloque completo de animación
|
||||
static void processAnimationParameter(const std::string& line, Animation& animation, const AnimationConfig& config); // Procesa un parámetro individual de animación
|
||||
static void parseFramesParameter(const std::string& frames_str, Animation& animation, const AnimationConfig& config); // Parsea el parámetro de frames (lista separada por comas)
|
||||
};
|
||||
@@ -20,45 +20,45 @@ enum class AssetType : int {
|
||||
|
||||
// Clase Asset: gestor de recursos (singleton)
|
||||
class Asset { // Gestor de recursos (singleton)
|
||||
public:
|
||||
// --- Métodos de singleton ---
|
||||
static void init(const std::string &executable_path); // Inicializa el objeto Asset
|
||||
static void destroy(); // Libera el objeto Asset
|
||||
static auto get() -> Asset *; // Obtiene el puntero al objeto Asset
|
||||
Asset(const Asset &) = delete; // No se permite copiar
|
||||
auto operator=(const Asset &) -> Asset & = delete; // No se permite asignar
|
||||
public:
|
||||
// --- Métodos de singleton ---
|
||||
static void init(const std::string &executable_path); // Inicializa el objeto Asset
|
||||
static void destroy(); // Libera el objeto Asset
|
||||
static auto get() -> Asset *; // Obtiene el puntero al objeto Asset
|
||||
Asset(const Asset &) = delete; // No se permite copiar
|
||||
auto operator=(const Asset &) -> Asset & = delete; // No se permite asignar
|
||||
|
||||
// --- Métodos para la gestión de recursos ---
|
||||
void add(const std::string &file, AssetType type, bool required = true, bool absolute = false); // Añade un recurso a la lista
|
||||
[[nodiscard]] auto get(const std::string &text) const -> std::string; // Obtiene la ruta completa de un recurso a partir de su nombre
|
||||
[[nodiscard]] auto check() const -> bool; // Verifica la existencia de todos los recursos requeridos
|
||||
[[nodiscard]] auto getListByType(AssetType type) const -> std::vector<std::string>; // Devuelve una lista de archivos de un tipo concreto
|
||||
// --- Métodos para la gestión de recursos ---
|
||||
void add(const std::string &file, AssetType type, bool required = true, bool absolute = false); // Añade un recurso a la lista
|
||||
[[nodiscard]] auto get(const std::string &text) const -> std::string; // Obtiene la ruta completa de un recurso a partir de su nombre
|
||||
[[nodiscard]] auto check() const -> bool; // Verifica la existencia de todos los recursos requeridos
|
||||
[[nodiscard]] auto getListByType(AssetType type) const -> std::vector<std::string>; // Devuelve una lista de archivos de un tipo concreto
|
||||
|
||||
private:
|
||||
// --- Estructura interna para almacenar información de cada recurso ---
|
||||
struct AssetItem { // Estructura para cada recurso
|
||||
std::string file; // Ruta del fichero desde la raíz del directorio
|
||||
AssetType type; // Tipo de recurso
|
||||
bool required; // Indica si el fichero es obligatorio
|
||||
private:
|
||||
// --- Estructura interna para almacenar información de cada recurso ---
|
||||
struct AssetItem { // Estructura para cada recurso
|
||||
std::string file; // Ruta del fichero desde la raíz del directorio
|
||||
AssetType type; // Tipo de recurso
|
||||
bool required; // Indica si el fichero es obligatorio
|
||||
|
||||
AssetItem(std::string file_path, AssetType asset_type, bool is_required)
|
||||
: file(std::move(file_path)), type(asset_type), required(is_required) {} // Constructor
|
||||
};
|
||||
AssetItem(std::string file_path, AssetType asset_type, bool is_required)
|
||||
: file(std::move(file_path)), type(asset_type), required(is_required) {} // Constructor
|
||||
};
|
||||
|
||||
// --- Variables internas ---
|
||||
int longest_name_ = 0; // Longitud del nombre más largo
|
||||
std::vector<AssetItem> file_list_; // Lista con todas las rutas de recursos
|
||||
std::string executable_path_; // Ruta del ejecutable
|
||||
// --- Variables internas ---
|
||||
int longest_name_ = 0; // Longitud del nombre más largo
|
||||
std::vector<AssetItem> file_list_; // Lista con todas las rutas de recursos
|
||||
std::string executable_path_; // Ruta del ejecutable
|
||||
|
||||
// --- Métodos internos ---
|
||||
[[nodiscard]] static auto checkFile(const std::string &path) -> bool; // Verifica si un archivo existe (interno)
|
||||
[[nodiscard]] static auto getTypeName(AssetType type) -> std::string; // Devuelve el nombre textual del tipo de recurso (interno)
|
||||
// --- Métodos internos ---
|
||||
[[nodiscard]] static auto checkFile(const std::string &path) -> bool; // Verifica si un archivo existe (interno)
|
||||
[[nodiscard]] static auto getTypeName(AssetType type) -> std::string; // Devuelve el nombre textual del tipo de recurso (interno)
|
||||
|
||||
// --- Patrón Singleton ---
|
||||
explicit Asset(std::string executable_path)
|
||||
: executable_path_(std::move(executable_path)) {} // Constructor privado
|
||||
~Asset() = default; // Destructor
|
||||
// --- Patrón Singleton ---
|
||||
explicit Asset(std::string executable_path)
|
||||
: executable_path_(std::move(executable_path)) {} // Constructor privado
|
||||
~Asset() = default; // Destructor
|
||||
|
||||
// --- Singleton ---
|
||||
static Asset *instance; // Instancia singleton
|
||||
// --- Singleton ---
|
||||
static Asset *instance; // Instancia singleton
|
||||
};
|
||||
138
source/audio.h
138
source/audio.h
@@ -5,90 +5,90 @@
|
||||
|
||||
// Clase Audio: gestor de audio (singleton)
|
||||
class Audio {
|
||||
public:
|
||||
enum class Group : int {
|
||||
ALL = -1,
|
||||
GAME = 0,
|
||||
INTERFACE = 1
|
||||
};
|
||||
public:
|
||||
enum class Group : int {
|
||||
ALL = -1,
|
||||
GAME = 0,
|
||||
INTERFACE = 1
|
||||
};
|
||||
|
||||
// --- Constantes ---
|
||||
static constexpr int MAX_VOLUME = 100;
|
||||
static constexpr int MIN_VOLUME = 0;
|
||||
static constexpr int FREQUENCY = 48000;
|
||||
// --- Constantes ---
|
||||
static constexpr int MAX_VOLUME = 100;
|
||||
static constexpr int MIN_VOLUME = 0;
|
||||
static constexpr int FREQUENCY = 48000;
|
||||
|
||||
// --- Métodos de singleton ---
|
||||
static void init(); // Inicializa el objeto Audio
|
||||
static void destroy(); // Libera el objeto Audio
|
||||
static auto get() -> Audio *; // Obtiene el puntero al objeto Audio
|
||||
Audio(const Audio &) = delete; // Evitar copia
|
||||
auto operator=(const Audio &) -> Audio & = delete; // Evitar asignación
|
||||
// --- Métodos de singleton ---
|
||||
static void init(); // Inicializa el objeto Audio
|
||||
static void destroy(); // Libera el objeto Audio
|
||||
static auto get() -> Audio *; // Obtiene el puntero al objeto Audio
|
||||
Audio(const Audio &) = delete; // Evitar copia
|
||||
auto operator=(const Audio &) -> Audio & = delete; // Evitar asignación
|
||||
|
||||
// --- Control de Música ---
|
||||
void playMusic(const std::string &name, int loop = -1); // Reproducir música en bucle
|
||||
void pauseMusic(); // Pausar reproducción de música
|
||||
void stopMusic(); // Detener completamente la música
|
||||
void fadeOutMusic(int milliseconds) const; // Fundido de salida de la música
|
||||
// --- Control de Música ---
|
||||
void playMusic(const std::string &name, int loop = -1); // Reproducir música en bucle
|
||||
void pauseMusic(); // Pausar reproducción de música
|
||||
void stopMusic(); // Detener completamente la música
|
||||
void fadeOutMusic(int milliseconds) const; // Fundido de salida de la música
|
||||
|
||||
// --- Control de Sonidos ---
|
||||
void playSound(const std::string &name, Group group = Group::GAME) const; // Reproducir sonido puntual
|
||||
void stopAllSounds() const; // Detener todos los sonidos
|
||||
// --- Control de Sonidos ---
|
||||
void playSound(const std::string &name, Group group = Group::GAME) const; // Reproducir sonido puntual
|
||||
void stopAllSounds() const; // Detener todos los sonidos
|
||||
|
||||
// --- Configuración General ---
|
||||
void enable(bool value); // Establecer estado general
|
||||
void toggleEnabled() { enabled_ = !enabled_; } // Alternar estado general
|
||||
void applySettings(); // Aplica la configuración
|
||||
// --- Configuración General ---
|
||||
void enable(bool value); // Establecer estado general
|
||||
void toggleEnabled() { enabled_ = !enabled_; } // Alternar estado general
|
||||
void applySettings(); // Aplica la configuración
|
||||
|
||||
// --- Configuración de Sonidos ---
|
||||
void enableSound() { sound_enabled_ = true; } // Habilitar sonidos
|
||||
void disableSound() { sound_enabled_ = false; } // Deshabilitar sonidos
|
||||
void enableSound(bool value) { sound_enabled_ = value; } // Establecer estado de sonidos
|
||||
void toggleSound() { sound_enabled_ = !sound_enabled_; } // Alternar estado de sonidos
|
||||
// --- Configuración de Sonidos ---
|
||||
void enableSound() { sound_enabled_ = true; } // Habilitar sonidos
|
||||
void disableSound() { sound_enabled_ = false; } // Deshabilitar sonidos
|
||||
void enableSound(bool value) { sound_enabled_ = value; } // Establecer estado de sonidos
|
||||
void toggleSound() { sound_enabled_ = !sound_enabled_; } // Alternar estado de sonidos
|
||||
|
||||
// --- Configuración de Música ---
|
||||
void enableMusic() { music_enabled_ = true; } // Habilitar música
|
||||
void disableMusic() { music_enabled_ = false; } // Deshabilitar música
|
||||
void enableMusic(bool value) { music_enabled_ = value; } // Establecer estado de música
|
||||
void toggleMusic() { music_enabled_ = !music_enabled_; } // Alternar estado de música
|
||||
// --- Configuración de Música ---
|
||||
void enableMusic() { music_enabled_ = true; } // Habilitar música
|
||||
void disableMusic() { music_enabled_ = false; } // Deshabilitar música
|
||||
void enableMusic(bool value) { music_enabled_ = value; } // Establecer estado de música
|
||||
void toggleMusic() { music_enabled_ = !music_enabled_; } // Alternar estado de música
|
||||
|
||||
// --- Control de Volumen ---
|
||||
void setSoundVolume(int volume, Group group = Group::ALL) const; // Ajustar volumen de efectos
|
||||
void setMusicVolume(int volume) const; // Ajustar volumen de música
|
||||
// --- Control de Volumen ---
|
||||
void setSoundVolume(int volume, Group group = Group::ALL) const; // Ajustar volumen de efectos
|
||||
void setMusicVolume(int volume) const; // Ajustar volumen de música
|
||||
|
||||
private:
|
||||
enum class MusicState {
|
||||
PLAYING,
|
||||
PAUSED,
|
||||
STOPPED,
|
||||
};
|
||||
private:
|
||||
enum class MusicState {
|
||||
PLAYING,
|
||||
PAUSED,
|
||||
STOPPED,
|
||||
};
|
||||
|
||||
struct Music {
|
||||
MusicState state; // Estado actual de la música (reproduciendo, detenido, en pausa)
|
||||
std::string name; // Última pista de música reproducida
|
||||
bool loop; // Indica si la última pista de música se debe reproducir en bucle
|
||||
struct Music {
|
||||
MusicState state; // Estado actual de la música (reproduciendo, detenido, en pausa)
|
||||
std::string name; // Última pista de música reproducida
|
||||
bool loop; // Indica si la última pista de música se debe reproducir en bucle
|
||||
|
||||
// Constructor para inicializar la música con valores predeterminados
|
||||
Music() : state(MusicState::STOPPED), loop(false) {}
|
||||
// Constructor para inicializar la música con valores predeterminados
|
||||
Music() : state(MusicState::STOPPED), loop(false) {}
|
||||
|
||||
// Constructor para inicializar con valores específicos
|
||||
Music(MusicState init_state, std::string init_name, bool init_loop)
|
||||
: state(init_state), name(std::move(init_name)), loop(init_loop) {}
|
||||
};
|
||||
// Constructor para inicializar con valores específicos
|
||||
Music(MusicState init_state, std::string init_name, bool init_loop)
|
||||
: state(init_state), name(std::move(init_name)), loop(init_loop) {}
|
||||
};
|
||||
|
||||
Music music_;
|
||||
Music music_;
|
||||
|
||||
// --- Variables de Estado ---
|
||||
bool enabled_ = true; // Estado general del audio
|
||||
bool sound_enabled_ = true; // Estado de los efectos de sonido
|
||||
bool music_enabled_ = true; // Estado de la música
|
||||
// --- Variables de Estado ---
|
||||
bool enabled_ = true; // Estado general del audio
|
||||
bool sound_enabled_ = true; // Estado de los efectos de sonido
|
||||
bool music_enabled_ = true; // Estado de la música
|
||||
|
||||
// --- Inicializa SDL Audio ---
|
||||
void initSDLAudio();
|
||||
// --- Inicializa SDL Audio ---
|
||||
void initSDLAudio();
|
||||
|
||||
// --- Patrón Singleton ---
|
||||
Audio(); // Constructor privado
|
||||
~Audio(); // Destructor privado
|
||||
// --- Patrón Singleton ---
|
||||
Audio(); // Constructor privado
|
||||
~Audio(); // Destructor privado
|
||||
|
||||
// --- Singleton ---
|
||||
static Audio *instance;
|
||||
// --- Singleton ---
|
||||
static Audio *instance;
|
||||
};
|
||||
@@ -169,13 +169,13 @@ class Balloon {
|
||||
bool sound_enabled_ = true; // Indica si los globos deben hacer algun sonido
|
||||
|
||||
// --- Métodos internos ---
|
||||
void shiftColliders(); // Alinea el círculo de colisión
|
||||
void shiftSprite(); // Alinea el sprite
|
||||
void zoomSprite(); // Establece el nivel de zoom del sprite
|
||||
void enableBounce(); // Activa el efecto de rebote
|
||||
void disableBounce(); // Detiene el efecto de rebote
|
||||
void updateBounce(); // Aplica el efecto de rebote
|
||||
void updateState(); // Actualiza los estados del globo
|
||||
void setAnimation(); // Establece la animación correspondiente
|
||||
void shiftColliders(); // Alinea el círculo de colisión
|
||||
void shiftSprite(); // Alinea el sprite
|
||||
void zoomSprite(); // Establece el nivel de zoom del sprite
|
||||
void enableBounce(); // Activa el efecto de rebote
|
||||
void disableBounce(); // Detiene el efecto de rebote
|
||||
void updateBounce(); // Aplica el efecto de rebote
|
||||
void updateState(); // Actualiza los estados del globo
|
||||
void setAnimation(); // Establece la animación correspondiente
|
||||
void playSound(const std::string &name) const; // Reproduce sonido
|
||||
};
|
||||
@@ -12,56 +12,56 @@ constexpr int NUMBER_OF_STAGES = 10;
|
||||
|
||||
// --- Estructuras de datos ---
|
||||
struct BalloonFormationParams {
|
||||
int x = 0; // Posición en el eje X donde crear el globo
|
||||
int y = 0; // Posición en el eje Y donde crear el globo
|
||||
float vel_x = 0.0F; // Velocidad inicial en el eje X
|
||||
BalloonType type = BalloonType::BALLOON; // Tipo de globo
|
||||
BalloonSize size = BalloonSize::SIZE1; // Tamaño de globo
|
||||
int creation_counter = 0; // Temporizador para la creación del globo
|
||||
int x = 0; // Posición en el eje X donde crear el globo
|
||||
int y = 0; // Posición en el eje Y donde crear el globo
|
||||
float vel_x = 0.0F; // Velocidad inicial en el eje X
|
||||
BalloonType type = BalloonType::BALLOON; // Tipo de globo
|
||||
BalloonSize size = BalloonSize::SIZE1; // Tamaño de globo
|
||||
int creation_counter = 0; // Temporizador para la creación del globo
|
||||
|
||||
// Constructor por defecto
|
||||
BalloonFormationParams() = default;
|
||||
// Constructor por defecto
|
||||
BalloonFormationParams() = default;
|
||||
|
||||
// Constructor con parámetros
|
||||
BalloonFormationParams(int x_val, int y_val, float vel_x_val, BalloonType type_val, BalloonSize size_val, int creation_counter_val)
|
||||
: x(x_val), y(y_val), vel_x(vel_x_val), type(type_val), size(size_val), creation_counter(creation_counter_val) {}
|
||||
// Constructor con parámetros
|
||||
BalloonFormationParams(int x_val, int y_val, float vel_x_val, BalloonType type_val, BalloonSize size_val, int creation_counter_val)
|
||||
: x(x_val), y(y_val), vel_x(vel_x_val), type(type_val), size(size_val), creation_counter(creation_counter_val) {}
|
||||
};
|
||||
|
||||
struct BalloonFormationUnit {
|
||||
int number_of_balloons; // Cantidad de globos que forman la formación
|
||||
std::vector<BalloonFormationParams> init; // Vector con todas las inicializaciones de los globos de la formación
|
||||
int number_of_balloons; // Cantidad de globos que forman la formación
|
||||
std::vector<BalloonFormationParams> init; // Vector con todas las inicializaciones de los globos de la formación
|
||||
|
||||
// Constructor con parámetros
|
||||
BalloonFormationUnit(int num_balloons, const std::vector<BalloonFormationParams> &init_params)
|
||||
: number_of_balloons(num_balloons), init(init_params) {}
|
||||
// Constructor con parámetros
|
||||
BalloonFormationUnit(int num_balloons, const std::vector<BalloonFormationParams> &init_params)
|
||||
: number_of_balloons(num_balloons), init(init_params) {}
|
||||
|
||||
// Constructor por defecto
|
||||
BalloonFormationUnit() : number_of_balloons(0) {}
|
||||
// Constructor por defecto
|
||||
BalloonFormationUnit() : number_of_balloons(0) {}
|
||||
};
|
||||
|
||||
using BalloonFormationPool = std::vector<const BalloonFormationUnit *>;
|
||||
|
||||
// --- Clase BalloonFormations ---
|
||||
class BalloonFormations {
|
||||
public:
|
||||
// --- Constructor y destructor ---
|
||||
BalloonFormations() {
|
||||
initBalloonFormations();
|
||||
initBalloonFormationPools();
|
||||
}
|
||||
~BalloonFormations() = default;
|
||||
public:
|
||||
// --- Constructor y destructor ---
|
||||
BalloonFormations() {
|
||||
initBalloonFormations();
|
||||
initBalloonFormationPools();
|
||||
}
|
||||
~BalloonFormations() = default;
|
||||
|
||||
// --- Getters ---
|
||||
auto getPool(int pool) -> const BalloonFormationPool & { return balloon_formation_pool_.at(pool); }
|
||||
auto getSet(int pool, int set) -> const BalloonFormationUnit & { return *balloon_formation_pool_.at(pool).at(set); }
|
||||
[[nodiscard]] auto getSet(int set) const -> const BalloonFormationUnit & { return balloon_formation_.at(set); }
|
||||
// --- Getters ---
|
||||
auto getPool(int pool) -> const BalloonFormationPool & { return balloon_formation_pool_.at(pool); }
|
||||
auto getSet(int pool, int set) -> const BalloonFormationUnit & { return *balloon_formation_pool_.at(pool).at(set); }
|
||||
[[nodiscard]] auto getSet(int set) const -> const BalloonFormationUnit & { return balloon_formation_.at(set); }
|
||||
|
||||
private:
|
||||
// --- Datos ---
|
||||
std::vector<BalloonFormationUnit> balloon_formation_; // Vector con todas las formaciones enemigas
|
||||
std::vector<BalloonFormationPool> balloon_formation_pool_; // Conjuntos de formaciones enemigas
|
||||
private:
|
||||
// --- Datos ---
|
||||
std::vector<BalloonFormationUnit> balloon_formation_; // Vector con todas las formaciones enemigas
|
||||
std::vector<BalloonFormationPool> balloon_formation_pool_; // Conjuntos de formaciones enemigas
|
||||
|
||||
// --- Métodos internos de inicialización ---
|
||||
void initBalloonFormations();
|
||||
void initBalloonFormationPools();
|
||||
// --- Métodos internos de inicialización ---
|
||||
void initBalloonFormations();
|
||||
void initBalloonFormationPools();
|
||||
};
|
||||
|
||||
@@ -18,90 +18,90 @@ using Balloons = std::vector<std::shared_ptr<Balloon>>;
|
||||
|
||||
// Clase BalloonManager
|
||||
class BalloonManager {
|
||||
public:
|
||||
// Constructor y Destructor
|
||||
BalloonManager();
|
||||
~BalloonManager() = default;
|
||||
public:
|
||||
// Constructor y Destructor
|
||||
BalloonManager();
|
||||
~BalloonManager() = default;
|
||||
|
||||
// Actualización y Renderizado
|
||||
void update(); // Actualiza el estado de los globos
|
||||
void render(); // Renderiza los globos en pantalla
|
||||
// Actualización y Renderizado
|
||||
void update(); // Actualiza el estado de los globos
|
||||
void render(); // Renderiza los globos en pantalla
|
||||
|
||||
// Gestión de globos
|
||||
void freeBalloons(); // Libera globos que ya no sirven
|
||||
// Gestión de globos
|
||||
void freeBalloons(); // Libera globos que ya no sirven
|
||||
|
||||
// Creación de formaciones enemigas
|
||||
void deployBalloonFormation(int stage); // Crea una formación de enemigos aleatoria
|
||||
void deploySet(int set); // Crea una formación específica
|
||||
void deploySet(int set, int y); // Crea una formación específica con coordenadas
|
||||
// Creación de formaciones enemigas
|
||||
void deployBalloonFormation(int stage); // Crea una formación de enemigos aleatoria
|
||||
void deploySet(int set); // Crea una formación específica
|
||||
void deploySet(int set, int y); // Crea una formación específica con coordenadas
|
||||
|
||||
// Creación de globos
|
||||
auto createBalloon(float x, int y, BalloonType type, BalloonSize size, float velx, float speed, int creation_timer) -> std::shared_ptr<Balloon>; // Crea un nuevo globo
|
||||
void createChildBalloon(const std::shared_ptr<Balloon> &balloon, const std::string &direction); // Crea un globo a partir de otro
|
||||
void createPowerBall(); // Crea una PowerBall
|
||||
void createTwoBigBalloons(); // Crea dos globos grandes
|
||||
void createRandomBalloons(); // Crea una disposición aleatoria de globos
|
||||
// Creación de globos
|
||||
auto createBalloon(float x, int y, BalloonType type, BalloonSize size, float velx, float speed, int creation_timer) -> std::shared_ptr<Balloon>; // Crea un nuevo globo
|
||||
void createChildBalloon(const std::shared_ptr<Balloon> &balloon, const std::string &direction); // Crea un globo a partir de otro
|
||||
void createPowerBall(); // Crea una PowerBall
|
||||
void createTwoBigBalloons(); // Crea dos globos grandes
|
||||
void createRandomBalloons(); // Crea una disposición aleatoria de globos
|
||||
|
||||
// Control de velocidad y despliegue
|
||||
void setBalloonSpeed(float speed); // Ajusta la velocidad de los globos
|
||||
void setDefaultBalloonSpeed(float speed) { default_balloon_speed_ = speed; }; // Establece la velocidad base
|
||||
void resetBalloonSpeed() { setBalloonSpeed(default_balloon_speed_); }; // Restablece la velocidad de los globos
|
||||
void updateBalloonDeployCounter(); // Actualiza el contador de despliegue
|
||||
auto canPowerBallBeCreated() -> bool; // Indica si se puede crear una PowerBall
|
||||
auto calculateScreenPower() -> int; // Calcula el poder de los globos en pantalla
|
||||
// Control de velocidad y despliegue
|
||||
void setBalloonSpeed(float speed); // Ajusta la velocidad de los globos
|
||||
void setDefaultBalloonSpeed(float speed) { default_balloon_speed_ = speed; }; // Establece la velocidad base
|
||||
void resetBalloonSpeed() { setBalloonSpeed(default_balloon_speed_); }; // Restablece la velocidad de los globos
|
||||
void updateBalloonDeployCounter(); // Actualiza el contador de despliegue
|
||||
auto canPowerBallBeCreated() -> bool; // Indica si se puede crear una PowerBall
|
||||
auto calculateScreenPower() -> int; // Calcula el poder de los globos en pantalla
|
||||
|
||||
// Manipulación de globos existentes
|
||||
auto popBalloon(std::shared_ptr<Balloon> balloon) -> int; // Explosiona un globo, creando otros si aplica
|
||||
auto destroyBalloon(std::shared_ptr<Balloon> &balloon) -> int; // Explosiona un globo sin crear otros
|
||||
auto destroyAllBalloons() -> int; // Destruye todos los globos
|
||||
void stopAllBalloons(); // Detiene el movimiento de los globos
|
||||
void startAllBalloons(); // Reactiva el movimiento de los globos
|
||||
// Manipulación de globos existentes
|
||||
auto popBalloon(std::shared_ptr<Balloon> balloon) -> int; // Explosiona un globo, creando otros si aplica
|
||||
auto destroyBalloon(std::shared_ptr<Balloon> &balloon) -> int; // Explosiona un globo sin crear otros
|
||||
auto destroyAllBalloons() -> int; // Destruye todos los globos
|
||||
void stopAllBalloons(); // Detiene el movimiento de los globos
|
||||
void startAllBalloons(); // Reactiva el movimiento de los globos
|
||||
|
||||
// Cambios de apariencia
|
||||
void reverseColorsToAllBalloons(); // Invierte los colores de los globos
|
||||
void normalColorsToAllBalloons(); // Restaura los colores originales
|
||||
// Cambios de apariencia
|
||||
void reverseColorsToAllBalloons(); // Invierte los colores de los globos
|
||||
void normalColorsToAllBalloons(); // Restaura los colores originales
|
||||
|
||||
// Configuración de sonido
|
||||
void setSounds(bool value); // Activa o desactiva los sonidos de los globos
|
||||
void setBouncingSounds(bool value); // Activa o desactiva los sonidos de rebote los globos
|
||||
void setPoppingSounds(bool value); // Activa o desactiva los sonidos de los globos al explotar
|
||||
// Configuración de sonido
|
||||
void setSounds(bool value); // Activa o desactiva los sonidos de los globos
|
||||
void setBouncingSounds(bool value); // Activa o desactiva los sonidos de rebote los globos
|
||||
void setPoppingSounds(bool value); // Activa o desactiva los sonidos de los globos al explotar
|
||||
|
||||
// Configuración de juego
|
||||
void setPlayArea(SDL_FRect play_area) { play_area_ = play_area; }; // Define el área de juego
|
||||
void setCreationTimeEnabled(bool value) { creation_time_enabled_ = value; }; // Activa o desactiva el tiempo de creación de globos
|
||||
void enableBalloonDeployment(bool value) { can_deploy_balloons_ = value; }; // Activa o desactiva la generación de globos
|
||||
// Configuración de juego
|
||||
void setPlayArea(SDL_FRect play_area) { play_area_ = play_area; }; // Define el área de juego
|
||||
void setCreationTimeEnabled(bool value) { creation_time_enabled_ = value; }; // Activa o desactiva el tiempo de creación de globos
|
||||
void enableBalloonDeployment(bool value) { can_deploy_balloons_ = value; }; // Activa o desactiva la generación de globos
|
||||
|
||||
// Obtención de información
|
||||
auto getMenace() -> int; // Obtiene el nivel de amenaza generado por los globos
|
||||
[[nodiscard]] auto getBalloonSpeed() const -> float { return balloon_speed_; }
|
||||
auto getBalloons() -> Balloons & { return balloons_; }
|
||||
[[nodiscard]] auto getNumBalloons() const -> int { return balloons_.size(); }
|
||||
// Obtención de información
|
||||
auto getMenace() -> int; // Obtiene el nivel de amenaza generado por los globos
|
||||
[[nodiscard]] auto getBalloonSpeed() const -> float { return balloon_speed_; }
|
||||
auto getBalloons() -> Balloons & { return balloons_; }
|
||||
[[nodiscard]] auto getNumBalloons() const -> int { return balloons_.size(); }
|
||||
|
||||
private:
|
||||
Balloons balloons_; // Vector con los globos activos
|
||||
std::unique_ptr<Explosions> explosions_; // Objeto para gestionar explosiones
|
||||
std::unique_ptr<BalloonFormations> balloon_formations_; // Objeto para manejar formaciones enemigas
|
||||
private:
|
||||
Balloons balloons_; // Vector con los globos activos
|
||||
std::unique_ptr<Explosions> explosions_; // Objeto para gestionar explosiones
|
||||
std::unique_ptr<BalloonFormations> balloon_formations_; // Objeto para manejar formaciones enemigas
|
||||
|
||||
std::vector<std::shared_ptr<Texture>> balloon_textures_; // Texturas de los globos
|
||||
std::vector<std::shared_ptr<Texture>> explosions_textures_; // Texturas de explosiones
|
||||
std::vector<std::shared_ptr<Texture>> balloon_textures_; // Texturas de los globos
|
||||
std::vector<std::shared_ptr<Texture>> explosions_textures_; // Texturas de explosiones
|
||||
|
||||
std::vector<std::vector<std::string>> balloon_animations_; // Animaciones de los globos
|
||||
std::vector<std::vector<std::string>> explosions_animations_; // Animaciones de las explosiones
|
||||
std::vector<std::vector<std::string>> balloon_animations_; // Animaciones de los globos
|
||||
std::vector<std::vector<std::string>> explosions_animations_; // Animaciones de las explosiones
|
||||
|
||||
// Variables de control de globos
|
||||
float balloon_speed_ = BALLOON_SPEED[0];
|
||||
float default_balloon_speed_ = BALLOON_SPEED[0];
|
||||
int balloon_deploy_counter_ = 0;
|
||||
bool power_ball_enabled_ = false;
|
||||
int power_ball_counter_ = 0;
|
||||
int last_balloon_deploy_ = 0;
|
||||
SDL_FRect play_area_ = param.game.play_area.rect;
|
||||
bool creation_time_enabled_ = true;
|
||||
bool can_deploy_balloons_ = true;
|
||||
bool bouncing_sound_enabled_ = false; // Si debe sonar el globo al rebotar
|
||||
bool poping_sound_enabled_ = true; // Si debe sonar el globo al explotar
|
||||
bool sound_enabled_ = true; // Indica si los globos deben hacer algun sonido
|
||||
// Variables de control de globos
|
||||
float balloon_speed_ = BALLOON_SPEED[0];
|
||||
float default_balloon_speed_ = BALLOON_SPEED[0];
|
||||
int balloon_deploy_counter_ = 0;
|
||||
bool power_ball_enabled_ = false;
|
||||
int power_ball_counter_ = 0;
|
||||
int last_balloon_deploy_ = 0;
|
||||
SDL_FRect play_area_ = param.game.play_area.rect;
|
||||
bool creation_time_enabled_ = true;
|
||||
bool can_deploy_balloons_ = true;
|
||||
bool bouncing_sound_enabled_ = false; // Si debe sonar el globo al rebotar
|
||||
bool poping_sound_enabled_ = true; // Si debe sonar el globo al explotar
|
||||
bool sound_enabled_ = true; // Indica si los globos deben hacer algun sonido
|
||||
|
||||
// Metodos privados
|
||||
void init();
|
||||
// Metodos privados
|
||||
void init();
|
||||
};
|
||||
|
||||
@@ -13,7 +13,6 @@ Bullet::Bullet(float x, float y, BulletType bullet_type, bool powered, int owner
|
||||
pos_y_(y),
|
||||
bullet_type_(bullet_type),
|
||||
owner_(owner) {
|
||||
|
||||
vel_x_ = calculateVelocity(bullet_type_);
|
||||
sprite_->setCurrentAnimation(buildAnimationString(bullet_type_, powered));
|
||||
|
||||
@@ -22,7 +21,7 @@ Bullet::Bullet(float x, float y, BulletType bullet_type, bool powered, int owner
|
||||
}
|
||||
|
||||
// Calcula la velocidad horizontal de la bala basada en su tipo
|
||||
float Bullet::calculateVelocity(BulletType bullet_type) {
|
||||
auto Bullet::calculateVelocity(BulletType bullet_type) -> float {
|
||||
switch (bullet_type) {
|
||||
case BulletType::LEFT:
|
||||
return VEL_X_LEFT;
|
||||
@@ -34,7 +33,7 @@ float Bullet::calculateVelocity(BulletType bullet_type) {
|
||||
}
|
||||
|
||||
// Construye el string de animación basado en el tipo de bala y si está potenciada
|
||||
std::string Bullet::buildAnimationString(BulletType bullet_type, bool powered) {
|
||||
auto Bullet::buildAnimationString(BulletType bullet_type, bool powered) -> std::string {
|
||||
std::string animation_string = powered ? "powered_" : "normal_";
|
||||
|
||||
switch (bullet_type) {
|
||||
|
||||
@@ -63,9 +63,9 @@ class Bullet {
|
||||
Circle collider_; // Círculo de colisión
|
||||
|
||||
// Métodos internos
|
||||
void shiftColliders(); // Ajusta el círculo de colisión
|
||||
void shiftSprite(); // Ajusta el sprite
|
||||
auto move() -> BulletMoveStatus; // Mueve la bala y devuelve su estado
|
||||
float calculateVelocity(BulletType bullet_type); // Calcula la velocidad horizontal de la bala basada en su tipo
|
||||
std::string buildAnimationString(BulletType bullet_type, bool powered); // Construye el string de animación basado en el tipo de bala y si está potenciada
|
||||
void shiftColliders(); // Ajusta el círculo de colisión
|
||||
void shiftSprite(); // Ajusta el sprite
|
||||
auto move() -> BulletMoveStatus; // Mueve la bala y devuelve su estado
|
||||
static auto calculateVelocity(BulletType bullet_type) -> float; // Calcula la velocidad horizontal de la bala basada en su tipo
|
||||
static auto buildAnimationString(BulletType bullet_type, bool powered) -> std::string; // Construye el string de animación basado en el tipo de bala y si está potenciada
|
||||
};
|
||||
|
||||
@@ -588,7 +588,7 @@ void Director::reset() {
|
||||
Lang::setLanguage(Options::settings.language);
|
||||
Audio::get()->stopMusic();
|
||||
Audio::get()->stopAllSounds();
|
||||
if (true) {
|
||||
{
|
||||
Resource::get()->reload();
|
||||
}
|
||||
Input::get()->discoverGameControllers();
|
||||
|
||||
@@ -1,54 +1,54 @@
|
||||
#pragma once
|
||||
|
||||
#include <string> // Para manejar cadenas de texto
|
||||
#include <span>
|
||||
#include <string> // Para manejar cadenas de texto
|
||||
|
||||
namespace Lang {
|
||||
enum class Code : int;
|
||||
}
|
||||
|
||||
class Director {
|
||||
public:
|
||||
// --- Constructor y destructor ---
|
||||
Director(int argc, std::span<char*> argv);
|
||||
~Director();
|
||||
public:
|
||||
// --- Constructor y destructor ---
|
||||
Director(int argc, std::span<char *> argv);
|
||||
~Director();
|
||||
|
||||
// --- Bucle principal ---
|
||||
auto run() -> int;
|
||||
// --- Bucle principal ---
|
||||
auto run() -> int;
|
||||
|
||||
private:
|
||||
// --- Variables internas ---
|
||||
std::string executable_path_; // Ruta del ejecutable
|
||||
std::string system_folder_; // Carpeta del sistema para almacenar datos
|
||||
private:
|
||||
// --- Variables internas ---
|
||||
std::string executable_path_; // Ruta del ejecutable
|
||||
std::string system_folder_; // Carpeta del sistema para almacenar datos
|
||||
|
||||
// --- Inicialización y cierre del sistema ---
|
||||
void init(); // Inicializa la aplicación
|
||||
void close(); // Cierra y libera recursos
|
||||
// --- Inicialización y cierre del sistema ---
|
||||
void init(); // Inicializa la aplicación
|
||||
static void close(); // Cierra y libera recursos
|
||||
|
||||
// --- Configuración inicial ---
|
||||
static void loadParams(); // Carga los parámetros del programa
|
||||
static void loadScoreFile(); // Carga el fichero de puntuaciones
|
||||
void createSystemFolder(const std::string &folder); // Crea la carpeta del sistema
|
||||
// --- Configuración inicial ---
|
||||
static void loadParams(); // Carga los parámetros del programa
|
||||
static void loadScoreFile(); // Carga el fichero de puntuaciones
|
||||
void createSystemFolder(const std::string &folder); // Crea la carpeta del sistema
|
||||
|
||||
// --- Gestión de entrada y archivos ---
|
||||
static void bindInputs(); // Asigna botones y teclas al sistema de entrada
|
||||
void setFileList(); // Crea el índice de archivos disponibles
|
||||
void checkProgramArguments(int argc, std::span<char*> argv); // Verifica los parámetros del programa // NOLINT(modernize-avoid-c-arrays)
|
||||
// --- Gestión de entrada y archivos ---
|
||||
static void bindInputs(); // Asigna botones y teclas al sistema de entrada
|
||||
void setFileList(); // Crea el índice de archivos disponibles
|
||||
void checkProgramArguments(int argc, std::span<char *> argv); // Verifica los parámetros del programa // NOLINT(modernize-avoid-c-arrays)
|
||||
|
||||
// --- Secciones del programa ---
|
||||
static void runLogo(); // Ejecuta la pantalla con el logo
|
||||
static void runIntro(); // Ejecuta la introducción del juego
|
||||
static void runTitle(); // Ejecuta la pantalla de título
|
||||
static void runGame(); // Inicia el juego
|
||||
static void runInstructions(); // Muestra las instrucciones
|
||||
static void runCredits(); // Muestra los créditos del juego
|
||||
static void runHiScoreTable(); // Muestra la tabla de puntuaciones
|
||||
static void runDemoGame(); // Ejecuta el modo demo
|
||||
void reset(); // Reinicia objetos y vuelve a la sección inicial
|
||||
// --- Secciones del programa ---
|
||||
static void runLogo(); // Ejecuta la pantalla con el logo
|
||||
static void runIntro(); // Ejecuta la introducción del juego
|
||||
static void runTitle(); // Ejecuta la pantalla de título
|
||||
static void runGame(); // Inicia el juego
|
||||
static void runInstructions(); // Muestra las instrucciones
|
||||
static void runCredits(); // Muestra los créditos del juego
|
||||
static void runHiScoreTable(); // Muestra la tabla de puntuaciones
|
||||
static void runDemoGame(); // Ejecuta el modo demo
|
||||
static void reset(); // Reinicia objetos y vuelve a la sección inicial
|
||||
|
||||
// --- Gestión de archivos de idioma ---
|
||||
auto getLangFile(Lang::Code code) -> std::string; // Obtiene un fichero de idioma según el código
|
||||
// --- Gestión de archivos de idioma ---
|
||||
auto getLangFile(Lang::Code code) -> std::string; // Obtiene un fichero de idioma según el código
|
||||
|
||||
// --- Apagado del sistema ---
|
||||
static void shutdownSystem(bool should_shutdown); // Apaga el sistema
|
||||
// --- Apagado del sistema ---
|
||||
static void shutdownSystem(bool should_shutdown); // Apaga el sistema
|
||||
};
|
||||
|
||||
@@ -11,32 +11,32 @@ constexpr size_t NAME_SIZE = 5;
|
||||
|
||||
// Clase EnterName
|
||||
class EnterName {
|
||||
public:
|
||||
EnterName();
|
||||
~EnterName() = default;
|
||||
public:
|
||||
EnterName();
|
||||
~EnterName() = default;
|
||||
|
||||
void init(const std::string &name = ""); // Inicializa con un nombre opcional
|
||||
void init(const std::string &name = ""); // Inicializa con un nombre opcional
|
||||
|
||||
void incPosition(); // Incrementa la posición del carácter actual
|
||||
void decPosition(); // Decrementa la posición del carácter actual
|
||||
void incIndex(); // Incrementa el índice del carácter en la lista
|
||||
void decIndex(); // Decrementa el índice del carácter en la lista
|
||||
void incPosition(); // Incrementa la posición del carácter actual
|
||||
void decPosition(); // Decrementa la posición del carácter actual
|
||||
void incIndex(); // Incrementa el índice del carácter en la lista
|
||||
void decIndex(); // Decrementa el índice del carácter en la lista
|
||||
|
||||
auto getFinalName() -> std::string; // Obtiene el nombre final introducido
|
||||
[[nodiscard]] auto getCurrentName() const -> std::string { return trim(name_); } // Obtiene el nombre actual en proceso
|
||||
auto getFinalName() -> std::string; // Obtiene el nombre final introducido
|
||||
[[nodiscard]] auto getCurrentName() const -> std::string { return trim(name_); } // Obtiene el nombre actual en proceso
|
||||
|
||||
[[nodiscard]] auto getPosition() const -> int { return position_; } // Posición actual del carácter editado
|
||||
[[nodiscard]] auto getPositionOverflow() const -> bool { return position_overflow_; } // Indica si la posición excede el límite
|
||||
[[nodiscard]] auto getPosition() const -> int { return position_; } // Posición actual del carácter editado
|
||||
[[nodiscard]] auto getPositionOverflow() const -> bool { return position_overflow_; } // Indica si la posición excede el límite
|
||||
|
||||
private:
|
||||
std::string character_list_; // Lista de caracteres permitidos
|
||||
std::string name_; // Nombre en proceso
|
||||
size_t position_ = 0; // Índice del carácter que se edita
|
||||
bool position_overflow_ = false; // Flag para exceder límite
|
||||
std::array<int, NAME_SIZE> character_index_; // Índices a "character_list_"
|
||||
private:
|
||||
std::string character_list_; // Lista de caracteres permitidos
|
||||
std::string name_; // Nombre en proceso
|
||||
size_t position_ = 0; // Índice del carácter que se edita
|
||||
bool position_overflow_ = false; // Flag para exceder límite
|
||||
std::array<int, NAME_SIZE> character_index_; // Índices a "character_list_"
|
||||
|
||||
void updateNameFromCharacterIndex(); // Actualiza "name_" según "character_index_"
|
||||
void initCharacterIndex(const std::string &name); // Inicializa índices desde el nombre
|
||||
[[nodiscard]] auto findIndex(char character) const -> int; // Busca el índice de un carácter en "character_list_"
|
||||
static auto getRandomName() -> std::string; // Devuelve un nombre al azar
|
||||
void updateNameFromCharacterIndex(); // Actualiza "name_" según "character_index_"
|
||||
void initCharacterIndex(const std::string &name); // Inicializa índices desde el nombre
|
||||
[[nodiscard]] auto findIndex(char character) const -> int; // Busca el índice de un carácter en "character_list_"
|
||||
static auto getRandomName() -> std::string; // Devuelve un nombre al azar
|
||||
};
|
||||
@@ -11,43 +11,43 @@ class Texture;
|
||||
|
||||
// Estructura para almacenar la información de una textura de explosión
|
||||
struct ExplosionTexture {
|
||||
int size; // Tamaño de la explosión
|
||||
std::shared_ptr<Texture> texture; // Textura para la explosión
|
||||
std::vector<std::string> animation; // Animación para la textura
|
||||
int size; // Tamaño de la explosión
|
||||
std::shared_ptr<Texture> texture; // Textura para la explosión
|
||||
std::vector<std::string> animation; // Animación para la textura
|
||||
|
||||
ExplosionTexture(int sz, std::shared_ptr<Texture> tex, const std::vector<std::string> &anim)
|
||||
: size(sz), texture(std::move(tex)), animation(anim) {}
|
||||
ExplosionTexture(int sz, std::shared_ptr<Texture> tex, const std::vector<std::string> &anim)
|
||||
: size(sz), texture(std::move(tex)), animation(anim) {}
|
||||
};
|
||||
|
||||
// Clase Explosions
|
||||
class Explosions {
|
||||
public:
|
||||
// Constructor y destructor
|
||||
Explosions() = default;
|
||||
~Explosions() = default;
|
||||
public:
|
||||
// Constructor y destructor
|
||||
Explosions() = default;
|
||||
~Explosions() = default;
|
||||
|
||||
// Actualiza la lógica de la clase
|
||||
void update();
|
||||
// Actualiza la lógica de la clase
|
||||
void update();
|
||||
|
||||
// Dibuja el objeto en pantalla
|
||||
void render();
|
||||
// Dibuja el objeto en pantalla
|
||||
void render();
|
||||
|
||||
// Añade texturas al objeto
|
||||
void addTexture(int size, std::shared_ptr<Texture> texture, const std::vector<std::string> &animation);
|
||||
// Añade texturas al objeto
|
||||
void addTexture(int size, std::shared_ptr<Texture> texture, const std::vector<std::string> &animation);
|
||||
|
||||
// Añade una explosión
|
||||
void add(int x, int y, int size);
|
||||
// Añade una explosión
|
||||
void add(int x, int y, int size);
|
||||
|
||||
private:
|
||||
// Vector con las texturas a utilizar
|
||||
std::vector<ExplosionTexture> textures_;
|
||||
private:
|
||||
// Vector con las texturas a utilizar
|
||||
std::vector<ExplosionTexture> textures_;
|
||||
|
||||
// Lista con todas las explosiones
|
||||
std::vector<std::unique_ptr<AnimatedSprite>> explosions_;
|
||||
// Lista con todas las explosiones
|
||||
std::vector<std::unique_ptr<AnimatedSprite>> explosions_;
|
||||
|
||||
// Vacia el vector de elementos finalizados
|
||||
void freeExplosions();
|
||||
// Vacia el vector de elementos finalizados
|
||||
void freeExplosions();
|
||||
|
||||
// Busca una textura a partir del tamaño
|
||||
auto getIndexBySize(int size) -> int;
|
||||
// Busca una textura a partir del tamaño
|
||||
auto getIndexBySize(int size) -> int;
|
||||
};
|
||||
2
source/external/.clang-format
vendored
Normal file
2
source/external/.clang-format
vendored
Normal file
@@ -0,0 +1,2 @@
|
||||
DisableFormat: true
|
||||
SortIncludes: Never
|
||||
@@ -30,61 +30,61 @@ enum class FadeState : Uint8 {
|
||||
};
|
||||
|
||||
class Fade {
|
||||
public:
|
||||
// --- Constructores y destructor ---
|
||||
Fade();
|
||||
~Fade();
|
||||
public:
|
||||
// --- Constructores y destructor ---
|
||||
Fade();
|
||||
~Fade();
|
||||
|
||||
// --- Métodos principales ---
|
||||
void reset(); // Resetea variables para reutilizar el fade
|
||||
void render(); // Dibuja la transición en pantalla
|
||||
void update(); // Actualiza el estado interno
|
||||
void activate(); // Activa el fade
|
||||
// --- Métodos principales ---
|
||||
void reset(); // Resetea variables para reutilizar el fade
|
||||
void render(); // Dibuja la transición en pantalla
|
||||
void update(); // Actualiza el estado interno
|
||||
void activate(); // Activa el fade
|
||||
|
||||
// --- Configuración ---
|
||||
void setColor(Uint8 r, Uint8 g, Uint8 b);
|
||||
void setColor(Color color);
|
||||
void setType(FadeType type) { type_ = type; }
|
||||
void setMode(FadeMode mode) { mode_ = mode; }
|
||||
void setPostDuration(int value) { post_duration_ = value; }
|
||||
void setPreDuration(int value) { pre_duration_ = value; }
|
||||
// --- Configuración ---
|
||||
void setColor(Uint8 r, Uint8 g, Uint8 b);
|
||||
void setColor(Color color);
|
||||
void setType(FadeType type) { type_ = type; }
|
||||
void setMode(FadeMode mode) { mode_ = mode; }
|
||||
void setPostDuration(int value) { post_duration_ = value; }
|
||||
void setPreDuration(int value) { pre_duration_ = value; }
|
||||
|
||||
// --- Getters ---
|
||||
[[nodiscard]] auto getValue() const -> int { return value_; }
|
||||
[[nodiscard]] auto isEnabled() const -> bool { return state_ != FadeState::NOT_ENABLED; }
|
||||
[[nodiscard]] auto hasEnded() const -> bool { return state_ == FadeState::FINISHED; }
|
||||
// --- Getters ---
|
||||
[[nodiscard]] auto getValue() const -> int { return value_; }
|
||||
[[nodiscard]] auto isEnabled() const -> bool { return state_ != FadeState::NOT_ENABLED; }
|
||||
[[nodiscard]] auto hasEnded() const -> bool { return state_ == FadeState::FINISHED; }
|
||||
|
||||
private:
|
||||
// --- Objetos y punteros ---
|
||||
SDL_Renderer *renderer_; // Renderizador de la ventana
|
||||
SDL_Texture *backbuffer_; // Backbuffer para efectos
|
||||
private:
|
||||
// --- Objetos y punteros ---
|
||||
SDL_Renderer *renderer_; // Renderizador de la ventana
|
||||
SDL_Texture *backbuffer_; // Backbuffer para efectos
|
||||
|
||||
// --- Variables de estado ---
|
||||
FadeType type_; // Tipo de fade
|
||||
FadeMode mode_; // Modo de fade
|
||||
FadeState state_ = FadeState::NOT_ENABLED; // Estado actual
|
||||
Uint16 counter_; // Contador interno
|
||||
// --- Variables de estado ---
|
||||
FadeType type_; // Tipo de fade
|
||||
FadeMode mode_; // Modo de fade
|
||||
FadeState state_ = FadeState::NOT_ENABLED; // Estado actual
|
||||
Uint16 counter_; // Contador interno
|
||||
|
||||
// --- Parámetros de color y geometría ---
|
||||
Uint8 r_, g_, b_, a_; // Color del fade
|
||||
SDL_FRect rect1_, rect2_; // Rectángulos para efectos
|
||||
// --- Parámetros de color y geometría ---
|
||||
Uint8 r_, g_, b_, a_; // Color del fade
|
||||
SDL_FRect rect1_, rect2_; // Rectángulos para efectos
|
||||
|
||||
// --- Parámetros para RANDOM_SQUARE ---
|
||||
int num_squares_width_; // Cuadrados en horizontal
|
||||
int num_squares_height_; // Cuadrados en vertical
|
||||
std::vector<SDL_FRect> square_; // Vector de cuadrados
|
||||
int fade_random_squares_delay_; // Delay entre cuadrados
|
||||
int fade_random_squares_mult_; // Cuadrados por paso
|
||||
// --- Parámetros para RANDOM_SQUARE ---
|
||||
int num_squares_width_; // Cuadrados en horizontal
|
||||
int num_squares_height_; // Cuadrados en vertical
|
||||
std::vector<SDL_FRect> square_; // Vector de cuadrados
|
||||
int fade_random_squares_delay_; // Delay entre cuadrados
|
||||
int fade_random_squares_mult_; // Cuadrados por paso
|
||||
|
||||
// --- Temporizadores ---
|
||||
int post_duration_ = 0, post_counter_ = 0;
|
||||
int pre_duration_ = 0, pre_counter_ = 0;
|
||||
// --- Temporizadores ---
|
||||
int post_duration_ = 0, post_counter_ = 0;
|
||||
int pre_duration_ = 0, pre_counter_ = 0;
|
||||
|
||||
// --- Valor de progreso ---
|
||||
int value_ = 0; // Estado del fade (0-100)
|
||||
// --- Valor de progreso ---
|
||||
int value_ = 0; // Estado del fade (0-100)
|
||||
|
||||
// --- Métodos internos ---
|
||||
void init(); // Inicializa variables
|
||||
void cleanBackbuffer(Uint8 r, Uint8 g, Uint8 b, Uint8 a); // Limpia el backbuffer
|
||||
static auto calculateValue(int min, int max, int current) -> int; // Calcula el valor del fade
|
||||
// --- Métodos internos ---
|
||||
void init(); // Inicializa variables
|
||||
void cleanBackbuffer(Uint8 r, Uint8 g, Uint8 b, Uint8 a); // Limpia el backbuffer
|
||||
static auto calculateValue(int min, int max, int current) -> int; // Calcula el valor del fade
|
||||
};
|
||||
@@ -10,73 +10,73 @@ class Texture;
|
||||
|
||||
// Clase GameLogo
|
||||
class GameLogo {
|
||||
public:
|
||||
// --- Constructores y destructor ---
|
||||
GameLogo(int x, int y);
|
||||
~GameLogo() = default;
|
||||
public:
|
||||
// --- Constructores y destructor ---
|
||||
GameLogo(int x, int y);
|
||||
~GameLogo() = default;
|
||||
|
||||
// --- Métodos principales ---
|
||||
void render(); // Pinta la clase en pantalla
|
||||
void update(); // Actualiza la lógica de la clase
|
||||
void enable(); // Activa la clase
|
||||
// --- Métodos principales ---
|
||||
void render(); // Pinta la clase en pantalla
|
||||
void update(); // Actualiza la lógica de la clase
|
||||
void enable(); // Activa la clase
|
||||
|
||||
// --- Getters ---
|
||||
[[nodiscard]] auto hasFinished() const -> bool; // Indica si ha terminado la animación
|
||||
// --- Getters ---
|
||||
[[nodiscard]] auto hasFinished() const -> bool; // Indica si ha terminado la animación
|
||||
|
||||
private:
|
||||
// --- Tipos internos ---
|
||||
enum class Status {
|
||||
DISABLED,
|
||||
MOVING,
|
||||
SHAKING,
|
||||
FINISHED,
|
||||
};
|
||||
private:
|
||||
// --- Tipos internos ---
|
||||
enum class Status {
|
||||
DISABLED,
|
||||
MOVING,
|
||||
SHAKING,
|
||||
FINISHED,
|
||||
};
|
||||
|
||||
struct Shake {
|
||||
int desp = 1; // Pixels de desplazamiento para agitar la pantalla en el eje x
|
||||
int delay = 2; // Retraso entre cada desplazamiento de la pantalla al agitarse
|
||||
int lenght = 8; // Cantidad de desplazamientos a realizar
|
||||
int remaining = lenght; // Cantidad de desplazamientos pendientes a realizar
|
||||
int counter = delay; // Contador para el retraso
|
||||
int origin = 0; // Valor inicial de la pantalla para dejarla igual tras el desplazamiento
|
||||
struct Shake {
|
||||
int desp = 1; // Pixels de desplazamiento para agitar la pantalla en el eje x
|
||||
int delay = 2; // Retraso entre cada desplazamiento de la pantalla al agitarse
|
||||
int lenght = 8; // Cantidad de desplazamientos a realizar
|
||||
int remaining = lenght; // Cantidad de desplazamientos pendientes a realizar
|
||||
int counter = delay; // Contador para el retraso
|
||||
int origin = 0; // Valor inicial de la pantalla para dejarla igual tras el desplazamiento
|
||||
|
||||
Shake() = default;
|
||||
Shake(int d, int de, int l, int o)
|
||||
: desp(d), delay(de), lenght(l), remaining(l), counter(de), origin(o) {}
|
||||
Shake() = default;
|
||||
Shake(int d, int de, int l, int o)
|
||||
: desp(d), delay(de), lenght(l), remaining(l), counter(de), origin(o) {}
|
||||
|
||||
void init(int d, int de, int l, int o) {
|
||||
desp = d;
|
||||
delay = de;
|
||||
lenght = l;
|
||||
remaining = l;
|
||||
counter = de;
|
||||
origin = o;
|
||||
}
|
||||
};
|
||||
void init(int d, int de, int l, int o) {
|
||||
desp = d;
|
||||
delay = de;
|
||||
lenght = l;
|
||||
remaining = l;
|
||||
counter = de;
|
||||
origin = o;
|
||||
}
|
||||
};
|
||||
|
||||
// --- Objetos y punteros ---
|
||||
std::shared_ptr<Texture> dust_texture_; // Textura con los graficos del polvo
|
||||
std::shared_ptr<Texture> coffee_texture_; // Textura con los graficos de la palabra "COFFEE"
|
||||
std::shared_ptr<Texture> crisis_texture_; // Textura con los graficos de la palabra "CRISIS"
|
||||
std::shared_ptr<Texture> arcade_edition_texture_; // Textura con los graficos de "Arcade Edition"
|
||||
// --- Objetos y punteros ---
|
||||
std::shared_ptr<Texture> dust_texture_; // Textura con los graficos del polvo
|
||||
std::shared_ptr<Texture> coffee_texture_; // Textura con los graficos de la palabra "COFFEE"
|
||||
std::shared_ptr<Texture> crisis_texture_; // Textura con los graficos de la palabra "CRISIS"
|
||||
std::shared_ptr<Texture> arcade_edition_texture_; // Textura con los graficos de "Arcade Edition"
|
||||
|
||||
std::unique_ptr<AnimatedSprite> dust_left_sprite_; // Sprite del polvo (izquierda)
|
||||
std::unique_ptr<AnimatedSprite> dust_right_sprite_; // Sprite del polvo (derecha)
|
||||
std::unique_ptr<SmartSprite> coffee_sprite_; // Sprite de "COFFEE"
|
||||
std::unique_ptr<SmartSprite> crisis_sprite_; // Sprite de "CRISIS"
|
||||
std::unique_ptr<Sprite> arcade_edition_sprite_; // Sprite de "Arcade Edition"
|
||||
std::unique_ptr<AnimatedSprite> dust_left_sprite_; // Sprite del polvo (izquierda)
|
||||
std::unique_ptr<AnimatedSprite> dust_right_sprite_; // Sprite del polvo (derecha)
|
||||
std::unique_ptr<SmartSprite> coffee_sprite_; // Sprite de "COFFEE"
|
||||
std::unique_ptr<SmartSprite> crisis_sprite_; // Sprite de "CRISIS"
|
||||
std::unique_ptr<Sprite> arcade_edition_sprite_; // Sprite de "Arcade Edition"
|
||||
|
||||
// --- Variables de estado ---
|
||||
float x_; // Posición X del logo
|
||||
float y_; // Posición Y del logo
|
||||
float zoom_ = 1.0F; // Zoom aplicado al texto "ARCADE EDITION"
|
||||
int post_finished_counter_ = 1; // Contador final tras animaciones
|
||||
// --- Variables de estado ---
|
||||
float x_; // Posición X del logo
|
||||
float y_; // Posición Y del logo
|
||||
float zoom_ = 1.0F; // Zoom aplicado al texto "ARCADE EDITION"
|
||||
int post_finished_counter_ = 1; // Contador final tras animaciones
|
||||
|
||||
Status coffee_crisis_status_ = Status::DISABLED; // Estado de "COFFEE CRISIS"
|
||||
Status arcade_edition_status_ = Status::DISABLED; // Estado de "ARCADE EDITION"
|
||||
Shake shake_; // Efecto de agitación
|
||||
Status coffee_crisis_status_ = Status::DISABLED; // Estado de "COFFEE CRISIS"
|
||||
Status arcade_edition_status_ = Status::DISABLED; // Estado de "ARCADE EDITION"
|
||||
Shake shake_; // Efecto de agitación
|
||||
|
||||
// --- Métodos internos ---
|
||||
void init(); // Inicializa las variables
|
||||
[[nodiscard]] auto getInitialVerticalDesp() const -> int; // Calcula el desplazamiento vertical inicial
|
||||
// --- Métodos internos ---
|
||||
void init(); // Inicializa las variables
|
||||
[[nodiscard]] auto getInitialVerticalDesp() const -> int; // Calcula el desplazamiento vertical inicial
|
||||
};
|
||||
@@ -80,7 +80,7 @@ class Input {
|
||||
void bindGameControllerButton(int controller_index, InputAction input_target, InputAction input_source); // Asigna inputs a otros inputs del mando
|
||||
|
||||
// --- Métodos de consulta de entrada ---
|
||||
void update(); // Comprueba fisicamente los botones y teclas que se han pulsado
|
||||
void update(); // Comprueba fisicamente los botones y teclas que se han pulsado
|
||||
auto checkInput(InputAction input, bool repeat = true, InputDevice device = InputDevice::ANY, int controller_index = 0) -> bool; // Comprueba si un input está activo
|
||||
auto checkAnyInput(InputDevice device = InputDevice::ANY, int controller_index = 0) -> bool; // Comprueba si hay al menos un input activo
|
||||
auto checkAnyButton(bool repeat = INPUT_DO_NOT_ALLOW_REPEAT) -> int; // Comprueba si hay algún botón pulsado
|
||||
@@ -93,7 +93,7 @@ class Input {
|
||||
[[nodiscard]] auto getJoyIndex(SDL_JoystickID id) const -> int; // Obtiene el índice del controlador a partir de un event.id
|
||||
|
||||
// --- Métodos de consulta y utilidades ---
|
||||
void printBindings(InputDevice device = InputDevice::KEYBOARD, int controller_index = 0) const; // Muestra por consola los controles asignados
|
||||
void printBindings(InputDevice device = InputDevice::KEYBOARD, int controller_index = 0) const; // Muestra por consola los controles asignados
|
||||
[[nodiscard]] auto getControllerBinding(int controller_index, InputAction input) const -> SDL_GamepadButton; // Obtiene el SDL_GamepadButton asignado a un input
|
||||
[[nodiscard]] static auto inputToString(InputAction input) -> std::string; // Convierte un InputAction a std::string
|
||||
[[nodiscard]] static auto stringToInput(const std::string &name) -> InputAction; // Convierte un std::string a InputAction
|
||||
@@ -138,12 +138,12 @@ class Input {
|
||||
std::string game_controller_db_path_; // Ruta al archivo gamecontrollerdb.txt
|
||||
|
||||
// --- Métodos internos ---
|
||||
void initSDLGamePad(); // Inicializa SDL para la gestión de mandos
|
||||
void initSDLGamePad(); // Inicializa SDL para la gestión de mandos
|
||||
auto checkAxisInput(InputAction input, int controller_index, bool repeat) -> bool; // Comprueba el eje del mando
|
||||
|
||||
// --- Constructor y destructor ---
|
||||
explicit Input(std::string game_controller_db_path); // Constructor privado
|
||||
~Input() = default; // Destructor privado
|
||||
explicit Input(std::string game_controller_db_path); // Constructor privado
|
||||
~Input() = default; // Destructor privado
|
||||
|
||||
// --- Singleton ---
|
||||
static Input *instance;
|
||||
|
||||
@@ -184,12 +184,12 @@ auto Item::getCoffeeMachineSpawn(int player_x, int item_width, int area_width, i
|
||||
return rand() % (exclude_left - LEFT_BOUND) + LEFT_BOUND;
|
||||
} // Lado derecho
|
||||
return rand() % (RIGHT_BOUND - exclude_right) + exclude_right;
|
||||
|
||||
}
|
||||
if (can_spawn_left) {
|
||||
// Solo lado izquierdo disponible
|
||||
return rand() % (exclude_left - LEFT_BOUND) + LEFT_BOUND;
|
||||
} else if (can_spawn_right) {
|
||||
}
|
||||
if (can_spawn_right) {
|
||||
// Solo lado derecho disponible
|
||||
return rand() % (RIGHT_BOUND - exclude_right) + exclude_right;
|
||||
} else {
|
||||
|
||||
120
source/item.h
120
source/item.h
@@ -27,78 +27,78 @@ enum class ItemType : int {
|
||||
// Clase Item.
|
||||
// Representa un objeto en el juego, con sus propiedades y métodos para gestionar su comportamiento.
|
||||
class Item {
|
||||
public:
|
||||
// Constantes
|
||||
static constexpr int COFFEE_MACHINE_WIDTH = 30;
|
||||
static constexpr int COFFEE_MACHINE_HEIGHT = 39;
|
||||
public:
|
||||
// Constantes
|
||||
static constexpr int COFFEE_MACHINE_WIDTH = 30;
|
||||
static constexpr int COFFEE_MACHINE_HEIGHT = 39;
|
||||
|
||||
// Constructor. Inicializa un objeto Item con el tipo, posición, área de juego, textura y animación.
|
||||
Item(ItemType type, float x, float y, SDL_FRect &play_area, std::shared_ptr<Texture> texture, const std::vector<std::string> &animation);
|
||||
// Constructor. Inicializa un objeto Item con el tipo, posición, área de juego, textura y animación.
|
||||
Item(ItemType type, float x, float y, SDL_FRect &play_area, std::shared_ptr<Texture> texture, const std::vector<std::string> &animation);
|
||||
|
||||
// Destructor.
|
||||
~Item() = default;
|
||||
// Destructor.
|
||||
~Item() = default;
|
||||
|
||||
// Centra el objeto en la posición X indicada, asegurando que no se salga del área de juego.
|
||||
void alignTo(int x);
|
||||
// Centra el objeto en la posición X indicada, asegurando que no se salga del área de juego.
|
||||
void alignTo(int x);
|
||||
|
||||
// Renderiza el objeto en pantalla si está habilitado.
|
||||
// Si el tiempo de vida es mayor que 200, renderiza el sprite.
|
||||
// Si es menor o igual a 200, renderiza el sprite de forma intermitente.
|
||||
void render();
|
||||
// Renderiza el objeto en pantalla si está habilitado.
|
||||
// Si el tiempo de vida es mayor que 200, renderiza el sprite.
|
||||
// Si es menor o igual a 200, renderiza el sprite de forma intermitente.
|
||||
void render();
|
||||
|
||||
// Desactiva el objeto estableciendo su estado enabled_ a false.
|
||||
void disable();
|
||||
// Desactiva el objeto estableciendo su estado enabled_ a false.
|
||||
void disable();
|
||||
|
||||
// Actualiza la posición, animación y contadores del objeto.
|
||||
// Llama a move(), sprite_->update() y updateTimeToLive().
|
||||
void update();
|
||||
// Actualiza la posición, animación y contadores del objeto.
|
||||
// Llama a move(), sprite_->update() y updateTimeToLive().
|
||||
void update();
|
||||
|
||||
// Getters
|
||||
[[nodiscard]] auto getPosX() const -> float { return pos_x_; }
|
||||
[[nodiscard]] auto getPosY() const -> float { return pos_y_; }
|
||||
[[nodiscard]] auto getWidth() const -> int { return width_; }
|
||||
[[nodiscard]] auto getHeight() const -> int { return height_; }
|
||||
[[nodiscard]] auto getType() const -> ItemType { return type_; }
|
||||
[[nodiscard]] auto isEnabled() const -> bool { return enabled_; }
|
||||
[[nodiscard]] auto isOnFloor() const -> bool { return floor_collision_; }
|
||||
auto getCollider() -> Circle & { return collider_; }
|
||||
// Getters
|
||||
[[nodiscard]] auto getPosX() const -> float { return pos_x_; }
|
||||
[[nodiscard]] auto getPosY() const -> float { return pos_y_; }
|
||||
[[nodiscard]] auto getWidth() const -> int { return width_; }
|
||||
[[nodiscard]] auto getHeight() const -> int { return height_; }
|
||||
[[nodiscard]] auto getType() const -> ItemType { return type_; }
|
||||
[[nodiscard]] auto isEnabled() const -> bool { return enabled_; }
|
||||
[[nodiscard]] auto isOnFloor() const -> bool { return floor_collision_; }
|
||||
auto getCollider() -> Circle & { return collider_; }
|
||||
|
||||
private:
|
||||
// Objetos y punteros
|
||||
std::unique_ptr<AnimatedSprite> sprite_; // Sprite con los gráficos del objeto
|
||||
private:
|
||||
// Objetos y punteros
|
||||
std::unique_ptr<AnimatedSprite> sprite_; // Sprite con los gráficos del objeto
|
||||
|
||||
// Variables de estado y físicas
|
||||
float pos_x_; // Posición X del objeto
|
||||
float pos_y_; // Posición Y del objeto
|
||||
int width_; // Ancho del objeto
|
||||
int height_; // Alto del objeto
|
||||
float vel_x_; // Velocidad en el eje X
|
||||
float vel_y_; // Velocidad en el eje Y
|
||||
float accel_x_ = 0.0F; // Aceleración en el eje X
|
||||
float accel_y_; // Aceleración en el eje Y
|
||||
bool floor_collision_ = false; // Indica si el objeto colisiona con el suelo
|
||||
ItemType type_; // Tipo de objeto
|
||||
bool enabled_ = true; // Indica si el objeto está habilitado
|
||||
Circle collider_; // Círculo de colisión del objeto
|
||||
SDL_FRect play_area_; // Rectángulo con la zona de juego
|
||||
Uint16 time_to_live_ = 600; // Tiempo que el objeto está presente
|
||||
// Variables de estado y físicas
|
||||
float pos_x_; // Posición X del objeto
|
||||
float pos_y_; // Posición Y del objeto
|
||||
int width_; // Ancho del objeto
|
||||
int height_; // Alto del objeto
|
||||
float vel_x_; // Velocidad en el eje X
|
||||
float vel_y_; // Velocidad en el eje Y
|
||||
float accel_x_ = 0.0F; // Aceleración en el eje X
|
||||
float accel_y_; // Aceleración en el eje Y
|
||||
bool floor_collision_ = false; // Indica si el objeto colisiona con el suelo
|
||||
ItemType type_; // Tipo de objeto
|
||||
bool enabled_ = true; // Indica si el objeto está habilitado
|
||||
Circle collider_; // Círculo de colisión del objeto
|
||||
SDL_FRect play_area_; // Rectángulo con la zona de juego
|
||||
Uint16 time_to_live_ = 600; // Tiempo que el objeto está presente
|
||||
|
||||
// Alinea el círculo de colisión con la posición del objeto.
|
||||
// Actualiza las coordenadas X e Y del colisionador.
|
||||
void shiftColliders();
|
||||
// Alinea el círculo de colisión con la posición del objeto.
|
||||
// Actualiza las coordenadas X e Y del colisionador.
|
||||
void shiftColliders();
|
||||
|
||||
// Coloca el sprite en la posición del objeto.
|
||||
// Actualiza las coordenadas X e Y del sprite.
|
||||
void shiftSprite();
|
||||
// Coloca el sprite en la posición del objeto.
|
||||
// Actualiza las coordenadas X e Y del sprite.
|
||||
void shiftSprite();
|
||||
|
||||
// Actualiza la posición y estados del objeto.
|
||||
// Controla las colisiones con los límites del área de juego y actualiza sprite y colisionador.
|
||||
void move();
|
||||
// Actualiza la posición y estados del objeto.
|
||||
// Controla las colisiones con los límites del área de juego y actualiza sprite y colisionador.
|
||||
void move();
|
||||
|
||||
// Actualiza el contador de tiempo de vida del objeto.
|
||||
// Si el tiempo de vida es mayor a 0, lo decrementa. Si llega a 0, desactiva el objeto.
|
||||
void updateTimeToLive();
|
||||
// Actualiza el contador de tiempo de vida del objeto.
|
||||
// Si el tiempo de vida es mayor a 0, lo decrementa. Si llega a 0, desactiva el objeto.
|
||||
void updateTimeToLive();
|
||||
|
||||
// Calcula la zona de aparición de la máquina de café
|
||||
static auto getCoffeeMachineSpawn(int player_x, int item_width, int area_width, int margin = 2) -> int;
|
||||
// Calcula la zona de aparición de la máquina de café
|
||||
static auto getCoffeeMachineSpawn(int player_x, int item_width, int area_width, int margin = 2) -> int;
|
||||
};
|
||||
|
||||
@@ -13,12 +13,12 @@ enum class Code : int {
|
||||
|
||||
// Estructura que representa un idioma
|
||||
struct Language {
|
||||
Code code; // Código que identifica al idioma
|
||||
std::string name; // Nombre que identifica el idioma
|
||||
std::string file_name; // Nombre del fichero con los textos
|
||||
Code code; // Código que identifica al idioma
|
||||
std::string name; // Nombre que identifica el idioma
|
||||
std::string file_name; // Nombre del fichero con los textos
|
||||
|
||||
Language(Code c, std::string n, std::string fn)
|
||||
: code(c), name(std::move(n)), file_name(std::move(fn)) {}
|
||||
Language(Code c, std::string n, std::string fn)
|
||||
: code(c), name(std::move(n)), file_name(std::move(fn)) {}
|
||||
};
|
||||
|
||||
// Carga los textos desde el fichero JSON especificado
|
||||
|
||||
@@ -13,41 +13,41 @@
|
||||
|
||||
// --- Estructura para las entradas de la tabla de records ---
|
||||
struct HiScoreEntry {
|
||||
std::string name; // Nombre
|
||||
int score; // Puntuación
|
||||
bool one_credit_complete; // Indica si se ha conseguido 1CC
|
||||
std::string name; // Nombre
|
||||
int score; // Puntuación
|
||||
bool one_credit_complete; // Indica si se ha conseguido 1CC
|
||||
|
||||
// Constructor
|
||||
explicit HiScoreEntry(const std::string &n = "", int s = 0, bool occ = false)
|
||||
: name(n.substr(0, 6)), score(s), one_credit_complete(occ) {}
|
||||
// Constructor
|
||||
explicit HiScoreEntry(const std::string &n = "", int s = 0, bool occ = false)
|
||||
: name(n.substr(0, 6)), score(s), one_credit_complete(occ) {}
|
||||
};
|
||||
|
||||
// --- Clase ManageHiScoreTable ---
|
||||
class ManageHiScoreTable {
|
||||
public:
|
||||
// Constructor
|
||||
explicit ManageHiScoreTable(std::vector<HiScoreEntry> &table)
|
||||
: table_(table) {}
|
||||
public:
|
||||
// Constructor
|
||||
explicit ManageHiScoreTable(std::vector<HiScoreEntry> &table)
|
||||
: table_(table) {}
|
||||
|
||||
// Destructor
|
||||
~ManageHiScoreTable() = default;
|
||||
// Destructor
|
||||
~ManageHiScoreTable() = default;
|
||||
|
||||
// Resetea la tabla a los valores por defecto
|
||||
void clear();
|
||||
// Resetea la tabla a los valores por defecto
|
||||
void clear();
|
||||
|
||||
// Añade un elemento a la tabla (devuelve la posición en la que se inserta)
|
||||
auto add(const HiScoreEntry &entry) -> int;
|
||||
// Añade un elemento a la tabla (devuelve la posición en la que se inserta)
|
||||
auto add(const HiScoreEntry &entry) -> int;
|
||||
|
||||
// Carga la tabla con los datos de un fichero
|
||||
auto loadFromFile(const std::string &file_path) -> bool;
|
||||
// Carga la tabla con los datos de un fichero
|
||||
auto loadFromFile(const std::string &file_path) -> bool;
|
||||
|
||||
// Guarda la tabla en un fichero
|
||||
auto saveToFile(const std::string &file_path) -> bool;
|
||||
// Guarda la tabla en un fichero
|
||||
auto saveToFile(const std::string &file_path) -> bool;
|
||||
|
||||
private:
|
||||
// Referencia a la tabla con los records
|
||||
std::vector<HiScoreEntry> &table_;
|
||||
private:
|
||||
// Referencia a la tabla con los records
|
||||
std::vector<HiScoreEntry> &table_;
|
||||
|
||||
// Ordena la tabla internamente
|
||||
void sort();
|
||||
// Ordena la tabla internamente
|
||||
void sort();
|
||||
};
|
||||
@@ -11,85 +11,85 @@ class Texture;
|
||||
|
||||
// Clase MovingSprite. Añade movimiento y efectos de rotación, zoom y flip al sprite
|
||||
class MovingSprite : public Sprite {
|
||||
public:
|
||||
// --- Estructura para la rotación ---
|
||||
struct Rotate {
|
||||
bool enabled{false}; // Indica si ha de rotar
|
||||
int counter{0}; // Contador
|
||||
int speed{1}; // Velocidad de giro
|
||||
double angle{0.0}; // Ángulo para dibujarlo
|
||||
float amount{0.0F}; // Cantidad de grados a girar en cada iteración
|
||||
SDL_FPoint center; // Centro de rotación
|
||||
public:
|
||||
// --- Estructura para la rotación ---
|
||||
struct Rotate {
|
||||
bool enabled{false}; // Indica si ha de rotar
|
||||
int counter{0}; // Contador
|
||||
int speed{1}; // Velocidad de giro
|
||||
double angle{0.0}; // Ángulo para dibujarlo
|
||||
float amount{0.0F}; // Cantidad de grados a girar en cada iteración
|
||||
SDL_FPoint center; // Centro de rotación
|
||||
|
||||
Rotate() : center({0.0F, 0.0F}) {}
|
||||
};
|
||||
Rotate() : center({0.0F, 0.0F}) {}
|
||||
};
|
||||
|
||||
// --- Constructores y destructor ---
|
||||
MovingSprite(std::shared_ptr<Texture> texture, SDL_FRect pos, MovingSprite::Rotate rotate, float zoom_w, float zoom_h, SDL_FlipMode flip);
|
||||
MovingSprite(std::shared_ptr<Texture> texture, SDL_FRect pos);
|
||||
explicit MovingSprite(std::shared_ptr<Texture> texture);
|
||||
~MovingSprite() override = default;
|
||||
// --- Constructores y destructor ---
|
||||
MovingSprite(std::shared_ptr<Texture> texture, SDL_FRect pos, MovingSprite::Rotate rotate, float zoom_w, float zoom_h, SDL_FlipMode flip);
|
||||
MovingSprite(std::shared_ptr<Texture> texture, SDL_FRect pos);
|
||||
explicit MovingSprite(std::shared_ptr<Texture> texture);
|
||||
~MovingSprite() override = default;
|
||||
|
||||
// --- Métodos principales ---
|
||||
virtual void update(); // Actualiza las variables internas del objeto
|
||||
void clear() override; // Reinicia todas las variables a cero
|
||||
void render() override; // Muestra el sprite por pantalla
|
||||
// --- Métodos principales ---
|
||||
virtual void update(); // Actualiza las variables internas del objeto
|
||||
void clear() override; // Reinicia todas las variables a cero
|
||||
void render() override; // Muestra el sprite por pantalla
|
||||
|
||||
// --- Getters de posición y movimiento ---
|
||||
[[nodiscard]] auto getPosX() const -> float { return x_; }
|
||||
[[nodiscard]] auto getPosY() const -> float { return y_; }
|
||||
[[nodiscard]] auto getVelX() const -> float { return vx_; }
|
||||
[[nodiscard]] auto getVelY() const -> float { return vy_; }
|
||||
[[nodiscard]] auto getAccelX() const -> float { return ax_; }
|
||||
[[nodiscard]] auto getAccelY() const -> float { return ay_; }
|
||||
// --- Getters de posición y movimiento ---
|
||||
[[nodiscard]] auto getPosX() const -> float { return x_; }
|
||||
[[nodiscard]] auto getPosY() const -> float { return y_; }
|
||||
[[nodiscard]] auto getVelX() const -> float { return vx_; }
|
||||
[[nodiscard]] auto getVelY() const -> float { return vy_; }
|
||||
[[nodiscard]] auto getAccelX() const -> float { return ax_; }
|
||||
[[nodiscard]] auto getAccelY() const -> float { return ay_; }
|
||||
|
||||
// --- Setters de movimiento ---
|
||||
void setVelX(float value) { vx_ = value; }
|
||||
void setVelY(float value) { vy_ = value; }
|
||||
void setAccelX(float value) { ax_ = value; }
|
||||
void setAccelY(float value) { ay_ = value; }
|
||||
// --- Setters de movimiento ---
|
||||
void setVelX(float value) { vx_ = value; }
|
||||
void setVelY(float value) { vy_ = value; }
|
||||
void setAccelX(float value) { ax_ = value; }
|
||||
void setAccelY(float value) { ay_ = value; }
|
||||
|
||||
// --- Rotación ---
|
||||
[[nodiscard]] auto isRotating() const -> bool { return rotate_.enabled; }
|
||||
void setZoomW(float value) { zoom_w_ = value; }
|
||||
void setZoomH(float value) { zoom_h_ = value; }
|
||||
void setAngle(double value) { rotate_.angle = value; }
|
||||
void setRotatingCenter(SDL_FPoint point) { rotate_.center = point; }
|
||||
void setRotate(bool enable); // Activa o desactiva el efecto de rotación
|
||||
void setRotateSpeed(int value) { rotate_.speed = std::max(1, value); }
|
||||
void setRotateAmount(double value) { rotate_.amount = value; }
|
||||
void switchRotate() { rotate_.amount *= -1; } // Cambia el sentido de la rotación
|
||||
// --- Rotación ---
|
||||
[[nodiscard]] auto isRotating() const -> bool { return rotate_.enabled; }
|
||||
void setZoomW(float value) { zoom_w_ = value; }
|
||||
void setZoomH(float value) { zoom_h_ = value; }
|
||||
void setAngle(double value) { rotate_.angle = value; }
|
||||
void setRotatingCenter(SDL_FPoint point) { rotate_.center = point; }
|
||||
void setRotate(bool enable); // Activa o desactiva el efecto de rotación
|
||||
void setRotateSpeed(int value) { rotate_.speed = std::max(1, value); }
|
||||
void setRotateAmount(double value) { rotate_.amount = value; }
|
||||
void switchRotate() { rotate_.amount *= -1; } // Cambia el sentido de la rotación
|
||||
|
||||
// --- Flip ---
|
||||
void setFlip(SDL_FlipMode flip) { flip_ = flip; }
|
||||
void flip() { flip_ = (flip_ == SDL_FLIP_HORIZONTAL) ? SDL_FLIP_NONE : SDL_FLIP_HORIZONTAL; }
|
||||
auto getFlip() -> SDL_FlipMode { return flip_; }
|
||||
// --- Flip ---
|
||||
void setFlip(SDL_FlipMode flip) { flip_ = flip; }
|
||||
void flip() { flip_ = (flip_ == SDL_FLIP_HORIZONTAL) ? SDL_FLIP_NONE : SDL_FLIP_HORIZONTAL; }
|
||||
auto getFlip() -> SDL_FlipMode { return flip_; }
|
||||
|
||||
// --- Posición y tamaño ---
|
||||
void setPos(SDL_FRect rect); // Establece la posición y el tamaño del objeto
|
||||
void setPos(float pos_x, float pos_y); // Establece la posición del objeto
|
||||
void setPosX(float pos_x); // Establece la posición X
|
||||
void setPosY(float pos_y); // Establece la posición Y
|
||||
// --- Posición y tamaño ---
|
||||
void setPos(SDL_FRect rect); // Establece la posición y el tamaño del objeto
|
||||
void setPos(float pos_x, float pos_y); // Establece la posición del objeto
|
||||
void setPosX(float pos_x); // Establece la posición X
|
||||
void setPosY(float pos_y); // Establece la posición Y
|
||||
|
||||
protected:
|
||||
// --- Variables de posición y movimiento ---
|
||||
float x_ = 0.0F; // Posición en el eje X
|
||||
float y_ = 0.0F; // Posición en el eje Y
|
||||
protected:
|
||||
// --- Variables de posición y movimiento ---
|
||||
float x_ = 0.0F; // Posición en el eje X
|
||||
float y_ = 0.0F; // Posición en el eje Y
|
||||
|
||||
float vx_ = 0.0F; // Velocidad en el eje X. Cantidad de píxeles a desplazarse
|
||||
float vy_ = 0.0F; // Velocidad en el eje Y. Cantidad de píxeles a desplazarse
|
||||
float vx_ = 0.0F; // Velocidad en el eje X. Cantidad de píxeles a desplazarse
|
||||
float vy_ = 0.0F; // Velocidad en el eje Y. Cantidad de píxeles a desplazarse
|
||||
|
||||
float ax_ = 0.0F; // Aceleración en el eje X. Variación de la velocidad
|
||||
float ay_ = 0.0F; // Aceleración en el eje Y. Variación de la velocidad
|
||||
float ax_ = 0.0F; // Aceleración en el eje X. Variación de la velocidad
|
||||
float ay_ = 0.0F; // Aceleración en el eje Y. Variación de la velocidad
|
||||
|
||||
// --- Efectos visuales ---
|
||||
Rotate rotate_; // Variables usadas para controlar la rotación del sprite
|
||||
float zoom_w_; // Zoom aplicado a la anchura
|
||||
float zoom_h_; // Zoom aplicado a la altura
|
||||
SDL_FlipMode flip_; // Indica cómo se voltea el sprite
|
||||
// --- Efectos visuales ---
|
||||
Rotate rotate_; // Variables usadas para controlar la rotación del sprite
|
||||
float zoom_w_; // Zoom aplicado a la anchura
|
||||
float zoom_h_; // Zoom aplicado a la altura
|
||||
SDL_FlipMode flip_; // Indica cómo se voltea el sprite
|
||||
|
||||
// --- Métodos internos ---
|
||||
void updateAngle() { rotate_.angle += rotate_.amount; } // Incrementa el valor del ángulo
|
||||
void move(); // Mueve el sprite según velocidad y aceleración
|
||||
void rotate(); // Rota el sprite según los parámetros de rotación
|
||||
// --- Métodos internos ---
|
||||
void updateAngle() { rotate_.angle += rotate_.amount; } // Incrementa el valor del ángulo
|
||||
void move(); // Mueve el sprite según velocidad y aceleración
|
||||
void rotate(); // Rota el sprite según los parámetros de rotación
|
||||
};
|
||||
@@ -56,12 +56,9 @@ void Notifier::update() {
|
||||
clearFinishedNotifications();
|
||||
}
|
||||
|
||||
bool Notifier::shouldProcessNotification(int index) const {
|
||||
auto Notifier::shouldProcessNotification(int index) const -> bool {
|
||||
// Si la notificación anterior está "saliendo", no hagas nada
|
||||
if (index > 0 && notifications_[index - 1].state == NotificationStatus::RISING) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
return !(index > 0 && notifications_[index - 1].state == NotificationStatus::RISING);
|
||||
}
|
||||
|
||||
void Notifier::processNotification(int index) {
|
||||
@@ -103,11 +100,11 @@ void Notifier::updateNotificationState(int index) {
|
||||
void Notifier::handleRisingState(int index) {
|
||||
auto& notification = notifications_[index];
|
||||
|
||||
const float step = (float)notification.counter / notification.travel_dist;
|
||||
const int alpha = 255 * step;
|
||||
const float STEP = (float)notification.counter / notification.travel_dist;
|
||||
const int ALPHA = 255 * STEP;
|
||||
|
||||
moveNotificationVertically(notification, param.notification.pos_v == NotifyPosition::TOP ? 1 : -1);
|
||||
notification.texture->setAlpha(alpha);
|
||||
notification.texture->setAlpha(ALPHA);
|
||||
|
||||
if (notification.rect.y == notification.y) {
|
||||
transitionToStayState(index);
|
||||
@@ -126,11 +123,11 @@ void Notifier::handleStayState(int index) {
|
||||
void Notifier::handleVanishingState(int index) {
|
||||
auto& notification = notifications_[index];
|
||||
|
||||
const float step = notification.counter / (float)notification.travel_dist;
|
||||
const int alpha = 255 * (1 - step);
|
||||
const float STEP = notification.counter / (float)notification.travel_dist;
|
||||
const int ALPHA = 255 * (1 - STEP);
|
||||
|
||||
moveNotificationVertically(notification, param.notification.pos_v == NotifyPosition::TOP ? -1 : 1);
|
||||
notification.texture->setAlpha(alpha);
|
||||
notification.texture->setAlpha(ALPHA);
|
||||
|
||||
if (notification.rect.y == notification.y - notification.travel_dist) {
|
||||
notification.state = NotificationStatus::FINISHED;
|
||||
|
||||
@@ -75,17 +75,17 @@ class Notifier {
|
||||
bool has_icons_; // Indica si el notificador tiene textura para iconos
|
||||
|
||||
// --- Métodos internos ---
|
||||
void clearFinishedNotifications(); // Elimina las notificaciones cuyo estado es FINISHED
|
||||
void clearAllNotifications(); // Elimina todas las notificaciones activas, sin importar el estado
|
||||
bool shouldProcessNotification(int index) const; // Determina si una notificación debe ser procesada (según su estado y posición)
|
||||
void processNotification(int index); // Procesa una notificación en la posición dada: actualiza su estado y comportamiento visual
|
||||
void playNotificationSoundIfNeeded(const Notification ¬ification); // Reproduce sonido asociado si es necesario (dependiendo del estado o contenido)
|
||||
void updateNotificationState(int index); // Actualiza el estado interno de una notificación (ej. de RISING a STAY)
|
||||
void handleRisingState(int index); // Lógica de animación para el estado RISING (apareciendo)
|
||||
void handleStayState(int index); // Lógica para mantener una notificación visible en el estado STAY
|
||||
void handleVanishingState(int index); // Lógica de animación para el estado VANISHING (desapareciendo)
|
||||
void moveNotificationVertically(Notification ¬ification, int direction); // Mueve verticalmente una notificación en una dirección dada (útil para animación en apilamiento)
|
||||
void transitionToStayState(int index); // Cambia el estado de una notificación de RISING a STAY cuando ha alcanzado su posición final
|
||||
void clearFinishedNotifications(); // Elimina las notificaciones cuyo estado es FINISHED
|
||||
void clearAllNotifications(); // Elimina todas las notificaciones activas, sin importar el estado
|
||||
[[nodiscard]] auto shouldProcessNotification(int index) const -> bool; // Determina si una notificación debe ser procesada (según su estado y posición)
|
||||
void processNotification(int index); // Procesa una notificación en la posición dada: actualiza su estado y comportamiento visual
|
||||
static void playNotificationSoundIfNeeded(const Notification ¬ification); // Reproduce sonido asociado si es necesario (dependiendo del estado o contenido)
|
||||
void updateNotificationState(int index); // Actualiza el estado interno de una notificación (ej. de RISING a STAY)
|
||||
void handleRisingState(int index); // Lógica de animación para el estado RISING (apareciendo)
|
||||
void handleStayState(int index); // Lógica para mantener una notificación visible en el estado STAY
|
||||
void handleVanishingState(int index); // Lógica de animación para el estado VANISHING (desapareciendo)
|
||||
static void moveNotificationVertically(Notification ¬ification, int direction); // Mueve verticalmente una notificación en una dirección dada (útil para animación en apilamiento)
|
||||
void transitionToStayState(int index); // Cambia el estado de una notificación de RISING a STAY cuando ha alcanzado su posición final
|
||||
|
||||
// --- Constructor y destructor ---
|
||||
Notifier(std::string icon_file, std::shared_ptr<Text> text); // Constructor privado
|
||||
|
||||
@@ -131,7 +131,7 @@ void loadParamsFromFile(const std::string& file_path) {
|
||||
}
|
||||
|
||||
auto setParams(const std::string& var, const std::string& value) -> bool {
|
||||
static const std::unordered_map<std::string, std::function<void(const std::string&)>> intParams = {
|
||||
static const std::unordered_map<std::string, std::function<void(const std::string&)>> INT_PARAMS = {
|
||||
{"game.width", [](const std::string& v) { param.game.width = std::stoi(v); }},
|
||||
{"game.height", [](const std::string& v) { param.game.height = std::stoi(v); }},
|
||||
{"game.item_size", [](const std::string& v) { param.game.item_size = std::stoi(v); }},
|
||||
@@ -159,7 +159,7 @@ auto setParams(const std::string& var, const std::string& value) -> bool {
|
||||
{"title.title_c_c_position", [](const std::string& v) { param.title.title_c_c_position = std::stoi(v); }},
|
||||
{"intro.text_distance_from_bottom", [](const std::string& v) { param.intro.text_distance_from_bottom = std::stoi(v); }}};
|
||||
|
||||
static const std::unordered_map<std::string, std::function<void(const std::string&)>> colorParams = {
|
||||
static const std::unordered_map<std::string, std::function<void(const std::string&)>> COLOR_PARAMS = {
|
||||
{"fade.color", [](const std::string& v) { param.fade.color = Color::fromHex(v); }},
|
||||
{"scoreboard.separator_color", [](const std::string& v) { param.scoreboard.separator_color = Color::fromHex(v); }},
|
||||
{"scoreboard.easy_color", [](const std::string& v) { param.scoreboard.easy_color = Color::fromHex(v); }},
|
||||
@@ -180,7 +180,7 @@ auto setParams(const std::string& var, const std::string& value) -> bool {
|
||||
{"debug.color", [](const std::string& v) { param.debug.color = Color::fromHex(v); }},
|
||||
{"resource.color", [](const std::string& v) { param.resource.color = Color::fromHex(v); }}};
|
||||
|
||||
static const std::unordered_map<std::string, std::function<void(const std::string&)>> boolParams = {
|
||||
static const std::unordered_map<std::string, std::function<void(const std::string&)>> BOOL_PARAMS = {
|
||||
{"game.hit_stop", [](const std::string& v) { param.game.hit_stop = stringToBool(v); }},
|
||||
{"scoreboard.separator_autocolor", [](const std::string& v) { param.scoreboard.separator_autocolor = stringToBool(v); }},
|
||||
{"scoreboard.text_autocolor", [](const std::string& v) { param.scoreboard.text_autocolor = stringToBool(v); }},
|
||||
@@ -188,7 +188,7 @@ auto setParams(const std::string& var, const std::string& value) -> bool {
|
||||
{"notification.sound", [](const std::string& v) { param.notification.sound = stringToBool(v); }},
|
||||
{"service_menu.drop_shadow", [](const std::string& v) { param.service_menu.drop_shadow = stringToBool(v); }}};
|
||||
|
||||
static const std::unordered_map<std::string, std::function<void(const std::string&)>> floatParams = {
|
||||
static const std::unordered_map<std::string, std::function<void(const std::string&)>> FLOAT_PARAMS = {
|
||||
{"balloon.settings[0].vel", [](const std::string& v) { param.balloon.settings.at(0).vel = std::stof(v); }},
|
||||
{"balloon.settings[0].grav", [](const std::string& v) { param.balloon.settings.at(0).grav = std::stof(v); }},
|
||||
{"balloon.settings[1].vel", [](const std::string& v) { param.balloon.settings.at(1).vel = std::stof(v); }},
|
||||
@@ -198,24 +198,24 @@ auto setParams(const std::string& var, const std::string& value) -> bool {
|
||||
{"balloon.settings[3].vel", [](const std::string& v) { param.balloon.settings.at(3).vel = std::stof(v); }},
|
||||
{"balloon.settings[3].grav", [](const std::string& v) { param.balloon.settings.at(3).grav = std::stof(v); }}};
|
||||
|
||||
static const std::unordered_map<std::string, std::function<void(const std::string&)>> stringParams = {
|
||||
static const std::unordered_map<std::string, std::function<void(const std::string&)>> STRING_PARAMS = {
|
||||
{"balloon.color[0]", [](const std::string& v) { param.balloon.color.at(0) = v; }},
|
||||
{"balloon.color[1]", [](const std::string& v) { param.balloon.color.at(1) = v; }},
|
||||
{"balloon.color[2]", [](const std::string& v) { param.balloon.color.at(2) = v; }},
|
||||
{"balloon.color[3]", [](const std::string& v) { param.balloon.color.at(3) = v; }}};
|
||||
|
||||
// Intentar cada mapa de parámetros
|
||||
auto tryMap = [&](const auto& paramMap) -> bool {
|
||||
auto it = paramMap.find(var);
|
||||
if (it != paramMap.end()) {
|
||||
auto try_map = [&](const auto& param_map) -> bool {
|
||||
auto it = param_map.find(var);
|
||||
if (it != param_map.end()) {
|
||||
it->second(value);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
if (tryMap(intParams) || tryMap(colorParams) || tryMap(boolParams) ||
|
||||
tryMap(floatParams) || tryMap(stringParams)) {
|
||||
if (try_map(INT_PARAMS) || try_map(COLOR_PARAMS) || try_map(BOOL_PARAMS) ||
|
||||
try_map(FLOAT_PARAMS) || try_map(STRING_PARAMS)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
144
source/param.h
144
source/param.h
@@ -9,125 +9,125 @@
|
||||
|
||||
// --- Parámetros del juego ---
|
||||
struct ParamGame {
|
||||
float width; // Ancho de la resolución nativa del juego
|
||||
float height; // Alto de la resolución nativa del juego
|
||||
float item_size; // Tamaño de los ítems del juego
|
||||
Zone play_area; // Rectángulo con la posición de la zona de juego
|
||||
Zone game_area; // Rectángulo con las dimensiones del juego
|
||||
int name_entry_idle_time; // Segundos para introducir el nombre al finalizar la partida si no se pulsa nada
|
||||
int name_entry_total_time; // Segundos totales para introducir el nombre al finalizar la partida
|
||||
Uint32 speed; // Velocidad a la que transcurre el juego
|
||||
bool hit_stop; // Indica si debe haber un paro cuando el jugador es golpeado por un globo
|
||||
Uint32 hit_stop_ms; // Cantidad de milisegundos que dura el hit_stop
|
||||
float width; // Ancho de la resolución nativa del juego
|
||||
float height; // Alto de la resolución nativa del juego
|
||||
float item_size; // Tamaño de los ítems del juego
|
||||
Zone play_area; // Rectángulo con la posición de la zona de juego
|
||||
Zone game_area; // Rectángulo con las dimensiones del juego
|
||||
int name_entry_idle_time; // Segundos para introducir el nombre al finalizar la partida si no se pulsa nada
|
||||
int name_entry_total_time; // Segundos totales para introducir el nombre al finalizar la partida
|
||||
Uint32 speed; // Velocidad a la que transcurre el juego
|
||||
bool hit_stop; // Indica si debe haber un paro cuando el jugador es golpeado por un globo
|
||||
Uint32 hit_stop_ms; // Cantidad de milisegundos que dura el hit_stop
|
||||
};
|
||||
|
||||
// --- Parámetros del fade ---
|
||||
struct ParamFade {
|
||||
Color color; // Color del fade
|
||||
float num_squares_width; // Cantidad total de cuadraditos en horizontal para el FadeType::RANDOM_SQUARE
|
||||
float num_squares_height; // Cantidad total de cuadraditos en vertical para el FadeType::RANDOM_SQUARE
|
||||
int random_squares_delay; // Duración entre cada pintado de cuadrados
|
||||
int random_squares_mult; // Cantidad de cuadrados que se pintarán cada vez
|
||||
int post_duration; // Duración final del fade
|
||||
float venetian_size; // Altura de los rectángulos para FadeType::VENETIAN
|
||||
Color color; // Color del fade
|
||||
float num_squares_width; // Cantidad total de cuadraditos en horizontal para el FadeType::RANDOM_SQUARE
|
||||
float num_squares_height; // Cantidad total de cuadraditos en vertical para el FadeType::RANDOM_SQUARE
|
||||
int random_squares_delay; // Duración entre cada pintado de cuadrados
|
||||
int random_squares_mult; // Cantidad de cuadrados que se pintarán cada vez
|
||||
int post_duration; // Duración final del fade
|
||||
float venetian_size; // Altura de los rectángulos para FadeType::VENETIAN
|
||||
};
|
||||
|
||||
// --- Parámetros de la pantalla de título ---
|
||||
struct ParamTitle {
|
||||
int press_start_position; // Posición del texto para empezar a jugar
|
||||
int title_duration; // Tiempo de inactividad del título
|
||||
int arcade_edition_position; // Posición del bitmap "Arcade Edition"
|
||||
int title_c_c_position; // Posición del bitmap "Coffee Crisis"
|
||||
Color bg_color; // Color para los tiles de fondo
|
||||
int press_start_position; // Posición del texto para empezar a jugar
|
||||
int title_duration; // Tiempo de inactividad del título
|
||||
int arcade_edition_position; // Posición del bitmap "Arcade Edition"
|
||||
int title_c_c_position; // Posición del bitmap "Coffee Crisis"
|
||||
Color bg_color; // Color para los tiles de fondo
|
||||
};
|
||||
|
||||
// --- Parámetros del fondo ---
|
||||
struct ParamBackground {
|
||||
Color attenuate_color; // Color para atenuar el fondo
|
||||
Color attenuate_color; // Color para atenuar el fondo
|
||||
};
|
||||
|
||||
// --- Parámetros de los globos ---
|
||||
struct ParamBalloon {
|
||||
struct Settings {
|
||||
float grav; // Aceleración en el eje Y. Modifica la velocidad
|
||||
float vel; // Velocidad inicial al rebotar contra el suelo
|
||||
struct Settings {
|
||||
float grav; // Aceleración en el eje Y. Modifica la velocidad
|
||||
float vel; // Velocidad inicial al rebotar contra el suelo
|
||||
|
||||
// Constructor
|
||||
explicit Settings(float grav_val = 0.0F, float vel_val = 0.0F)
|
||||
: grav(grav_val), vel(vel_val) {}
|
||||
};
|
||||
// Constructor
|
||||
explicit Settings(float grav_val = 0.0F, float vel_val = 0.0F)
|
||||
: grav(grav_val), vel(vel_val) {}
|
||||
};
|
||||
|
||||
std::array<Settings, 4> settings;
|
||||
std::array<std::string, 4> color;
|
||||
bool bouncing_sound; // Indica si los globos hacer sonido al rebotar
|
||||
std::array<Settings, 4> settings;
|
||||
std::array<std::string, 4> color;
|
||||
bool bouncing_sound; // Indica si los globos hacer sonido al rebotar
|
||||
};
|
||||
|
||||
// --- Parámetros de las notificaciones ---
|
||||
struct ParamNotification {
|
||||
NotifyPosition pos_h; // Ubicación horizontal de las notificaciones en pantalla
|
||||
NotifyPosition pos_v; // Ubicación vertical de las notificaciones en pantalla
|
||||
bool sound; // Indica si las notificaciones suenan
|
||||
Color color; // Color de las notificaciones
|
||||
NotifyPosition pos_h; // Ubicación horizontal de las notificaciones en pantalla
|
||||
NotifyPosition pos_v; // Ubicación vertical de las notificaciones en pantalla
|
||||
bool sound; // Indica si las notificaciones suenan
|
||||
Color color; // Color de las notificaciones
|
||||
};
|
||||
|
||||
// --- Parámetros del marcador ---
|
||||
struct ParamScoreboard {
|
||||
SDL_FRect rect; // Posición y tamaño del marcador
|
||||
bool separator_autocolor; // El separado establece su color de forma automatica
|
||||
Color separator_color; // Color del separador si se pone de forma manual
|
||||
Color easy_color; // Color del marcador segun la dificultad
|
||||
Color normal_color; // Color del marcador segun la dificultad
|
||||
Color hard_color; // Color del marcador segun la dificultad
|
||||
bool text_autocolor; // El texto establece su color de forma automatica
|
||||
Color text_color1; // Color del texto
|
||||
Color text_color2; // Color del texto
|
||||
int skip_countdown_value; // Valor a partir del cual se puede saltar la cuenta atras
|
||||
SDL_FRect rect; // Posición y tamaño del marcador
|
||||
bool separator_autocolor; // El separado establece su color de forma automatica
|
||||
Color separator_color; // Color del separador si se pone de forma manual
|
||||
Color easy_color; // Color del marcador segun la dificultad
|
||||
Color normal_color; // Color del marcador segun la dificultad
|
||||
Color hard_color; // Color del marcador segun la dificultad
|
||||
bool text_autocolor; // El texto establece su color de forma automatica
|
||||
Color text_color1; // Color del texto
|
||||
Color text_color2; // Color del texto
|
||||
int skip_countdown_value; // Valor a partir del cual se puede saltar la cuenta atras
|
||||
};
|
||||
|
||||
// --- Parámetros del menú de servicio ---
|
||||
struct ParamServiceMenu {
|
||||
Color title_color;
|
||||
Color text_color;
|
||||
Color selected_color;
|
||||
Color bg_color;
|
||||
bool drop_shadow;
|
||||
Color title_color;
|
||||
Color text_color;
|
||||
Color selected_color;
|
||||
Color bg_color;
|
||||
bool drop_shadow;
|
||||
};
|
||||
|
||||
// --- Parámetros de la intro ---
|
||||
struct ParamIntro {
|
||||
Color bg_color;
|
||||
Color card_color;
|
||||
Color shadow_color;
|
||||
int text_distance_from_bottom;
|
||||
Color bg_color;
|
||||
Color card_color;
|
||||
Color shadow_color;
|
||||
int text_distance_from_bottom;
|
||||
};
|
||||
|
||||
// --- Parámetros para Debug ---
|
||||
struct ParamDebug {
|
||||
Color color;
|
||||
Color color;
|
||||
};
|
||||
|
||||
// --- Parámetros para Resource ---
|
||||
struct ParamResource {
|
||||
Color color;
|
||||
Color color;
|
||||
};
|
||||
|
||||
// --- Estructura principal para almacenar todos los parámetros del juego ---
|
||||
struct Param {
|
||||
ParamGame game; // Parámetros del juego
|
||||
ParamFade fade; // Parámetros del fade
|
||||
ParamScoreboard scoreboard; // Rectángulo del marcador
|
||||
ParamTitle title; // Parámetros de la pantalla de título
|
||||
ParamBackground background; // Parámetros del fondo
|
||||
ParamBalloon balloon; // Parámetros de los globos
|
||||
ParamNotification notification; // Parámetros de las notificaciones
|
||||
ParamServiceMenu service_menu; // Parámetros del menú de servicio
|
||||
ParamIntro intro; // Parámetros de la intro
|
||||
ParamDebug debug; // Parámetros para Debug
|
||||
ParamResource resource; // Parámetros para Resource
|
||||
ParamGame game; // Parámetros del juego
|
||||
ParamFade fade; // Parámetros del fade
|
||||
ParamScoreboard scoreboard; // Rectángulo del marcador
|
||||
ParamTitle title; // Parámetros de la pantalla de título
|
||||
ParamBackground background; // Parámetros del fondo
|
||||
ParamBalloon balloon; // Parámetros de los globos
|
||||
ParamNotification notification; // Parámetros de las notificaciones
|
||||
ParamServiceMenu service_menu; // Parámetros del menú de servicio
|
||||
ParamIntro intro; // Parámetros de la intro
|
||||
ParamDebug debug; // Parámetros para Debug
|
||||
ParamResource resource; // Parámetros para Resource
|
||||
|
||||
// Constructor
|
||||
Param()
|
||||
: game(), fade(), scoreboard(), title(), background(), balloon(), notification(), service_menu(), intro(), debug(), resource() {}
|
||||
// Constructor
|
||||
Param()
|
||||
: game(), fade(), scoreboard(), title(), background(), balloon(), notification(), service_menu(), intro(), debug(), resource() {}
|
||||
};
|
||||
|
||||
// --- Variable global con los parámetros del juego ---
|
||||
|
||||
@@ -25,15 +25,15 @@ enum class PathCentered {
|
||||
|
||||
// --- Estructura Path: define un recorrido para el sprite ---
|
||||
struct Path {
|
||||
std::vector<SDL_FPoint> spots; // Puntos por los que se desplazará el sprite
|
||||
int waiting_counter; // Tiempo de espera una vez en el destino
|
||||
bool on_destination = false; // Indica si ha llegado al destino
|
||||
bool finished = false; // Indica si ha terminado de esperarse
|
||||
int counter = 0; // Contador interno
|
||||
std::vector<SDL_FPoint> spots; // Puntos por los que se desplazará el sprite
|
||||
int waiting_counter; // Tiempo de espera una vez en el destino
|
||||
bool on_destination = false; // Indica si ha llegado al destino
|
||||
bool finished = false; // Indica si ha terminado de esperarse
|
||||
int counter = 0; // Contador interno
|
||||
|
||||
// Constructor
|
||||
Path(const std::vector<SDL_FPoint> &spots_init, int waiting_counter_init)
|
||||
: spots(spots_init), waiting_counter(waiting_counter_init) {}
|
||||
// Constructor
|
||||
Path(const std::vector<SDL_FPoint> &spots_init, int waiting_counter_init)
|
||||
: spots(spots_init), waiting_counter(waiting_counter_init) {}
|
||||
};
|
||||
|
||||
// Devuelve un vector con los puntos que conforman la ruta
|
||||
@@ -41,36 +41,36 @@ auto createPath(float start, float end, PathType type, float fixed_pos, int step
|
||||
|
||||
// --- Clase PathSprite: Sprite que sigue uno o varios recorridos ---
|
||||
class PathSprite : public Sprite {
|
||||
public:
|
||||
// --- Constructor y destructor ---
|
||||
explicit PathSprite(std::shared_ptr<Texture> texture)
|
||||
: Sprite(texture) {}
|
||||
~PathSprite() override = default;
|
||||
public:
|
||||
// --- Constructor y destructor ---
|
||||
explicit PathSprite(std::shared_ptr<Texture> texture)
|
||||
: Sprite(texture) {}
|
||||
~PathSprite() override = default;
|
||||
|
||||
// --- Métodos principales ---
|
||||
void update(); // Actualiza la posición del sprite según el recorrido
|
||||
void render() override; // Muestra el sprite por pantalla
|
||||
// --- Métodos principales ---
|
||||
void update(); // Actualiza la posición del sprite según el recorrido
|
||||
void render() override; // Muestra el sprite por pantalla
|
||||
|
||||
// --- Gestión de recorridos ---
|
||||
void addPath(Path path, bool centered = false); // Añade un recorrido (Path)
|
||||
void addPath(std::vector<SDL_FPoint> spots, int waiting_counter = 0); // Añade un recorrido a partir de puntos
|
||||
void addPath(int start, int end, PathType type, int fixed_pos, int steps, const std::function<double(double)> &easing_function, int waiting_counter = 0); // Añade un recorrido generado
|
||||
// --- Gestión de recorridos ---
|
||||
void addPath(Path path, bool centered = false); // Añade un recorrido (Path)
|
||||
void addPath(std::vector<SDL_FPoint> spots, int waiting_counter = 0); // Añade un recorrido a partir de puntos
|
||||
void addPath(int start, int end, PathType type, int fixed_pos, int steps, const std::function<double(double)> &easing_function, int waiting_counter = 0); // Añade un recorrido generado
|
||||
|
||||
// --- Estado y control ---
|
||||
void enable(); // Habilita el objeto
|
||||
[[nodiscard]] auto hasFinished() const -> bool; // Indica si ha terminado todos los recorridos
|
||||
// --- Estado y control ---
|
||||
void enable(); // Habilita el objeto
|
||||
[[nodiscard]] auto hasFinished() const -> bool; // Indica si ha terminado todos los recorridos
|
||||
|
||||
// --- Getters ---
|
||||
[[nodiscard]] auto getCurrentPath() const -> int { return current_path_; } // Devuelve el índice del recorrido actual
|
||||
// --- Getters ---
|
||||
[[nodiscard]] auto getCurrentPath() const -> int { return current_path_; } // Devuelve el índice del recorrido actual
|
||||
|
||||
private:
|
||||
// --- Variables internas ---
|
||||
bool enabled_ = false; // Indica si el objeto está habilitado
|
||||
bool has_finished_ = false; // Indica si el objeto ha finalizado el recorrido
|
||||
int current_path_ = 0; // Recorrido que se está recorriendo actualmente
|
||||
std::vector<Path> paths_; // Caminos a recorrer por el sprite
|
||||
private:
|
||||
// --- Variables internas ---
|
||||
bool enabled_ = false; // Indica si el objeto está habilitado
|
||||
bool has_finished_ = false; // Indica si el objeto ha finalizado el recorrido
|
||||
int current_path_ = 0; // Recorrido que se está recorriendo actualmente
|
||||
std::vector<Path> paths_; // Caminos a recorrer por el sprite
|
||||
|
||||
// --- Métodos internos ---
|
||||
void moveThroughCurrentPath(); // Coloca el sprite en los diferentes puntos del recorrido
|
||||
void goToNextPathOrDie(); // Cambia de recorrido o finaliza
|
||||
// --- Métodos internos ---
|
||||
void moveThroughCurrentPath(); // Coloca el sprite en los diferentes puntos del recorrido
|
||||
void goToNextPathOrDie(); // Cambia de recorrido o finaliza
|
||||
};
|
||||
@@ -147,182 +147,217 @@ void Player::setInputEnteringName(InputAction input) {
|
||||
// Mueve el jugador a la posición y animación que le corresponde
|
||||
void Player::move() {
|
||||
switch (playing_state_) {
|
||||
case PlayerState::PLAYING: {
|
||||
// Mueve el jugador a derecha o izquierda
|
||||
pos_x_ += vel_x_;
|
||||
|
||||
// Si el jugador abandona el area de juego por los laterales, restaura su posición
|
||||
const float MIN_X = play_area_.x - 5;
|
||||
const float MAX_X = play_area_.w + 5 - WIDTH;
|
||||
pos_x_ = std::clamp(pos_x_, MIN_X, MAX_X);
|
||||
|
||||
shiftSprite();
|
||||
case PlayerState::PLAYING:
|
||||
handlePlayingMovement();
|
||||
break;
|
||||
}
|
||||
case PlayerState::ROLLING: {
|
||||
// Si el jugador abandona el area de juego por los laterales lo hace rebotar
|
||||
const int X = player_sprite_->getPosX();
|
||||
const int MIN_X = play_area_.x;
|
||||
const int MAX_X = play_area_.x + play_area_.w - WIDTH;
|
||||
if ((X < MIN_X) || (X > MAX_X)) {
|
||||
player_sprite_->setPosX(std::clamp(X, MIN_X, MAX_X));
|
||||
player_sprite_->setVelX(-player_sprite_->getVelX());
|
||||
playSound("jump.wav");
|
||||
}
|
||||
|
||||
// Si el jugador toca el suelo rebota y si tiene poca velocidad, se detiene y cambia de estado
|
||||
if (player_sprite_->getPosY() > play_area_.h - HEIGHT) {
|
||||
if (player_sprite_->getVelY() < 2.0F) {
|
||||
// Si la velocidad de rebote es baja, lo detiene y cambia de estado
|
||||
const auto NEXT_PLAYER_STATUS = isEligibleForHighScore() ? PlayerState::ENTERING_NAME : PlayerState::CONTINUE;
|
||||
demo_ ? setPlayingState(PlayerState::LYING_ON_THE_FLOOR_FOREVER) : setPlayingState(NEXT_PLAYER_STATUS);
|
||||
pos_x_ = player_sprite_->getPosX();
|
||||
pos_y_ = default_pos_y_;
|
||||
player_sprite_->clear();
|
||||
shiftSprite();
|
||||
playSound("jump.wav");
|
||||
} else {
|
||||
// Decrementa las velocidades de rebote
|
||||
player_sprite_->setPosY(play_area_.h - HEIGHT);
|
||||
player_sprite_->setVelY(player_sprite_->getVelY() * -0.5F);
|
||||
player_sprite_->setVelX(player_sprite_->getVelX() * 0.75F);
|
||||
player_sprite_->setAnimationSpeed(player_sprite_->getAnimationSpeed() * 2);
|
||||
playSound("jump.wav");
|
||||
}
|
||||
}
|
||||
case PlayerState::ROLLING:
|
||||
handleRollingMovement();
|
||||
break;
|
||||
}
|
||||
case PlayerState::TITLE_ANIMATION: {
|
||||
// Si el jugador abandona el area de juego por los laterales lo detiene
|
||||
/*const int X = player_sprite_->getPosX();
|
||||
const int MIN_X = play_area_.x - WIDTH;
|
||||
const int MAX_X = play_area_.x + play_area_.w;
|
||||
if ((X < MIN_X) || (X > MAX_X))
|
||||
{
|
||||
setPlayingState(PlayerState::TITLE_HIDDEN);
|
||||
}
|
||||
|
||||
// Si el jugador toca el suelo rebota lo detiene
|
||||
if (player_sprite_->getPosY() > play_area_.h)
|
||||
{
|
||||
setPlayingState(PlayerState::TITLE_HIDDEN);
|
||||
}*/
|
||||
|
||||
switch (id_) {
|
||||
case 1:
|
||||
setInputPlaying(InputAction::LEFT);
|
||||
break;
|
||||
case 2:
|
||||
setInputPlaying(InputAction::RIGHT);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
pos_x_ += vel_x_ * 2.0F;
|
||||
const float MIN_X = -WIDTH;
|
||||
const float MAX_X = play_area_.w;
|
||||
pos_x_ = std::clamp(pos_x_, MIN_X, MAX_X);
|
||||
shiftSprite();
|
||||
|
||||
if (pos_x_ == MIN_X || pos_x_ == MAX_X) {
|
||||
setPlayingState(PlayerState::TITLE_HIDDEN);
|
||||
}
|
||||
case PlayerState::TITLE_ANIMATION:
|
||||
handleTitleAnimation();
|
||||
break;
|
||||
}
|
||||
case PlayerState::CONTINUE_TIME_OUT: {
|
||||
// Si el cadaver desaparece por el suelo, cambia de estado
|
||||
if (player_sprite_->getPosY() > play_area_.h) {
|
||||
setPlayingState(PlayerState::WAITING);
|
||||
}
|
||||
case PlayerState::CONTINUE_TIME_OUT:
|
||||
handleContinueTimeOut();
|
||||
break;
|
||||
}
|
||||
case PlayerState::LEAVING_SCREEN: {
|
||||
++step_counter_;
|
||||
if (step_counter_ % 10 == 0) {
|
||||
playSound("walk.wav");
|
||||
}
|
||||
|
||||
switch (id_) {
|
||||
case 1:
|
||||
setInputPlaying(InputAction::LEFT);
|
||||
break;
|
||||
case 2:
|
||||
setInputPlaying(InputAction::RIGHT);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
pos_x_ += vel_x_;
|
||||
const float MIN_X = -WIDTH;
|
||||
const float MAX_X = play_area_.w;
|
||||
pos_x_ = std::clamp(pos_x_, MIN_X, MAX_X);
|
||||
shiftSprite();
|
||||
|
||||
if (pos_x_ == MIN_X || pos_x_ == MAX_X) {
|
||||
setPlayingState(PlayerState::GAME_OVER);
|
||||
}
|
||||
case PlayerState::LEAVING_SCREEN:
|
||||
handleLeavingScreen();
|
||||
break;
|
||||
}
|
||||
case PlayerState::ENTERING_SCREEN: {
|
||||
++step_counter_;
|
||||
if (step_counter_ % 10 == 0) {
|
||||
playSound("walk.wav");
|
||||
}
|
||||
|
||||
switch (id_) {
|
||||
case 1:
|
||||
setInputPlaying(InputAction::RIGHT);
|
||||
pos_x_ += vel_x_;
|
||||
if (pos_x_ > default_pos_x_) {
|
||||
pos_x_ = default_pos_x_;
|
||||
setPlayingState(PlayerState::PLAYING);
|
||||
setInvulnerable(false);
|
||||
}
|
||||
break;
|
||||
case 2:
|
||||
setInputPlaying(InputAction::LEFT);
|
||||
pos_x_ += vel_x_;
|
||||
if (pos_x_ < default_pos_x_) {
|
||||
pos_x_ = default_pos_x_;
|
||||
setPlayingState(PlayerState::PLAYING);
|
||||
setInvulnerable(false);
|
||||
}
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
shiftSprite();
|
||||
case PlayerState::ENTERING_SCREEN:
|
||||
handleEnteringScreen();
|
||||
break;
|
||||
}
|
||||
case PlayerState::CREDITS: {
|
||||
pos_x_ += vel_x_ / 2.0F;
|
||||
if (vel_x_ > 0) {
|
||||
// setInputPlaying(InputAction::RIGHT);
|
||||
if (pos_x_ > param.game.game_area.rect.w - WIDTH) {
|
||||
pos_x_ = param.game.game_area.rect.w - WIDTH;
|
||||
vel_x_ *= -1;
|
||||
}
|
||||
} else {
|
||||
// setInputPlaying(InputAction::LEFT);
|
||||
if (pos_x_ < param.game.game_area.rect.x) {
|
||||
pos_x_ = param.game.game_area.rect.x;
|
||||
vel_x_ *= -1;
|
||||
}
|
||||
}
|
||||
|
||||
if (pos_x_ > param.game.game_area.center_x - WIDTH / 2) {
|
||||
setWalkingState(PlayerState::WALKING_LEFT);
|
||||
} else {
|
||||
setWalkingState(PlayerState::WALKING_RIGHT);
|
||||
}
|
||||
shiftSprite();
|
||||
case PlayerState::CREDITS:
|
||||
handleCreditsMovement();
|
||||
break;
|
||||
}
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
void Player::handlePlayingMovement() {
|
||||
// Mueve el jugador a derecha o izquierda
|
||||
pos_x_ += vel_x_;
|
||||
|
||||
// Si el jugador abandona el area de juego por los laterales, restaura su posición
|
||||
const float MIN_X = play_area_.x - 5;
|
||||
const float MAX_X = play_area_.w + 5 - WIDTH;
|
||||
pos_x_ = std::clamp(pos_x_, MIN_X, MAX_X);
|
||||
|
||||
shiftSprite();
|
||||
}
|
||||
|
||||
void Player::handleRollingMovement() {
|
||||
handleRollingBoundaryCollision();
|
||||
handleRollingGroundCollision();
|
||||
}
|
||||
|
||||
void Player::handleRollingBoundaryCollision() {
|
||||
const int X = player_sprite_->getPosX();
|
||||
const int MIN_X = play_area_.x;
|
||||
const int MAX_X = play_area_.x + play_area_.w - WIDTH;
|
||||
|
||||
if ((X < MIN_X) || (X > MAX_X)) {
|
||||
player_sprite_->setPosX(std::clamp(X, MIN_X, MAX_X));
|
||||
player_sprite_->setVelX(-player_sprite_->getVelX());
|
||||
playSound("jump.wav");
|
||||
}
|
||||
}
|
||||
|
||||
void Player::handleRollingGroundCollision() {
|
||||
if (player_sprite_->getPosY() <= play_area_.h - HEIGHT) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (player_sprite_->getVelY() < 2.0F) {
|
||||
handleRollingStop();
|
||||
} else {
|
||||
handleRollingBounce();
|
||||
}
|
||||
}
|
||||
|
||||
void Player::handleRollingStop() {
|
||||
const auto NEXT_PLAYER_STATUS = isEligibleForHighScore() ? PlayerState::ENTERING_NAME : PlayerState::CONTINUE;
|
||||
|
||||
const auto NEXT_STATE = demo_ ? PlayerState::LYING_ON_THE_FLOOR_FOREVER : NEXT_PLAYER_STATUS;
|
||||
|
||||
setPlayingState(NEXT_STATE);
|
||||
pos_x_ = player_sprite_->getPosX();
|
||||
pos_y_ = default_pos_y_;
|
||||
player_sprite_->clear();
|
||||
shiftSprite();
|
||||
playSound("jump.wav");
|
||||
}
|
||||
|
||||
void Player::handleRollingBounce() {
|
||||
player_sprite_->setPosY(play_area_.h - HEIGHT);
|
||||
player_sprite_->setVelY(player_sprite_->getVelY() * -0.5F);
|
||||
player_sprite_->setVelX(player_sprite_->getVelX() * 0.75F);
|
||||
player_sprite_->setAnimationSpeed(player_sprite_->getAnimationSpeed() * 2);
|
||||
playSound("jump.wav");
|
||||
}
|
||||
|
||||
void Player::handleTitleAnimation() {
|
||||
setInputBasedOnPlayerId();
|
||||
|
||||
pos_x_ += vel_x_ * 2.0F;
|
||||
const float MIN_X = -WIDTH;
|
||||
const float MAX_X = play_area_.w;
|
||||
pos_x_ = std::clamp(pos_x_, MIN_X, MAX_X);
|
||||
shiftSprite();
|
||||
|
||||
if (pos_x_ == MIN_X || pos_x_ == MAX_X) {
|
||||
setPlayingState(PlayerState::TITLE_HIDDEN);
|
||||
}
|
||||
}
|
||||
|
||||
void Player::handleContinueTimeOut() {
|
||||
// Si el cadaver desaparece por el suelo, cambia de estado
|
||||
if (player_sprite_->getPosY() > play_area_.h) {
|
||||
setPlayingState(PlayerState::WAITING);
|
||||
}
|
||||
}
|
||||
|
||||
void Player::handleLeavingScreen() {
|
||||
updateStepCounter();
|
||||
setInputBasedOnPlayerId();
|
||||
|
||||
pos_x_ += vel_x_;
|
||||
const float MIN_X = -WIDTH;
|
||||
const float MAX_X = play_area_.w;
|
||||
pos_x_ = std::clamp(pos_x_, MIN_X, MAX_X);
|
||||
shiftSprite();
|
||||
|
||||
if (pos_x_ == MIN_X || pos_x_ == MAX_X) {
|
||||
setPlayingState(PlayerState::GAME_OVER);
|
||||
}
|
||||
}
|
||||
|
||||
void Player::handleEnteringScreen() {
|
||||
updateStepCounter();
|
||||
|
||||
if (id_ == 1) {
|
||||
handlePlayer1Entering();
|
||||
} else if (id_ == 2) {
|
||||
handlePlayer2Entering();
|
||||
}
|
||||
|
||||
shiftSprite();
|
||||
}
|
||||
|
||||
void Player::handlePlayer1Entering() {
|
||||
setInputPlaying(InputAction::RIGHT);
|
||||
pos_x_ += vel_x_;
|
||||
if (pos_x_ > default_pos_x_) {
|
||||
pos_x_ = default_pos_x_;
|
||||
setPlayingState(PlayerState::PLAYING);
|
||||
setInvulnerable(false);
|
||||
}
|
||||
}
|
||||
|
||||
void Player::handlePlayer2Entering() {
|
||||
setInputPlaying(InputAction::LEFT);
|
||||
pos_x_ += vel_x_;
|
||||
if (pos_x_ < default_pos_x_) {
|
||||
pos_x_ = default_pos_x_;
|
||||
setPlayingState(PlayerState::PLAYING);
|
||||
setInvulnerable(false);
|
||||
}
|
||||
}
|
||||
|
||||
void Player::handleCreditsMovement() {
|
||||
pos_x_ += vel_x_ / 2.0F;
|
||||
|
||||
if (vel_x_ > 0) {
|
||||
handleCreditsRightMovement();
|
||||
} else {
|
||||
handleCreditsLeftMovement();
|
||||
}
|
||||
|
||||
updateWalkingStateForCredits();
|
||||
shiftSprite();
|
||||
}
|
||||
|
||||
void Player::handleCreditsRightMovement() {
|
||||
if (pos_x_ > param.game.game_area.rect.w - WIDTH) {
|
||||
pos_x_ = param.game.game_area.rect.w - WIDTH;
|
||||
vel_x_ *= -1;
|
||||
}
|
||||
}
|
||||
|
||||
void Player::handleCreditsLeftMovement() {
|
||||
if (pos_x_ < param.game.game_area.rect.x) {
|
||||
pos_x_ = param.game.game_area.rect.x;
|
||||
vel_x_ *= -1;
|
||||
}
|
||||
}
|
||||
|
||||
void Player::updateWalkingStateForCredits() {
|
||||
if (pos_x_ > param.game.game_area.center_x - WIDTH / 2) {
|
||||
setWalkingState(PlayerState::WALKING_LEFT);
|
||||
} else {
|
||||
setWalkingState(PlayerState::WALKING_RIGHT);
|
||||
}
|
||||
}
|
||||
|
||||
void Player::setInputBasedOnPlayerId() {
|
||||
switch (id_) {
|
||||
case 1:
|
||||
setInputPlaying(InputAction::LEFT);
|
||||
break;
|
||||
case 2:
|
||||
setInputPlaying(InputAction::RIGHT);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
void Player::updateStepCounter() {
|
||||
++step_counter_;
|
||||
if (step_counter_ % 10 == 0) {
|
||||
playSound("walk.wav");
|
||||
}
|
||||
}
|
||||
|
||||
// Pinta el jugador en pantalla
|
||||
void Player::render() {
|
||||
if (power_up_ && isPlaying()) {
|
||||
@@ -404,63 +439,88 @@ void Player::setAnimation() {
|
||||
|
||||
// Actualiza el valor de la variable
|
||||
void Player::updateCooldown() {
|
||||
if (playing_state_ == PlayerState::PLAYING) {
|
||||
if (cant_fire_counter_ > 0) {
|
||||
cooling_state_counter_ = COOLING_DURATION;
|
||||
|
||||
// La mitad del tiempo que no puede disparar tiene el brazo arriba (PlayerState::FIRING)
|
||||
// y la otra mitad en retroceso (PlayerState::RECOILING)
|
||||
if (cant_fire_counter_ == recoiling_state_duration_ / 2) {
|
||||
switch (firing_state_) {
|
||||
case PlayerState::FIRING_LEFT:
|
||||
setFiringState(PlayerState::RECOILING_LEFT);
|
||||
break;
|
||||
case PlayerState::FIRING_RIGHT:
|
||||
setFiringState(PlayerState::RECOILING_RIGHT);
|
||||
break;
|
||||
case PlayerState::FIRING_UP:
|
||||
setFiringState(PlayerState::RECOILING_UP);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
--cant_fire_counter_;
|
||||
if (cant_fire_counter_ == 0) {
|
||||
recoiling_state_counter_ = recoiling_state_duration_;
|
||||
}
|
||||
} else {
|
||||
if (recoiling_state_counter_ > 0) {
|
||||
--recoiling_state_counter_;
|
||||
} else {
|
||||
if (cooling_state_counter_ > COOLING_COMPLETE) {
|
||||
if (cooling_state_counter_ == COOLING_DURATION) {
|
||||
switch (firing_state_) {
|
||||
case PlayerState::RECOILING_LEFT:
|
||||
setFiringState(PlayerState::COOLING_LEFT);
|
||||
break;
|
||||
case PlayerState::RECOILING_RIGHT:
|
||||
setFiringState(PlayerState::COOLING_RIGHT);
|
||||
break;
|
||||
case PlayerState::RECOILING_UP:
|
||||
setFiringState(PlayerState::COOLING_UP);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
--cooling_state_counter_;
|
||||
}
|
||||
|
||||
if (cooling_state_counter_ == COOLING_COMPLETE) {
|
||||
setFiringState(PlayerState::FIRING_NONE);
|
||||
cooling_state_counter_ = -1;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (playing_state_ != PlayerState::PLAYING) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (cant_fire_counter_ > 0) {
|
||||
handleFiringCooldown();
|
||||
} else {
|
||||
handleRecoilAndCooling();
|
||||
}
|
||||
}
|
||||
|
||||
void Player::handleFiringCooldown() {
|
||||
cooling_state_counter_ = COOLING_DURATION;
|
||||
|
||||
// Transition to recoiling state at halfway point
|
||||
if (cant_fire_counter_ == recoiling_state_duration_ / 2) {
|
||||
transitionToRecoiling();
|
||||
}
|
||||
|
||||
--cant_fire_counter_;
|
||||
if (cant_fire_counter_ == 0) {
|
||||
recoiling_state_counter_ = recoiling_state_duration_;
|
||||
}
|
||||
}
|
||||
|
||||
void Player::handleRecoilAndCooling() {
|
||||
if (recoiling_state_counter_ > 0) {
|
||||
--recoiling_state_counter_;
|
||||
return;
|
||||
}
|
||||
|
||||
handleCoolingState();
|
||||
}
|
||||
|
||||
void Player::handleCoolingState() {
|
||||
if (cooling_state_counter_ > COOLING_COMPLETE) {
|
||||
if (cooling_state_counter_ == COOLING_DURATION) {
|
||||
transitionToCooling();
|
||||
}
|
||||
--cooling_state_counter_;
|
||||
}
|
||||
|
||||
if (cooling_state_counter_ == COOLING_COMPLETE) {
|
||||
completeCooling();
|
||||
}
|
||||
}
|
||||
|
||||
void Player::transitionToRecoiling() {
|
||||
switch (firing_state_) {
|
||||
case PlayerState::FIRING_LEFT:
|
||||
setFiringState(PlayerState::RECOILING_LEFT);
|
||||
break;
|
||||
case PlayerState::FIRING_RIGHT:
|
||||
setFiringState(PlayerState::RECOILING_RIGHT);
|
||||
break;
|
||||
case PlayerState::FIRING_UP:
|
||||
setFiringState(PlayerState::RECOILING_UP);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
void Player::transitionToCooling() {
|
||||
switch (firing_state_) {
|
||||
case PlayerState::RECOILING_LEFT:
|
||||
setFiringState(PlayerState::COOLING_LEFT);
|
||||
break;
|
||||
case PlayerState::RECOILING_RIGHT:
|
||||
setFiringState(PlayerState::COOLING_RIGHT);
|
||||
break;
|
||||
case PlayerState::RECOILING_UP:
|
||||
setFiringState(PlayerState::COOLING_UP);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
void Player::completeCooling() {
|
||||
setFiringState(PlayerState::FIRING_NONE);
|
||||
cooling_state_counter_ = -1;
|
||||
}
|
||||
|
||||
// Actualiza al jugador a su posicion, animación y controla los contadores
|
||||
|
||||
@@ -228,4 +228,28 @@ class Player {
|
||||
void playSound(const std::string &name) const; // Hace sonar un sonido
|
||||
[[nodiscard]] auto isRenderable() const -> bool; // Indica si se puede dibujar el objeto
|
||||
void addScoreToScoreBoard() const; // Añade una puntuación a la tabla de records
|
||||
void handleFiringCooldown(); // Gestiona el tiempo de espera después de disparar antes de permitir otro disparo
|
||||
void handleRecoilAndCooling(); // Procesa simultáneamente el retroceso del arma y la transición al estado de enfriamiento si aplica
|
||||
void handleCoolingState(); // Actualiza la lógica interna mientras el sistema está en estado de enfriamiento
|
||||
void transitionToRecoiling(); // Cambia el estado actual al de retroceso después de disparar
|
||||
void transitionToCooling(); // Cambia el estado actual al de enfriamiento (por ejemplo, tras una ráfaga o sobrecalentamiento)
|
||||
void completeCooling(); // Finaliza el proceso de enfriamiento y restablece el estado listo para disparar
|
||||
void handlePlayingMovement(); // Gestiona el movimiento del personaje u objeto durante el estado de juego activo
|
||||
void handleRollingMovement(); // Actualiza la lógica de movimiento de "rodar" (posiblemente tras impacto o acción especial)
|
||||
void handleRollingBoundaryCollision(); // Detecta y maneja colisiones del objeto rodante con los límites de la pantalla
|
||||
void handleRollingGroundCollision(); // Gestiona la interacción del objeto rodante con el suelo (rebotes, frenado, etc.)
|
||||
void handleRollingStop(); // Detiene el movimiento del objeto rodante cuando se cumplen las condiciones necesarias
|
||||
void handleRollingBounce(); // Aplica una lógica de rebote al colisionar con superficies durante el rodamiento
|
||||
void handleTitleAnimation(); // Ejecuta la animación del título en pantalla (ej. entrada, parpadeo o desplazamiento)
|
||||
void handleContinueTimeOut(); // Gestiona el tiempo de espera en la pantalla de "Continuar" y decide si pasar a otro estado
|
||||
void handleLeavingScreen(); // Lógica para salir de la pantalla actual (transición visual o cambio de escena)
|
||||
void handleEnteringScreen(); // Lógica para entrar en una nueva pantalla, posiblemente con animación o retraso
|
||||
void handlePlayer1Entering(); // Controla la animación o posición de entrada del Jugador 1 en pantalla
|
||||
void handlePlayer2Entering(); // Controla la animación o posición de entrada del Jugador 2 en pantalla
|
||||
void handleCreditsMovement(); // Movimiento general en la pantalla de créditos (desplazamiento vertical u horizontal)
|
||||
void handleCreditsRightMovement(); // Lógica específica para mover los créditos hacia la derecha
|
||||
void handleCreditsLeftMovement(); // Lógica específica para mover los créditos hacia la izquierda
|
||||
void updateWalkingStateForCredits(); // Actualiza el estado de caminata de algún personaje u elemento animado en los créditos
|
||||
void setInputBasedOnPlayerId(); // Asocia las entradas de control en función del identificador del jugador (teclas, mando, etc.)
|
||||
void updateStepCounter(); // Incrementa o ajusta el contador de pasos para animaciones o mecánicas relacionadas con movimiento
|
||||
};
|
||||
@@ -18,133 +18,133 @@ struct JA_Sound_t;
|
||||
|
||||
// --- Clase Resource: gestiona todos los recursos del juego (singleton) ---
|
||||
class Resource {
|
||||
public:
|
||||
// --- Métodos de singleton ---
|
||||
static void init(); // Inicializa el objeto Resource
|
||||
static void destroy(); // Libera el objeto Resource
|
||||
static auto get() -> Resource *; // Obtiene el puntero al objeto Resource
|
||||
public:
|
||||
// --- Métodos de singleton ---
|
||||
static void init(); // Inicializa el objeto Resource
|
||||
static void destroy(); // Libera el objeto Resource
|
||||
static auto get() -> Resource *; // Obtiene el puntero al objeto Resource
|
||||
|
||||
// --- Métodos de acceso a recursos ---
|
||||
auto getSound(const std::string &name) -> JA_Sound_t *; // Obtiene el sonido por nombre
|
||||
auto getMusic(const std::string &name) -> JA_Music_t *; // Obtiene la música por nombre
|
||||
auto getTexture(const std::string &name) -> std::shared_ptr<Texture>; // Obtiene la textura por nombre
|
||||
auto getTextFile(const std::string &name) -> std::shared_ptr<TextFile>; // Obtiene el fichero de texto por nombre
|
||||
auto getText(const std::string &name) -> std::shared_ptr<Text>; // Obtiene el objeto de texto por nombre
|
||||
auto getAnimation(const std::string &name) -> AnimationsFileBuffer &; // Obtiene la animación por nombre
|
||||
auto getDemoData(int index) -> DemoData &; // Obtiene los datos de demo por índice
|
||||
// --- Métodos de acceso a recursos ---
|
||||
auto getSound(const std::string &name) -> JA_Sound_t *; // Obtiene el sonido por nombre
|
||||
auto getMusic(const std::string &name) -> JA_Music_t *; // Obtiene la música por nombre
|
||||
auto getTexture(const std::string &name) -> std::shared_ptr<Texture>; // Obtiene la textura por nombre
|
||||
auto getTextFile(const std::string &name) -> std::shared_ptr<TextFile>; // Obtiene el fichero de texto por nombre
|
||||
auto getText(const std::string &name) -> std::shared_ptr<Text>; // Obtiene el objeto de texto por nombre
|
||||
auto getAnimation(const std::string &name) -> AnimationsFileBuffer &; // Obtiene la animación por nombre
|
||||
auto getDemoData(int index) -> DemoData &; // Obtiene los datos de demo por índice
|
||||
|
||||
// --- Métodos de recarga de recursos ---
|
||||
void reload(); // Recarga todos los recursos
|
||||
void reloadTextures(); // Recarga solo las texturas
|
||||
// --- Métodos de recarga de recursos ---
|
||||
void reload(); // Recarga todos los recursos
|
||||
void reloadTextures(); // Recarga solo las texturas
|
||||
|
||||
private:
|
||||
// --- Estructuras para recursos individuales ---
|
||||
struct ResourceSound {
|
||||
std::string name; // Nombre del sonido
|
||||
JA_Sound_t *sound; // Objeto con el sonido
|
||||
private:
|
||||
// --- Estructuras para recursos individuales ---
|
||||
struct ResourceSound {
|
||||
std::string name; // Nombre del sonido
|
||||
JA_Sound_t *sound; // Objeto con el sonido
|
||||
|
||||
ResourceSound(std::string name, JA_Sound_t *sound)
|
||||
: name(std::move(name)), sound(sound) {}
|
||||
};
|
||||
ResourceSound(std::string name, JA_Sound_t *sound)
|
||||
: name(std::move(name)), sound(sound) {}
|
||||
};
|
||||
|
||||
struct ResourceMusic {
|
||||
std::string name; // Nombre de la música
|
||||
JA_Music_t *music; // Objeto con la música
|
||||
struct ResourceMusic {
|
||||
std::string name; // Nombre de la música
|
||||
JA_Music_t *music; // Objeto con la música
|
||||
|
||||
ResourceMusic(std::string name, JA_Music_t *music)
|
||||
: name(std::move(name)), music(music) {}
|
||||
};
|
||||
ResourceMusic(std::string name, JA_Music_t *music)
|
||||
: name(std::move(name)), music(music) {}
|
||||
};
|
||||
|
||||
struct ResourceTexture {
|
||||
std::string name; // Nombre de la textura
|
||||
std::shared_ptr<Texture> texture; // Objeto con la textura
|
||||
struct ResourceTexture {
|
||||
std::string name; // Nombre de la textura
|
||||
std::shared_ptr<Texture> texture; // Objeto con la textura
|
||||
|
||||
ResourceTexture(std::string name, std::shared_ptr<Texture> texture)
|
||||
: name(std::move(name)), texture(std::move(texture)) {}
|
||||
};
|
||||
ResourceTexture(std::string name, std::shared_ptr<Texture> texture)
|
||||
: name(std::move(name)), texture(std::move(texture)) {}
|
||||
};
|
||||
|
||||
struct ResourceTextFile {
|
||||
std::string name; // Nombre del fichero
|
||||
std::shared_ptr<TextFile> text_file; // Objeto con los descriptores de la fuente de texto
|
||||
struct ResourceTextFile {
|
||||
std::string name; // Nombre del fichero
|
||||
std::shared_ptr<TextFile> text_file; // Objeto con los descriptores de la fuente de texto
|
||||
|
||||
ResourceTextFile(std::string name, std::shared_ptr<TextFile> text_file)
|
||||
: name(std::move(name)), text_file(std::move(text_file)) {}
|
||||
};
|
||||
ResourceTextFile(std::string name, std::shared_ptr<TextFile> text_file)
|
||||
: name(std::move(name)), text_file(std::move(text_file)) {}
|
||||
};
|
||||
|
||||
struct ResourceText {
|
||||
std::string name; // Nombre del objeto
|
||||
std::shared_ptr<Text> text; // Objeto de texto
|
||||
struct ResourceText {
|
||||
std::string name; // Nombre del objeto
|
||||
std::shared_ptr<Text> text; // Objeto de texto
|
||||
|
||||
ResourceText(std::string name, std::shared_ptr<Text> text)
|
||||
: name(std::move(name)), text(std::move(text)) {}
|
||||
};
|
||||
ResourceText(std::string name, std::shared_ptr<Text> text)
|
||||
: name(std::move(name)), text(std::move(text)) {}
|
||||
};
|
||||
|
||||
struct ResourceAnimation {
|
||||
std::string name; // Nombre de la animación
|
||||
AnimationsFileBuffer animation; // Objeto con las animaciones
|
||||
struct ResourceAnimation {
|
||||
std::string name; // Nombre de la animación
|
||||
AnimationsFileBuffer animation; // Objeto con las animaciones
|
||||
|
||||
ResourceAnimation(std::string name, AnimationsFileBuffer animation)
|
||||
: name(std::move(name)), animation(std::move(animation)) {}
|
||||
};
|
||||
ResourceAnimation(std::string name, AnimationsFileBuffer animation)
|
||||
: name(std::move(name)), animation(std::move(animation)) {}
|
||||
};
|
||||
|
||||
// --- Estructura para el progreso de carga ---
|
||||
struct ResourceCount {
|
||||
size_t total; // Número total de recursos
|
||||
size_t loaded; // Número de recursos cargados
|
||||
// --- Estructura para el progreso de carga ---
|
||||
struct ResourceCount {
|
||||
size_t total; // Número total de recursos
|
||||
size_t loaded; // Número de recursos cargados
|
||||
|
||||
ResourceCount() : total(0), loaded(0) {}
|
||||
ResourceCount(size_t total) : total(total), loaded(0) {}
|
||||
ResourceCount() : total(0), loaded(0) {}
|
||||
ResourceCount(size_t total) : total(total), loaded(0) {}
|
||||
|
||||
void add(size_t amount) { loaded += amount; }
|
||||
void increase() { loaded++; }
|
||||
[[nodiscard]] auto getPercentage() const -> float {
|
||||
return total > 0 ? static_cast<float>(loaded) / static_cast<float>(total) : 0.0F;
|
||||
}
|
||||
};
|
||||
void add(size_t amount) { loaded += amount; }
|
||||
void increase() { loaded++; }
|
||||
[[nodiscard]] auto getPercentage() const -> float {
|
||||
return total > 0 ? static_cast<float>(loaded) / static_cast<float>(total) : 0.0F;
|
||||
}
|
||||
};
|
||||
|
||||
// --- Vectores de recursos ---
|
||||
std::vector<ResourceSound> sounds_; // Vector con los sonidos
|
||||
std::vector<ResourceMusic> musics_; // Vector con las músicas
|
||||
std::vector<ResourceTexture> textures_; // Vector con las texturas
|
||||
std::vector<ResourceTextFile> text_files_; // Vector con los ficheros de texto
|
||||
std::vector<ResourceText> texts_; // Vector con los objetos de texto
|
||||
std::vector<ResourceAnimation> animations_; // Vector con las animaciones
|
||||
std::vector<DemoData> demos_; // Vector con los ficheros de datos para el modo demostración
|
||||
// --- Vectores de recursos ---
|
||||
std::vector<ResourceSound> sounds_; // Vector con los sonidos
|
||||
std::vector<ResourceMusic> musics_; // Vector con las músicas
|
||||
std::vector<ResourceTexture> textures_; // Vector con las texturas
|
||||
std::vector<ResourceTextFile> text_files_; // Vector con los ficheros de texto
|
||||
std::vector<ResourceText> texts_; // Vector con los objetos de texto
|
||||
std::vector<ResourceAnimation> animations_; // Vector con las animaciones
|
||||
std::vector<DemoData> demos_; // Vector con los ficheros de datos para el modo demostración
|
||||
|
||||
// --- Progreso de carga ---
|
||||
ResourceCount loading_count_; // Contador de recursos cargados
|
||||
std::shared_ptr<Text> loading_text_; // Texto para escribir en pantalla
|
||||
std::string loading_resource_name_; // Nombre del recurso que se está cargando
|
||||
SDL_FRect loading_wired_rect_;
|
||||
SDL_FRect loading_full_rect_;
|
||||
// --- Progreso de carga ---
|
||||
ResourceCount loading_count_; // Contador de recursos cargados
|
||||
std::shared_ptr<Text> loading_text_; // Texto para escribir en pantalla
|
||||
std::string loading_resource_name_; // Nombre del recurso que se está cargando
|
||||
SDL_FRect loading_wired_rect_;
|
||||
SDL_FRect loading_full_rect_;
|
||||
|
||||
// --- Métodos internos de carga y gestión ---
|
||||
void loadSounds(); // Carga los sonidos
|
||||
void loadMusics(); // Carga las músicas
|
||||
void loadTextures(); // Carga las texturas
|
||||
void loadTextFiles(); // Carga los ficheros de texto
|
||||
void loadAnimations(); // Carga las animaciones
|
||||
void loadDemoData(); // Carga los datos para el modo demostración
|
||||
void addPalettes(); // Añade paletas a las texturas
|
||||
void createTextures(); // Crea las texturas a partir de los datos cargados
|
||||
void createText(); // Crea los objetos de texto
|
||||
void clear(); // Vacía todos los vectores de recursos
|
||||
void load(); // Carga todos los recursos
|
||||
void clearSounds(); // Vacía el vector de sonidos
|
||||
void clearMusics(); // Vacía el vector de músicas
|
||||
// --- Métodos internos de carga y gestión ---
|
||||
void loadSounds(); // Carga los sonidos
|
||||
void loadMusics(); // Carga las músicas
|
||||
void loadTextures(); // Carga las texturas
|
||||
void loadTextFiles(); // Carga los ficheros de texto
|
||||
void loadAnimations(); // Carga las animaciones
|
||||
void loadDemoData(); // Carga los datos para el modo demostración
|
||||
void addPalettes(); // Añade paletas a las texturas
|
||||
void createTextures(); // Crea las texturas a partir de los datos cargados
|
||||
void createText(); // Crea los objetos de texto
|
||||
void clear(); // Vacía todos los vectores de recursos
|
||||
void load(); // Carga todos los recursos
|
||||
void clearSounds(); // Vacía el vector de sonidos
|
||||
void clearMusics(); // Vacía el vector de músicas
|
||||
|
||||
// --- Métodos internos para gestionar el progreso ---
|
||||
void calculateTotalResources(); // Calcula el número de recursos para cargar
|
||||
void renderProgress(); // Muestra el progreso de carga
|
||||
static void checkEvents(); // Comprueba los eventos durante la carga
|
||||
void updateLoadingProgress(std::string name); // Actualiza el progreso de carga
|
||||
void initProgressBar(); // Inicializa los rectangulos que definen la barra de progreso
|
||||
void updateProgressBar(); // Actualiza la barra de estado
|
||||
// --- Métodos internos para gestionar el progreso ---
|
||||
void calculateTotalResources(); // Calcula el número de recursos para cargar
|
||||
void renderProgress(); // Muestra el progreso de carga
|
||||
static void checkEvents(); // Comprueba los eventos durante la carga
|
||||
void updateLoadingProgress(std::string name); // Actualiza el progreso de carga
|
||||
void initProgressBar(); // Inicializa los rectangulos que definen la barra de progreso
|
||||
void updateProgressBar(); // Actualiza la barra de estado
|
||||
|
||||
// --- Constructores y destructor privados (singleton) ---
|
||||
Resource(); // Constructor privado
|
||||
~Resource(); // Destructor privado
|
||||
// --- Constructores y destructor privados (singleton) ---
|
||||
Resource(); // Constructor privado
|
||||
~Resource(); // Destructor privado
|
||||
|
||||
// --- Instancia singleton ---
|
||||
static Resource *instance; // Instancia única de Resource
|
||||
// --- Instancia singleton ---
|
||||
static Resource *instance; // Instancia única de Resource
|
||||
};
|
||||
@@ -160,10 +160,10 @@ void Scoreboard::fillPanelTextures() {
|
||||
SDL_SetRenderTarget(renderer_, temp);
|
||||
}
|
||||
|
||||
void Scoreboard::renderPanelContent(size_t panelIndex) {
|
||||
switch (panel_[panelIndex].mode) {
|
||||
void Scoreboard::renderPanelContent(size_t panel_index) {
|
||||
switch (panel_[panel_index].mode) {
|
||||
case ScoreboardMode::SCORE:
|
||||
renderScoreMode(panelIndex);
|
||||
renderScoreMode(panel_index);
|
||||
break;
|
||||
case ScoreboardMode::DEMO:
|
||||
renderDemoMode();
|
||||
@@ -178,30 +178,30 @@ void Scoreboard::renderPanelContent(size_t panelIndex) {
|
||||
renderStageInfoMode();
|
||||
break;
|
||||
case ScoreboardMode::CONTINUE:
|
||||
renderContinueMode(panelIndex);
|
||||
renderContinueMode(panel_index);
|
||||
break;
|
||||
case ScoreboardMode::ENTER_NAME:
|
||||
renderEnterNameMode(panelIndex);
|
||||
renderEnterNameMode(panel_index);
|
||||
break;
|
||||
case ScoreboardMode::SHOW_NAME:
|
||||
renderShowNameMode(panelIndex);
|
||||
renderShowNameMode(panel_index);
|
||||
break;
|
||||
case ScoreboardMode::GAME_COMPLETED:
|
||||
renderGameCompletedMode(panelIndex);
|
||||
renderGameCompletedMode(panel_index);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
void Scoreboard::renderScoreMode(size_t panelIndex) {
|
||||
void Scoreboard::renderScoreMode(size_t panel_index) {
|
||||
// SCORE
|
||||
text_scoreboard_->writeDX(TEXT_COLOR | TEXT_CENTER, slot4_1_.x, slot4_1_.y, name_[panelIndex], 1, text_color1_);
|
||||
text_scoreboard_->writeDX(TEXT_COLOR | TEXT_CENTER, slot4_2_.x, slot4_2_.y, updateScoreText(score_[panelIndex]), 1, text_color2_);
|
||||
text_scoreboard_->writeDX(TEXT_COLOR | TEXT_CENTER, slot4_1_.x, slot4_1_.y, name_[panel_index], 1, text_color1_);
|
||||
text_scoreboard_->writeDX(TEXT_COLOR | TEXT_CENTER, slot4_2_.x, slot4_2_.y, updateScoreText(score_[panel_index]), 1, text_color2_);
|
||||
|
||||
// MULT
|
||||
text_scoreboard_->writeDX(TEXT_COLOR | TEXT_CENTER, slot4_3_.x, slot4_3_.y, Lang::getText("[SCOREBOARD] 3"), 1, text_color1_);
|
||||
text_scoreboard_->writeDX(TEXT_COLOR | TEXT_CENTER, slot4_4_.x, slot4_4_.y, "x" + std::to_string(mult_[panelIndex]).substr(0, 3), 1, text_color2_);
|
||||
text_scoreboard_->writeDX(TEXT_COLOR | TEXT_CENTER, slot4_4_.x, slot4_4_.y, "x" + std::to_string(mult_[panel_index]).substr(0, 3), 1, text_color2_);
|
||||
}
|
||||
|
||||
void Scoreboard::renderDemoMode() {
|
||||
@@ -253,74 +253,74 @@ void Scoreboard::renderStageInfoMode() {
|
||||
text_scoreboard_->writeDX(TEXT_CENTER | TEXT_COLOR, slot4_4_.x, slot4_4_.y, NAME + updateScoreText(hi_score_), 1, text_color2_);
|
||||
}
|
||||
|
||||
void Scoreboard::renderContinueMode(size_t panelIndex) {
|
||||
void Scoreboard::renderContinueMode(size_t panel_index) {
|
||||
// SCORE
|
||||
text_scoreboard_->writeDX(TEXT_CENTER | TEXT_COLOR, slot4_1_.x, slot4_1_.y, name_[panelIndex], 1, text_color1_);
|
||||
text_scoreboard_->writeDX(TEXT_CENTER | TEXT_COLOR, slot4_2_.x, slot4_2_.y, updateScoreText(score_[panelIndex]), 1, text_color2_);
|
||||
text_scoreboard_->writeDX(TEXT_CENTER | TEXT_COLOR, slot4_1_.x, slot4_1_.y, name_[panel_index], 1, text_color1_);
|
||||
text_scoreboard_->writeDX(TEXT_CENTER | TEXT_COLOR, slot4_2_.x, slot4_2_.y, updateScoreText(score_[panel_index]), 1, text_color2_);
|
||||
|
||||
// CONTINUE
|
||||
text_scoreboard_->writeDX(TEXT_CENTER | TEXT_COLOR, slot4_3_.x, slot4_3_.y, Lang::getText("[SCOREBOARD] 10"), 1, text_color1_);
|
||||
text_scoreboard_->writeDX(TEXT_CENTER | TEXT_COLOR, slot4_4_.x, slot4_4_.y, std::to_string(continue_counter_[panelIndex]), 1, text_color2_);
|
||||
text_scoreboard_->writeDX(TEXT_CENTER | TEXT_COLOR, slot4_4_.x, slot4_4_.y, std::to_string(continue_counter_[panel_index]), 1, text_color2_);
|
||||
}
|
||||
|
||||
void Scoreboard::renderEnterNameMode(size_t panelIndex) {
|
||||
void Scoreboard::renderEnterNameMode(size_t panel_index) {
|
||||
// SCORE
|
||||
text_scoreboard_->writeDX(TEXT_CENTER | TEXT_COLOR, slot4_1_.x, slot4_1_.y, name_[panelIndex], 1, text_color1_);
|
||||
text_scoreboard_->writeDX(TEXT_CENTER | TEXT_COLOR, slot4_2_.x, slot4_2_.y, updateScoreText(score_[panelIndex]), 1, text_color2_);
|
||||
text_scoreboard_->writeDX(TEXT_CENTER | TEXT_COLOR, slot4_1_.x, slot4_1_.y, name_[panel_index], 1, text_color1_);
|
||||
text_scoreboard_->writeDX(TEXT_CENTER | TEXT_COLOR, slot4_2_.x, slot4_2_.y, updateScoreText(score_[panel_index]), 1, text_color2_);
|
||||
|
||||
// ENTER NAME
|
||||
text_scoreboard_->writeDX(TEXT_CENTER | TEXT_COLOR, slot4_3_.x, slot4_3_.y, Lang::getText("[SCOREBOARD] 11"), 1, text_color1_);
|
||||
|
||||
renderNameInputField(panelIndex);
|
||||
renderNameInputField(panel_index);
|
||||
}
|
||||
|
||||
void Scoreboard::renderNameInputField(size_t panelIndex) {
|
||||
void Scoreboard::renderNameInputField(size_t panel_index) {
|
||||
SDL_FRect rect = {enter_name_pos_.x, enter_name_pos_.y, 5.0F, 7.0F};
|
||||
|
||||
// Recorre todos los slots de letras del nombre
|
||||
for (size_t j = 0; j < NAME_SIZE; ++j) {
|
||||
// Selecciona el color
|
||||
const Color COLOR = j < selector_pos_[panelIndex] ? text_color2_ : text_color1_;
|
||||
const Color COLOR = j < selector_pos_[panel_index] ? text_color2_ : text_color1_;
|
||||
|
||||
if (j != selector_pos_[panelIndex] || time_counter_ % 3 == 0) {
|
||||
if (j != selector_pos_[panel_index] || time_counter_ % 3 == 0) {
|
||||
// Dibuja la linea
|
||||
if (j >= selector_pos_[panelIndex]) {
|
||||
if (j >= selector_pos_[panel_index]) {
|
||||
SDL_SetRenderDrawColor(renderer_, COLOR.r, COLOR.g, COLOR.b, 255);
|
||||
SDL_RenderLine(renderer_, rect.x, rect.y + rect.h, rect.x + rect.w, rect.y + rect.h);
|
||||
}
|
||||
|
||||
// Dibuja la letra
|
||||
if (j < record_name_[panelIndex].size()) {
|
||||
text_scoreboard_->writeColored(rect.x, rect.y, record_name_[panelIndex].substr(j, 1), COLOR);
|
||||
if (j < record_name_[panel_index].size()) {
|
||||
text_scoreboard_->writeColored(rect.x, rect.y, record_name_[panel_index].substr(j, 1), COLOR);
|
||||
}
|
||||
}
|
||||
rect.x += 7;
|
||||
}
|
||||
}
|
||||
|
||||
void Scoreboard::renderShowNameMode(size_t panelIndex) {
|
||||
void Scoreboard::renderShowNameMode(size_t panel_index) {
|
||||
// SCORE
|
||||
text_scoreboard_->writeDX(TEXT_CENTER | TEXT_COLOR, slot4_1_.x, slot4_1_.y, name_[panelIndex], 1, text_color1_);
|
||||
text_scoreboard_->writeDX(TEXT_CENTER | TEXT_COLOR, slot4_2_.x, slot4_2_.y, updateScoreText(score_[panelIndex]), 1, text_color2_);
|
||||
text_scoreboard_->writeDX(TEXT_CENTER | TEXT_COLOR, slot4_1_.x, slot4_1_.y, name_[panel_index], 1, text_color1_);
|
||||
text_scoreboard_->writeDX(TEXT_CENTER | TEXT_COLOR, slot4_2_.x, slot4_2_.y, updateScoreText(score_[panel_index]), 1, text_color2_);
|
||||
|
||||
// NAME
|
||||
text_scoreboard_->writeDX(TEXT_CENTER | TEXT_COLOR, slot4_3_.x, slot4_3_.y, Lang::getText("[SCOREBOARD] 11"), 1, text_color1_);
|
||||
|
||||
/* TEXTO CENTRADO */
|
||||
text_scoreboard_->writeDX(TEXT_CENTER | TEXT_COLOR, slot4_4_.x, slot4_4_.y, record_name_[panelIndex], 1, getColorLikeKnightRider(name_colors_, loop_counter_ / 5));
|
||||
text_scoreboard_->writeDX(TEXT_CENTER | TEXT_COLOR, slot4_4_.x, slot4_4_.y, record_name_[panel_index], 1, getColorLikeKnightRider(name_colors_, loop_counter_ / 5));
|
||||
|
||||
/* TEXTO A LA IZQUIERDA */
|
||||
// text_scoreboard_->writeColored(enter_name_pos_.x, enter_name_pos_.y, record_name_[panelIndex], getColorLikeKnightRider(name_colors_, loop_counter_ / 5));
|
||||
}
|
||||
|
||||
void Scoreboard::renderGameCompletedMode(size_t panelIndex) {
|
||||
void Scoreboard::renderGameCompletedMode(size_t panel_index) {
|
||||
// GAME OVER
|
||||
text_scoreboard_->writeDX(TEXT_CENTER | TEXT_COLOR, slot4_1_.x, slot4_1_.y + 4, Lang::getText("[SCOREBOARD] 7"), 1, text_color1_);
|
||||
|
||||
// SCORE
|
||||
if (time_counter_ % 10 < 8) {
|
||||
text_scoreboard_->writeDX(TEXT_CENTER | TEXT_COLOR, slot4_3_.x, slot4_3_.y - 2, Lang::getText("[SCOREBOARD] 14"), 1, text_color1_);
|
||||
text_scoreboard_->writeDX(TEXT_CENTER | TEXT_COLOR, slot4_4_.x, slot4_4_.y - 2, updateScoreText(score_[panelIndex]), 1, text_color2_);
|
||||
text_scoreboard_->writeDX(TEXT_CENTER | TEXT_COLOR, slot4_4_.x, slot4_4_.y - 2, updateScoreText(score_[panel_index]), 1, text_color2_);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -85,16 +85,16 @@ class Scoreboard {
|
||||
std::array<int, SCOREBOARD_MAX_PANELS> continue_counter_ = {}; // Tiempo para continuar de los jugadores
|
||||
std::array<Panel, SCOREBOARD_MAX_PANELS> panel_ = {}; // Lista con todos los paneles del marcador
|
||||
|
||||
int stage_ = 1; // Número de fase actual
|
||||
int hi_score_ = 0; // Máxima puntuación
|
||||
float power_ = 0; // Poder actual de la fase
|
||||
std::string hi_score_name_; // Nombre del jugador con la máxima puntuación
|
||||
Color color_; // Color del marcador
|
||||
SDL_FRect rect_ = {0, 0, 320, 40}; // Posición y dimensiones del marcador
|
||||
Uint64 ticks_ = SDL_GetTicks(); // Variable donde almacenar el valor de SDL_GetTicks()
|
||||
int time_counter_ = 0; // Contador de segundos
|
||||
int loop_counter_ = 0; // Contador de bucle
|
||||
std::vector<Color> name_colors_; // Colores para destacar el nombre una vez introducido
|
||||
int stage_ = 1; // Número de fase actual
|
||||
int hi_score_ = 0; // Máxima puntuación
|
||||
float power_ = 0; // Poder actual de la fase
|
||||
std::string hi_score_name_; // Nombre del jugador con la máxima puntuación
|
||||
Color color_; // Color del marcador
|
||||
SDL_FRect rect_ = {0, 0, 320, 40}; // Posición y dimensiones del marcador
|
||||
Uint64 ticks_ = SDL_GetTicks(); // Variable donde almacenar el valor de SDL_GetTicks()
|
||||
int time_counter_ = 0; // Contador de segundos
|
||||
int loop_counter_ = 0; // Contador de bucle
|
||||
std::vector<Color> name_colors_; // Colores para destacar el nombre una vez introducido
|
||||
|
||||
// --- Variables de aspecto ---
|
||||
Color text_color1_, text_color2_; // Colores para los marcadores del texto;
|
||||
@@ -104,26 +104,26 @@ class Scoreboard {
|
||||
SDL_FPoint enter_name_pos_;
|
||||
|
||||
// --- Métodos internos ---
|
||||
void recalculateAnchors(); // Recalcula las anclas de los elementos
|
||||
void recalculateAnchors(); // Recalcula las anclas de los elementos
|
||||
static auto updateScoreText(int num) -> std::string; // Transforma un valor numérico en una cadena de 7 cifras
|
||||
void createBackgroundTexture(); // Crea la textura de fondo
|
||||
void createPanelTextures(); // Crea las texturas de los paneles
|
||||
void fillPanelTextures(); // Rellena los diferentes paneles del marcador
|
||||
void fillBackgroundTexture(); // Rellena la textura de fondo
|
||||
void updateTimeCounter(); // Actualiza el contador
|
||||
void renderSeparator(); // Dibuja la línea que separa la zona de juego del marcador
|
||||
void iniNameColors(); // Inicializa el vector de colores para el nombre
|
||||
void renderPanelContent(size_t panelIndex);
|
||||
void renderScoreMode(size_t panelIndex);
|
||||
void renderDemoMode();
|
||||
void renderWaitingMode();
|
||||
void renderGameOverMode();
|
||||
void renderStageInfoMode();
|
||||
void renderContinueMode(size_t panelIndex);
|
||||
void renderEnterNameMode(size_t panelIndex);
|
||||
void renderNameInputField(size_t panelIndex);
|
||||
void renderShowNameMode(size_t panelIndex);
|
||||
void renderGameCompletedMode(size_t panelIndex);
|
||||
void createBackgroundTexture(); // Crea la textura de fondo
|
||||
void createPanelTextures(); // Crea las texturas de los paneles
|
||||
void fillPanelTextures(); // Rellena los diferentes paneles del marcador
|
||||
void fillBackgroundTexture(); // Rellena la textura de fondo
|
||||
void updateTimeCounter(); // Actualiza el contador
|
||||
void renderSeparator(); // Dibuja la línea que separa la zona de juego del marcador
|
||||
void iniNameColors(); // Inicializa el vector de colores para el nombre
|
||||
void renderPanelContent(size_t panel_index);
|
||||
void renderScoreMode(size_t panel_index);
|
||||
void renderDemoMode();
|
||||
void renderWaitingMode();
|
||||
void renderGameOverMode();
|
||||
void renderStageInfoMode();
|
||||
void renderContinueMode(size_t panel_index);
|
||||
void renderEnterNameMode(size_t panel_index);
|
||||
void renderNameInputField(size_t panel_index);
|
||||
void renderShowNameMode(size_t panel_index);
|
||||
void renderGameCompletedMode(size_t panel_index);
|
||||
|
||||
// --- Constructor y destructor privados (singleton) ---
|
||||
Scoreboard();
|
||||
|
||||
336
source/screen.h
336
source/screen.h
@@ -14,201 +14,201 @@ class Text;
|
||||
|
||||
// Clase Screen: gestiona la ventana, el renderizador y los efectos visuales globales
|
||||
class Screen {
|
||||
public:
|
||||
// --- Métodos de singleton ---
|
||||
static void init(); // Inicializa el objeto Screen
|
||||
static void destroy(); // Libera el objeto Screen
|
||||
static auto get() -> Screen *; // Obtiene el puntero al objeto Screen
|
||||
public:
|
||||
// --- Métodos de singleton ---
|
||||
static void init(); // Inicializa el objeto Screen
|
||||
static void destroy(); // Libera el objeto Screen
|
||||
static auto get() -> Screen *; // Obtiene el puntero al objeto Screen
|
||||
|
||||
// --- Métodos principales ---
|
||||
void update(); // Actualiza la lógica de la clase
|
||||
void coreUpdate(); // Actualiza los elementos mínimos
|
||||
void clean(Color color = Color(0x00, 0x00, 0x00)); // Limpia la pantalla
|
||||
void start(); // Prepara para empezar a dibujar en la textura de juego
|
||||
void render(); // Vuelca el contenido del renderizador en pantalla
|
||||
void coreRender(); // Vuelca el contenido del renderizador en pantalla exceptuando ciertas partes
|
||||
// --- Métodos principales ---
|
||||
void update(); // Actualiza la lógica de la clase
|
||||
void coreUpdate(); // Actualiza los elementos mínimos
|
||||
void clean(Color color = Color(0x00, 0x00, 0x00)); // Limpia la pantalla
|
||||
void start(); // Prepara para empezar a dibujar en la textura de juego
|
||||
void render(); // Vuelca el contenido del renderizador en pantalla
|
||||
void coreRender(); // Vuelca el contenido del renderizador en pantalla exceptuando ciertas partes
|
||||
|
||||
// --- Configuración de ventana y render ---
|
||||
void setFullscreenMode(); // Establece el modo de pantalla completa
|
||||
void toggleFullscreen(); // Cambia entre pantalla completa y ventana
|
||||
void setWindowZoom(int size); // Cambia el tamaño de la ventana
|
||||
auto decWindowSize() -> bool; // Reduce el tamaño de la ventana
|
||||
auto incWindowSize() -> bool; // Aumenta el tamaño de la ventana
|
||||
void applySettings(); // Aplica los valores de las opciones
|
||||
void initShaders(); // Inicializa los shaders
|
||||
// --- Configuración de ventana y render ---
|
||||
void setFullscreenMode(); // Establece el modo de pantalla completa
|
||||
void toggleFullscreen(); // Cambia entre pantalla completa y ventana
|
||||
void setWindowZoom(int size); // Cambia el tamaño de la ventana
|
||||
auto decWindowSize() -> bool; // Reduce el tamaño de la ventana
|
||||
auto incWindowSize() -> bool; // Aumenta el tamaño de la ventana
|
||||
void applySettings(); // Aplica los valores de las opciones
|
||||
void initShaders(); // Inicializa los shaders
|
||||
|
||||
// --- Efectos visuales ---
|
||||
void shake(int desp = 2, int delay = 3, int lenght = 8) { shake_effect_.enable(src_rect_, dst_rect_, desp, delay, lenght); } // Agita la pantalla
|
||||
void flash(Color color, int lenght = 10, int delay = 0) { flash_effect_ = FlashEffect(true, lenght, delay, color); } // Pone la pantalla de color
|
||||
void toggleShaders(); // Alterna entre activar y desactivar los shaders
|
||||
void toggleIntegerScale(); // Alterna entre activar y desactivar el escalado entero
|
||||
void toggleVSync(); // Alterna entre activar y desactivar el V-Sync
|
||||
void setVSync(bool enabled); // Establece el estado del V-Sync
|
||||
void attenuate(bool value) { attenuate_effect_ = value; } // Atenúa la pantalla
|
||||
// --- Efectos visuales ---
|
||||
void shake(int desp = 2, int delay = 3, int lenght = 8) { shake_effect_.enable(src_rect_, dst_rect_, desp, delay, lenght); } // Agita la pantalla
|
||||
void flash(Color color, int lenght = 10, int delay = 0) { flash_effect_ = FlashEffect(true, lenght, delay, color); } // Pone la pantalla de color
|
||||
void toggleShaders(); // Alterna entre activar y desactivar los shaders
|
||||
void toggleIntegerScale(); // Alterna entre activar y desactivar el escalado entero
|
||||
void toggleVSync(); // Alterna entre activar y desactivar el V-Sync
|
||||
void setVSync(bool enabled); // Establece el estado del V-Sync
|
||||
void attenuate(bool value) { attenuate_effect_ = value; } // Atenúa la pantalla
|
||||
|
||||
// --- Getters ---
|
||||
auto getRenderer() -> SDL_Renderer * { return renderer_; } // Obtiene el renderizador
|
||||
void show() { SDL_ShowWindow(window_); } // Muestra la ventana
|
||||
void hide() { SDL_HideWindow(window_); } // Oculta la ventana
|
||||
void getSingletons(); // Obtiene los punteros a los singletones
|
||||
[[nodiscard]] static auto getVSync() -> bool { return Options::video.v_sync; } // Obtiene el valor de V-Sync
|
||||
[[nodiscard]] auto getText() const -> std::shared_ptr<Text> { return text_; } // Obtiene el puntero al texto de Screen
|
||||
// --- Getters ---
|
||||
auto getRenderer() -> SDL_Renderer * { return renderer_; } // Obtiene el renderizador
|
||||
void show() { SDL_ShowWindow(window_); } // Muestra la ventana
|
||||
void hide() { SDL_HideWindow(window_); } // Oculta la ventana
|
||||
void getSingletons(); // Obtiene los punteros a los singletones
|
||||
[[nodiscard]] static auto getVSync() -> bool { return Options::video.v_sync; } // Obtiene el valor de V-Sync
|
||||
[[nodiscard]] auto getText() const -> std::shared_ptr<Text> { return text_; } // Obtiene el puntero al texto de Screen
|
||||
|
||||
#ifdef DEBUG
|
||||
// --- Debug ---
|
||||
void toggleDebugInfo() { debug_info_.show = !debug_info_.show; }
|
||||
void setDebugInfoEnabled(bool value) { debug_info_.show = value; }
|
||||
// --- Debug ---
|
||||
void toggleDebugInfo() { debug_info_.show = !debug_info_.show; }
|
||||
void setDebugInfoEnabled(bool value) { debug_info_.show = value; }
|
||||
#endif
|
||||
|
||||
private:
|
||||
// --- Constantes ---
|
||||
static constexpr int WINDOWS_DECORATIONS = 35;
|
||||
private:
|
||||
// --- Constantes ---
|
||||
static constexpr int WINDOWS_DECORATIONS = 35;
|
||||
|
||||
// --- Estructuras internas ---
|
||||
struct FPS {
|
||||
Uint32 ticks{0}; // Tiempo en milisegundos desde que se comenzó a contar.
|
||||
int frame_count{0}; // Número acumulado de frames en el intervalo.
|
||||
int last_value{0}; // Número de frames calculado en el último segundo.
|
||||
// --- Estructuras internas ---
|
||||
struct FPS {
|
||||
Uint32 ticks{0}; // Tiempo en milisegundos desde que se comenzó a contar.
|
||||
int frame_count{0}; // Número acumulado de frames en el intervalo.
|
||||
int last_value{0}; // Número de frames calculado en el último segundo.
|
||||
|
||||
FPS() = default;
|
||||
void increment() { frame_count++; }
|
||||
auto calculate(Uint32 current_ticks) -> int {
|
||||
if (current_ticks - ticks >= 1000) {
|
||||
last_value = frame_count;
|
||||
frame_count = 0;
|
||||
ticks = current_ticks;
|
||||
}
|
||||
return last_value;
|
||||
}
|
||||
};
|
||||
|
||||
// Efecto de flash en pantalla: pinta la pantalla de un color durante unos frames
|
||||
struct FlashEffect {
|
||||
bool enabled; // Indica si el efecto está activo
|
||||
int lenght; // Duración total del efecto en frames
|
||||
int delay; // Retraso antes de mostrar el flash
|
||||
int counter; // Contador de frames restantes
|
||||
Color color; // Color del flash
|
||||
|
||||
explicit FlashEffect(bool enabled = false, int lenght = 0, int delay = 0, Color color = Color(0xFF, 0xFF, 0xFF))
|
||||
: enabled(enabled), lenght(lenght), delay(delay), counter(lenght), color(color) {}
|
||||
|
||||
void update() { (enabled && counter > 0) ? counter-- : static_cast<int>(enabled = false); }
|
||||
[[nodiscard]] auto isRendarable() const -> bool { return enabled && counter < lenght - delay; }
|
||||
};
|
||||
|
||||
// Efecto de sacudida/agitación de pantalla: mueve la imagen para simular un temblor
|
||||
struct ShakeEffect {
|
||||
int desp; // Desplazamiento máximo de la sacudida (en píxeles)
|
||||
int delay; // Frames entre cada movimiento de sacudida
|
||||
int counter; // Contador de frames para el siguiente movimiento
|
||||
int lenght; // Duración total del efecto en frames
|
||||
int remaining; // Frames restantes de sacudida
|
||||
int original_pos; // Posición original de la imagen (x)
|
||||
int original_width; // Ancho original de la imagen
|
||||
bool enabled; // Indica si el efecto está activo
|
||||
|
||||
explicit ShakeEffect(bool en = false, int dp = 2, int dl = 3, int cnt = 0, int len = 8, int rem = 0, int orig_pos = 0, int orig_width = 800)
|
||||
: desp(dp), delay(dl), counter(cnt), lenght(len), remaining(rem), original_pos(orig_pos), original_width(orig_width), enabled(en) {}
|
||||
|
||||
// Activa el efecto de sacudida y guarda la posición y tamaño originales
|
||||
void enable(SDL_FRect &src_rect, SDL_FRect &dst_rect, int new_desp = -1, int new_delay = -1, int new_lenght = -1) {
|
||||
if (!enabled) {
|
||||
enabled = true;
|
||||
original_pos = src_rect.x;
|
||||
original_width = src_rect.w;
|
||||
|
||||
// Usar nuevos valores si se proporcionan, sino mantener los actuales
|
||||
if (new_desp != -1) {
|
||||
desp = new_desp;
|
||||
}
|
||||
if (new_delay != -1) {
|
||||
delay = new_delay;
|
||||
}
|
||||
if (new_lenght != -1) {
|
||||
lenght = new_lenght;
|
||||
FPS() = default;
|
||||
void increment() { frame_count++; }
|
||||
auto calculate(Uint32 current_ticks) -> int {
|
||||
if (current_ticks - ticks >= 1000) {
|
||||
last_value = frame_count;
|
||||
frame_count = 0;
|
||||
ticks = current_ticks;
|
||||
}
|
||||
return last_value;
|
||||
}
|
||||
};
|
||||
|
||||
src_rect.w -= desp;
|
||||
dst_rect.w = src_rect.w;
|
||||
}
|
||||
remaining = lenght;
|
||||
counter = delay;
|
||||
}
|
||||
// Efecto de flash en pantalla: pinta la pantalla de un color durante unos frames
|
||||
struct FlashEffect {
|
||||
bool enabled; // Indica si el efecto está activo
|
||||
int lenght; // Duración total del efecto en frames
|
||||
int delay; // Retraso antes de mostrar el flash
|
||||
int counter; // Contador de frames restantes
|
||||
Color color; // Color del flash
|
||||
|
||||
// Actualiza el estado del efecto de sacudida
|
||||
void update(SDL_FRect &src_rect, SDL_FRect &dst_rect) {
|
||||
if (enabled) {
|
||||
if (counter > 0) {
|
||||
counter--;
|
||||
} else {
|
||||
explicit FlashEffect(bool enabled = false, int lenght = 0, int delay = 0, Color color = Color(0xFF, 0xFF, 0xFF))
|
||||
: enabled(enabled), lenght(lenght), delay(delay), counter(lenght), color(color) {}
|
||||
|
||||
void update() { (enabled && counter > 0) ? counter-- : static_cast<int>(enabled = false); }
|
||||
[[nodiscard]] auto isRendarable() const -> bool { return enabled && counter < lenght - delay; }
|
||||
};
|
||||
|
||||
// Efecto de sacudida/agitación de pantalla: mueve la imagen para simular un temblor
|
||||
struct ShakeEffect {
|
||||
int desp; // Desplazamiento máximo de la sacudida (en píxeles)
|
||||
int delay; // Frames entre cada movimiento de sacudida
|
||||
int counter; // Contador de frames para el siguiente movimiento
|
||||
int lenght; // Duración total del efecto en frames
|
||||
int remaining; // Frames restantes de sacudida
|
||||
int original_pos; // Posición original de la imagen (x)
|
||||
int original_width; // Ancho original de la imagen
|
||||
bool enabled; // Indica si el efecto está activo
|
||||
|
||||
explicit ShakeEffect(bool en = false, int dp = 2, int dl = 3, int cnt = 0, int len = 8, int rem = 0, int orig_pos = 0, int orig_width = 800)
|
||||
: desp(dp), delay(dl), counter(cnt), lenght(len), remaining(rem), original_pos(orig_pos), original_width(orig_width), enabled(en) {}
|
||||
|
||||
// Activa el efecto de sacudida y guarda la posición y tamaño originales
|
||||
void enable(SDL_FRect &src_rect, SDL_FRect &dst_rect, int new_desp = -1, int new_delay = -1, int new_lenght = -1) {
|
||||
if (!enabled) {
|
||||
enabled = true;
|
||||
original_pos = src_rect.x;
|
||||
original_width = src_rect.w;
|
||||
|
||||
// Usar nuevos valores si se proporcionan, sino mantener los actuales
|
||||
if (new_desp != -1) {
|
||||
desp = new_desp;
|
||||
}
|
||||
if (new_delay != -1) {
|
||||
delay = new_delay;
|
||||
}
|
||||
if (new_lenght != -1) {
|
||||
lenght = new_lenght;
|
||||
}
|
||||
|
||||
src_rect.w -= desp;
|
||||
dst_rect.w = src_rect.w;
|
||||
}
|
||||
remaining = lenght;
|
||||
counter = delay;
|
||||
const auto SRC_DESP = (remaining % 2 == 0) ? 0 : desp;
|
||||
const auto DST_DESP = (remaining % 2 == 1) ? 0 : desp;
|
||||
src_rect.x = original_pos + SRC_DESP;
|
||||
dst_rect.x = original_pos + DST_DESP;
|
||||
remaining--;
|
||||
if (remaining == -1) {
|
||||
enabled = false;
|
||||
src_rect.x = original_pos;
|
||||
src_rect.w = original_width;
|
||||
dst_rect.x = original_pos;
|
||||
dst_rect.w = original_width;
|
||||
}
|
||||
|
||||
// Actualiza el estado del efecto de sacudida
|
||||
void update(SDL_FRect &src_rect, SDL_FRect &dst_rect) {
|
||||
if (enabled) {
|
||||
if (counter > 0) {
|
||||
counter--;
|
||||
} else {
|
||||
counter = delay;
|
||||
const auto SRC_DESP = (remaining % 2 == 0) ? 0 : desp;
|
||||
const auto DST_DESP = (remaining % 2 == 1) ? 0 : desp;
|
||||
src_rect.x = original_pos + SRC_DESP;
|
||||
dst_rect.x = original_pos + DST_DESP;
|
||||
remaining--;
|
||||
if (remaining == -1) {
|
||||
enabled = false;
|
||||
src_rect.x = original_pos;
|
||||
src_rect.w = original_width;
|
||||
dst_rect.x = original_pos;
|
||||
dst_rect.w = original_width;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[[nodiscard]] auto isEnabled() const -> bool { return enabled; }
|
||||
};
|
||||
[[nodiscard]] auto isEnabled() const -> bool { return enabled; }
|
||||
};
|
||||
|
||||
#ifdef DEBUG
|
||||
struct Debug {
|
||||
std::shared_ptr<Text> text;
|
||||
bool show = false;
|
||||
};
|
||||
struct Debug {
|
||||
std::shared_ptr<Text> text;
|
||||
bool show = false;
|
||||
};
|
||||
|
||||
#endif
|
||||
|
||||
// --- Singleton ---
|
||||
static Screen *instance;
|
||||
// --- Singleton ---
|
||||
static Screen *instance;
|
||||
|
||||
// --- Objetos y punteros ---
|
||||
SDL_Window *window_; // Ventana de la aplicación
|
||||
SDL_Renderer *renderer_; // El renderizador de la ventana
|
||||
SDL_Texture *game_canvas_; // Textura donde se dibuja todo antes de volcarse al renderizador
|
||||
ServiceMenu *service_menu_; // Objeto para mostrar el menú de servicio
|
||||
Notifier *notifier_; // Objeto para mostrar las notificaciones por pantalla
|
||||
// --- Objetos y punteros ---
|
||||
SDL_Window *window_; // Ventana de la aplicación
|
||||
SDL_Renderer *renderer_; // El renderizador de la ventana
|
||||
SDL_Texture *game_canvas_; // Textura donde se dibuja todo antes de volcarse al renderizador
|
||||
ServiceMenu *service_menu_; // Objeto para mostrar el menú de servicio
|
||||
Notifier *notifier_; // Objeto para mostrar las notificaciones por pantalla
|
||||
|
||||
// --- Variables de estado ---
|
||||
SDL_FRect src_rect_; // Coordenadas de origen para dibujar la textura del juego
|
||||
SDL_FRect dst_rect_; // Coordenadas destino para dibujar la textura del juego
|
||||
FPS fps_; // Gestión de frames por segundo
|
||||
std::string shader_source_; // Almacena el contenido del archivo GLSL
|
||||
FlashEffect flash_effect_; // Efecto de flash en pantalla
|
||||
ShakeEffect shake_effect_; // Efecto de agitar la pantalla
|
||||
bool attenuate_effect_ = false; // Indica si la pantalla ha de estar atenuada
|
||||
// --- Variables de estado ---
|
||||
SDL_FRect src_rect_; // Coordenadas de origen para dibujar la textura del juego
|
||||
SDL_FRect dst_rect_; // Coordenadas destino para dibujar la textura del juego
|
||||
FPS fps_; // Gestión de frames por segundo
|
||||
std::string shader_source_; // Almacena el contenido del archivo GLSL
|
||||
FlashEffect flash_effect_; // Efecto de flash en pantalla
|
||||
ShakeEffect shake_effect_; // Efecto de agitar la pantalla
|
||||
bool attenuate_effect_ = false; // Indica si la pantalla ha de estar atenuada
|
||||
#ifdef DEBUG
|
||||
Debug debug_info_; // Información de debug
|
||||
Debug debug_info_; // Información de debug
|
||||
#endif
|
||||
|
||||
// --- Texto ---
|
||||
std::shared_ptr<Text> text_; // Objeto para escribir texto en pantalla
|
||||
// --- Texto ---
|
||||
std::shared_ptr<Text> text_; // Objeto para escribir texto en pantalla
|
||||
|
||||
// --- Métodos internos ---
|
||||
auto initSDLVideo() -> bool; // Arranca SDL VIDEO y crea la ventana
|
||||
void renderFlash(); // Dibuja el efecto de flash en la pantalla
|
||||
void renderShake(); // Aplica el efecto de agitar la pantalla
|
||||
void renderInfo(); // Muestra información por pantalla
|
||||
void renderScreen(); // Selecciona y ejecuta el método de renderizado adecuado
|
||||
void loadShaders(); // Carga el contenido del archivo GLSL
|
||||
void adjustWindowSize(); // Calcula el tamaño de la ventana
|
||||
static void getDisplayInfo(); // Obtiene información sobre la pantalla
|
||||
void renderOverlays(); // Renderiza todos los overlays y efectos
|
||||
void renderAttenuate(); // Atenúa la pantalla
|
||||
void createText(); // Crea el objeto de texto
|
||||
// --- Métodos internos ---
|
||||
auto initSDLVideo() -> bool; // Arranca SDL VIDEO y crea la ventana
|
||||
void renderFlash(); // Dibuja el efecto de flash en la pantalla
|
||||
void renderShake(); // Aplica el efecto de agitar la pantalla
|
||||
void renderInfo(); // Muestra información por pantalla
|
||||
void renderScreen(); // Selecciona y ejecuta el método de renderizado adecuado
|
||||
void loadShaders(); // Carga el contenido del archivo GLSL
|
||||
void adjustWindowSize(); // Calcula el tamaño de la ventana
|
||||
static void getDisplayInfo(); // Obtiene información sobre la pantalla
|
||||
void renderOverlays(); // Renderiza todos los overlays y efectos
|
||||
void renderAttenuate(); // Atenúa la pantalla
|
||||
void createText(); // Crea el objeto de texto
|
||||
|
||||
// --- Constructores y destructor ---
|
||||
Screen();
|
||||
~Screen();
|
||||
// --- Constructores y destructor ---
|
||||
Screen();
|
||||
~Screen();
|
||||
};
|
||||
@@ -9,7 +9,7 @@
|
||||
#include <stdexcept> // Para runtime_error
|
||||
#include <string> // Para basic_string, string
|
||||
#include <string_view>
|
||||
#include <vector> // Para vector
|
||||
#include <vector> // Para vector
|
||||
|
||||
#include "audio.h" // Para Audio
|
||||
#include "balloon_manager.h" // Para BalloonManager
|
||||
@@ -33,7 +33,6 @@
|
||||
// Textos
|
||||
constexpr std::string_view TEXT_COPYRIGHT = "@2020,2025 JailDesigner";
|
||||
|
||||
|
||||
// Constructor
|
||||
Credits::Credits()
|
||||
: balloon_manager_(std::make_unique<BalloonManager>()),
|
||||
|
||||
@@ -101,10 +101,10 @@ class Credits {
|
||||
SDL_FRect border_rect_ = play_area_; // Delimitador de ventana
|
||||
|
||||
// --- Métodos del bucle principal ---
|
||||
void update(); // Actualización principal de la lógica
|
||||
void render(); // Renderizado de la escena
|
||||
void update(); // Actualización principal de la lógica
|
||||
void render(); // Renderizado de la escena
|
||||
static void checkEvents(); // Manejo de eventos
|
||||
void checkInput(); // Procesamiento de entrada
|
||||
void checkInput(); // Procesamiento de entrada
|
||||
|
||||
// --- Métodos de renderizado ---
|
||||
void fillTextTexture(); // Crear textura de texto de créditos
|
||||
|
||||
@@ -2,8 +2,8 @@
|
||||
|
||||
#include <SDL3/SDL.h> // Para SDL_GetTicks, SDL_SetRenderTarget
|
||||
|
||||
#include <algorithm> // Para find_if, clamp, find, min
|
||||
#include <array>
|
||||
#include <algorithm> // Para find_if, clamp, find, min
|
||||
#include <cstdlib> // Para rand, size_t
|
||||
#include <functional> // Para function
|
||||
#include <iterator> // Para distance, size
|
||||
|
||||
@@ -37,209 +37,209 @@ constexpr int TOTAL_SCORE_DATA = 3;
|
||||
|
||||
// Clase Game
|
||||
class Game {
|
||||
public:
|
||||
// Constructor
|
||||
Game(int player_id, int current_stage, bool demo);
|
||||
public:
|
||||
// Constructor
|
||||
Game(int player_id, int current_stage, bool demo);
|
||||
|
||||
// Destructor
|
||||
~Game();
|
||||
// Destructor
|
||||
~Game();
|
||||
|
||||
// Bucle principal del juego
|
||||
void run();
|
||||
// Bucle principal del juego
|
||||
void run();
|
||||
|
||||
private:
|
||||
// --- Tipos internos ---
|
||||
enum class GameState {
|
||||
FADE_IN,
|
||||
ENTERING_PLAYER,
|
||||
SHOWING_GET_READY_MESSAGE,
|
||||
PLAYING,
|
||||
COMPLETED,
|
||||
GAME_OVER,
|
||||
};
|
||||
private:
|
||||
// --- Tipos internos ---
|
||||
enum class GameState {
|
||||
FADE_IN,
|
||||
ENTERING_PLAYER,
|
||||
SHOWING_GET_READY_MESSAGE,
|
||||
PLAYING,
|
||||
COMPLETED,
|
||||
GAME_OVER,
|
||||
};
|
||||
|
||||
// --- Constantes internas ---
|
||||
static constexpr int HELP_COUNTER = 1000;
|
||||
static constexpr int GAME_COMPLETED_START_FADE = 500;
|
||||
static constexpr int GAME_COMPLETED_END = 700;
|
||||
static constexpr int GAME_OVER_COUNTER = 350;
|
||||
static constexpr int TIME_STOPPED_COUNTER = 360;
|
||||
static constexpr int ITEM_POINTS_1_DISK_ODDS = 10;
|
||||
static constexpr int ITEM_POINTS_2_GAVINA_ODDS = 6;
|
||||
static constexpr int ITEM_POINTS_3_PACMAR_ODDS = 3;
|
||||
static constexpr int ITEM_CLOCK_ODDS = 5;
|
||||
static constexpr int ITEM_COFFEE_ODDS = 5;
|
||||
static constexpr int ITEM_POWER_BALL_ODDS = 0;
|
||||
static constexpr int ITEM_COFFEE_MACHINE_ODDS = 4;
|
||||
// --- Constantes internas ---
|
||||
static constexpr int HELP_COUNTER = 1000;
|
||||
static constexpr int GAME_COMPLETED_START_FADE = 500;
|
||||
static constexpr int GAME_COMPLETED_END = 700;
|
||||
static constexpr int GAME_OVER_COUNTER = 350;
|
||||
static constexpr int TIME_STOPPED_COUNTER = 360;
|
||||
static constexpr int ITEM_POINTS_1_DISK_ODDS = 10;
|
||||
static constexpr int ITEM_POINTS_2_GAVINA_ODDS = 6;
|
||||
static constexpr int ITEM_POINTS_3_PACMAR_ODDS = 3;
|
||||
static constexpr int ITEM_CLOCK_ODDS = 5;
|
||||
static constexpr int ITEM_COFFEE_ODDS = 5;
|
||||
static constexpr int ITEM_POWER_BALL_ODDS = 0;
|
||||
static constexpr int ITEM_COFFEE_MACHINE_ODDS = 4;
|
||||
|
||||
// --- Estructuras ---
|
||||
struct Helper {
|
||||
bool need_coffee{false}; // Indica si se necesitan cafes
|
||||
bool need_coffee_machine{false}; // Indica si se necesita PowerUp
|
||||
bool need_power_ball{false}; // Indica si se necesita una PowerBall
|
||||
int counter; // Contador para no dar ayudas consecutivas
|
||||
int item_disk_odds; // Probabilidad de aparición del objeto
|
||||
int item_gavina_odds; // Probabilidad de aparición del objeto
|
||||
int item_pacmar_odds; // Probabilidad de aparición del objeto
|
||||
int item_clock_odds; // Probabilidad de aparición del objeto
|
||||
int item_coffee_odds; // Probabilidad de aparición del objeto
|
||||
int item_coffee_machine_odds; // Probabilidad de aparición del objeto
|
||||
// --- Estructuras ---
|
||||
struct Helper {
|
||||
bool need_coffee{false}; // Indica si se necesitan cafes
|
||||
bool need_coffee_machine{false}; // Indica si se necesita PowerUp
|
||||
bool need_power_ball{false}; // Indica si se necesita una PowerBall
|
||||
int counter; // Contador para no dar ayudas consecutivas
|
||||
int item_disk_odds; // Probabilidad de aparición del objeto
|
||||
int item_gavina_odds; // Probabilidad de aparición del objeto
|
||||
int item_pacmar_odds; // Probabilidad de aparición del objeto
|
||||
int item_clock_odds; // Probabilidad de aparición del objeto
|
||||
int item_coffee_odds; // Probabilidad de aparición del objeto
|
||||
int item_coffee_machine_odds; // Probabilidad de aparición del objeto
|
||||
|
||||
Helper()
|
||||
: counter(HELP_COUNTER),
|
||||
item_disk_odds(ITEM_POINTS_1_DISK_ODDS),
|
||||
item_gavina_odds(ITEM_POINTS_2_GAVINA_ODDS),
|
||||
item_pacmar_odds(ITEM_POINTS_3_PACMAR_ODDS),
|
||||
item_clock_odds(ITEM_CLOCK_ODDS),
|
||||
item_coffee_odds(ITEM_COFFEE_ODDS),
|
||||
item_coffee_machine_odds(ITEM_COFFEE_MACHINE_ODDS) {}
|
||||
};
|
||||
Helper()
|
||||
: counter(HELP_COUNTER),
|
||||
item_disk_odds(ITEM_POINTS_1_DISK_ODDS),
|
||||
item_gavina_odds(ITEM_POINTS_2_GAVINA_ODDS),
|
||||
item_pacmar_odds(ITEM_POINTS_3_PACMAR_ODDS),
|
||||
item_clock_odds(ITEM_CLOCK_ODDS),
|
||||
item_coffee_odds(ITEM_COFFEE_ODDS),
|
||||
item_coffee_machine_odds(ITEM_COFFEE_MACHINE_ODDS) {}
|
||||
};
|
||||
|
||||
// --- Objetos y punteros ---
|
||||
SDL_Renderer *renderer_; // El renderizador de la ventana
|
||||
Screen *screen_; // Objeto encargado de dibujar en pantalla
|
||||
Input *input_; // Manejador de entrada
|
||||
Scoreboard *scoreboard_; // Objeto para dibujar el marcador
|
||||
// --- Objetos y punteros ---
|
||||
SDL_Renderer *renderer_; // El renderizador de la ventana
|
||||
Screen *screen_; // Objeto encargado de dibujar en pantalla
|
||||
Input *input_; // Manejador de entrada
|
||||
Scoreboard *scoreboard_; // Objeto para dibujar el marcador
|
||||
|
||||
std::unique_ptr<Background> background_; // Objeto para dibujar el fondo del juego
|
||||
std::unique_ptr<Background> background_; // Objeto para dibujar el fondo del juego
|
||||
|
||||
SDL_Texture *canvas_; // Textura para dibujar la zona de juego
|
||||
SDL_Texture *canvas_; // Textura para dibujar la zona de juego
|
||||
|
||||
std::vector<std::shared_ptr<Player>> players_; // Vector con los jugadores
|
||||
std::vector<std::unique_ptr<Bullet>> bullets_; // Vector con las balas
|
||||
std::vector<std::unique_ptr<Item>> items_; // Vector con los items
|
||||
std::vector<std::unique_ptr<SmartSprite>> smart_sprites_; // Vector con los smartsprites
|
||||
std::vector<std::unique_ptr<PathSprite>> path_sprites_; // Vector con los pathsprites
|
||||
std::vector<std::shared_ptr<Player>> players_; // Vector con los jugadores
|
||||
std::vector<std::unique_ptr<Bullet>> bullets_; // Vector con las balas
|
||||
std::vector<std::unique_ptr<Item>> items_; // Vector con los items
|
||||
std::vector<std::unique_ptr<SmartSprite>> smart_sprites_; // Vector con los smartsprites
|
||||
std::vector<std::unique_ptr<PathSprite>> path_sprites_; // Vector con los pathsprites
|
||||
|
||||
std::vector<std::shared_ptr<Texture>> item_textures_; // Vector con las texturas de los items
|
||||
std::vector<std::vector<std::shared_ptr<Texture>>> player_textures_; // Vector con todas las texturas de los jugadores
|
||||
std::vector<std::shared_ptr<Texture>> item_textures_; // Vector con las texturas de los items
|
||||
std::vector<std::vector<std::shared_ptr<Texture>>> player_textures_; // Vector con todas las texturas de los jugadores
|
||||
|
||||
std::vector<std::shared_ptr<Texture>> game_text_textures_; // Vector con las texturas para los sprites con textos
|
||||
std::vector<std::shared_ptr<Texture>> game_text_textures_; // Vector con las texturas para los sprites con textos
|
||||
|
||||
std::vector<std::vector<std::string>> item_animations_; // Vector con las animaciones de los items
|
||||
std::vector<std::vector<std::string>> player_animations_; // Vector con las animaciones del jugador
|
||||
std::vector<std::vector<std::string>> item_animations_; // Vector con las animaciones de los items
|
||||
std::vector<std::vector<std::string>> player_animations_; // Vector con las animaciones del jugador
|
||||
|
||||
std::unique_ptr<Fade> fade_in_; // Objeto para renderizar fades
|
||||
std::unique_ptr<Fade> fade_out_; // Objeto para renderizar fades
|
||||
std::unique_ptr<BalloonManager> balloon_manager_; // Objeto para gestionar los globos
|
||||
std::unique_ptr<Tabe> tabe_; // Objeto para gestionar el Tabe Volaor
|
||||
std::vector<Path> paths_; // Vector con los recorridos precalculados almacenados
|
||||
std::unique_ptr<Fade> fade_in_; // Objeto para renderizar fades
|
||||
std::unique_ptr<Fade> fade_out_; // Objeto para renderizar fades
|
||||
std::unique_ptr<BalloonManager> balloon_manager_; // Objeto para gestionar los globos
|
||||
std::unique_ptr<Tabe> tabe_; // Objeto para gestionar el Tabe Volaor
|
||||
std::vector<Path> paths_; // Vector con los recorridos precalculados almacenados
|
||||
|
||||
// --- Variables de estado ---
|
||||
HiScoreEntry hi_score_ = HiScoreEntry(
|
||||
Options::settings.hi_score_table[0].name,
|
||||
Options::settings.hi_score_table[0].score); // Máxima puntuación y nombre de quien la ostenta
|
||||
// --- Variables de estado ---
|
||||
HiScoreEntry hi_score_ = HiScoreEntry(
|
||||
Options::settings.hi_score_table[0].name,
|
||||
Options::settings.hi_score_table[0].score); // Máxima puntuación y nombre de quien la ostenta
|
||||
|
||||
Demo demo_; // Variable con todas las variables relacionadas con el modo demo
|
||||
Options::DifficultyCode difficulty_ = Options::settings.difficulty; // Dificultad del juego
|
||||
Helper helper_; // Variable para gestionar las ayudas
|
||||
Uint64 ticks_ = 0; // Contador de ticks para ajustar la velocidad del programa
|
||||
bool coffee_machine_enabled_ = false; // Indica si hay una máquina de café en el terreno de juego
|
||||
bool hi_score_achieved_ = false; // Indica si se ha superado la puntuación máxima
|
||||
bool paused_ = false; // Indica si el juego está pausado (no se deberia de poder utilizar en el modo arcade)
|
||||
// bool paused_by_service_menu_ = false;
|
||||
float difficulty_score_multiplier_; // Multiplicador de puntos en función de la dificultad
|
||||
int counter_ = 0; // Contador para el juego
|
||||
int game_completed_counter_ = 0; // Contador para el tramo final, cuando se ha completado la partida y ya no aparecen más enemigos
|
||||
int game_over_counter_ = GAME_OVER_COUNTER; // Contador para el estado de fin de partida
|
||||
int time_stopped_counter_ = 0; // Temporizador para llevar la cuenta del tiempo detenido
|
||||
int total_power_to_complete_game_; // La suma del poder necesario para completar todas las fases
|
||||
int menace_current_ = 0; // Nivel de amenaza actual
|
||||
int menace_threshold_ = 0; // Umbral del nivel de amenaza. Si el nivel de amenaza cae por debajo del umbral, se generan más globos. Si el umbral aumenta, aumenta el número de globos
|
||||
GameState state_ = GameState::FADE_IN; // Estado
|
||||
std::vector<std::shared_ptr<Player>> players_to_reorder_;
|
||||
Demo demo_; // Variable con todas las variables relacionadas con el modo demo
|
||||
Options::DifficultyCode difficulty_ = Options::settings.difficulty; // Dificultad del juego
|
||||
Helper helper_; // Variable para gestionar las ayudas
|
||||
Uint64 ticks_ = 0; // Contador de ticks para ajustar la velocidad del programa
|
||||
bool coffee_machine_enabled_ = false; // Indica si hay una máquina de café en el terreno de juego
|
||||
bool hi_score_achieved_ = false; // Indica si se ha superado la puntuación máxima
|
||||
bool paused_ = false; // Indica si el juego está pausado (no se deberia de poder utilizar en el modo arcade)
|
||||
// bool paused_by_service_menu_ = false;
|
||||
float difficulty_score_multiplier_; // Multiplicador de puntos en función de la dificultad
|
||||
int counter_ = 0; // Contador para el juego
|
||||
int game_completed_counter_ = 0; // Contador para el tramo final, cuando se ha completado la partida y ya no aparecen más enemigos
|
||||
int game_over_counter_ = GAME_OVER_COUNTER; // Contador para el estado de fin de partida
|
||||
int time_stopped_counter_ = 0; // Temporizador para llevar la cuenta del tiempo detenido
|
||||
int total_power_to_complete_game_; // La suma del poder necesario para completar todas las fases
|
||||
int menace_current_ = 0; // Nivel de amenaza actual
|
||||
int menace_threshold_ = 0; // Umbral del nivel de amenaza. Si el nivel de amenaza cae por debajo del umbral, se generan más globos. Si el umbral aumenta, aumenta el número de globos
|
||||
GameState state_ = GameState::FADE_IN; // Estado
|
||||
std::vector<std::shared_ptr<Player>> players_to_reorder_;
|
||||
|
||||
#ifdef DEBUG
|
||||
bool auto_pop_balloons_ = false; // Si es true, incrementa automaticamente los globos explotados
|
||||
bool auto_pop_balloons_ = false; // Si es true, incrementa automaticamente los globos explotados
|
||||
|
||||
// Comprueba los eventos en el modo DEBUG
|
||||
void checkDebugEvents(const SDL_Event &event);
|
||||
// Comprueba los eventos en el modo DEBUG
|
||||
void checkDebugEvents(const SDL_Event &event);
|
||||
#endif
|
||||
|
||||
// --- Métodos internos ---
|
||||
void update(); // Actualiza el juego
|
||||
void render(); // Dibuja el juego
|
||||
void checkEvents(); // Comprueba los eventos que hay en cola
|
||||
void setResources(); // Asigna texturas y animaciones
|
||||
void updateHiScore(); // Actualiza el valor de HiScore en caso necesario
|
||||
void updatePlayers(); // Actualiza las variables del jugador
|
||||
void renderPlayers(); // Dibuja a los jugadores
|
||||
void updateStage(); // Comprueba si hay cambio de fase y actualiza las variables
|
||||
void updateGameStateGameOver(); // Actualiza el estado de fin de la partida
|
||||
void destroyAllItems(); // Destruye todos los items
|
||||
auto checkPlayerBalloonCollision(std::shared_ptr<Player> &player) -> std::shared_ptr<Balloon>; // Comprueba la colisión entre el jugador y los globos activos
|
||||
void checkPlayerItemCollision(std::shared_ptr<Player> &player); // Comprueba la colisión entre el jugador y los items
|
||||
void checkBulletCollision(); // Comprueba y procesa la colisión de las balas
|
||||
void updateBullets(); // Mueve las balas activas
|
||||
void renderBullets(); // Pinta las balas activas
|
||||
void createBullet(int x, int y, BulletType kind, bool powered_up, int owner); // Crea un objeto bala
|
||||
void freeBullets(); // Vacia el vector de balas
|
||||
void updateItems(); // Actualiza los items
|
||||
void renderItems(); // Pinta los items activos
|
||||
auto dropItem() -> ItemType; // Devuelve un item en función del azar
|
||||
void createItem(ItemType type, float x, float y); // Crea un objeto item
|
||||
void freeItems(); // Vacia el vector de items
|
||||
void createItemText(int x, std::shared_ptr<Texture> texture); // Crea un objeto PathSprite
|
||||
void createMessage(const std::vector<Path> &paths, std::shared_ptr<Texture> texture); // Crea un objeto PathSprite
|
||||
void freeSmartSprites(); // Vacia el vector de smartsprites
|
||||
void freePathSprites(); // Vacia el vector de pathsprites
|
||||
void throwCoffee(int x, int y); // Crea un SpriteSmart para arrojar el item café al recibir un impacto
|
||||
void updateSmartSprites(); // Actualiza los SpriteSmarts
|
||||
void renderSmartSprites(); // Pinta los SpriteSmarts activos
|
||||
void updatePathSprites(); // Actualiza los PathSprites
|
||||
void renderPathSprites(); // Pinta los PathSprites activos
|
||||
void handlePlayerCollision(std::shared_ptr<Player> &player); // Acciones a realizar cuando el jugador colisiona con un globo
|
||||
void updateTimeStopped(); // Actualiza y comprueba el valor de la variable
|
||||
void updateBackground(); // Actualiza el fondo
|
||||
void initPaths(); // Inicializa las variables que contienen puntos de ruta para mover objetos
|
||||
void enableTimeStopItem(); // Habilita el efecto del item de detener el tiempo
|
||||
void disableTimeStopItem(); // Deshabilita el efecto del item de detener el tiempo
|
||||
void updateHelper(); // Actualiza las variables de ayuda
|
||||
auto allPlayersAreWaitingOrGameOver() -> bool; // Comprueba si todos los jugadores han terminado de jugar
|
||||
auto allPlayersAreGameOver() -> bool; // Comprueba si todos los jugadores han terminado de jugar
|
||||
auto allPlayersAreNotPlaying() -> bool; // Comprueba si todos los jugadores han terminado de jugar
|
||||
void updateScoreboard(); // Actualiza el marcador
|
||||
void fillCanvas(); // Dibuja los elementos de la zona de juego en su textura
|
||||
void pause(bool value); // Pausa el juego
|
||||
void addScoreToScoreBoard(const std::shared_ptr<Player> &player); // Añade una puntuación a la tabla de records
|
||||
void checkAndUpdatePlayerStatus(int active_player_index, int inactive_player_index); // Saca del estado de GAME OVER al jugador si el otro está activo
|
||||
void checkPlayersStatusPlaying(); // Comprueba el estado de juego de los jugadores
|
||||
auto getPlayer(int id) -> std::shared_ptr<Player>; // Obtiene un jugador a partir de su "id"
|
||||
static auto getController(int player_id) -> int; // Obtiene un controlador a partir del "id" del jugador
|
||||
void checkInput(); // Gestiona la entrada durante el juego
|
||||
void checkPauseInput(); // Verifica si alguno de los controladores ha solicitado una pausa y actualiza el estado de pausa del juego.
|
||||
void demoHandleInput(); // Gestiona las entradas de los jugadores en el modo demo, incluyendo movimientos y disparos automáticos.
|
||||
void demoHandlePassInput(); // Gestiona las entradas de los jugadores en el modo demo para saltarse la demo.
|
||||
void demoHandlePlayerInput(const std::shared_ptr<Player> &player, int index); // Procesa las entradas para un jugador específico durante el modo demo.
|
||||
void handleFireInput(const std::shared_ptr<Player> &player, BulletType bullet_type); // Maneja el disparo de un jugador, incluyendo la creación de balas y la gestión del tiempo de espera entre disparos.
|
||||
void handlePlayersInput(); // Gestiona las entradas de todos los jugadores en el modo normal (fuera del modo demo).
|
||||
void handleNormalPlayerInput(const std::shared_ptr<Player> &player); // Maneja las entradas de movimiento y disparo para un jugador en modo normal.
|
||||
void handleFireInputs(const std::shared_ptr<Player> &player, bool autofire, int controller_index); // Procesa las entradas de disparo del jugador, permitiendo disparos automáticos si está habilitado.
|
||||
void handlePlayerContinue(const std::shared_ptr<Player> &player); // Maneja la continuación del jugador cuando no está jugando, permitiendo que continúe si se pulsa el botón de inicio.
|
||||
void handleNameInput(const std::shared_ptr<Player> &player); // Procesa las entradas para la introducción del nombre del jugador.
|
||||
void initDemo(int player_id); // Inicializa las variables para el modo DEMO
|
||||
void setTotalPower(); // Calcula el poder total necesario para completar el juego
|
||||
void initScoreboard(); // Inicializa el marcador
|
||||
void initDifficultyVars(); // Inicializa las opciones relacionadas con la dificultad
|
||||
void initPlayers(int player_id); // Inicializa los jugadores
|
||||
static void playMusic(); // Hace sonar la música
|
||||
void stopMusic() const; // Detiene la música
|
||||
void playSound(const std::string &name) const; // Hace sonar un sonido
|
||||
void updateDemo(); // Actualiza las variables durante el modo demo
|
||||
void updateGameStateFadeIn(); // Actualiza las variables durante dicho estado
|
||||
void updateGameStateEnteringPlayer(); // Actualiza las variables durante dicho estado
|
||||
void updateGameStateShowingGetReadyMessage(); // Actualiza las variables durante dicho estado
|
||||
void updateGameStatePlaying(); // Actualiza las variables durante el transcurso normal del juego
|
||||
void updateGameStateCompleted(); // Gestiona eventos para el estado del final del juego
|
||||
void checkState(); // Comprueba el estado del juego
|
||||
void cleanVectors(); // Vacía los vectores de elementos deshabilitados
|
||||
void updateMenace(); // Gestiona el nivel de amenaza
|
||||
void evaluateAndSetMenace(); // Calcula y establece el valor de amenaza en funcion de los globos activos
|
||||
void checkAndUpdateBalloonSpeed(); // Actualiza la velocidad de los globos en funcion del poder acumulado de la fase
|
||||
void setState(GameState state); // Cambia el estado del juego
|
||||
void movePlayersToFront(); // Organiza los jugadores para que los vivos se pinten sobre los muertos
|
||||
void checkServiceMenu(); // Comprueba si está activo el menu de servicio para poner el juego en pausa
|
||||
// --- Métodos internos ---
|
||||
void update(); // Actualiza el juego
|
||||
void render(); // Dibuja el juego
|
||||
void checkEvents(); // Comprueba los eventos que hay en cola
|
||||
void setResources(); // Asigna texturas y animaciones
|
||||
void updateHiScore(); // Actualiza el valor de HiScore en caso necesario
|
||||
void updatePlayers(); // Actualiza las variables del jugador
|
||||
void renderPlayers(); // Dibuja a los jugadores
|
||||
void updateStage(); // Comprueba si hay cambio de fase y actualiza las variables
|
||||
void updateGameStateGameOver(); // Actualiza el estado de fin de la partida
|
||||
void destroyAllItems(); // Destruye todos los items
|
||||
auto checkPlayerBalloonCollision(std::shared_ptr<Player> &player) -> std::shared_ptr<Balloon>; // Comprueba la colisión entre el jugador y los globos activos
|
||||
void checkPlayerItemCollision(std::shared_ptr<Player> &player); // Comprueba la colisión entre el jugador y los items
|
||||
void checkBulletCollision(); // Comprueba y procesa la colisión de las balas
|
||||
void updateBullets(); // Mueve las balas activas
|
||||
void renderBullets(); // Pinta las balas activas
|
||||
void createBullet(int x, int y, BulletType kind, bool powered_up, int owner); // Crea un objeto bala
|
||||
void freeBullets(); // Vacia el vector de balas
|
||||
void updateItems(); // Actualiza los items
|
||||
void renderItems(); // Pinta los items activos
|
||||
auto dropItem() -> ItemType; // Devuelve un item en función del azar
|
||||
void createItem(ItemType type, float x, float y); // Crea un objeto item
|
||||
void freeItems(); // Vacia el vector de items
|
||||
void createItemText(int x, std::shared_ptr<Texture> texture); // Crea un objeto PathSprite
|
||||
void createMessage(const std::vector<Path> &paths, std::shared_ptr<Texture> texture); // Crea un objeto PathSprite
|
||||
void freeSmartSprites(); // Vacia el vector de smartsprites
|
||||
void freePathSprites(); // Vacia el vector de pathsprites
|
||||
void throwCoffee(int x, int y); // Crea un SpriteSmart para arrojar el item café al recibir un impacto
|
||||
void updateSmartSprites(); // Actualiza los SpriteSmarts
|
||||
void renderSmartSprites(); // Pinta los SpriteSmarts activos
|
||||
void updatePathSprites(); // Actualiza los PathSprites
|
||||
void renderPathSprites(); // Pinta los PathSprites activos
|
||||
void handlePlayerCollision(std::shared_ptr<Player> &player); // Acciones a realizar cuando el jugador colisiona con un globo
|
||||
void updateTimeStopped(); // Actualiza y comprueba el valor de la variable
|
||||
void updateBackground(); // Actualiza el fondo
|
||||
void initPaths(); // Inicializa las variables que contienen puntos de ruta para mover objetos
|
||||
void enableTimeStopItem(); // Habilita el efecto del item de detener el tiempo
|
||||
void disableTimeStopItem(); // Deshabilita el efecto del item de detener el tiempo
|
||||
void updateHelper(); // Actualiza las variables de ayuda
|
||||
auto allPlayersAreWaitingOrGameOver() -> bool; // Comprueba si todos los jugadores han terminado de jugar
|
||||
auto allPlayersAreGameOver() -> bool; // Comprueba si todos los jugadores han terminado de jugar
|
||||
auto allPlayersAreNotPlaying() -> bool; // Comprueba si todos los jugadores han terminado de jugar
|
||||
void updateScoreboard(); // Actualiza el marcador
|
||||
void fillCanvas(); // Dibuja los elementos de la zona de juego en su textura
|
||||
void pause(bool value); // Pausa el juego
|
||||
void addScoreToScoreBoard(const std::shared_ptr<Player> &player); // Añade una puntuación a la tabla de records
|
||||
void checkAndUpdatePlayerStatus(int active_player_index, int inactive_player_index); // Saca del estado de GAME OVER al jugador si el otro está activo
|
||||
void checkPlayersStatusPlaying(); // Comprueba el estado de juego de los jugadores
|
||||
auto getPlayer(int id) -> std::shared_ptr<Player>; // Obtiene un jugador a partir de su "id"
|
||||
static auto getController(int player_id) -> int; // Obtiene un controlador a partir del "id" del jugador
|
||||
void checkInput(); // Gestiona la entrada durante el juego
|
||||
void checkPauseInput(); // Verifica si alguno de los controladores ha solicitado una pausa y actualiza el estado de pausa del juego.
|
||||
void demoHandleInput(); // Gestiona las entradas de los jugadores en el modo demo, incluyendo movimientos y disparos automáticos.
|
||||
void demoHandlePassInput(); // Gestiona las entradas de los jugadores en el modo demo para saltarse la demo.
|
||||
void demoHandlePlayerInput(const std::shared_ptr<Player> &player, int index); // Procesa las entradas para un jugador específico durante el modo demo.
|
||||
void handleFireInput(const std::shared_ptr<Player> &player, BulletType bullet_type); // Maneja el disparo de un jugador, incluyendo la creación de balas y la gestión del tiempo de espera entre disparos.
|
||||
void handlePlayersInput(); // Gestiona las entradas de todos los jugadores en el modo normal (fuera del modo demo).
|
||||
void handleNormalPlayerInput(const std::shared_ptr<Player> &player); // Maneja las entradas de movimiento y disparo para un jugador en modo normal.
|
||||
void handleFireInputs(const std::shared_ptr<Player> &player, bool autofire, int controller_index); // Procesa las entradas de disparo del jugador, permitiendo disparos automáticos si está habilitado.
|
||||
void handlePlayerContinue(const std::shared_ptr<Player> &player); // Maneja la continuación del jugador cuando no está jugando, permitiendo que continúe si se pulsa el botón de inicio.
|
||||
void handleNameInput(const std::shared_ptr<Player> &player); // Procesa las entradas para la introducción del nombre del jugador.
|
||||
void initDemo(int player_id); // Inicializa las variables para el modo DEMO
|
||||
void setTotalPower(); // Calcula el poder total necesario para completar el juego
|
||||
void initScoreboard(); // Inicializa el marcador
|
||||
void initDifficultyVars(); // Inicializa las opciones relacionadas con la dificultad
|
||||
void initPlayers(int player_id); // Inicializa los jugadores
|
||||
static void playMusic(); // Hace sonar la música
|
||||
void stopMusic() const; // Detiene la música
|
||||
void playSound(const std::string &name) const; // Hace sonar un sonido
|
||||
void updateDemo(); // Actualiza las variables durante el modo demo
|
||||
void updateGameStateFadeIn(); // Actualiza las variables durante dicho estado
|
||||
void updateGameStateEnteringPlayer(); // Actualiza las variables durante dicho estado
|
||||
void updateGameStateShowingGetReadyMessage(); // Actualiza las variables durante dicho estado
|
||||
void updateGameStatePlaying(); // Actualiza las variables durante el transcurso normal del juego
|
||||
void updateGameStateCompleted(); // Gestiona eventos para el estado del final del juego
|
||||
void checkState(); // Comprueba el estado del juego
|
||||
void cleanVectors(); // Vacía los vectores de elementos deshabilitados
|
||||
void updateMenace(); // Gestiona el nivel de amenaza
|
||||
void evaluateAndSetMenace(); // Calcula y establece el valor de amenaza en funcion de los globos activos
|
||||
void checkAndUpdateBalloonSpeed(); // Actualiza la velocidad de los globos en funcion del poder acumulado de la fase
|
||||
void setState(GameState state); // Cambia el estado del juego
|
||||
void movePlayersToFront(); // Organiza los jugadores para que los vivos se pinten sobre los muertos
|
||||
void checkServiceMenu(); // Comprueba si está activo el menu de servicio para poner el juego en pausa
|
||||
#ifdef RECORDING
|
||||
void updateRecording(); // Actualiza las variables durante el modo de grabación
|
||||
void updateRecording(); // Actualiza las variables durante el modo de grabación
|
||||
#endif
|
||||
};
|
||||
@@ -27,52 +27,52 @@ struct Path;
|
||||
|
||||
// Clase HiScoreTable
|
||||
class HiScoreTable {
|
||||
public:
|
||||
// Constructor
|
||||
HiScoreTable();
|
||||
public:
|
||||
// Constructor
|
||||
HiScoreTable();
|
||||
|
||||
// Destructor
|
||||
~HiScoreTable();
|
||||
// Destructor
|
||||
~HiScoreTable();
|
||||
|
||||
// Bucle principal
|
||||
void run();
|
||||
// Bucle principal
|
||||
void run();
|
||||
|
||||
private:
|
||||
// --- Constantes ---
|
||||
static constexpr Uint16 COUNTER_END = 800; // Valor final para el contador
|
||||
private:
|
||||
// --- Constantes ---
|
||||
static constexpr Uint16 COUNTER_END = 800; // Valor final para el contador
|
||||
|
||||
// --- Objetos y punteros ---
|
||||
SDL_Renderer *renderer_; // El renderizador de la ventana
|
||||
SDL_Texture *backbuffer_; // Textura para usar como backbuffer
|
||||
// --- Objetos y punteros ---
|
||||
SDL_Renderer *renderer_; // El renderizador de la ventana
|
||||
SDL_Texture *backbuffer_; // Textura para usar como backbuffer
|
||||
|
||||
std::unique_ptr<Fade> fade_; // Objeto para renderizar fades
|
||||
std::unique_ptr<Background> background_; // Objeto para dibujar el fondo del juego
|
||||
std::unique_ptr<Sprite> header_; // Sprite con la cabecera del texto
|
||||
std::vector<std::shared_ptr<PathSprite>> entry_names_; // Lista con los sprites de cada uno de los nombres de la tabla de records
|
||||
std::vector<Path> paths_; // Vector con los recorridos precalculados
|
||||
std::unique_ptr<Fade> fade_; // Objeto para renderizar fades
|
||||
std::unique_ptr<Background> background_; // Objeto para dibujar el fondo del juego
|
||||
std::unique_ptr<Sprite> header_; // Sprite con la cabecera del texto
|
||||
std::vector<std::shared_ptr<PathSprite>> entry_names_; // Lista con los sprites de cada uno de los nombres de la tabla de records
|
||||
std::vector<Path> paths_; // Vector con los recorridos precalculados
|
||||
|
||||
// --- Variables ---
|
||||
Uint16 counter_ = 0; // Contador
|
||||
Uint64 ticks_; // Contador de ticks para ajustar la velocidad del programa
|
||||
SDL_FRect view_area_; // Parte de la textura que se muestra en pantalla
|
||||
FadeMode fade_mode_; // Modo de fade a utilizar
|
||||
Color background_fade_color_; // Color de atenuación del fondo
|
||||
std::vector<Color> entry_colors_; // Colores para destacar las entradas en la tabla
|
||||
// --- Variables ---
|
||||
Uint16 counter_ = 0; // Contador
|
||||
Uint64 ticks_; // Contador de ticks para ajustar la velocidad del programa
|
||||
SDL_FRect view_area_; // Parte de la textura que se muestra en pantalla
|
||||
FadeMode fade_mode_; // Modo de fade a utilizar
|
||||
Color background_fade_color_; // Color de atenuación del fondo
|
||||
std::vector<Color> entry_colors_; // Colores para destacar las entradas en la tabla
|
||||
|
||||
// --- Métodos internos ---
|
||||
void update(); // Actualiza las variables
|
||||
void render(); // Pinta en pantalla
|
||||
static void checkEvents(); // Comprueba los eventos
|
||||
static void checkInput(); // Comprueba las entradas
|
||||
static auto format(int number) -> std::string; // Convierte un entero a un string con separadores de miles
|
||||
void fillTexture(); // Dibuja los sprites en la textura
|
||||
void updateFade(); // Gestiona el fade
|
||||
void createSprites(); // Crea los sprites con los textos
|
||||
void updateSprites(); // Actualiza las posiciones de los sprites de texto
|
||||
void initFade(); // Inicializa el fade
|
||||
void initBackground(); // Inicializa el fondo
|
||||
auto getEntryColor(int counter) -> Color; // Obtiene un color del vector de colores de entradas
|
||||
void iniEntryColors(); // Inicializa los colores de las entradas
|
||||
void glowEntryNames(); // Hace brillar los nombres de la tabla de records
|
||||
void updateCounter(); // Gestiona el contador
|
||||
// --- Métodos internos ---
|
||||
void update(); // Actualiza las variables
|
||||
void render(); // Pinta en pantalla
|
||||
static void checkEvents(); // Comprueba los eventos
|
||||
static void checkInput(); // Comprueba las entradas
|
||||
static auto format(int number) -> std::string; // Convierte un entero a un string con separadores de miles
|
||||
void fillTexture(); // Dibuja los sprites en la textura
|
||||
void updateFade(); // Gestiona el fade
|
||||
void createSprites(); // Crea los sprites con los textos
|
||||
void updateSprites(); // Actualiza las posiciones de los sprites de texto
|
||||
void initFade(); // Inicializa el fade
|
||||
void initBackground(); // Inicializa el fondo
|
||||
auto getEntryColor(int counter) -> Color; // Obtiene un color del vector de colores de entradas
|
||||
void iniEntryColors(); // Inicializa los colores de las entradas
|
||||
void glowEntryNames(); // Hace brillar los nombres de la tabla de records
|
||||
void updateCounter(); // Gestiona el contador
|
||||
};
|
||||
@@ -26,62 +26,62 @@ class TiledBG;
|
||||
|
||||
// Estructura para almacenar información de línea animada
|
||||
struct Line {
|
||||
int y; // Coordenada Y de la línea
|
||||
float x; // Coordenada X inicial (usamos float para mayor precisión en el suavizado)
|
||||
int direction; // Dirección de movimiento: -1 para izquierda, 1 para derecha
|
||||
Uint32 start_time{0}; // Tiempo de inicio del movimiento
|
||||
int y; // Coordenada Y de la línea
|
||||
float x; // Coordenada X inicial (usamos float para mayor precisión en el suavizado)
|
||||
int direction; // Dirección de movimiento: -1 para izquierda, 1 para derecha
|
||||
Uint32 start_time{0}; // Tiempo de inicio del movimiento
|
||||
|
||||
// Constructor de Line
|
||||
Line(int y, float x, int direction)
|
||||
: y(y), x(x), direction(direction) {}
|
||||
// Constructor de Line
|
||||
Line(int y, float x, int direction)
|
||||
: y(y), x(x), direction(direction) {}
|
||||
};
|
||||
|
||||
// Clase Instructions
|
||||
class Instructions {
|
||||
public:
|
||||
// Constructor
|
||||
Instructions();
|
||||
public:
|
||||
// Constructor
|
||||
Instructions();
|
||||
|
||||
// Destructor
|
||||
~Instructions();
|
||||
// Destructor
|
||||
~Instructions();
|
||||
|
||||
// Bucle principal
|
||||
void run();
|
||||
// Bucle principal
|
||||
void run();
|
||||
|
||||
private:
|
||||
// --- Objetos y punteros ---
|
||||
SDL_Renderer *renderer_; // El renderizador de la ventana
|
||||
SDL_Texture *texture_; // Textura fija con el texto
|
||||
SDL_Texture *backbuffer_; // Textura para usar como backbuffer
|
||||
private:
|
||||
// --- Objetos y punteros ---
|
||||
SDL_Renderer *renderer_; // El renderizador de la ventana
|
||||
SDL_Texture *texture_; // Textura fija con el texto
|
||||
SDL_Texture *backbuffer_; // Textura para usar como backbuffer
|
||||
|
||||
std::vector<std::shared_ptr<Texture>> item_textures_; // Vector con las texturas de los items
|
||||
std::vector<std::unique_ptr<Sprite>> sprites_; // Vector con los sprites de los items
|
||||
std::shared_ptr<Text> text_; // Objeto para escribir texto
|
||||
std::unique_ptr<TiledBG> tiled_bg_; // Objeto para dibujar el mosaico animado de fondo
|
||||
std::unique_ptr<Fade> fade_; // Objeto para renderizar fades
|
||||
std::vector<std::shared_ptr<Texture>> item_textures_; // Vector con las texturas de los items
|
||||
std::vector<std::unique_ptr<Sprite>> sprites_; // Vector con los sprites de los items
|
||||
std::shared_ptr<Text> text_; // Objeto para escribir texto
|
||||
std::unique_ptr<TiledBG> tiled_bg_; // Objeto para dibujar el mosaico animado de fondo
|
||||
std::unique_ptr<Fade> fade_; // Objeto para renderizar fades
|
||||
|
||||
// --- Variables ---
|
||||
int counter_ = 0; // Contador para manejar el progreso en la pantalla de instrucciones
|
||||
Uint64 ticks_ = 0; // Contador de ticks para ajustar la velocidad del programa
|
||||
SDL_FRect view_; // Vista del backbuffer que se va a mostrar por pantalla
|
||||
SDL_FPoint sprite_pos_ = {0, 0}; // Posición del primer sprite en la lista
|
||||
float item_space_ = 2.0; // Espacio entre los items en pantalla
|
||||
std::vector<Line> lines_; // Vector que contiene las líneas animadas en la pantalla
|
||||
bool all_lines_off_screen_ = false; // Indica si todas las líneas han salido de la pantalla
|
||||
Uint32 start_delay_time_ = 0; // Tiempo de inicio del retraso para mover las líneas
|
||||
bool start_delay_triggered_ = false; // Bandera para determinar si el retraso ha comenzado
|
||||
// --- Variables ---
|
||||
int counter_ = 0; // Contador para manejar el progreso en la pantalla de instrucciones
|
||||
Uint64 ticks_ = 0; // Contador de ticks para ajustar la velocidad del programa
|
||||
SDL_FRect view_; // Vista del backbuffer que se va a mostrar por pantalla
|
||||
SDL_FPoint sprite_pos_ = {0, 0}; // Posición del primer sprite en la lista
|
||||
float item_space_ = 2.0; // Espacio entre los items en pantalla
|
||||
std::vector<Line> lines_; // Vector que contiene las líneas animadas en la pantalla
|
||||
bool all_lines_off_screen_ = false; // Indica si todas las líneas han salido de la pantalla
|
||||
Uint32 start_delay_time_ = 0; // Tiempo de inicio del retraso para mover las líneas
|
||||
bool start_delay_triggered_ = false; // Bandera para determinar si el retraso ha comenzado
|
||||
|
||||
// --- Métodos internos ---
|
||||
void update(); // Actualiza las variables
|
||||
void render(); // Pinta en pantalla
|
||||
static void checkEvents(); // Comprueba los eventos
|
||||
static void checkInput(); // Comprueba las entradas
|
||||
void fillTexture(); // Rellena la textura de texto
|
||||
void fillBackbuffer(); // Rellena el backbuffer
|
||||
void iniSprites(); // Inicializa los sprites de los items
|
||||
void updateSprites(); // Actualiza los sprites
|
||||
static auto initializeLines(int height) -> std::vector<Line>; // Inicializa las líneas animadas
|
||||
static auto moveLines(std::vector<Line> &lines, int width, float duration, Uint32 start_delay) -> bool; // Mueve las líneas
|
||||
static void renderLines(SDL_Renderer *renderer, SDL_Texture *texture, const std::vector<Line> &lines); // Renderiza las líneas
|
||||
void updateBackbuffer(); // Gestiona la textura con los gráficos
|
||||
// --- Métodos internos ---
|
||||
void update(); // Actualiza las variables
|
||||
void render(); // Pinta en pantalla
|
||||
static void checkEvents(); // Comprueba los eventos
|
||||
static void checkInput(); // Comprueba las entradas
|
||||
void fillTexture(); // Rellena la textura de texto
|
||||
void fillBackbuffer(); // Rellena el backbuffer
|
||||
void iniSprites(); // Inicializa los sprites de los items
|
||||
void updateSprites(); // Actualiza los sprites
|
||||
static auto initializeLines(int height) -> std::vector<Line>; // Inicializa las líneas animadas
|
||||
static auto moveLines(std::vector<Line> &lines, int width, float duration, Uint32 start_delay) -> bool; // Mueve las líneas
|
||||
static void renderLines(SDL_Renderer *renderer, SDL_Texture *texture, const std::vector<Line> &lines); // Renderiza las líneas
|
||||
void updateBackbuffer(); // Gestiona la textura con los gráficos
|
||||
};
|
||||
@@ -18,55 +18,55 @@
|
||||
|
||||
// Clase Intro
|
||||
class Intro {
|
||||
public:
|
||||
// Constructor
|
||||
Intro();
|
||||
public:
|
||||
// Constructor
|
||||
Intro();
|
||||
|
||||
// Destructor
|
||||
~Intro() = default;
|
||||
// Destructor
|
||||
~Intro() = default;
|
||||
|
||||
// Bucle principal
|
||||
void run();
|
||||
// Bucle principal
|
||||
void run();
|
||||
|
||||
private:
|
||||
// --- Estados internos ---
|
||||
enum class IntroState {
|
||||
SCENES,
|
||||
POST,
|
||||
};
|
||||
private:
|
||||
// --- Estados internos ---
|
||||
enum class IntroState {
|
||||
SCENES,
|
||||
POST,
|
||||
};
|
||||
|
||||
enum class IntroPostState {
|
||||
STOP_BG,
|
||||
END,
|
||||
};
|
||||
enum class IntroPostState {
|
||||
STOP_BG,
|
||||
END,
|
||||
};
|
||||
|
||||
// --- Objetos ---
|
||||
std::vector<std::unique_ptr<PathSprite>> card_sprites_; // Vector con los sprites inteligentes para los dibujos de la intro
|
||||
std::vector<std::unique_ptr<PathSprite>> shadow_sprites_; // Vector con los sprites inteligentes para las sombras
|
||||
std::vector<std::unique_ptr<Writer>> texts_; // Textos de la intro
|
||||
std::unique_ptr<TiledBG> tiled_bg_; // Fondo en mosaico
|
||||
// std::unique_ptr<Sprite> shadow_square_for_text_; // Sprite
|
||||
// --- Objetos ---
|
||||
std::vector<std::unique_ptr<PathSprite>> card_sprites_; // Vector con los sprites inteligentes para los dibujos de la intro
|
||||
std::vector<std::unique_ptr<PathSprite>> shadow_sprites_; // Vector con los sprites inteligentes para las sombras
|
||||
std::vector<std::unique_ptr<Writer>> texts_; // Textos de la intro
|
||||
std::unique_ptr<TiledBG> tiled_bg_; // Fondo en mosaico
|
||||
// std::unique_ptr<Sprite> shadow_square_for_text_; // Sprite
|
||||
|
||||
// --- Variables ---
|
||||
Uint64 ticks_ = 0; // Contador de ticks para ajustar la velocidad del programa
|
||||
int scene_ = 0; // Indica qué escena está activa
|
||||
IntroState state_ = IntroState::SCENES; // Estado principal de la intro
|
||||
IntroPostState post_state_ = IntroPostState::STOP_BG; // Estado POST
|
||||
Uint32 state_start_time_; // Tiempo de inicio del estado actual
|
||||
Color bg_color_ = param.intro.bg_color; // Color de fondo
|
||||
// --- Variables ---
|
||||
Uint64 ticks_ = 0; // Contador de ticks para ajustar la velocidad del programa
|
||||
int scene_ = 0; // Indica qué escena está activa
|
||||
IntroState state_ = IntroState::SCENES; // Estado principal de la intro
|
||||
IntroPostState post_state_ = IntroPostState::STOP_BG; // Estado POST
|
||||
Uint32 state_start_time_; // Tiempo de inicio del estado actual
|
||||
Color bg_color_ = param.intro.bg_color; // Color de fondo
|
||||
|
||||
// --- Métodos internos ---
|
||||
void update(); // Actualiza las variables del objeto
|
||||
void render(); // Dibuja el objeto en pantalla
|
||||
void checkEvents(); // Comprueba los eventos
|
||||
static void checkInput(); // Comprueba las entradas
|
||||
void updateScenes(); // Actualiza las escenas de la intro
|
||||
void initSprites(); // Inicializa las imágenes
|
||||
void initTexts(); // Inicializa los textos
|
||||
void updateSprites(); // Actualiza los sprites
|
||||
void updateTexts(); // Actualiza los textos
|
||||
void renderSprites(); // Dibuja los sprites
|
||||
void renderTexts(); // Dibuja los textos
|
||||
static void renderTextRect(); // Dibuja el rectangulo de fondo del texto;
|
||||
void updatePostState(); // Actualiza el estado POST
|
||||
// --- Métodos internos ---
|
||||
void update(); // Actualiza las variables del objeto
|
||||
void render(); // Dibuja el objeto en pantalla
|
||||
void checkEvents(); // Comprueba los eventos
|
||||
static void checkInput(); // Comprueba las entradas
|
||||
void updateScenes(); // Actualiza las escenas de la intro
|
||||
void initSprites(); // Inicializa las imágenes
|
||||
void initTexts(); // Inicializa los textos
|
||||
void updateSprites(); // Actualiza los sprites
|
||||
void updateTexts(); // Actualiza los textos
|
||||
void renderSprites(); // Dibuja los sprites
|
||||
void renderTexts(); // Dibuja los textos
|
||||
static void renderTextRect(); // Dibuja el rectangulo de fondo del texto;
|
||||
void updatePostState(); // Actualiza el estado POST
|
||||
};
|
||||
|
||||
@@ -19,42 +19,42 @@ struct Color;
|
||||
|
||||
// --- Clase Logo ---
|
||||
class Logo {
|
||||
public:
|
||||
// Constructor
|
||||
Logo();
|
||||
public:
|
||||
// Constructor
|
||||
Logo();
|
||||
|
||||
// Destructor
|
||||
~Logo();
|
||||
// Destructor
|
||||
~Logo();
|
||||
|
||||
// Bucle principal
|
||||
void run();
|
||||
// Bucle principal
|
||||
void run();
|
||||
|
||||
private:
|
||||
// --- Constantes ---
|
||||
static constexpr int SHOW_SINCE_SPRITE_COUNTER_MARK = 70; // Tiempo del contador en el que empieza a verse el sprite de "SINCE 1998"
|
||||
static constexpr int INIT_FADE_COUNTER_MARK = 300; // Tiempo del contador cuando inicia el fade a negro
|
||||
static constexpr int END_LOGO_COUNTER_MARK = 400; // Tiempo del contador para terminar el logo
|
||||
static constexpr int POST_LOGO_DURATION = 20; // Tiempo que dura el logo con el fade al máximo
|
||||
static constexpr int SPEED = 8; // Velocidad de desplazamiento de cada línea
|
||||
private:
|
||||
// --- Constantes ---
|
||||
static constexpr int SHOW_SINCE_SPRITE_COUNTER_MARK = 70; // Tiempo del contador en el que empieza a verse el sprite de "SINCE 1998"
|
||||
static constexpr int INIT_FADE_COUNTER_MARK = 300; // Tiempo del contador cuando inicia el fade a negro
|
||||
static constexpr int END_LOGO_COUNTER_MARK = 400; // Tiempo del contador para terminar el logo
|
||||
static constexpr int POST_LOGO_DURATION = 20; // Tiempo que dura el logo con el fade al máximo
|
||||
static constexpr int SPEED = 8; // Velocidad de desplazamiento de cada línea
|
||||
|
||||
// --- Objetos y punteros ---
|
||||
std::shared_ptr<Texture> since_texture_; // Textura con los gráficos "Since 1998"
|
||||
std::unique_ptr<Sprite> since_sprite_; // Sprite para manejar la since_texture
|
||||
std::shared_ptr<Texture> jail_texture_; // Textura con los gráficos "JAILGAMES"
|
||||
std::vector<std::unique_ptr<Sprite>> jail_sprite_; // Vector con los sprites de cada línea que forman el bitmap JAILGAMES
|
||||
// --- Objetos y punteros ---
|
||||
std::shared_ptr<Texture> since_texture_; // Textura con los gráficos "Since 1998"
|
||||
std::unique_ptr<Sprite> since_sprite_; // Sprite para manejar la since_texture
|
||||
std::shared_ptr<Texture> jail_texture_; // Textura con los gráficos "JAILGAMES"
|
||||
std::vector<std::unique_ptr<Sprite>> jail_sprite_; // Vector con los sprites de cada línea que forman el bitmap JAILGAMES
|
||||
|
||||
// --- Variables ---
|
||||
std::vector<Color> color_; // Vector con los colores para el fade
|
||||
int counter_ = 0; // Contador
|
||||
Uint64 ticks_ = 0; // Contador de ticks para ajustar la velocidad del programa
|
||||
SDL_FPoint dest_; // Posición donde dibujar el logo
|
||||
// --- Variables ---
|
||||
std::vector<Color> color_; // Vector con los colores para el fade
|
||||
int counter_ = 0; // Contador
|
||||
Uint64 ticks_ = 0; // Contador de ticks para ajustar la velocidad del programa
|
||||
SDL_FPoint dest_; // Posición donde dibujar el logo
|
||||
|
||||
// --- Métodos internos ---
|
||||
void update(); // Actualiza las variables
|
||||
void render(); // Dibuja en pantalla
|
||||
static void checkEvents(); // Comprueba el manejador de eventos
|
||||
static void checkInput(); // Comprueba las entradas
|
||||
void updateJAILGAMES(); // Gestiona el logo de JAILGAMES
|
||||
void renderJAILGAMES(); // Renderiza el logo de JAILGAMES
|
||||
void updateTextureColors(); // Gestiona el color de las texturas
|
||||
// --- Métodos internos ---
|
||||
void update(); // Actualiza las variables
|
||||
void render(); // Dibuja en pantalla
|
||||
static void checkEvents(); // Comprueba el manejador de eventos
|
||||
static void checkInput(); // Comprueba las entradas
|
||||
void updateJAILGAMES(); // Gestiona el logo de JAILGAMES
|
||||
void renderJAILGAMES(); // Renderiza el logo de JAILGAMES
|
||||
void updateTextureColors(); // Gestiona el color de las texturas
|
||||
};
|
||||
|
||||
@@ -3,8 +3,8 @@
|
||||
#include <SDL3/SDL.h> // Para Uint32
|
||||
|
||||
#include <memory> // Para unique_ptr, shared_ptr
|
||||
#include <vector>
|
||||
#include <string_view>
|
||||
#include <vector>
|
||||
|
||||
#include "section.h" // Para Options
|
||||
|
||||
@@ -19,7 +19,6 @@ class TiledBG;
|
||||
// Textos
|
||||
constexpr std::string_view TEXT_COPYRIGHT = "@2020,2025 JailDesigner";
|
||||
|
||||
|
||||
// Parámetros
|
||||
constexpr bool ALLOW_TITLE_ANIMATION_SKIP = false;
|
||||
|
||||
@@ -31,68 +30,68 @@ constexpr bool ALLOW_TITLE_ANIMATION_SKIP = false;
|
||||
|
||||
// Clase Title
|
||||
class Title {
|
||||
public:
|
||||
// --- Constructores y destructor ---
|
||||
Title();
|
||||
~Title();
|
||||
public:
|
||||
// --- Constructores y destructor ---
|
||||
Title();
|
||||
~Title();
|
||||
|
||||
// --- Método principal ---
|
||||
void run(); // Bucle para el título del juego
|
||||
// --- Método principal ---
|
||||
void run(); // Bucle para el título del juego
|
||||
|
||||
private:
|
||||
// --- Enumeraciones ---
|
||||
enum class TitleState {
|
||||
LOGO_ANIMATING, // El logo está animándose
|
||||
LOGO_FINISHED, // El logo ha terminado de animarse
|
||||
START_HAS_BEEN_PRESSED, // Se ha pulsado el botón de start
|
||||
};
|
||||
private:
|
||||
// --- Enumeraciones ---
|
||||
enum class TitleState {
|
||||
LOGO_ANIMATING, // El logo está animándose
|
||||
LOGO_FINISHED, // El logo ha terminado de animarse
|
||||
START_HAS_BEEN_PRESSED, // Se ha pulsado el botón de start
|
||||
};
|
||||
|
||||
// --- Estructura para definir anclas ---
|
||||
struct Anchor {
|
||||
int mini_logo;
|
||||
int copyright_text;
|
||||
};
|
||||
// --- Estructura para definir anclas ---
|
||||
struct Anchor {
|
||||
int mini_logo;
|
||||
int copyright_text;
|
||||
};
|
||||
|
||||
// --- Objetos y punteros ---
|
||||
std::shared_ptr<Text> text_; // Objeto de texto para escribir en pantalla
|
||||
std::unique_ptr<Fade> fade_; // Fundido en pantalla
|
||||
std::unique_ptr<TiledBG> tiled_bg_; // Fondo animado de tiles
|
||||
std::unique_ptr<GameLogo> game_logo_; // Logo del juego
|
||||
std::unique_ptr<Sprite> mini_logo_sprite_; // Logo JailGames mini
|
||||
std::unique_ptr<DefineButtons> define_buttons_; // Definición de botones del joystick
|
||||
std::vector<std::shared_ptr<Player>> players_; // Vector de jugadores
|
||||
// --- Objetos y punteros ---
|
||||
std::shared_ptr<Text> text_; // Objeto de texto para escribir en pantalla
|
||||
std::unique_ptr<Fade> fade_; // Fundido en pantalla
|
||||
std::unique_ptr<TiledBG> tiled_bg_; // Fondo animado de tiles
|
||||
std::unique_ptr<GameLogo> game_logo_; // Logo del juego
|
||||
std::unique_ptr<Sprite> mini_logo_sprite_; // Logo JailGames mini
|
||||
std::unique_ptr<DefineButtons> define_buttons_; // Definición de botones del joystick
|
||||
std::vector<std::shared_ptr<Player>> players_; // Vector de jugadores
|
||||
|
||||
// --- Variables de estado ---
|
||||
int counter_ = 0; // Temporizador para la pantalla de título
|
||||
Uint64 ticks_ = 0; // Contador de ticks para ajustar la velocidad
|
||||
Section::Name next_section_; // Siguiente sección a cargar
|
||||
Section::Options selection_ = Section::Options::TITLE_TIME_OUT; // Opción elegida en el título
|
||||
int num_controllers_; // Número de mandos conectados
|
||||
TitleState state_; // Estado actual de la sección
|
||||
bool should_render_start_prompt_ = false; // Indica si se muestra o no el texto de PRESS START BUTTON TO PLAY
|
||||
bool player1_start_pressed_ = false; // Indica si se ha pulsdo el boton de empezar a jugar para el jugador 1
|
||||
bool player2_start_pressed_ = false; // Indica si se ha pulsdo el boton de empezar a jugar para el jugador 2
|
||||
// --- Variables de estado ---
|
||||
int counter_ = 0; // Temporizador para la pantalla de título
|
||||
Uint64 ticks_ = 0; // Contador de ticks para ajustar la velocidad
|
||||
Section::Name next_section_; // Siguiente sección a cargar
|
||||
Section::Options selection_ = Section::Options::TITLE_TIME_OUT; // Opción elegida en el título
|
||||
int num_controllers_; // Número de mandos conectados
|
||||
TitleState state_; // Estado actual de la sección
|
||||
bool should_render_start_prompt_ = false; // Indica si se muestra o no el texto de PRESS START BUTTON TO PLAY
|
||||
bool player1_start_pressed_ = false; // Indica si se ha pulsdo el boton de empezar a jugar para el jugador 1
|
||||
bool player2_start_pressed_ = false; // Indica si se ha pulsdo el boton de empezar a jugar para el jugador 2
|
||||
|
||||
// -- Variables de diseño ---
|
||||
Anchor anchor_; // Anclas para definir la posición de los elementos del titulo
|
||||
// -- Variables de diseño ---
|
||||
Anchor anchor_; // Anclas para definir la posición de los elementos del titulo
|
||||
|
||||
// --- Métodos internos ---
|
||||
void update(); // Actualiza las variables del objeto
|
||||
void render(); // Dibuja el objeto en pantalla
|
||||
void checkEvents(); // Comprueba los eventos
|
||||
void checkInput(); // Comprueba las entradas
|
||||
void resetCounter(); // Reinicia el contador interno
|
||||
void swapControllers(); // Intercambia la asignación de mandos a los jugadores
|
||||
static void swapKeyboard(); // Intercambia el teclado de jugador
|
||||
static void showControllers(); // Muestra información sobre los controles y los jugadores
|
||||
void updateFade(); // Actualiza el efecto de fundido (fade in/out)
|
||||
void updateState(); // Actualiza el estado actual del título
|
||||
void updateStartPrompt(); // Actualiza el mensaje de "Pulsa Start"
|
||||
void renderStartPrompt(); // Dibuja el mensaje de "Pulsa Start" en pantalla
|
||||
void renderCopyright(); // Dibuja el aviso de copyright
|
||||
void setState(TitleState state); // Cambia el estado del título
|
||||
void initPlayers(); // Inicializa los jugadores
|
||||
void renderPlayers(); // Renderiza los jugadores
|
||||
void updatePlayers(); // Actualza los jugadores
|
||||
auto getPlayer(int id) -> std::shared_ptr<Player>; // Obtiene un jugador a partir de su "id"
|
||||
// --- Métodos internos ---
|
||||
void update(); // Actualiza las variables del objeto
|
||||
void render(); // Dibuja el objeto en pantalla
|
||||
void checkEvents(); // Comprueba los eventos
|
||||
void checkInput(); // Comprueba las entradas
|
||||
void resetCounter(); // Reinicia el contador interno
|
||||
static void swapControllers(); // Intercambia la asignación de mandos a los jugadores
|
||||
static void swapKeyboard(); // Intercambia el teclado de jugador
|
||||
static void showControllers(); // Muestra información sobre los controles y los jugadores
|
||||
void updateFade(); // Actualiza el efecto de fundido (fade in/out)
|
||||
void updateState(); // Actualiza el estado actual del título
|
||||
void updateStartPrompt(); // Actualiza el mensaje de "Pulsa Start"
|
||||
void renderStartPrompt(); // Dibuja el mensaje de "Pulsa Start" en pantalla
|
||||
void renderCopyright(); // Dibuja el aviso de copyright
|
||||
void setState(TitleState state); // Cambia el estado del título
|
||||
void initPlayers(); // Inicializa los jugadores
|
||||
void renderPlayers(); // Renderiza los jugadores
|
||||
void updatePlayers(); // Actualza los jugadores
|
||||
auto getPlayer(int id) -> std::shared_ptr<Player>; // Obtiene un jugador a partir de su "id"
|
||||
};
|
||||
@@ -8,38 +8,38 @@ class Texture;
|
||||
|
||||
// Clase SmartSprite: Sprite animado que se mueve hacia un destino y puede deshabilitarse automáticamente
|
||||
class SmartSprite : public AnimatedSprite {
|
||||
public:
|
||||
// --- Constructor y destructor ---
|
||||
explicit SmartSprite(std::shared_ptr<Texture> texture)
|
||||
: AnimatedSprite(texture) {}
|
||||
~SmartSprite() override = default;
|
||||
public:
|
||||
// --- Constructor y destructor ---
|
||||
explicit SmartSprite(std::shared_ptr<Texture> texture)
|
||||
: AnimatedSprite(texture) {}
|
||||
~SmartSprite() override = default;
|
||||
|
||||
// --- Métodos principales ---
|
||||
void update() override; // Actualiza la posición y comprueba si ha llegado a su destino
|
||||
void render() override; // Dibuja el sprite
|
||||
// --- Métodos principales ---
|
||||
void update() override; // Actualiza la posición y comprueba si ha llegado a su destino
|
||||
void render() override; // Dibuja el sprite
|
||||
|
||||
// --- Getters ---
|
||||
auto getDestX() const -> int { return dest_x_; } // Obtiene la posición de destino en X
|
||||
auto getDestY() const -> int { return dest_y_; } // Obtiene la posición de destino en Y
|
||||
auto isOnDestination() const -> bool { return on_destination_; } // Indica si está en el destino
|
||||
auto hasFinished() const -> bool { return finished_; } // Indica si ya ha terminado
|
||||
// --- Getters ---
|
||||
auto getDestX() const -> int { return dest_x_; } // Obtiene la posición de destino en X
|
||||
auto getDestY() const -> int { return dest_y_; } // Obtiene la posición de destino en Y
|
||||
auto isOnDestination() const -> bool { return on_destination_; } // Indica si está en el destino
|
||||
auto hasFinished() const -> bool { return finished_; } // Indica si ya ha terminado
|
||||
|
||||
// --- Setters ---
|
||||
void setFinishedCounter(int value) { finished_counter_ = value; } // Establece el contador para deshabilitarlo
|
||||
void setDestX(int x) { dest_x_ = x; } // Establece la posición de destino en X
|
||||
void setDestY(int y) { dest_y_ = y; } // Establece la posición de destino en Y
|
||||
void setEnabled(bool value) { enabled_ = value; } // Habilita o deshabilita el objeto
|
||||
// --- Setters ---
|
||||
void setFinishedCounter(int value) { finished_counter_ = value; } // Establece el contador para deshabilitarlo
|
||||
void setDestX(int x) { dest_x_ = x; } // Establece la posición de destino en X
|
||||
void setDestY(int y) { dest_y_ = y; } // Establece la posición de destino en Y
|
||||
void setEnabled(bool value) { enabled_ = value; } // Habilita o deshabilita el objeto
|
||||
|
||||
private:
|
||||
// --- Variables internas ---
|
||||
bool on_destination_ = false; // Indica si está en el destino
|
||||
int dest_x_ = 0; // Posición de destino en el eje X
|
||||
int dest_y_ = 0; // Posición de destino en el eje Y
|
||||
int finished_counter_ = 0; // Contador para deshabilitarlo
|
||||
bool finished_ = false; // Indica si ya ha terminado
|
||||
bool enabled_ = false; // Indica si el objeto está habilitado
|
||||
private:
|
||||
// --- Variables internas ---
|
||||
bool on_destination_ = false; // Indica si está en el destino
|
||||
int dest_x_ = 0; // Posición de destino en el eje X
|
||||
int dest_y_ = 0; // Posición de destino en el eje Y
|
||||
int finished_counter_ = 0; // Contador para deshabilitarlo
|
||||
bool finished_ = false; // Indica si ya ha terminado
|
||||
bool enabled_ = false; // Indica si el objeto está habilitado
|
||||
|
||||
// --- Métodos internos ---
|
||||
void checkFinished(); // Comprueba si ha terminado
|
||||
void checkMove(); // Comprueba el movimiento
|
||||
// --- Métodos internos ---
|
||||
void checkFinished(); // Comprueba si ha terminado
|
||||
void checkMove(); // Comprueba el movimiento
|
||||
};
|
||||
@@ -8,54 +8,54 @@ class Texture;
|
||||
|
||||
// Clase Sprite: representa un objeto gráfico básico con posición, tamaño y textura
|
||||
class Sprite {
|
||||
public:
|
||||
// --- Constructores y destructor ---
|
||||
Sprite(std::shared_ptr<Texture> texture, float pos_x, float pos_y, float width, float height);
|
||||
Sprite(std::shared_ptr<Texture> texture, SDL_FRect rect);
|
||||
explicit Sprite(std::shared_ptr<Texture> texture);
|
||||
virtual ~Sprite() = default;
|
||||
public:
|
||||
// --- Constructores y destructor ---
|
||||
Sprite(std::shared_ptr<Texture> texture, float pos_x, float pos_y, float width, float height);
|
||||
Sprite(std::shared_ptr<Texture> texture, SDL_FRect rect);
|
||||
explicit Sprite(std::shared_ptr<Texture> texture);
|
||||
virtual ~Sprite() = default;
|
||||
|
||||
// --- Renderizado y control ---
|
||||
virtual void render(); // Muestra el sprite por pantalla
|
||||
virtual void clear(); // Reinicia las variables a cero
|
||||
// --- Renderizado y control ---
|
||||
virtual void render(); // Muestra el sprite por pantalla
|
||||
virtual void clear(); // Reinicia las variables a cero
|
||||
|
||||
// --- Getters de posición y tamaño ---
|
||||
[[nodiscard]] auto getX() const -> float { return pos_.x; }
|
||||
[[nodiscard]] auto getY() const -> float { return pos_.y; }
|
||||
[[nodiscard]] auto getWidth() const -> float { return pos_.w; }
|
||||
[[nodiscard]] auto getHeight() const -> float { return pos_.h; }
|
||||
[[nodiscard]] auto getPosition() const -> SDL_FRect { return pos_; }
|
||||
auto getRect() -> SDL_FRect& { return pos_; }
|
||||
// --- Getters de posición y tamaño ---
|
||||
[[nodiscard]] auto getX() const -> float { return pos_.x; }
|
||||
[[nodiscard]] auto getY() const -> float { return pos_.y; }
|
||||
[[nodiscard]] auto getWidth() const -> float { return pos_.w; }
|
||||
[[nodiscard]] auto getHeight() const -> float { return pos_.h; }
|
||||
[[nodiscard]] auto getPosition() const -> SDL_FRect { return pos_; }
|
||||
auto getRect() -> SDL_FRect& { return pos_; }
|
||||
|
||||
// --- Setters de posición y tamaño ---
|
||||
void setX(float pos_x) { pos_.x = pos_x; }
|
||||
void setY(float pos_y) { pos_.y = pos_y; }
|
||||
void setWidth(float width) { pos_.w = width; }
|
||||
void setHeight(float height) { pos_.h = height; }
|
||||
void setPosition(float pos_x, float pos_y);
|
||||
void setPosition(SDL_FPoint point);
|
||||
void setPosition(SDL_FRect rect) { pos_ = rect; }
|
||||
// --- Setters de posición y tamaño ---
|
||||
void setX(float pos_x) { pos_.x = pos_x; }
|
||||
void setY(float pos_y) { pos_.y = pos_y; }
|
||||
void setWidth(float width) { pos_.w = width; }
|
||||
void setHeight(float height) { pos_.h = height; }
|
||||
void setPosition(float pos_x, float pos_y);
|
||||
void setPosition(SDL_FPoint point);
|
||||
void setPosition(SDL_FRect rect) { pos_ = rect; }
|
||||
|
||||
// --- Zoom ---
|
||||
void setZoom(float zoom) { zoom_ = zoom; }
|
||||
// --- Zoom ---
|
||||
void setZoom(float zoom) { zoom_ = zoom; }
|
||||
|
||||
// --- Modificación de posición ---
|
||||
void incX(float value) { pos_.x += value; }
|
||||
void incY(float value) { pos_.y += value; }
|
||||
// --- Modificación de posición ---
|
||||
void incX(float value) { pos_.x += value; }
|
||||
void incY(float value) { pos_.y += value; }
|
||||
|
||||
// --- Sprite clip ---
|
||||
[[nodiscard]] auto getSpriteClip() const -> SDL_FRect { return sprite_clip_; }
|
||||
void setSpriteClip(SDL_FRect rect) { sprite_clip_ = rect; }
|
||||
void setSpriteClip(float pos_x, float pos_y, float width, float height) { sprite_clip_ = SDL_FRect{pos_x, pos_y, width, height}; }
|
||||
// --- Sprite clip ---
|
||||
[[nodiscard]] auto getSpriteClip() const -> SDL_FRect { return sprite_clip_; }
|
||||
void setSpriteClip(SDL_FRect rect) { sprite_clip_ = rect; }
|
||||
void setSpriteClip(float pos_x, float pos_y, float width, float height) { sprite_clip_ = SDL_FRect{pos_x, pos_y, width, height}; }
|
||||
|
||||
// --- Textura ---
|
||||
[[nodiscard]] auto getTexture() const -> std::shared_ptr<Texture> { return texture_; }
|
||||
void setTexture(std::shared_ptr<Texture> texture) { texture_ = texture; }
|
||||
// --- Textura ---
|
||||
[[nodiscard]] auto getTexture() const -> std::shared_ptr<Texture> { return texture_; }
|
||||
void setTexture(std::shared_ptr<Texture> texture) { texture_ = texture; }
|
||||
|
||||
protected:
|
||||
// --- Variables internas ---
|
||||
std::shared_ptr<Texture> texture_; // Textura donde están todos los dibujos del sprite
|
||||
SDL_FRect pos_; // Posición y tamaño donde dibujar el sprite
|
||||
SDL_FRect sprite_clip_; // Rectángulo de origen de la textura que se dibujará en pantalla
|
||||
double zoom_ = 1.0F; // Zoom aplicado a la textura
|
||||
protected:
|
||||
// --- Variables internas ---
|
||||
std::shared_ptr<Texture> texture_; // Textura donde están todos los dibujos del sprite
|
||||
SDL_FRect pos_; // Posición y tamaño donde dibujar el sprite
|
||||
SDL_FRect sprite_clip_; // Rectángulo de origen de la textura que se dibujará en pantalla
|
||||
double zoom_ = 1.0F; // Zoom aplicado a la textura
|
||||
};
|
||||
@@ -10,13 +10,13 @@
|
||||
namespace Stage {
|
||||
// --- Estructura con los datos de una fase ---
|
||||
struct Stage {
|
||||
int power_to_complete; // Cantidad de poder que se necesita para completar la fase
|
||||
int min_menace; // Umbral mínimo de amenaza de la fase
|
||||
int max_menace; // Umbral máximo de amenaza de la fase
|
||||
int power_to_complete; // Cantidad de poder que se necesita para completar la fase
|
||||
int min_menace; // Umbral mínimo de amenaza de la fase
|
||||
int max_menace; // Umbral máximo de amenaza de la fase
|
||||
|
||||
// Constructor
|
||||
Stage(int power_to_complete, int min_menace, int max_menace)
|
||||
: power_to_complete(power_to_complete), min_menace(min_menace), max_menace(max_menace) {}
|
||||
// Constructor
|
||||
Stage(int power_to_complete, int min_menace, int max_menace)
|
||||
: power_to_complete(power_to_complete), min_menace(min_menace), max_menace(max_menace) {}
|
||||
};
|
||||
|
||||
// --- Variables globales del estado de las fases ---
|
||||
@@ -28,6 +28,6 @@ extern bool power_can_be_added; // Indica si se puede añadir poder a la fase
|
||||
|
||||
// --- Funciones principales ---
|
||||
auto get(int index) -> Stage; // Devuelve una fase por índice
|
||||
void init(); // Inicializa las variables del namespace Stage
|
||||
void addPower(int amount); // Añade poder a la fase actual
|
||||
void init(); // Inicializa las variables del namespace Stage
|
||||
void addPower(int amount); // Añade poder a la fase actual
|
||||
} // namespace Stage
|
||||
@@ -5,9 +5,9 @@
|
||||
|
||||
#include <algorithm> // Para max
|
||||
#include <array>
|
||||
#include <cmath> // Para abs
|
||||
#include <cstdlib> // Para rand, abs
|
||||
#include <string> // Para basic_string
|
||||
#include <cmath> // Para abs
|
||||
#include <cstdlib> // Para rand, abs
|
||||
#include <string> // Para basic_string
|
||||
|
||||
#include "audio.h" // Para Audio
|
||||
#include "param.h" // Para Param, ParamGame, param
|
||||
|
||||
202
source/tabe.h
202
source/tabe.h
@@ -9,128 +9,128 @@
|
||||
|
||||
// --- Enumeraciones para dirección y estado ---
|
||||
enum class TabeDirection : int {
|
||||
TO_THE_LEFT = 0,
|
||||
TO_THE_RIGHT = 1,
|
||||
TO_THE_LEFT = 0,
|
||||
TO_THE_RIGHT = 1,
|
||||
};
|
||||
|
||||
enum class TabeState : int {
|
||||
FLY = 0,
|
||||
HIT = 1,
|
||||
FLY = 0,
|
||||
HIT = 1,
|
||||
};
|
||||
|
||||
// --- Estructura para el temporizador del Tabe ---
|
||||
struct TabeTimer {
|
||||
private:
|
||||
static constexpr Uint32 MINUTES_TO_MILLISECONDS = 60000; // Factor de conversión de minutos a milisegundos
|
||||
private:
|
||||
static constexpr Uint32 MINUTES_TO_MILLISECONDS = 60000; // Factor de conversión de minutos a milisegundos
|
||||
|
||||
public:
|
||||
Uint32 time_until_next_spawn; // Tiempo restante para la próxima aparición
|
||||
Uint32 min_spawn_time; // Tiempo mínimo entre apariciones (en milisegundos)
|
||||
Uint32 max_spawn_time; // Tiempo máximo entre apariciones (en milisegundos)
|
||||
Uint32 current_time; // Tiempo actual
|
||||
Uint32 delta_time; // Diferencia de tiempo desde la última actualización
|
||||
Uint32 last_time; // Tiempo de la última actualización
|
||||
bool is_paused{false}; // Indica si el temporizador está pausado
|
||||
public:
|
||||
Uint32 time_until_next_spawn; // Tiempo restante para la próxima aparición
|
||||
Uint32 min_spawn_time; // Tiempo mínimo entre apariciones (en milisegundos)
|
||||
Uint32 max_spawn_time; // Tiempo máximo entre apariciones (en milisegundos)
|
||||
Uint32 current_time; // Tiempo actual
|
||||
Uint32 delta_time; // Diferencia de tiempo desde la última actualización
|
||||
Uint32 last_time; // Tiempo de la última actualización
|
||||
bool is_paused{false}; // Indica si el temporizador está pausado
|
||||
|
||||
// Constructor - los parámetros min_time y max_time están en mintos
|
||||
TabeTimer(float min_time, float max_time)
|
||||
: min_spawn_time(static_cast<Uint32>(min_time * MINUTES_TO_MILLISECONDS)),
|
||||
max_spawn_time(static_cast<Uint32>(max_time * MINUTES_TO_MILLISECONDS)),
|
||||
current_time(SDL_GetTicks()) {
|
||||
reset();
|
||||
}
|
||||
|
||||
// Restablece el temporizador con un nuevo tiempo hasta la próxima aparición
|
||||
void reset() {
|
||||
Uint32 range = max_spawn_time - min_spawn_time;
|
||||
time_until_next_spawn = min_spawn_time + rand() % (range + 1);
|
||||
last_time = SDL_GetTicks();
|
||||
}
|
||||
|
||||
// Actualiza el temporizador, decrementando el tiempo hasta la próxima aparición
|
||||
void update() {
|
||||
current_time = SDL_GetTicks();
|
||||
|
||||
// Solo actualizar si no está pausado
|
||||
if (!is_paused) {
|
||||
delta_time = current_time - last_time;
|
||||
|
||||
if (time_until_next_spawn > delta_time) {
|
||||
time_until_next_spawn -= delta_time;
|
||||
} else {
|
||||
time_until_next_spawn = 0;
|
||||
// Constructor - los parámetros min_time y max_time están en mintos
|
||||
TabeTimer(float min_time, float max_time)
|
||||
: min_spawn_time(static_cast<Uint32>(min_time * MINUTES_TO_MILLISECONDS)),
|
||||
max_spawn_time(static_cast<Uint32>(max_time * MINUTES_TO_MILLISECONDS)),
|
||||
current_time(SDL_GetTicks()) {
|
||||
reset();
|
||||
}
|
||||
}
|
||||
|
||||
// Siempre actualizar last_time para evitar saltos de tiempo al despausar
|
||||
last_time = current_time;
|
||||
}
|
||||
|
||||
// Pausa o reanuda el temporizador
|
||||
void setPaused(bool paused) {
|
||||
if (is_paused != paused) {
|
||||
is_paused = paused;
|
||||
// Al despausar, actualizar last_time para evitar saltos
|
||||
if (!paused) {
|
||||
last_time = SDL_GetTicks();
|
||||
// Restablece el temporizador con un nuevo tiempo hasta la próxima aparición
|
||||
void reset() {
|
||||
Uint32 range = max_spawn_time - min_spawn_time;
|
||||
time_until_next_spawn = min_spawn_time + rand() % (range + 1);
|
||||
last_time = SDL_GetTicks();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Indica si el temporizador ha finalizado
|
||||
[[nodiscard]] auto shouldSpawn() const -> bool {
|
||||
return time_until_next_spawn == 0 && !is_paused;
|
||||
}
|
||||
// Actualiza el temporizador, decrementando el tiempo hasta la próxima aparición
|
||||
void update() {
|
||||
current_time = SDL_GetTicks();
|
||||
|
||||
// Solo actualizar si no está pausado
|
||||
if (!is_paused) {
|
||||
delta_time = current_time - last_time;
|
||||
|
||||
if (time_until_next_spawn > delta_time) {
|
||||
time_until_next_spawn -= delta_time;
|
||||
} else {
|
||||
time_until_next_spawn = 0;
|
||||
}
|
||||
}
|
||||
|
||||
// Siempre actualizar last_time para evitar saltos de tiempo al despausar
|
||||
last_time = current_time;
|
||||
}
|
||||
|
||||
// Pausa o reanuda el temporizador
|
||||
void setPaused(bool paused) {
|
||||
if (is_paused != paused) {
|
||||
is_paused = paused;
|
||||
// Al despausar, actualizar last_time para evitar saltos
|
||||
if (!paused) {
|
||||
last_time = SDL_GetTicks();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Indica si el temporizador ha finalizado
|
||||
[[nodiscard]] auto shouldSpawn() const -> bool {
|
||||
return time_until_next_spawn == 0 && !is_paused;
|
||||
}
|
||||
};
|
||||
|
||||
// --- Clase Tabe ---
|
||||
class Tabe {
|
||||
public:
|
||||
// --- Constructores y destructor ---
|
||||
Tabe();
|
||||
~Tabe() = default;
|
||||
public:
|
||||
// --- Constructores y destructor ---
|
||||
Tabe();
|
||||
~Tabe() = default;
|
||||
|
||||
// --- Métodos principales ---
|
||||
void update(); // Actualiza la lógica
|
||||
void render(); // Dibuja el objeto
|
||||
void enable(); // Habilita el objeto
|
||||
void setState(TabeState state); // Establece el estado
|
||||
auto tryToGetBonus() -> bool; // Intenta obtener el bonus
|
||||
void pauseTimer(bool value); // Detiene/activa el timer
|
||||
// --- Métodos principales ---
|
||||
void update(); // Actualiza la lógica
|
||||
void render(); // Dibuja el objeto
|
||||
void enable(); // Habilita el objeto
|
||||
void setState(TabeState state); // Establece el estado
|
||||
auto tryToGetBonus() -> bool; // Intenta obtener el bonus
|
||||
void pauseTimer(bool value); // Detiene/activa el timer
|
||||
|
||||
// --- Getters ---
|
||||
auto getCollider() -> SDL_FRect& { return sprite_->getRect(); } // Obtiene el área de colisión
|
||||
[[nodiscard]] auto isEnabled() const -> bool { return enabled_; } // Indica si el objeto está activo
|
||||
// --- Getters ---
|
||||
auto getCollider() -> SDL_FRect& { return sprite_->getRect(); } // Obtiene el área de colisión
|
||||
[[nodiscard]] auto isEnabled() const -> bool { return enabled_; } // Indica si el objeto está activo
|
||||
|
||||
private:
|
||||
// --- Constantes ---
|
||||
static constexpr int WIDTH = 32;
|
||||
static constexpr int HEIGHT = 32;
|
||||
private:
|
||||
// --- Constantes ---
|
||||
static constexpr int WIDTH = 32;
|
||||
static constexpr int HEIGHT = 32;
|
||||
|
||||
// --- Objetos y punteros ---
|
||||
std::unique_ptr<AnimatedSprite> sprite_; // Sprite con los gráficos y animaciones
|
||||
// --- Objetos y punteros ---
|
||||
std::unique_ptr<AnimatedSprite> sprite_; // Sprite con los gráficos y animaciones
|
||||
|
||||
// --- Variables de estado ---
|
||||
float x_ = 0; // Posición X
|
||||
float y_ = 0; // Posición Y
|
||||
float speed_ = 0.0F; // Velocidad de movimiento
|
||||
float accel_ = 0.0F; // Aceleración
|
||||
int fly_distance_ = 0; // Distancia de vuelo
|
||||
int waiting_counter_ = 0; // Tiempo que pasa quieto
|
||||
bool enabled_ = false; // Indica si el objeto está activo
|
||||
TabeDirection direction_ = TabeDirection::TO_THE_LEFT; // Dirección actual
|
||||
TabeDirection destiny_ = TabeDirection::TO_THE_LEFT; // Destino
|
||||
TabeState state_ = TabeState::FLY; // Estado actual
|
||||
int hit_counter_ = 0; // Contador para el estado HIT
|
||||
int number_of_hits_ = 0; // Cantidad de disparos recibidos
|
||||
bool has_bonus_ = true; // Indica si aún tiene el bonus para soltar
|
||||
TabeTimer timer_; // Temporizador para gestionar la aparición
|
||||
// --- Variables de estado ---
|
||||
float x_ = 0; // Posición X
|
||||
float y_ = 0; // Posición Y
|
||||
float speed_ = 0.0F; // Velocidad de movimiento
|
||||
float accel_ = 0.0F; // Aceleración
|
||||
int fly_distance_ = 0; // Distancia de vuelo
|
||||
int waiting_counter_ = 0; // Tiempo que pasa quieto
|
||||
bool enabled_ = false; // Indica si el objeto está activo
|
||||
TabeDirection direction_ = TabeDirection::TO_THE_LEFT; // Dirección actual
|
||||
TabeDirection destiny_ = TabeDirection::TO_THE_LEFT; // Destino
|
||||
TabeState state_ = TabeState::FLY; // Estado actual
|
||||
int hit_counter_ = 0; // Contador para el estado HIT
|
||||
int number_of_hits_ = 0; // Cantidad de disparos recibidos
|
||||
bool has_bonus_ = true; // Indica si aún tiene el bonus para soltar
|
||||
TabeTimer timer_; // Temporizador para gestionar la aparición
|
||||
|
||||
// --- Métodos internos ---
|
||||
void move(); // Mueve el objeto
|
||||
void shiftSprite() { sprite_->setPos(x_, y_); } // Actualiza la posición del sprite
|
||||
void setRandomFlyPath(TabeDirection direction, int lenght); // Establece un vuelo aleatorio
|
||||
void updateState(); // Actualiza el estado
|
||||
void updateTimer(); // Actualiza el temporizador
|
||||
void disable(); // Deshabilita el objeto
|
||||
// --- Métodos internos ---
|
||||
void move(); // Mueve el objeto
|
||||
void shiftSprite() { sprite_->setPos(x_, y_); } // Actualiza la posición del sprite
|
||||
void setRandomFlyPath(TabeDirection direction, int lenght); // Establece un vuelo aleatorio
|
||||
void updateState(); // Actualiza el estado
|
||||
void updateTimer(); // Actualiza el temporizador
|
||||
void disable(); // Deshabilita el objeto
|
||||
};
|
||||
@@ -243,7 +243,7 @@ auto Texture::loadSurface(const std::string &file_path) -> std::shared_ptr<Surfa
|
||||
|
||||
// Si el constructor de Surface espera un std::shared_ptr<Uint8[]>:
|
||||
size_t pixel_count = raw_pixels.size();
|
||||
auto pixels = std::shared_ptr<Uint8[]>(new Uint8[pixel_count], std::default_delete<Uint8[]>()); // NOLINT(modernize-avoid-c-arrays)
|
||||
auto pixels = std::shared_ptr<Uint8[]>(new Uint8[pixel_count], std::default_delete<Uint8[]>()); // NOLINT(modernize-avoid-c-arrays)
|
||||
std::memcpy(pixels.get(), raw_pixels.data(), pixel_count);
|
||||
|
||||
auto surface = std::make_shared<Surface>(w, h, pixels);
|
||||
|
||||
@@ -16,66 +16,66 @@ using Palette = std::array<Uint32, 256>;
|
||||
|
||||
// Definición de Surface para imágenes con paleta
|
||||
struct Surface {
|
||||
std::shared_ptr<Uint8[]> data; // NOLINT(modernize-avoid-c-arrays)
|
||||
Uint16 w, h;
|
||||
std::shared_ptr<Uint8[]> data; // NOLINT(modernize-avoid-c-arrays)
|
||||
Uint16 w, h;
|
||||
|
||||
// Constructor
|
||||
Surface(Uint16 width, Uint16 height, std::shared_ptr<Uint8[]> pixels) // NOLINT(modernize-avoid-c-arrays)
|
||||
: data(std::move(pixels)), w(width), h(height) {}
|
||||
// Constructor
|
||||
Surface(Uint16 width, Uint16 height, std::shared_ptr<Uint8[]> pixels) // NOLINT(modernize-avoid-c-arrays)
|
||||
: data(std::move(pixels)), w(width), h(height) {}
|
||||
};
|
||||
|
||||
// Clase Texture: gestiona texturas, paletas y renderizado
|
||||
class Texture {
|
||||
public:
|
||||
// --- Constructores y destructor ---
|
||||
explicit Texture(SDL_Renderer *renderer, std::string path = std::string());
|
||||
~Texture();
|
||||
public:
|
||||
// --- Constructores y destructor ---
|
||||
explicit Texture(SDL_Renderer *renderer, std::string path = std::string());
|
||||
~Texture();
|
||||
|
||||
// --- Carga y creación ---
|
||||
auto loadFromFile(const std::string &path) -> bool; // Carga una imagen desde un fichero
|
||||
auto createBlank(int width, int height, SDL_PixelFormat format = SDL_PIXELFORMAT_RGBA8888, SDL_TextureAccess access = SDL_TEXTUREACCESS_STREAMING) -> bool; // Crea una textura en blanco
|
||||
auto reLoad() -> bool; // Recarga la textura
|
||||
// --- Carga y creación ---
|
||||
auto loadFromFile(const std::string &path) -> bool; // Carga una imagen desde un fichero
|
||||
auto createBlank(int width, int height, SDL_PixelFormat format = SDL_PIXELFORMAT_RGBA8888, SDL_TextureAccess access = SDL_TEXTUREACCESS_STREAMING) -> bool; // Crea una textura en blanco
|
||||
auto reLoad() -> bool; // Recarga la textura
|
||||
|
||||
// --- Renderizado ---
|
||||
void render(int x, int y, SDL_FRect *clip = nullptr, float zoom_w = 1, float zoom_h = 1, double angle = 0.0, SDL_FPoint *center = nullptr, SDL_FlipMode flip = SDL_FLIP_NONE); // Renderiza la textura en un punto específico
|
||||
void setAsRenderTarget(SDL_Renderer *renderer); // Establece la textura como objetivo de renderizado
|
||||
// --- Renderizado ---
|
||||
void render(int x, int y, SDL_FRect *clip = nullptr, float zoom_w = 1, float zoom_h = 1, double angle = 0.0, SDL_FPoint *center = nullptr, SDL_FlipMode flip = SDL_FLIP_NONE); // Renderiza la textura en un punto específico
|
||||
void setAsRenderTarget(SDL_Renderer *renderer); // Establece la textura como objetivo de renderizado
|
||||
|
||||
// --- Modificadores de color y blending ---
|
||||
void setColor(Uint8 red, Uint8 green, Uint8 blue); // Establece el color para la modulación
|
||||
void setColor(Color color); // Establece el color para la modulación
|
||||
void setBlendMode(SDL_BlendMode blending); // Establece el blending
|
||||
void setAlpha(Uint8 alpha); // Establece el alpha para la modulación
|
||||
// --- Modificadores de color y blending ---
|
||||
void setColor(Uint8 red, Uint8 green, Uint8 blue); // Establece el color para la modulación
|
||||
void setColor(Color color); // Establece el color para la modulación
|
||||
void setBlendMode(SDL_BlendMode blending); // Establece el blending
|
||||
void setAlpha(Uint8 alpha); // Establece el alpha para la modulación
|
||||
|
||||
// --- Paletas ---
|
||||
void addPaletteFromGifFile(const std::string &path); // Añade una paleta a la lista
|
||||
void addPaletteFromPalFile(const std::string &path); // Añade una paleta a la lista
|
||||
void setPaletteColor(int palette, int index, Uint32 color); // Establece un color de la paleta
|
||||
void setPalette(size_t palette); // Cambia la paleta de la textura
|
||||
// --- Paletas ---
|
||||
void addPaletteFromGifFile(const std::string &path); // Añade una paleta a la lista
|
||||
void addPaletteFromPalFile(const std::string &path); // Añade una paleta a la lista
|
||||
void setPaletteColor(int palette, int index, Uint32 color); // Establece un color de la paleta
|
||||
void setPalette(size_t palette); // Cambia la paleta de la textura
|
||||
|
||||
// --- Getters ---
|
||||
[[nodiscard]] auto getWidth() const -> int; // Obtiene el ancho de la imagen
|
||||
[[nodiscard]] auto getHeight() const -> int; // Obtiene el alto de la imagen
|
||||
auto getSDLTexture() -> SDL_Texture *; // Obtiene la textura SDL
|
||||
auto getRenderer() -> SDL_Renderer *; // Obtiene el renderizador
|
||||
// --- Getters ---
|
||||
[[nodiscard]] auto getWidth() const -> int; // Obtiene el ancho de la imagen
|
||||
[[nodiscard]] auto getHeight() const -> int; // Obtiene el alto de la imagen
|
||||
auto getSDLTexture() -> SDL_Texture *; // Obtiene la textura SDL
|
||||
auto getRenderer() -> SDL_Renderer *; // Obtiene el renderizador
|
||||
|
||||
private:
|
||||
// --- Objetos y punteros ---
|
||||
SDL_Renderer *renderer_; // Renderizador donde dibujar la textura
|
||||
SDL_Texture *texture_ = nullptr; // La textura
|
||||
std::shared_ptr<Surface> surface_ = nullptr; // Surface para usar imágenes en formato gif con paleta
|
||||
private:
|
||||
// --- Objetos y punteros ---
|
||||
SDL_Renderer *renderer_; // Renderizador donde dibujar la textura
|
||||
SDL_Texture *texture_ = nullptr; // La textura
|
||||
std::shared_ptr<Surface> surface_ = nullptr; // Surface para usar imágenes en formato gif con paleta
|
||||
|
||||
// --- Variables ---
|
||||
std::string path_; // Ruta de la imagen de la textura
|
||||
int width_ = 0; // Ancho de la imagen
|
||||
int height_ = 0; // Alto de la imagen
|
||||
std::vector<Palette> palettes_; // Vector con las diferentes paletas
|
||||
int current_palette_ = 0; // Índice de la paleta en uso
|
||||
// --- Variables ---
|
||||
std::string path_; // Ruta de la imagen de la textura
|
||||
int width_ = 0; // Ancho de la imagen
|
||||
int height_ = 0; // Alto de la imagen
|
||||
std::vector<Palette> palettes_; // Vector con las diferentes paletas
|
||||
int current_palette_ = 0; // Índice de la paleta en uso
|
||||
|
||||
// --- Métodos internos ---
|
||||
auto loadSurface(const std::string &file_name) -> std::shared_ptr<Surface>; // Crea una surface desde un fichero .gif
|
||||
void flipSurface(); // Vuelca la surface en la textura
|
||||
static auto loadPaletteFromFile(const std::string &file_name) -> Palette; // Carga una paleta desde un fichero
|
||||
void unloadTexture(); // Libera la memoria de la textura
|
||||
void unloadSurface(); // Libera la surface actual
|
||||
static auto readPalFile(const std::string &file_path) -> Palette; // Carga una paleta desde un archivo .pal
|
||||
// --- Métodos internos ---
|
||||
auto loadSurface(const std::string &file_name) -> std::shared_ptr<Surface>; // Crea una surface desde un fichero .gif
|
||||
void flipSurface(); // Vuelca la surface en la textura
|
||||
static auto loadPaletteFromFile(const std::string &file_name) -> Palette; // Carga una paleta desde un fichero
|
||||
void unloadTexture(); // Libera la memoria de la textura
|
||||
void unloadSurface(); // Libera la surface actual
|
||||
static auto readPalFile(const std::string &file_path) -> Palette; // Carga una paleta desde un archivo .pal
|
||||
};
|
||||
@@ -1,6 +1,7 @@
|
||||
#pragma once
|
||||
|
||||
#include <SDL3/SDL.h> // Para SDL_FRect, SDL_SetTextureColorMod, SDL_Renderer, SDL_Texture
|
||||
|
||||
#include <array>
|
||||
|
||||
#include "utils.h" // Para Color
|
||||
@@ -21,43 +22,43 @@ enum class TiledBGMode : int {
|
||||
|
||||
// Clase TiledBG
|
||||
class TiledBG {
|
||||
public:
|
||||
// --- Constructores y destructor ---
|
||||
TiledBG(SDL_FRect pos, TiledBGMode mode);
|
||||
~TiledBG();
|
||||
public:
|
||||
// --- Constructores y destructor ---
|
||||
TiledBG(SDL_FRect pos, TiledBGMode mode);
|
||||
~TiledBG();
|
||||
|
||||
// --- Métodos principales ---
|
||||
void render(); // Pinta la clase en pantalla
|
||||
void update(); // Actualiza la lógica de la clase
|
||||
// --- Métodos principales ---
|
||||
void render(); // Pinta la clase en pantalla
|
||||
void update(); // Actualiza la lógica de la clase
|
||||
|
||||
// --- Configuración ---
|
||||
void setSpeed(float speed) { speed_ = speed; } // Establece la velocidad
|
||||
void stopGracefully() { stopping_ = true; } // Detiene el desplazamiento de forma ordenada
|
||||
void setColor(Color color) { SDL_SetTextureColorMod(canvas_, color.r, color.g, color.b); } // Cambia el color de la textura
|
||||
// --- Configuración ---
|
||||
void setSpeed(float speed) { speed_ = speed; } // Establece la velocidad
|
||||
void stopGracefully() { stopping_ = true; } // Detiene el desplazamiento de forma ordenada
|
||||
void setColor(Color color) { SDL_SetTextureColorMod(canvas_, color.r, color.g, color.b); } // Cambia el color de la textura
|
||||
|
||||
// --- Getters ---
|
||||
[[nodiscard]] auto isStopped() const -> bool { return speed_ == 0.0F; } // Indica si está parado
|
||||
// --- Getters ---
|
||||
[[nodiscard]] auto isStopped() const -> bool { return speed_ == 0.0F; } // Indica si está parado
|
||||
|
||||
private:
|
||||
// --- Constantes ---
|
||||
static constexpr int TILE_WIDTH = 64; // Ancho del tile
|
||||
static constexpr int TILE_HEIGHT = 64; // Alto del tile
|
||||
private:
|
||||
// --- Constantes ---
|
||||
static constexpr int TILE_WIDTH = 64; // Ancho del tile
|
||||
static constexpr int TILE_HEIGHT = 64; // Alto del tile
|
||||
|
||||
// --- Objetos y punteros ---
|
||||
SDL_Renderer *renderer_; // El renderizador de la ventana
|
||||
SDL_Texture *canvas_; // Textura donde dibujar el fondo formado por tiles
|
||||
// --- Objetos y punteros ---
|
||||
SDL_Renderer *renderer_; // El renderizador de la ventana
|
||||
SDL_Texture *canvas_; // Textura donde dibujar el fondo formado por tiles
|
||||
|
||||
// --- Variables de estado ---
|
||||
SDL_FRect pos_; // Posición y tamaño del mosaico
|
||||
SDL_FRect window_; // Ventana visible para la textura de fondo del título
|
||||
TiledBGMode mode_; // Tipo de movimiento del mosaico
|
||||
std::array<double, 360> sin_; // Vector con los valores del seno precalculados
|
||||
float desp_ = 0.0F; // Desplazamiento aplicado
|
||||
float speed_ = 1.0F; // Incremento que se añade al desplazamiento a cada bucle
|
||||
bool stopping_ = false; // Indica si se está deteniendo
|
||||
// --- Variables de estado ---
|
||||
SDL_FRect pos_; // Posición y tamaño del mosaico
|
||||
SDL_FRect window_; // Ventana visible para la textura de fondo del título
|
||||
TiledBGMode mode_; // Tipo de movimiento del mosaico
|
||||
std::array<double, 360> sin_; // Vector con los valores del seno precalculados
|
||||
float desp_ = 0.0F; // Desplazamiento aplicado
|
||||
float speed_ = 1.0F; // Incremento que se añade al desplazamiento a cada bucle
|
||||
bool stopping_ = false; // Indica si se está deteniendo
|
||||
|
||||
// --- Métodos internos ---
|
||||
void fillTexture(); // Rellena la textura con el contenido
|
||||
void updateDesp() { desp_ += speed_; } // Actualiza el desplazamiento
|
||||
void updateStop(); // Detiene el desplazamiento de forma ordenada
|
||||
// --- Métodos internos ---
|
||||
void fillTexture(); // Rellena la textura con el contenido
|
||||
void updateDesp() { desp_ += speed_; } // Actualiza el desplazamiento
|
||||
void updateStop(); // Detiene el desplazamiento de forma ordenada
|
||||
};
|
||||
@@ -15,161 +15,161 @@
|
||||
// --- Interfaz Base para todas las Opciones del Menú ---
|
||||
|
||||
class MenuOption {
|
||||
public:
|
||||
enum class Behavior {
|
||||
ADJUST,
|
||||
SELECT
|
||||
};
|
||||
public:
|
||||
enum class Behavior {
|
||||
ADJUST,
|
||||
SELECT
|
||||
};
|
||||
|
||||
MenuOption(std::string caption, ServiceMenu::SettingsGroup group, bool hidden = false)
|
||||
: caption_(std::move(caption)), group_(group), hidden_(hidden) {}
|
||||
MenuOption(std::string caption, ServiceMenu::SettingsGroup group, bool hidden = false)
|
||||
: caption_(std::move(caption)), group_(group), hidden_(hidden) {}
|
||||
|
||||
virtual ~MenuOption() = default;
|
||||
virtual ~MenuOption() = default;
|
||||
|
||||
[[nodiscard]] auto getCaption() const -> const std::string & { return caption_; }
|
||||
[[nodiscard]] auto getGroup() const -> ServiceMenu::SettingsGroup { return group_; }
|
||||
[[nodiscard]] auto isHidden() const -> bool { return hidden_; }
|
||||
void setHidden(bool hidden) { hidden_ = hidden; }
|
||||
[[nodiscard]] auto getCaption() const -> const std::string & { return caption_; }
|
||||
[[nodiscard]] auto getGroup() const -> ServiceMenu::SettingsGroup { return group_; }
|
||||
[[nodiscard]] auto isHidden() const -> bool { return hidden_; }
|
||||
void setHidden(bool hidden) { hidden_ = hidden; }
|
||||
|
||||
[[nodiscard]] virtual auto getBehavior() const -> Behavior = 0;
|
||||
[[nodiscard]] virtual auto getValueAsString() const -> std::string { return ""; }
|
||||
virtual void adjustValue(bool adjust_up) {}
|
||||
[[nodiscard]] virtual auto getTargetGroup() const -> ServiceMenu::SettingsGroup { return ServiceMenu::SettingsGroup::MAIN; }
|
||||
virtual void executeAction() {}
|
||||
[[nodiscard]] virtual auto getBehavior() const -> Behavior = 0;
|
||||
[[nodiscard]] virtual auto getValueAsString() const -> std::string { return ""; }
|
||||
virtual void adjustValue(bool adjust_up) {}
|
||||
[[nodiscard]] virtual auto getTargetGroup() const -> ServiceMenu::SettingsGroup { return ServiceMenu::SettingsGroup::MAIN; }
|
||||
virtual void executeAction() {}
|
||||
|
||||
// Método virtual para que cada opción calcule el ancho de su valor más largo.
|
||||
virtual auto getMaxValueWidth(Text *text_renderer) const -> int { return 0; }
|
||||
// Método virtual para que cada opción calcule el ancho de su valor más largo.
|
||||
virtual auto getMaxValueWidth(Text *text_renderer) const -> int { return 0; }
|
||||
|
||||
protected:
|
||||
std::string caption_;
|
||||
ServiceMenu::SettingsGroup group_;
|
||||
bool hidden_;
|
||||
protected:
|
||||
std::string caption_;
|
||||
ServiceMenu::SettingsGroup group_;
|
||||
bool hidden_;
|
||||
};
|
||||
|
||||
// --- Clases Derivadas ---
|
||||
|
||||
class BoolOption : public MenuOption {
|
||||
public:
|
||||
BoolOption(const std::string &cap, ServiceMenu::SettingsGroup grp, bool *var)
|
||||
: MenuOption(cap, grp), linked_variable_(var) {}
|
||||
public:
|
||||
BoolOption(const std::string &cap, ServiceMenu::SettingsGroup grp, bool *var)
|
||||
: MenuOption(cap, grp), linked_variable_(var) {}
|
||||
|
||||
[[nodiscard]] auto getBehavior() const -> Behavior override { return Behavior::ADJUST; }
|
||||
[[nodiscard]] auto getValueAsString() const -> std::string override {
|
||||
return *linked_variable_ ? Lang::getText("[SERVICE_MENU] ON") : Lang::getText("[SERVICE_MENU] OFF");
|
||||
}
|
||||
void adjustValue(bool /*adjust_up*/) override {
|
||||
*linked_variable_ = !*linked_variable_;
|
||||
}
|
||||
auto getMaxValueWidth(Text *text_renderer) const -> int override {
|
||||
return std::max(
|
||||
text_renderer->lenght(Lang::getText("[SERVICE_MENU] ON"), -2),
|
||||
text_renderer->lenght(Lang::getText("[SERVICE_MENU] OFF"), -2));
|
||||
}
|
||||
[[nodiscard]] auto getBehavior() const -> Behavior override { return Behavior::ADJUST; }
|
||||
[[nodiscard]] auto getValueAsString() const -> std::string override {
|
||||
return *linked_variable_ ? Lang::getText("[SERVICE_MENU] ON") : Lang::getText("[SERVICE_MENU] OFF");
|
||||
}
|
||||
void adjustValue(bool /*adjust_up*/) override {
|
||||
*linked_variable_ = !*linked_variable_;
|
||||
}
|
||||
auto getMaxValueWidth(Text *text_renderer) const -> int override {
|
||||
return std::max(
|
||||
text_renderer->lenght(Lang::getText("[SERVICE_MENU] ON"), -2),
|
||||
text_renderer->lenght(Lang::getText("[SERVICE_MENU] OFF"), -2));
|
||||
}
|
||||
|
||||
private:
|
||||
bool *linked_variable_;
|
||||
private:
|
||||
bool *linked_variable_;
|
||||
};
|
||||
|
||||
class IntOption : public MenuOption {
|
||||
public:
|
||||
IntOption(const std::string &cap, ServiceMenu::SettingsGroup grp, int *var, int min, int max, int step)
|
||||
: MenuOption(cap, grp), linked_variable_(var), min_value_(min), max_value_(max), step_value_(step) {}
|
||||
public:
|
||||
IntOption(const std::string &cap, ServiceMenu::SettingsGroup grp, int *var, int min, int max, int step)
|
||||
: MenuOption(cap, grp), linked_variable_(var), min_value_(min), max_value_(max), step_value_(step) {}
|
||||
|
||||
[[nodiscard]] auto getBehavior() const -> Behavior override { return Behavior::ADJUST; }
|
||||
[[nodiscard]] auto getValueAsString() const -> std::string override { return std::to_string(*linked_variable_); }
|
||||
void adjustValue(bool adjust_up) override {
|
||||
int new_value = *linked_variable_ + (adjust_up ? step_value_ : -step_value_);
|
||||
*linked_variable_ = std::clamp(new_value, min_value_, max_value_);
|
||||
}
|
||||
auto getMaxValueWidth(Text *text_renderer) const -> int override {
|
||||
int max_width = 0;
|
||||
[[nodiscard]] auto getBehavior() const -> Behavior override { return Behavior::ADJUST; }
|
||||
[[nodiscard]] auto getValueAsString() const -> std::string override { return std::to_string(*linked_variable_); }
|
||||
void adjustValue(bool adjust_up) override {
|
||||
int new_value = *linked_variable_ + (adjust_up ? step_value_ : -step_value_);
|
||||
*linked_variable_ = std::clamp(new_value, min_value_, max_value_);
|
||||
}
|
||||
auto getMaxValueWidth(Text *text_renderer) const -> int override {
|
||||
int max_width = 0;
|
||||
|
||||
// Iterar por todos los valores posibles en el rango
|
||||
for (int value = min_value_; value <= max_value_; value += step_value_) {
|
||||
int width = text_renderer->lenght(std::to_string(value), -2);
|
||||
max_width = std::max(max_width, width);
|
||||
// Iterar por todos los valores posibles en el rango
|
||||
for (int value = min_value_; value <= max_value_; value += step_value_) {
|
||||
int width = text_renderer->lenght(std::to_string(value), -2);
|
||||
max_width = std::max(max_width, width);
|
||||
}
|
||||
|
||||
return max_width;
|
||||
}
|
||||
|
||||
return max_width;
|
||||
}
|
||||
|
||||
private:
|
||||
int *linked_variable_;
|
||||
int min_value_, max_value_, step_value_;
|
||||
private:
|
||||
int *linked_variable_;
|
||||
int min_value_, max_value_, step_value_;
|
||||
};
|
||||
|
||||
class ListOption : public MenuOption {
|
||||
public:
|
||||
ListOption(const std::string &cap, ServiceMenu::SettingsGroup grp, std::vector<std::string> values, std::function<std::string()> current_value_getter, std::function<void(const std::string &)> new_value_setter)
|
||||
: MenuOption(cap, grp),
|
||||
value_list_(std::move(values)),
|
||||
getter_(std::move(current_value_getter)),
|
||||
setter_(std::move(new_value_setter)) {
|
||||
sync();
|
||||
}
|
||||
public:
|
||||
ListOption(const std::string &cap, ServiceMenu::SettingsGroup grp, std::vector<std::string> values, std::function<std::string()> current_value_getter, std::function<void(const std::string &)> new_value_setter)
|
||||
: MenuOption(cap, grp),
|
||||
value_list_(std::move(values)),
|
||||
getter_(std::move(current_value_getter)),
|
||||
setter_(std::move(new_value_setter)) {
|
||||
sync();
|
||||
}
|
||||
|
||||
void sync() {
|
||||
std::string current_value = getter_();
|
||||
for (size_t i = 0; i < value_list_.size(); ++i) {
|
||||
if (value_list_[i] == current_value) {
|
||||
list_index_ = i;
|
||||
return;
|
||||
void sync() {
|
||||
std::string current_value = getter_();
|
||||
for (size_t i = 0; i < value_list_.size(); ++i) {
|
||||
if (value_list_[i] == current_value) {
|
||||
list_index_ = i;
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[[nodiscard]] auto getBehavior() const -> Behavior override { return Behavior::ADJUST; }
|
||||
[[nodiscard]] auto getValueAsString() const -> std::string override {
|
||||
return value_list_.empty() ? "" : value_list_[list_index_];
|
||||
}
|
||||
void adjustValue(bool adjust_up) override {
|
||||
if (value_list_.empty()) {
|
||||
return;
|
||||
[[nodiscard]] auto getBehavior() const -> Behavior override { return Behavior::ADJUST; }
|
||||
[[nodiscard]] auto getValueAsString() const -> std::string override {
|
||||
return value_list_.empty() ? "" : value_list_[list_index_];
|
||||
}
|
||||
size_t size = value_list_.size();
|
||||
list_index_ = (adjust_up) ? (list_index_ + 1) % size
|
||||
: (list_index_ + size - 1) % size;
|
||||
setter_(value_list_[list_index_]);
|
||||
}
|
||||
auto getMaxValueWidth(Text *text_renderer) const -> int override {
|
||||
int max_w = 0;
|
||||
for (const auto &val : value_list_) {
|
||||
max_w = std::max(max_w, text_renderer->lenght(val, -2));
|
||||
void adjustValue(bool adjust_up) override {
|
||||
if (value_list_.empty()) {
|
||||
return;
|
||||
}
|
||||
size_t size = value_list_.size();
|
||||
list_index_ = (adjust_up) ? (list_index_ + 1) % size
|
||||
: (list_index_ + size - 1) % size;
|
||||
setter_(value_list_[list_index_]);
|
||||
}
|
||||
auto getMaxValueWidth(Text *text_renderer) const -> int override {
|
||||
int max_w = 0;
|
||||
for (const auto &val : value_list_) {
|
||||
max_w = std::max(max_w, text_renderer->lenght(val, -2));
|
||||
}
|
||||
return max_w;
|
||||
}
|
||||
return max_w;
|
||||
}
|
||||
|
||||
private:
|
||||
std::vector<std::string> value_list_;
|
||||
std::function<std::string()> getter_;
|
||||
std::function<void(const std::string &)> setter_;
|
||||
size_t list_index_{0};
|
||||
private:
|
||||
std::vector<std::string> value_list_;
|
||||
std::function<std::string()> getter_;
|
||||
std::function<void(const std::string &)> setter_;
|
||||
size_t list_index_{0};
|
||||
};
|
||||
|
||||
class FolderOption : public MenuOption {
|
||||
public:
|
||||
FolderOption(const std::string &cap, ServiceMenu::SettingsGroup grp, ServiceMenu::SettingsGroup target)
|
||||
: MenuOption(cap, grp), target_group_(target) {}
|
||||
public:
|
||||
FolderOption(const std::string &cap, ServiceMenu::SettingsGroup grp, ServiceMenu::SettingsGroup target)
|
||||
: MenuOption(cap, grp), target_group_(target) {}
|
||||
|
||||
[[nodiscard]] auto getBehavior() const -> Behavior override { return Behavior::SELECT; }
|
||||
[[nodiscard]] auto getTargetGroup() const -> ServiceMenu::SettingsGroup override { return target_group_; }
|
||||
[[nodiscard]] auto getBehavior() const -> Behavior override { return Behavior::SELECT; }
|
||||
[[nodiscard]] auto getTargetGroup() const -> ServiceMenu::SettingsGroup override { return target_group_; }
|
||||
|
||||
private:
|
||||
ServiceMenu::SettingsGroup target_group_;
|
||||
private:
|
||||
ServiceMenu::SettingsGroup target_group_;
|
||||
};
|
||||
|
||||
class ActionOption : public MenuOption {
|
||||
public:
|
||||
ActionOption(const std::string &cap, ServiceMenu::SettingsGroup grp, std::function<void()> action, bool hidden = false)
|
||||
: MenuOption(cap, grp, hidden), action_(std::move(action)) {}
|
||||
public:
|
||||
ActionOption(const std::string &cap, ServiceMenu::SettingsGroup grp, std::function<void()> action, bool hidden = false)
|
||||
: MenuOption(cap, grp, hidden), action_(std::move(action)) {}
|
||||
|
||||
[[nodiscard]] auto getBehavior() const -> Behavior override { return Behavior::SELECT; }
|
||||
void executeAction() override {
|
||||
if (action_) {
|
||||
action_();
|
||||
[[nodiscard]] auto getBehavior() const -> Behavior override { return Behavior::SELECT; }
|
||||
void executeAction() override {
|
||||
if (action_) {
|
||||
action_();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
std::function<void()> action_;
|
||||
private:
|
||||
std::function<void()> action_;
|
||||
};
|
||||
|
||||
@@ -12,98 +12,98 @@ class MenuOption;
|
||||
class MenuRenderer; // <-- Nuevo
|
||||
|
||||
class ServiceMenu {
|
||||
public:
|
||||
enum class SettingsGroup {
|
||||
VIDEO,
|
||||
AUDIO,
|
||||
SETTINGS,
|
||||
SYSTEM,
|
||||
MAIN
|
||||
};
|
||||
public:
|
||||
enum class SettingsGroup {
|
||||
VIDEO,
|
||||
AUDIO,
|
||||
SETTINGS,
|
||||
SYSTEM,
|
||||
MAIN
|
||||
};
|
||||
|
||||
enum class GroupAlignment {
|
||||
CENTERED,
|
||||
LEFT
|
||||
};
|
||||
enum class GroupAlignment {
|
||||
CENTERED,
|
||||
LEFT
|
||||
};
|
||||
|
||||
// --- Constantes públicas que el Renderer podría necesitar ---
|
||||
static constexpr size_t OPTIONS_HORIZONTAL_PADDING = 20;
|
||||
static constexpr size_t MIN_WIDTH = 240;
|
||||
static constexpr size_t MIN_GAP_OPTION_VALUE = 30;
|
||||
// --- Constantes públicas que el Renderer podría necesitar ---
|
||||
static constexpr size_t OPTIONS_HORIZONTAL_PADDING = 20;
|
||||
static constexpr size_t MIN_WIDTH = 240;
|
||||
static constexpr size_t MIN_GAP_OPTION_VALUE = 30;
|
||||
|
||||
// --- Métodos de singleton ---
|
||||
static void init();
|
||||
static void destroy();
|
||||
static auto get() -> ServiceMenu *;
|
||||
ServiceMenu(const ServiceMenu &) = delete;
|
||||
auto operator=(const ServiceMenu &) -> ServiceMenu & = delete;
|
||||
// --- Métodos de singleton ---
|
||||
static void init();
|
||||
static void destroy();
|
||||
static auto get() -> ServiceMenu *;
|
||||
ServiceMenu(const ServiceMenu &) = delete;
|
||||
auto operator=(const ServiceMenu &) -> ServiceMenu & = delete;
|
||||
|
||||
// --- Métodos principales ---
|
||||
void toggle();
|
||||
void render();
|
||||
void update();
|
||||
void reset();
|
||||
// --- Métodos principales ---
|
||||
void toggle();
|
||||
void render();
|
||||
void update();
|
||||
void reset();
|
||||
|
||||
// --- Lógica de navegación ---
|
||||
void setSelectorUp();
|
||||
void setSelectorDown();
|
||||
void adjustOption(bool adjust_up);
|
||||
void selectOption();
|
||||
void moveBack();
|
||||
// --- Lógica de navegación ---
|
||||
void setSelectorUp();
|
||||
void setSelectorDown();
|
||||
void adjustOption(bool adjust_up);
|
||||
void selectOption();
|
||||
void moveBack();
|
||||
|
||||
// --- Getters para que el Renderer pueda leer el estado ---
|
||||
[[nodiscard]] auto isEnabled() const -> bool { return enabled_; }
|
||||
[[nodiscard]] auto getTitle() const -> const std::string & { return title_; }
|
||||
[[nodiscard]] auto getCurrentGroup() const -> SettingsGroup { return current_settings_group_; }
|
||||
[[nodiscard]] auto getCurrentGroupAlignment() const -> GroupAlignment;
|
||||
[[nodiscard]] auto getDisplayOptions() const -> const std::vector<MenuOption *> & { return display_options_; }
|
||||
[[nodiscard]] auto getAllOptions() const -> const std::vector<std::unique_ptr<MenuOption>> & { return options_; }
|
||||
[[nodiscard]] auto getSelectedIndex() const -> size_t { return selected_; }
|
||||
[[nodiscard]] auto getOptionPairs() const -> const std::vector<std::pair<std::string, std::string>> & { return option_pairs_; }
|
||||
[[nodiscard]] auto countOptionsInGroup(SettingsGroup group) const -> size_t;
|
||||
// --- Getters para que el Renderer pueda leer el estado ---
|
||||
[[nodiscard]] auto isEnabled() const -> bool { return enabled_; }
|
||||
[[nodiscard]] auto getTitle() const -> const std::string & { return title_; }
|
||||
[[nodiscard]] auto getCurrentGroup() const -> SettingsGroup { return current_settings_group_; }
|
||||
[[nodiscard]] auto getCurrentGroupAlignment() const -> GroupAlignment;
|
||||
[[nodiscard]] auto getDisplayOptions() const -> const std::vector<MenuOption *> & { return display_options_; }
|
||||
[[nodiscard]] auto getAllOptions() const -> const std::vector<std::unique_ptr<MenuOption>> & { return options_; }
|
||||
[[nodiscard]] auto getSelectedIndex() const -> size_t { return selected_; }
|
||||
[[nodiscard]] auto getOptionPairs() const -> const std::vector<std::pair<std::string, std::string>> & { return option_pairs_; }
|
||||
[[nodiscard]] auto countOptionsInGroup(SettingsGroup group) const -> size_t;
|
||||
|
||||
private:
|
||||
// --- Lógica de estado del menú (Modelo) ---
|
||||
bool enabled_ = false;
|
||||
std::vector<std::unique_ptr<MenuOption>> options_;
|
||||
std::vector<MenuOption *> display_options_;
|
||||
std::vector<std::pair<std::string, std::string>> option_pairs_;
|
||||
private:
|
||||
// --- Lógica de estado del menú (Modelo) ---
|
||||
bool enabled_ = false;
|
||||
std::vector<std::unique_ptr<MenuOption>> options_;
|
||||
std::vector<MenuOption *> display_options_;
|
||||
std::vector<std::pair<std::string, std::string>> option_pairs_;
|
||||
|
||||
SettingsGroup current_settings_group_;
|
||||
SettingsGroup previous_settings_group_;
|
||||
std::string title_;
|
||||
size_t selected_ = 0;
|
||||
size_t main_menu_selected_ = 0;
|
||||
SettingsGroup current_settings_group_;
|
||||
SettingsGroup previous_settings_group_;
|
||||
std::string title_;
|
||||
size_t selected_ = 0;
|
||||
size_t main_menu_selected_ = 0;
|
||||
|
||||
// --- Mensaje de reinicio ---
|
||||
std::unique_ptr<UIMessage> restart_message_ui_;
|
||||
bool last_pending_changes_ = false;
|
||||
// --- Mensaje de reinicio ---
|
||||
std::unique_ptr<UIMessage> restart_message_ui_;
|
||||
bool last_pending_changes_ = false;
|
||||
|
||||
// --- La Vista ---
|
||||
std::unique_ptr<MenuRenderer> renderer_;
|
||||
// --- La Vista ---
|
||||
std::unique_ptr<MenuRenderer> renderer_;
|
||||
|
||||
// --- Métodos de lógica interna ---
|
||||
void updateDisplayOptions();
|
||||
void updateOptionPairs();
|
||||
void initializeOptions();
|
||||
void updateMenu();
|
||||
void applySettings();
|
||||
void applyVideoSettings();
|
||||
static void applyAudioSettings();
|
||||
void applySettingsSettings();
|
||||
[[nodiscard]] auto getOptionByCaption(const std::string &caption) const -> MenuOption *;
|
||||
void adjustListValues();
|
||||
static void playMoveSound();
|
||||
static void playAdjustSound();
|
||||
static void playSelectSound();
|
||||
static void playBackSound();
|
||||
[[nodiscard]] static auto settingsGroupToString(SettingsGroup group) -> std::string;
|
||||
void setHiddenOptions();
|
||||
// --- Métodos de lógica interna ---
|
||||
void updateDisplayOptions();
|
||||
void updateOptionPairs();
|
||||
void initializeOptions();
|
||||
void updateMenu();
|
||||
void applySettings();
|
||||
void applyVideoSettings();
|
||||
static void applyAudioSettings();
|
||||
void applySettingsSettings();
|
||||
[[nodiscard]] auto getOptionByCaption(const std::string &caption) const -> MenuOption *;
|
||||
void adjustListValues();
|
||||
static void playMoveSound();
|
||||
static void playAdjustSound();
|
||||
static void playSelectSound();
|
||||
static void playBackSound();
|
||||
[[nodiscard]] static auto settingsGroupToString(SettingsGroup group) -> std::string;
|
||||
void setHiddenOptions();
|
||||
|
||||
// --- Constructores y destructor privados (singleton) ---
|
||||
ServiceMenu();
|
||||
~ServiceMenu() = default;
|
||||
// --- Constructores y destructor privados (singleton) ---
|
||||
ServiceMenu();
|
||||
~ServiceMenu() = default;
|
||||
|
||||
// --- Instancia singleton ---
|
||||
static ServiceMenu *instance;
|
||||
// --- Instancia singleton ---
|
||||
static ServiceMenu *instance;
|
||||
};
|
||||
|
||||
@@ -15,7 +15,7 @@ void UIMessage::show() {
|
||||
return; // Ya está visible y quieto
|
||||
}
|
||||
|
||||
start_y_ = DESP; // Empieza 8 píxeles arriba de la posición base
|
||||
start_y_ = DESP; // Empieza 8 píxeles arriba de la posición base
|
||||
target_y_ = 0.0F; // La posición final es la base
|
||||
y_offset_ = start_y_;
|
||||
anim_step_ = 0;
|
||||
@@ -30,7 +30,7 @@ void UIMessage::hide() {
|
||||
}
|
||||
|
||||
start_y_ = y_offset_; // Comienza desde la posición actual
|
||||
target_y_ = DESP; // Termina 8 píxeles arriba de la base
|
||||
target_y_ = DESP; // Termina 8 píxeles arriba de la base
|
||||
anim_step_ = 0;
|
||||
animating_ = true;
|
||||
}
|
||||
|
||||
@@ -9,48 +9,48 @@ class Text;
|
||||
|
||||
// Clase para mostrar mensajes animados en la interfaz de usuario
|
||||
class UIMessage {
|
||||
public:
|
||||
// Constructor: recibe el renderizador de texto, el mensaje y el color
|
||||
UIMessage(std::shared_ptr<Text> text_renderer, std::string message_text, const Color &color);
|
||||
public:
|
||||
// Constructor: recibe el renderizador de texto, el mensaje y el color
|
||||
UIMessage(std::shared_ptr<Text> text_renderer, std::string message_text, const Color &color);
|
||||
|
||||
// Muestra el mensaje con animación de entrada
|
||||
void show();
|
||||
// Muestra el mensaje con animación de entrada
|
||||
void show();
|
||||
|
||||
// Oculta el mensaje con animación de salida
|
||||
void hide();
|
||||
// Oculta el mensaje con animación de salida
|
||||
void hide();
|
||||
|
||||
// Actualiza el estado de la animación (debe llamarse cada frame)
|
||||
void update();
|
||||
// Actualiza el estado de la animación (debe llamarse cada frame)
|
||||
void update();
|
||||
|
||||
// Dibuja el mensaje en pantalla si está visible
|
||||
void render();
|
||||
// Dibuja el mensaje en pantalla si está visible
|
||||
void render();
|
||||
|
||||
// Indica si el mensaje está visible actualmente
|
||||
[[nodiscard]] auto isVisible() const -> bool;
|
||||
// Indica si el mensaje está visible actualmente
|
||||
[[nodiscard]] auto isVisible() const -> bool;
|
||||
|
||||
// Permite actualizar la posición del mensaje (por ejemplo, si el menú se mueve)
|
||||
void setPosition(float new_base_x, float new_base_y);
|
||||
// Permite actualizar la posición del mensaje (por ejemplo, si el menú se mueve)
|
||||
void setPosition(float new_base_x, float new_base_y);
|
||||
|
||||
private:
|
||||
// --- Configuración ---
|
||||
std::shared_ptr<Text> text_renderer_; // Renderizador de texto
|
||||
std::string text_; // Texto del mensaje a mostrar
|
||||
Color color_; // Color del texto
|
||||
private:
|
||||
// --- Configuración ---
|
||||
std::shared_ptr<Text> text_renderer_; // Renderizador de texto
|
||||
std::string text_; // Texto del mensaje a mostrar
|
||||
Color color_; // Color del texto
|
||||
|
||||
// --- Estado ---
|
||||
bool visible_ = false; // Indica si el mensaje está visible
|
||||
bool animating_ = false; // Indica si el mensaje está en proceso de animación
|
||||
float base_x_ = 0.0F; // Posición X base donde se muestra el mensaje
|
||||
float base_y_ = 0.0F; // Posición Y base donde se muestra el mensaje
|
||||
float y_offset_ = 0.0F; // Desplazamiento vertical actual del mensaje (para animación)
|
||||
// --- Estado ---
|
||||
bool visible_ = false; // Indica si el mensaje está visible
|
||||
bool animating_ = false; // Indica si el mensaje está en proceso de animación
|
||||
float base_x_ = 0.0F; // Posición X base donde se muestra el mensaje
|
||||
float base_y_ = 0.0F; // Posición Y base donde se muestra el mensaje
|
||||
float y_offset_ = 0.0F; // Desplazamiento vertical actual del mensaje (para animación)
|
||||
|
||||
// --- Animación ---
|
||||
float start_y_ = 0.0F; // Posición Y inicial de la animación
|
||||
float target_y_ = 0.0F; // Posición Y objetivo de la animación
|
||||
int anim_step_ = 0; // Paso actual de la animación
|
||||
static constexpr int ANIMATION_STEPS = 8; // Número total de pasos de la animación
|
||||
static constexpr float DESP = -8.0F; // Distancia a desplazarse
|
||||
// --- Animación ---
|
||||
float start_y_ = 0.0F; // Posición Y inicial de la animación
|
||||
float target_y_ = 0.0F; // Posición Y objetivo de la animación
|
||||
int anim_step_ = 0; // Paso actual de la animación
|
||||
static constexpr int ANIMATION_STEPS = 8; // Número total de pasos de la animación
|
||||
static constexpr float DESP = -8.0F; // Distancia a desplazarse
|
||||
|
||||
// Actualiza la interpolación de la animación (ease out/in cubic)
|
||||
void updateAnimation();
|
||||
// Actualiza la interpolación de la animación (ease out/in cubic)
|
||||
void updateAnimation();
|
||||
};
|
||||
@@ -8,51 +8,51 @@ class Text;
|
||||
|
||||
// Clase Writer. Pinta texto en pantalla letra a letra a partir de una cadena y un objeto Text
|
||||
class Writer {
|
||||
public:
|
||||
// Constructor
|
||||
explicit Writer(std::shared_ptr<Text> text)
|
||||
: text_(std::move(text)) {}
|
||||
public:
|
||||
// Constructor
|
||||
explicit Writer(std::shared_ptr<Text> text)
|
||||
: text_(std::move(text)) {}
|
||||
|
||||
// Destructor
|
||||
~Writer() = default;
|
||||
// Destructor
|
||||
~Writer() = default;
|
||||
|
||||
// Actualiza el objeto
|
||||
void update();
|
||||
// Actualiza el objeto
|
||||
void update();
|
||||
|
||||
// Dibuja el objeto en pantalla
|
||||
void render() const;
|
||||
// Dibuja el objeto en pantalla
|
||||
void render() const;
|
||||
|
||||
// Setters
|
||||
void setPosX(int value); // Establece la posición X
|
||||
void setPosY(int value); // Establece la posición Y
|
||||
void setKerning(int value); // Establece el kerning (espaciado entre caracteres)
|
||||
void setCaption(const std::string &text); // Establece el texto a escribir
|
||||
void setSpeed(int value); // Establece la velocidad de escritura
|
||||
void setEnabled(bool value); // Habilita o deshabilita el objeto
|
||||
void setFinishedCounter(int time); // Establece el temporizador para deshabilitar el objeto
|
||||
// Setters
|
||||
void setPosX(int value); // Establece la posición X
|
||||
void setPosY(int value); // Establece la posición Y
|
||||
void setKerning(int value); // Establece el kerning (espaciado entre caracteres)
|
||||
void setCaption(const std::string &text); // Establece el texto a escribir
|
||||
void setSpeed(int value); // Establece la velocidad de escritura
|
||||
void setEnabled(bool value); // Habilita o deshabilita el objeto
|
||||
void setFinishedCounter(int time); // Establece el temporizador para deshabilitar el objeto
|
||||
|
||||
// Centra la cadena de texto a un punto X
|
||||
void center(int x);
|
||||
// Centra la cadena de texto a un punto X
|
||||
void center(int x);
|
||||
|
||||
// Getters
|
||||
[[nodiscard]] auto isEnabled() const -> bool; // Indica si el objeto está habilitado
|
||||
[[nodiscard]] auto hasFinished() const -> bool; // Indica si ya ha terminado
|
||||
// Getters
|
||||
[[nodiscard]] auto isEnabled() const -> bool; // Indica si el objeto está habilitado
|
||||
[[nodiscard]] auto hasFinished() const -> bool; // Indica si ya ha terminado
|
||||
|
||||
private:
|
||||
// --- Objetos y punteros ---
|
||||
std::shared_ptr<Text> text_; // Objeto encargado de escribir el texto
|
||||
private:
|
||||
// --- Objetos y punteros ---
|
||||
std::shared_ptr<Text> text_; // Objeto encargado de escribir el texto
|
||||
|
||||
// --- Variables de estado ---
|
||||
int pos_x_ = 0; // Posición en el eje X donde empezar a escribir el texto
|
||||
int pos_y_ = 0; // Posición en el eje Y donde empezar a escribir el texto
|
||||
int kerning_ = 0; // Kerning del texto, es decir, espaciado entre caracteres
|
||||
std::string caption_; // El texto para escribir
|
||||
int speed_ = 0; // Velocidad de escritura
|
||||
int writing_counter_ = 0; // Temporizador de escritura para cada caracter
|
||||
int index_ = 0; // Posición del texto que se está escribiendo
|
||||
int lenght_ = 0; // Longitud de la cadena a escribir
|
||||
bool completed_ = false; // Indica si se ha escrito todo el texto
|
||||
bool enabled_ = false; // Indica si el objeto está habilitado
|
||||
int enabled_counter_ = 0; // Temporizador para deshabilitar el objeto
|
||||
bool finished_ = false; // Indica si ya ha terminado
|
||||
// --- Variables de estado ---
|
||||
int pos_x_ = 0; // Posición en el eje X donde empezar a escribir el texto
|
||||
int pos_y_ = 0; // Posición en el eje Y donde empezar a escribir el texto
|
||||
int kerning_ = 0; // Kerning del texto, es decir, espaciado entre caracteres
|
||||
std::string caption_; // El texto para escribir
|
||||
int speed_ = 0; // Velocidad de escritura
|
||||
int writing_counter_ = 0; // Temporizador de escritura para cada caracter
|
||||
int index_ = 0; // Posición del texto que se está escribiendo
|
||||
int lenght_ = 0; // Longitud de la cadena a escribir
|
||||
bool completed_ = false; // Indica si se ha escrito todo el texto
|
||||
bool enabled_ = false; // Indica si el objeto está habilitado
|
||||
int enabled_counter_ = 0; // Temporizador para deshabilitar el objeto
|
||||
bool finished_ = false; // Indica si ya ha terminado
|
||||
};
|
||||
Reference in New Issue
Block a user