revisió de capçaleres
This commit is contained in:
@@ -1,18 +1,22 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
#include <SDL3/SDL_rect.h> // Para SDL_FRect
|
#include <SDL3/SDL_rect.h>
|
||||||
#include <memory> // Para shared_ptr
|
#include <memory>
|
||||||
#include <string> // Para string
|
#include <string>
|
||||||
#include <vector> // Para vector
|
#include <vector>
|
||||||
#include "moving_sprite.h" // Para MovingSprite
|
|
||||||
|
#include "moving_sprite.h"
|
||||||
|
|
||||||
|
// Declaraciones adelantadas
|
||||||
class Texture;
|
class Texture;
|
||||||
|
|
||||||
|
// === Estructura de Animación ===
|
||||||
struct Animation
|
struct Animation
|
||||||
{
|
{
|
||||||
std::string name; // Nombre de la animación
|
std::string name; // Nombre de la animación
|
||||||
std::vector<SDL_FRect> frames; // Frames que componen la animación
|
std::vector<SDL_FRect> frames; // Frames que componen la animación
|
||||||
int speed; // Velocidad de reproducción
|
int speed; // Velocidad de reproducción
|
||||||
int loop; // Frame al que vuelve la animación al terminar (-1 para no repetir)
|
int loop; // Frame de vuelta al terminar (-1 para no repetir)
|
||||||
bool completed; // Indica si la animación ha finalizado
|
bool completed; // Indica si la animación ha finalizado
|
||||||
int current_frame; // Frame actual en reproducción
|
int current_frame; // Frame actual en reproducción
|
||||||
int counter; // Contador para la animación
|
int counter; // Contador para la animación
|
||||||
@@ -20,39 +24,41 @@ struct Animation
|
|||||||
Animation() : name(std::string()), speed(5), loop(0), completed(false), current_frame(0), counter(0) {}
|
Animation() : name(std::string()), speed(5), loop(0), completed(false), current_frame(0), counter(0) {}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// === Alias de Tipos ===
|
||||||
using AnimationsFileBuffer = std::vector<std::string>;
|
using AnimationsFileBuffer = std::vector<std::string>;
|
||||||
|
|
||||||
|
// === Funciones Globales ===
|
||||||
// Carga las animaciones desde un fichero en un vector
|
// Carga las animaciones desde un fichero en un vector
|
||||||
AnimationsFileBuffer loadAnimationsFromFile(const std::string &file_path);
|
AnimationsFileBuffer loadAnimationsFromFile(const std::string &file_path);
|
||||||
|
|
||||||
class AnimatedSprite : public MovingSprite
|
class AnimatedSprite : public MovingSprite
|
||||||
{
|
{
|
||||||
public:
|
public:
|
||||||
// Constructor
|
// Constructores
|
||||||
AnimatedSprite(std::shared_ptr<Texture> texture, const std::string &file_path);
|
AnimatedSprite(std::shared_ptr<Texture> texture, const std::string &file_path);
|
||||||
AnimatedSprite(std::shared_ptr<Texture> texture, const AnimationsFileBuffer &animations);
|
AnimatedSprite(std::shared_ptr<Texture> texture, const AnimationsFileBuffer &animations);
|
||||||
explicit AnimatedSprite(std::shared_ptr<Texture> texture)
|
explicit AnimatedSprite(std::shared_ptr<Texture> texture) : MovingSprite(texture) {}
|
||||||
: MovingSprite(texture) {}
|
|
||||||
|
|
||||||
// Destructor
|
|
||||||
virtual ~AnimatedSprite() override = default;
|
virtual ~AnimatedSprite() override = default;
|
||||||
|
|
||||||
// Actualización del objeto
|
// === Actualización ===
|
||||||
void update() override; // Actualiza la animación
|
void update() override; // Actualiza la animación
|
||||||
bool animationIsCompleted(); // Comprueba si la animación ha terminado
|
|
||||||
int getIndex(const std::string &name); // Obtiene el índice de una animación según su nombre
|
|
||||||
|
|
||||||
// Manipulación de animaciones
|
// === Control de Animaciones ===
|
||||||
void setCurrentAnimation(const std::string &name = "default"); // Establece animación por nombre
|
void setCurrentAnimation(const std::string &name = "default"); // Establecer por nombre
|
||||||
void setCurrentAnimation(int index = 0); // Establece animación por índice
|
void setCurrentAnimation(int index = 0); // Establecer por índice
|
||||||
void resetAnimation(); // Reinicia la animación
|
void resetAnimation(); // Reiniciar la animación
|
||||||
|
|
||||||
|
// === Consultas ===
|
||||||
|
bool animationIsCompleted(); // Comprobar si ha terminado
|
||||||
|
int getIndex(const std::string &name); // Obtener índice por nombre
|
||||||
|
|
||||||
protected:
|
protected:
|
||||||
// Almacenamiento de animaciones
|
// === Datos de Animación ===
|
||||||
std::vector<Animation> animations_; // Vector de animaciones disponibles
|
std::vector<Animation> animations_; // Vector de animaciones disponibles
|
||||||
int current_animation_ = 0; // Índice de la animación activa
|
int current_animation_ = 0; // Índice de la animación activa
|
||||||
|
|
||||||
// Procesos internos
|
// === Métodos Internos ===
|
||||||
void animate(); // Calcula el frame actual de la animación
|
void animate(); // Calcular el frame actual de la animación
|
||||||
void loadFromAnimationsFileBuffer(const AnimationsFileBuffer &source); // Carga animaciones desde un buffer
|
void loadFromAnimationsFileBuffer(const AnimationsFileBuffer &source); // Cargar desde buffer
|
||||||
};
|
};
|
||||||
@@ -1,9 +1,11 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
#include <string> // Para manejar cadenas de texto
|
#include <string>
|
||||||
#include <vector> // Para estructuras dinámicas de datos
|
#include <vector>
|
||||||
#include "utils.h" // Para la función getPath
|
|
||||||
|
|
||||||
|
#include "utils.h"
|
||||||
|
|
||||||
|
// === Enumeraciones ===
|
||||||
enum class AssetType : int
|
enum class AssetType : int
|
||||||
{
|
{
|
||||||
BITMAP,
|
BITMAP,
|
||||||
@@ -18,57 +20,52 @@ enum class AssetType : int
|
|||||||
MAX_ASSET_TYPE,
|
MAX_ASSET_TYPE,
|
||||||
};
|
};
|
||||||
|
|
||||||
// Clase Asset
|
|
||||||
class Asset
|
class Asset
|
||||||
{
|
{
|
||||||
public:
|
public:
|
||||||
// Obtención de la instancia única (*Meyers Singleton*)
|
// === Singleton ===
|
||||||
static Asset &get()
|
static Asset &get() // Obtención de la instancia única (Meyers Singleton)
|
||||||
{
|
{
|
||||||
static Asset instance;
|
static Asset instance;
|
||||||
return instance;
|
return instance;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// === Inicialización ===
|
||||||
void init(const std::string &executable_path)
|
void init(const std::string &executable_path)
|
||||||
{
|
{
|
||||||
executable_path_ = getPath(executable_path);
|
executable_path_ = getPath(executable_path);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Manejo de archivos
|
// === Gestión de Recursos ===
|
||||||
void add(const std::string &file, AssetType type, bool required = true, bool absolute = false); // Añade un recurso
|
void add(const std::string &file, AssetType type, bool required = true, bool absolute = false); // Añadir recurso
|
||||||
std::string get(const std::string &text) const; // Devuelve la ruta completa de un recurso
|
std::string get(const std::string &text) const; // Obtener ruta completa
|
||||||
bool check() const; // Verifica la existencia de todos los elementos
|
bool check() const; // Verificar existencia
|
||||||
std::vector<std::string> getListByType(AssetType type) const; // Obtiene lista de recursos de un tipo específico
|
std::vector<std::string> getListByType(AssetType type) const; // Lista por tipo
|
||||||
|
|
||||||
private:
|
private:
|
||||||
// Estructura para definir un recurso
|
// === Estructura Interna ===
|
||||||
struct AssetItem
|
struct AssetItem
|
||||||
{
|
{
|
||||||
std::string file; // Ruta del fichero desde la raíz del directorio
|
std::string file; // Ruta del fichero desde la raíz del directorio
|
||||||
AssetType type; // Tipo de recurso
|
AssetType type; // Tipo de recurso
|
||||||
bool required; // Indica si el fichero es obligatorio
|
bool required; // Indica si el fichero es obligatorio
|
||||||
|
|
||||||
// Constructor
|
|
||||||
AssetItem(const std::string &filePath, AssetType assetType, bool isRequired)
|
AssetItem(const std::string &filePath, AssetType assetType, bool isRequired)
|
||||||
: file(filePath), type(assetType), required(isRequired) {}
|
: file(filePath), type(assetType), required(isRequired) {}
|
||||||
};
|
};
|
||||||
|
|
||||||
// Variables internas
|
// === Variables Internas ===
|
||||||
int longest_name_ = 0; // Longitud del nombre de archivo más largo
|
int longest_name_ = 0; // Longitud del nombre más largo
|
||||||
std::vector<AssetItem> file_list_; // Lista con todas las rutas de los archivos
|
std::vector<AssetItem> file_list_; // Lista con todas las rutas
|
||||||
std::string executable_path_; // Ruta del ejecutable
|
std::string executable_path_; // Ruta del ejecutable
|
||||||
|
|
||||||
// Métodos internos
|
// === Métodos Internos ===
|
||||||
bool checkFile(const std::string &path) const; // Verifica si un archivo existe
|
bool checkFile(const std::string &path) const; // Verificar si archivo existe
|
||||||
std::string getTypeName(AssetType type) const; // Obtiene el nombre textual del tipo de recurso
|
std::string getTypeName(AssetType type) const; // Obtener nombre textual del tipo
|
||||||
|
|
||||||
// Constructor privado
|
// === Patrón Singleton ===
|
||||||
Asset() = default;
|
Asset() = default; // Constructor privado
|
||||||
|
~Asset() = default; // Destructor privado
|
||||||
// Destructor privado
|
Asset(const Asset &) = delete; // Evitar copia
|
||||||
~Asset() = default;
|
Asset &operator=(const Asset &) = delete; // Evitar asignación
|
||||||
|
};
|
||||||
// Evita copia y asignación
|
|
||||||
Asset(const Asset &) = delete;
|
|
||||||
Asset &operator=(const Asset &) = delete;
|
|
||||||
};
|
|
||||||
@@ -1,61 +1,60 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
#include <string>
|
#include <string>
|
||||||
|
|
||||||
#include "audio.h"
|
#include "audio.h"
|
||||||
|
|
||||||
class Audio
|
class Audio
|
||||||
{
|
{
|
||||||
public:
|
public:
|
||||||
// Obtención de la instancia única (*Meyers Singleton*)
|
// === Singleton ===
|
||||||
static Audio &get()
|
static Audio &get() // Obtención de la instancia única (Meyers Singleton)
|
||||||
{
|
{
|
||||||
static Audio instance;
|
static Audio instance;
|
||||||
return instance;
|
return instance;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Manejo de reproducción de música
|
// === Control de Música ===
|
||||||
void playMusic(const std::string &name, int loop = -1); // Reproduce música en bucle
|
void playMusic(const std::string &name, int loop = -1); // Reproducir en bucle
|
||||||
void pauseMusic(); // Pausa la reproducción de música
|
void pauseMusic(); // Pausar reproducción
|
||||||
void stopMusic(); // Detiene la música completamente
|
void stopMusic(); // Detener completamente
|
||||||
void fadeOutMusic(int milliseconds); // Fundido de salida de la música
|
void fadeOutMusic(int milliseconds); // Fundido de salida
|
||||||
|
|
||||||
// Manejo de efectos de sonido
|
// === Control de Sonidos ===
|
||||||
void playSound(const std::string &name); // Reproduce un sonido puntual
|
void playSound(const std::string &name); // Reproducir sonido puntual
|
||||||
void stopAllSounds(); // Detiene todos los sonidos activos
|
void stopAllSounds(); // Detener todos los sonidos
|
||||||
|
|
||||||
// Configuración de audio general
|
// === Configuración General ===
|
||||||
void enable() { enabled_ = true; } // Habilita el audio
|
void enable() { enabled_ = true; } // Habilitar audio
|
||||||
void disable() { enabled_ = false; } // Deshabilita el audio
|
void disable() { enabled_ = false; } // Deshabilitar audio
|
||||||
void enable(bool value) { enabled_ = value; } // Establece estado del audio
|
void enable(bool value) { enabled_ = value; } // Establecer estado
|
||||||
void toggleEnabled() { enabled_ = !enabled_; } // Alterna estado del audio
|
void toggleEnabled() { enabled_ = !enabled_; } // Alternar estado
|
||||||
|
|
||||||
// Configuración de sonido
|
// === Configuración de Sonidos ===
|
||||||
void enableSound() { sound_enabled_ = true; } // Habilita los sonidos
|
void enableSound() { sound_enabled_ = true; } // Habilitar sonidos
|
||||||
void disableSound() { sound_enabled_ = false; } // Deshabilita los sonidos
|
void disableSound() { sound_enabled_ = false; } // Deshabilitar sonidos
|
||||||
void enableSound(bool value) { sound_enabled_ = value; } // Establece estado de sonidos
|
void enableSound(bool value) { sound_enabled_ = value; } // Establecer estado
|
||||||
void toggleSound() { sound_enabled_ = !sound_enabled_; } // Alterna estado de sonidos
|
void toggleSound() { sound_enabled_ = !sound_enabled_; } // Alternar estado
|
||||||
|
|
||||||
// Configuración de música
|
// === Configuración de Música ===
|
||||||
void enableMusic() { music_enabled_ = true; } // Habilita la música
|
void enableMusic() { music_enabled_ = true; } // Habilitar música
|
||||||
void disableMusic() { music_enabled_ = false; } // Deshabilita la música
|
void disableMusic() { music_enabled_ = false; } // Deshabilitar música
|
||||||
void enableMusic(bool value) { music_enabled_ = value; } // Establece estado de música
|
void enableMusic(bool value) { music_enabled_ = value; } // Establecer estado
|
||||||
void toggleMusic() { music_enabled_ = !music_enabled_; } // Alterna estado de música
|
void toggleMusic() { music_enabled_ = !music_enabled_; } // Alternar estado
|
||||||
|
|
||||||
// Control de volumen
|
// === Control de Volumen ===
|
||||||
void setSoundVolume(int volume); // Ajusta volumen de efectos de sonido
|
void setSoundVolume(int volume); // Ajustar volumen de efectos
|
||||||
void setMusicVolume(int volume); // Ajusta volumen de música
|
void setMusicVolume(int volume); // Ajustar volumen de música
|
||||||
|
|
||||||
private:
|
private:
|
||||||
// Variables internas
|
// === Variables de Estado ===
|
||||||
bool enabled_ = true; // Estado general del audio
|
bool enabled_ = true; // Estado general del audio
|
||||||
bool sound_enabled_ = true; // Estado de los efectos de sonido
|
bool sound_enabled_ = true; // Estado de los efectos de sonido
|
||||||
bool music_enabled_ = true; // Estado de la música
|
bool music_enabled_ = true; // Estado de la música
|
||||||
|
|
||||||
// Constructor privado (Meyers Singleton)
|
// === Patrón Singleton ===
|
||||||
Audio();
|
Audio(); // Constructor privado
|
||||||
~Audio();
|
~Audio(); // Destructor privado
|
||||||
|
Audio(const Audio &) = delete; // Evitar copia
|
||||||
// Prevención de copia y asignación
|
Audio &operator=(const Audio &) = delete; // Evitar asignación
|
||||||
Audio(const Audio &) = delete;
|
};
|
||||||
Audio &operator=(const Audio &) = delete;
|
|
||||||
};
|
|
||||||
215
source/balloon.h
215
source/balloon.h
@@ -7,19 +7,18 @@
|
|||||||
#include <vector> // Para vector
|
#include <vector> // Para vector
|
||||||
#include "animated_sprite.h" // Para AnimatedSprite
|
#include "animated_sprite.h" // Para AnimatedSprite
|
||||||
#include "utils.h" // Para Circle
|
#include "utils.h" // Para Circle
|
||||||
class Texture; // lines 9-9
|
|
||||||
|
|
||||||
// Cantidad de elementos del vector con los valores de la deformación del globo al rebotar
|
class Texture;
|
||||||
constexpr int MAX_BOUNCE = 10;
|
|
||||||
|
// --- Constantes relacionadas con globos ---
|
||||||
|
constexpr int MAX_BOUNCE = 10; // Cantidad de elementos del vector de deformación
|
||||||
|
|
||||||
// Puntos de globo
|
|
||||||
constexpr int BALLOON_SCORE[] = {50, 100, 200, 400};
|
constexpr int BALLOON_SCORE[] = {50, 100, 200, 400};
|
||||||
constexpr int BALLOON_POWER[] = {1, 3, 7, 15};
|
constexpr int BALLOON_POWER[] = {1, 3, 7, 15};
|
||||||
constexpr int BALLOON_MENACE[] = {1, 2, 4, 8};
|
constexpr int BALLOON_MENACE[] = {1, 2, 4, 8};
|
||||||
constexpr int BALLOON_SIZE[] = {10, 16, 26, 48, 49};
|
constexpr int BALLOON_SIZE[] = {10, 16, 26, 48, 49};
|
||||||
const std::string BALLOON_SOUND[] = {"bubble1.wav", "bubble2.wav", "bubble3.wav", "bubble4.wav"};
|
const std::string BALLOON_SOUND[] = {"bubble1.wav", "bubble2.wav", "bubble3.wav", "bubble4.wav"};
|
||||||
|
|
||||||
// Tamaños de globo
|
|
||||||
enum class BalloonSize : Uint8
|
enum class BalloonSize : Uint8
|
||||||
{
|
{
|
||||||
SIZE1 = 0,
|
SIZE1 = 0,
|
||||||
@@ -28,7 +27,6 @@ enum class BalloonSize : Uint8
|
|||||||
SIZE4 = 3,
|
SIZE4 = 3,
|
||||||
};
|
};
|
||||||
|
|
||||||
// Clases de globo
|
|
||||||
enum class BalloonType : Uint8
|
enum class BalloonType : Uint8
|
||||||
{
|
{
|
||||||
BALLOON = 0,
|
BALLOON = 0,
|
||||||
@@ -36,116 +34,23 @@ enum class BalloonType : Uint8
|
|||||||
POWERBALL = 2,
|
POWERBALL = 2,
|
||||||
};
|
};
|
||||||
|
|
||||||
// Velocidad del globo
|
|
||||||
constexpr float BALLOON_VELX_POSITIVE = 0.7f;
|
constexpr float BALLOON_VELX_POSITIVE = 0.7f;
|
||||||
constexpr float BALLOON_VELX_NEGATIVE = -0.7f;
|
constexpr float BALLOON_VELX_NEGATIVE = -0.7f;
|
||||||
|
|
||||||
// Indice para las animaciones de los globos
|
|
||||||
constexpr int BALLOON_MOVING_ANIMATION = 0;
|
constexpr int BALLOON_MOVING_ANIMATION = 0;
|
||||||
constexpr int BALLOON_POP_ANIMATION = 1;
|
constexpr int BALLOON_POP_ANIMATION = 1;
|
||||||
constexpr int BALLOON_BORN_ANIMATION = 2;
|
constexpr int BALLOON_BORN_ANIMATION = 2;
|
||||||
|
|
||||||
// Velocidades a las que se mueven los globos
|
|
||||||
constexpr float BALLOON_SPEED[] = {0.60f, 0.70f, 0.80f, 0.90f, 1.00f};
|
constexpr float BALLOON_SPEED[] = {0.60f, 0.70f, 0.80f, 0.90f, 1.00f};
|
||||||
|
|
||||||
// PowerBall
|
|
||||||
constexpr int POWERBALL_SCREENPOWER_MINIMUM = 10;
|
constexpr int POWERBALL_SCREENPOWER_MINIMUM = 10;
|
||||||
constexpr int POWERBALL_COUNTER = 8;
|
constexpr int POWERBALL_COUNTER = 8;
|
||||||
|
|
||||||
// Clase Balloon
|
// --- Clase Balloon ---
|
||||||
class Balloon
|
class Balloon
|
||||||
{
|
{
|
||||||
private:
|
|
||||||
// Estructura para el efecto de los rebotes en los globos
|
|
||||||
struct Bouncing
|
|
||||||
{
|
|
||||||
bool enabled = false; // Si el efecto está activo
|
|
||||||
Uint8 counter = 0; // Contador para el efecto
|
|
||||||
Uint8 speed = 2; // Velocidad a la que transcurre el efecto
|
|
||||||
float zoomW = 1.0f; // Zoom aplicado a la anchura
|
|
||||||
float zoomH = 1.0f; // Zoom aplicado a la altura
|
|
||||||
float despX = 0.0f; // Desplazamiento de pixeles en el eje X antes de pintar el objeto con zoom
|
|
||||||
float despY = 0.0f; // Desplazamiento de pixeles en el eje Y antes de pintar el objeto con zoom
|
|
||||||
|
|
||||||
float w[MAX_BOUNCE] = {1.10f, 1.05f, 1.00f, 0.95f, 0.90f, 0.95f, 1.00f, 1.02f, 1.05f, 1.02f}; // Vector con los valores de zoom para el ancho del globo
|
|
||||||
float h[MAX_BOUNCE] = {0.90f, 0.95f, 1.00f, 1.05f, 1.10f, 1.05f, 1.00f, 0.98f, 0.95f, 0.98f}; // Vector con los valores de zoom para el alto del globo
|
|
||||||
|
|
||||||
// Constructor por defecto
|
|
||||||
Bouncing() = default;
|
|
||||||
|
|
||||||
// Método reset
|
|
||||||
void reset()
|
|
||||||
{
|
|
||||||
counter = 0;
|
|
||||||
zoomW = 1.0f;
|
|
||||||
zoomH = 1.0f;
|
|
||||||
despX = 0.0f;
|
|
||||||
despY = 0.0f;
|
|
||||||
}
|
|
||||||
} bouncing_;
|
|
||||||
|
|
||||||
// Objetos y punteros
|
|
||||||
std::unique_ptr<AnimatedSprite> sprite_; // Sprite del objeto globo
|
|
||||||
|
|
||||||
// Variables
|
|
||||||
float x_; // Posición en el eje X
|
|
||||||
float y_; // Posición en el eje Y
|
|
||||||
float w_; // Ancho
|
|
||||||
float h_; // Alto
|
|
||||||
float vx_; // Velocidad en el eje X. Cantidad de pixeles a desplazarse
|
|
||||||
float vy_; // Velocidad en el eje Y. Cantidad de pixeles a desplazarse
|
|
||||||
float gravity_; // Aceleración en el eje Y. Modifica la velocidad
|
|
||||||
float default_vy_; // Velocidad inicial que tienen al rebotar contra el suelo
|
|
||||||
float max_vy_; // Máxima velocidad que puede alcanzar el objeto en el eje Y
|
|
||||||
bool being_created_; // Indica si el globo se está creando
|
|
||||||
bool enabled_ = true; // Indica si el globo esta activo
|
|
||||||
bool invulnerable_; // Indica si el globo es invulnerable
|
|
||||||
bool stopped_; // Indica si el globo está parado
|
|
||||||
bool use_reversed_colors_ = false; // Indica si se ha de usar el color secundario del globo como color principal
|
|
||||||
Circle collider_; // Circulo de colisión del objeto
|
|
||||||
Uint16 creation_counter_; // Temporizador para controlar el estado "creandose"
|
|
||||||
Uint16 creation_counter_ini_; // Valor inicial para el temporizador para controlar el estado "creandose"
|
|
||||||
Uint16 score_; // Puntos que da el globo al ser destruido
|
|
||||||
BalloonType type_; // Clase de globo
|
|
||||||
BalloonSize size_; // Tamaño del globo
|
|
||||||
Uint8 menace_; // Cantidad de amenaza que genera el globo
|
|
||||||
Uint32 counter_ = 0; // Contador interno
|
|
||||||
float travel_y_ = 1.0f; // Distancia que ha de recorrer el globo en el eje Y antes de que se le aplique la gravedad
|
|
||||||
float speed_; // Velocidad a la que se mueven los globos
|
|
||||||
Uint8 power_; // Cantidad de poder que alberga el globo
|
|
||||||
SDL_FRect play_area_; // Zona por donde se puede mover el globo
|
|
||||||
std::string sound_; // Archivo de sonido que hace el globo al rebotar
|
|
||||||
bool sound_enabled_ = false; // Indica si ha de sonar el sonido del globo al rebotar
|
|
||||||
|
|
||||||
// Alinea el circulo de colisión con la posición del objeto globo
|
|
||||||
void shiftColliders();
|
|
||||||
|
|
||||||
// Alinea el sprite con la posición del objeto globo
|
|
||||||
void shiftSprite();
|
|
||||||
|
|
||||||
// Establece el nivel de zoom del sprite
|
|
||||||
void zoomSprite();
|
|
||||||
|
|
||||||
// Activa el efecto
|
|
||||||
void enableBounce();
|
|
||||||
|
|
||||||
// Detiene el efecto
|
|
||||||
void disableBounce();
|
|
||||||
|
|
||||||
// Aplica el efecto
|
|
||||||
void updateBounce();
|
|
||||||
|
|
||||||
// Actualiza los estados del globo
|
|
||||||
void updateState();
|
|
||||||
|
|
||||||
// Establece la animación correspondiente
|
|
||||||
void setAnimation();
|
|
||||||
|
|
||||||
// Reproduce el sonido al rebotar
|
|
||||||
void playSound();
|
|
||||||
|
|
||||||
public:
|
public:
|
||||||
// Constructor
|
// --- Constructores y destructor ---
|
||||||
Balloon(
|
Balloon(
|
||||||
float x,
|
float x,
|
||||||
float y,
|
float y,
|
||||||
@@ -157,35 +62,21 @@ public:
|
|||||||
SDL_FRect play_area,
|
SDL_FRect play_area,
|
||||||
std::shared_ptr<Texture> texture,
|
std::shared_ptr<Texture> texture,
|
||||||
const std::vector<std::string> &animation);
|
const std::vector<std::string> &animation);
|
||||||
|
|
||||||
// Destructor
|
|
||||||
~Balloon() = default;
|
~Balloon() = default;
|
||||||
|
|
||||||
// Centra el globo en la posición X
|
// --- Métodos principales ---
|
||||||
void alignTo(int x);
|
void alignTo(int x); // Centra el globo en la posición X
|
||||||
|
void render(); // Pinta el globo en la pantalla
|
||||||
|
void move(); // Actualiza la posición y estados del globo
|
||||||
|
void update(); // Actualiza el globo (posición, animación, contadores)
|
||||||
|
void stop(); // Detiene el globo
|
||||||
|
void start(); // Pone el globo en movimiento
|
||||||
|
|
||||||
// Pinta el globo en la pantalla
|
// --- Métodos de color ---
|
||||||
void render();
|
void useReverseColor(); // Pone el color alternativo en el globo
|
||||||
|
void useNormalColor(); // Pone el color normal en el globo
|
||||||
|
|
||||||
// Actualiza la posición y estados del globo
|
// --- Getters ---
|
||||||
void move();
|
|
||||||
|
|
||||||
// Actualiza al globo a su posicion, animación y controla los contadores
|
|
||||||
void update();
|
|
||||||
|
|
||||||
// Detiene el globo
|
|
||||||
void stop();
|
|
||||||
|
|
||||||
// Pone el globo en movimiento
|
|
||||||
void start();
|
|
||||||
|
|
||||||
// Pone el color alternativo en el globo
|
|
||||||
void useReverseColor();
|
|
||||||
|
|
||||||
// Pone el color normal en el globo
|
|
||||||
void useNormalColor();
|
|
||||||
|
|
||||||
// Getters
|
|
||||||
float getPosX() const { return x_; }
|
float getPosX() const { return x_; }
|
||||||
float getPosY() const { return y_; }
|
float getPosY() const { return y_; }
|
||||||
int getWidth() const { return w_; }
|
int getWidth() const { return w_; }
|
||||||
@@ -204,10 +95,80 @@ public:
|
|||||||
bool isUsingReversedColor() { return use_reversed_colors_; }
|
bool isUsingReversedColor() { return use_reversed_colors_; }
|
||||||
bool canBePopped() const { return !isBeingCreated(); }
|
bool canBePopped() const { return !isBeingCreated(); }
|
||||||
|
|
||||||
// Setters
|
// --- Setters ---
|
||||||
void setVelY(float vel_y) { vy_ = vel_y; }
|
void setVelY(float vel_y) { vy_ = vel_y; }
|
||||||
void setSpeed(float speed) { speed_ = speed; }
|
void setSpeed(float speed) { speed_ = speed; }
|
||||||
void setInvulnerable(bool value) { invulnerable_ = value; }
|
void setInvulnerable(bool value) { invulnerable_ = value; }
|
||||||
void setSound(bool value) { sound_enabled_ = value; }
|
void setSound(bool value) { sound_enabled_ = value; }
|
||||||
void disable() { enabled_ = false; }
|
void disable() { enabled_ = false; }
|
||||||
|
|
||||||
|
private:
|
||||||
|
// --- Estructura para el efecto de rebote ---
|
||||||
|
struct Bouncing
|
||||||
|
{
|
||||||
|
bool enabled = false; // Si el efecto está activo
|
||||||
|
Uint8 counter = 0; // Contador para el efecto
|
||||||
|
Uint8 speed = 2; // Velocidad del efecto
|
||||||
|
float zoomW = 1.0f; // Zoom en anchura
|
||||||
|
float zoomH = 1.0f; // Zoom en altura
|
||||||
|
float despX = 0.0f; // Desplazamiento X antes de pintar
|
||||||
|
float despY = 0.0f; // Desplazamiento Y antes de pintar
|
||||||
|
|
||||||
|
float w[MAX_BOUNCE] = {1.10f, 1.05f, 1.00f, 0.95f, 0.90f, 0.95f, 1.00f, 1.02f, 1.05f, 1.02f}; // Zoom ancho
|
||||||
|
float h[MAX_BOUNCE] = {0.90f, 0.95f, 1.00f, 1.05f, 1.10f, 1.05f, 1.00f, 0.98f, 0.95f, 0.98f}; // Zoom alto
|
||||||
|
|
||||||
|
Bouncing() = default;
|
||||||
|
void reset()
|
||||||
|
{
|
||||||
|
counter = 0;
|
||||||
|
zoomW = 1.0f;
|
||||||
|
zoomH = 1.0f;
|
||||||
|
despX = 0.0f;
|
||||||
|
despY = 0.0f;
|
||||||
|
}
|
||||||
|
} bouncing_;
|
||||||
|
|
||||||
|
// --- Objetos y punteros ---
|
||||||
|
std::unique_ptr<AnimatedSprite> sprite_; // Sprite del objeto globo
|
||||||
|
|
||||||
|
// --- Variables de estado y físicas ---
|
||||||
|
float x_; // Posición X
|
||||||
|
float y_; // Posición Y
|
||||||
|
float w_; // Ancho
|
||||||
|
float h_; // Alto
|
||||||
|
float vx_; // Velocidad X
|
||||||
|
float vy_; // Velocidad Y
|
||||||
|
float gravity_; // Aceleración en Y
|
||||||
|
float default_vy_; // Velocidad inicial al rebotar
|
||||||
|
float max_vy_; // Máxima velocidad en Y
|
||||||
|
bool being_created_; // Si el globo se está creando
|
||||||
|
bool enabled_ = true; // Si el globo está activo
|
||||||
|
bool invulnerable_; // Si el globo es invulnerable
|
||||||
|
bool stopped_; // Si el globo está parado
|
||||||
|
bool use_reversed_colors_ = false; // Si se usa el color alternativo
|
||||||
|
Circle collider_; // Círculo de colisión
|
||||||
|
Uint16 creation_counter_; // Temporizador de creación
|
||||||
|
Uint16 creation_counter_ini_; // Valor inicial del temporizador de creación
|
||||||
|
Uint16 score_; // Puntos al destruir el globo
|
||||||
|
BalloonType type_; // Tipo de globo
|
||||||
|
BalloonSize size_; // Tamaño de globo
|
||||||
|
Uint8 menace_; // Amenaza que genera el globo
|
||||||
|
Uint32 counter_ = 0; // Contador interno
|
||||||
|
float travel_y_ = 1.0f; // Distancia a recorrer en Y antes de aplicar gravedad
|
||||||
|
float speed_; // Velocidad del globo
|
||||||
|
Uint8 power_; // Poder que alberga el globo
|
||||||
|
SDL_FRect play_area_; // Zona de movimiento del globo
|
||||||
|
std::string sound_; // Archivo de sonido al rebotar
|
||||||
|
bool sound_enabled_ = false; // Si debe sonar el globo al rebotar
|
||||||
|
|
||||||
|
// --- 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 playSound(); // Reproduce el sonido al rebotar
|
||||||
};
|
};
|
||||||
@@ -3,13 +3,13 @@
|
|||||||
#include "balloon.h" // Para BALLOON_VELX_NEGATIVE, BALLOON_VELX_POSITIVE
|
#include "balloon.h" // Para BALLOON_VELX_NEGATIVE, BALLOON_VELX_POSITIVE
|
||||||
#include <vector>
|
#include <vector>
|
||||||
|
|
||||||
// Constantes de configuración
|
// --- Constantes de configuración ---
|
||||||
constexpr int NUMBER_OF_BALLOON_FORMATIONS = 100;
|
constexpr int NUMBER_OF_BALLOON_FORMATIONS = 100;
|
||||||
constexpr int MAX_NUMBER_OF_BALLOONS_IN_A_FORMATION = 50;
|
constexpr int MAX_NUMBER_OF_BALLOONS_IN_A_FORMATION = 50;
|
||||||
constexpr int NUMBER_OF_SETS_PER_POOL = 10;
|
constexpr int NUMBER_OF_SETS_PER_POOL = 10;
|
||||||
constexpr int NUMBER_OF_STAGES = 10;
|
constexpr int NUMBER_OF_STAGES = 10;
|
||||||
|
|
||||||
// Estructuras de datos
|
// --- Estructuras de datos ---
|
||||||
struct BalloonFormationParams
|
struct BalloonFormationParams
|
||||||
{
|
{
|
||||||
int x = 0; // Posición en el eje X donde crear el globo
|
int x = 0; // Posición en el eje X donde crear el globo
|
||||||
@@ -42,30 +42,29 @@ struct BalloonFormationUnit
|
|||||||
|
|
||||||
using BalloonFormationPool = std::vector<const BalloonFormationUnit *>;
|
using BalloonFormationPool = std::vector<const BalloonFormationUnit *>;
|
||||||
|
|
||||||
// Clase BalloonFormations
|
// --- Clase BalloonFormations ---
|
||||||
class BalloonFormations
|
class BalloonFormations
|
||||||
{
|
{
|
||||||
public:
|
public:
|
||||||
// Constructor
|
// --- Constructor y destructor ---
|
||||||
BalloonFormations()
|
BalloonFormations()
|
||||||
{
|
{
|
||||||
initBalloonFormations();
|
initBalloonFormations();
|
||||||
initBalloonFormationPools();
|
initBalloonFormationPools();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Destructor
|
|
||||||
~BalloonFormations() = default;
|
~BalloonFormations() = default;
|
||||||
|
|
||||||
// Getters
|
// --- Getters ---
|
||||||
const BalloonFormationPool &getPool(int pool) { return balloon_formation_pool_.at(pool); }
|
const BalloonFormationPool &getPool(int pool) { return balloon_formation_pool_.at(pool); }
|
||||||
const BalloonFormationUnit &getSet(int pool, int set) { return *balloon_formation_pool_.at(pool).at(set); }
|
const BalloonFormationUnit &getSet(int pool, int set) { return *balloon_formation_pool_.at(pool).at(set); }
|
||||||
const BalloonFormationUnit &getSet(int set) const { return balloon_formation_.at(set); }
|
const BalloonFormationUnit &getSet(int set) const { return balloon_formation_.at(set); }
|
||||||
|
|
||||||
private:
|
private:
|
||||||
|
// --- Datos ---
|
||||||
std::vector<BalloonFormationUnit> balloon_formation_; // Vector con todas las formaciones enemigas
|
std::vector<BalloonFormationUnit> balloon_formation_; // Vector con todas las formaciones enemigas
|
||||||
std::vector<BalloonFormationPool> balloon_formation_pool_; // Conjuntos de formaciones enemigas
|
std::vector<BalloonFormationPool> balloon_formation_pool_; // Conjuntos de formaciones enemigas
|
||||||
|
|
||||||
// Métodos internos de inicialización
|
// --- Métodos internos de inicialización ---
|
||||||
void initBalloonFormations();
|
void initBalloonFormations();
|
||||||
void initBalloonFormationPools();
|
void initBalloonFormationPools();
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -4,7 +4,7 @@
|
|||||||
#include <memory> // Para shared_ptr, unique_ptr
|
#include <memory> // Para shared_ptr, unique_ptr
|
||||||
#include "sprite.h" // Para Sprite
|
#include "sprite.h" // Para Sprite
|
||||||
#include "utils.h" // Para Circle
|
#include "utils.h" // Para Circle
|
||||||
class Texture; // lines 8-8
|
class Texture;
|
||||||
|
|
||||||
// Tipos de balas
|
// Tipos de balas
|
||||||
enum class BulletType : Uint8
|
enum class BulletType : Uint8
|
||||||
@@ -25,6 +25,23 @@ enum class BulletMoveStatus : Uint8
|
|||||||
// Clase Bullet
|
// Clase Bullet
|
||||||
class Bullet
|
class Bullet
|
||||||
{
|
{
|
||||||
|
public:
|
||||||
|
// Constructor y Destructor
|
||||||
|
Bullet(float x, float y, BulletType bullet_type, bool powered_up, int owner, std::shared_ptr<Texture> texture);
|
||||||
|
~Bullet() = default;
|
||||||
|
|
||||||
|
// Métodos principales
|
||||||
|
void render(); // Dibuja la bala en pantalla
|
||||||
|
BulletMoveStatus move(); // Mueve la bala y devuelve su estado
|
||||||
|
|
||||||
|
// Estado de la bala
|
||||||
|
bool isEnabled() const; // Comprueba si está activa
|
||||||
|
void disable(); // Desactiva la bala
|
||||||
|
|
||||||
|
// Getters
|
||||||
|
int getOwner() const; // Devuelve el identificador del dueño
|
||||||
|
Circle &getCollider(); // Devuelve el círculo de colisión
|
||||||
|
|
||||||
private:
|
private:
|
||||||
// Constantes
|
// Constantes
|
||||||
static constexpr float BULLET_WIDTH_ = 12.0f;
|
static constexpr float BULLET_WIDTH_ = 12.0f;
|
||||||
@@ -33,39 +50,18 @@ private:
|
|||||||
static constexpr float BULLET_VEL_X_LEFT_ = -2.0f;
|
static constexpr float BULLET_VEL_X_LEFT_ = -2.0f;
|
||||||
static constexpr float BULLET_VEL_X_RIGHT_ = 2.0f;
|
static constexpr float BULLET_VEL_X_RIGHT_ = 2.0f;
|
||||||
|
|
||||||
std::unique_ptr<Sprite> sprite_; // Sprite con los gráficos y métodos de pintado
|
// Propiedades
|
||||||
|
std::unique_ptr<Sprite> sprite_; // Sprite con los gráficos
|
||||||
|
|
||||||
float pos_x_; // Posición en el eje X
|
float pos_x_; // Posición en el eje X
|
||||||
float pos_y_; // Posición en el eje Y
|
float pos_y_; // Posición en el eje Y
|
||||||
float vel_x_; // Velocidad en el eje X
|
float vel_x_; // Velocidad en el eje X
|
||||||
|
|
||||||
BulletType bullet_type_; // Tipo de objeto
|
BulletType bullet_type_; // Tipo de bala
|
||||||
int owner_; // Identificador del dueño del objeto
|
int owner_; // Identificador del dueño
|
||||||
Circle collider_; // Círculo de colisión del objeto
|
Circle collider_; // Círculo de colisión
|
||||||
|
|
||||||
void shiftColliders(); // Alinea el círculo de colisión con el objeto
|
// Métodos internos
|
||||||
void shiftSprite(); // Alinea el sprite con el objeto
|
void shiftColliders(); // Ajusta el círculo de colisión
|
||||||
|
void shiftSprite(); // Ajusta el sprite
|
||||||
public:
|
|
||||||
// Constructor
|
|
||||||
Bullet(float x, float y, BulletType bullet_type, bool powered_up, int owner, std::shared_ptr<Texture> texture);
|
|
||||||
|
|
||||||
// Destructor
|
|
||||||
~Bullet() = default;
|
|
||||||
|
|
||||||
// Pinta el objeto en pantalla
|
|
||||||
void render();
|
|
||||||
|
|
||||||
// Actualiza la posición y estado del objeto
|
|
||||||
BulletMoveStatus move();
|
|
||||||
|
|
||||||
// Comprueba si el objeto está habilitado
|
|
||||||
bool isEnabled() const;
|
|
||||||
|
|
||||||
// Deshabilita el objeto
|
|
||||||
void disable();
|
|
||||||
|
|
||||||
// Obtiene parámetros
|
|
||||||
int getOwner() const;
|
|
||||||
Circle &getCollider();
|
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -33,11 +33,11 @@ constexpr const char TEXT_COPYRIGHT[] = "@2020,2025 JailDesigner";
|
|||||||
// Constructor
|
// Constructor
|
||||||
Credits::Credits()
|
Credits::Credits()
|
||||||
: balloon_manager_(std::make_unique<BalloonManager>()),
|
: balloon_manager_(std::make_unique<BalloonManager>()),
|
||||||
text_texture_(SDL_CreateTexture(Screen::get()->getRenderer(), SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, param.game.width, param.game.height)),
|
|
||||||
canvas_(SDL_CreateTexture(Screen::get()->getRenderer(), SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, param.game.width, param.game.height)),
|
|
||||||
tiled_bg_(std::make_unique<TiledBG>(param.game.game_area.rect, TiledBGMode::DIAGONAL)),
|
tiled_bg_(std::make_unique<TiledBG>(param.game.game_area.rect, TiledBGMode::DIAGONAL)),
|
||||||
fade_in_(std::make_unique<Fade>()),
|
fade_in_(std::make_unique<Fade>()),
|
||||||
fade_out_(std::make_unique<Fade>())
|
fade_out_(std::make_unique<Fade>()),
|
||||||
|
text_texture_(SDL_CreateTexture(Screen::get()->getRenderer(), SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, param.game.width, param.game.height)),
|
||||||
|
canvas_(SDL_CreateTexture(Screen::get()->getRenderer(), SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, param.game.width, param.game.height))
|
||||||
{
|
{
|
||||||
if (!text_texture_)
|
if (!text_texture_)
|
||||||
{
|
{
|
||||||
|
|||||||
194
source/credits.h
194
source/credits.h
@@ -1,113 +1,125 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
#include <SDL3/SDL_rect.h> // Para SDL_FRect
|
#include <SDL3/SDL_rect.h>
|
||||||
#include <SDL3/SDL_render.h> // Para SDL_Texture
|
#include <SDL3/SDL_render.h>
|
||||||
#include <SDL3/SDL_stdinc.h> // Para Uint32
|
#include <SDL3/SDL_stdinc.h>
|
||||||
#include <memory> // Para unique_ptr, shared_ptr
|
#include <memory>
|
||||||
#include <vector> // Para vector
|
#include <vector>
|
||||||
#include "options.h" // Para Options, OptionsAudio, OptionsMusic
|
|
||||||
#include "param.h" // Para Param, ParamGame, param
|
#include "options.h"
|
||||||
#include "utils.h" // Para Zone
|
#include "param.h"
|
||||||
class BalloonManager; // lines 8-8
|
#include "utils.h"
|
||||||
class Fade; // lines 11-11
|
|
||||||
class Player; // lines 10-10
|
// Declaraciones adelantadas
|
||||||
class TiledBG; // lines 9-9
|
class BalloonManager;
|
||||||
|
class Fade;
|
||||||
|
class Player;
|
||||||
|
class TiledBG;
|
||||||
|
|
||||||
constexpr int PLAY_AREA_HEIGHT = 200;
|
constexpr int PLAY_AREA_HEIGHT = 200;
|
||||||
|
|
||||||
class Credits
|
class Credits
|
||||||
{
|
{
|
||||||
|
public:
|
||||||
|
Credits();
|
||||||
|
~Credits();
|
||||||
|
|
||||||
|
void run(); // Bucle principal
|
||||||
|
|
||||||
private:
|
private:
|
||||||
// Objetos
|
// === Objetos Principales ===
|
||||||
std::unique_ptr<BalloonManager> balloon_manager_; // Objeto para gestionar los globos
|
std::unique_ptr<BalloonManager> balloon_manager_; // Gestión de globos
|
||||||
SDL_Texture *text_texture_; // Textura con el texto
|
std::unique_ptr<TiledBG> tiled_bg_; // Mosaico animado de fondo
|
||||||
SDL_Texture *canvas_; // Textura donde dibujarlo todo
|
std::unique_ptr<Fade> fade_in_; // Fundido de entrada
|
||||||
std::unique_ptr<TiledBG> tiled_bg_; // Objeto para dibujar el mosaico animado de fondo
|
std::unique_ptr<Fade> fade_out_; // Fundido de salida
|
||||||
std::unique_ptr<Fade> fade_in_; // Objeto para realizar el fundido de entrada
|
std::vector<std::shared_ptr<Player>> players_; // Vector de jugadores
|
||||||
std::unique_ptr<Fade> fade_out_; // Objeto para realizar el fundido de salida
|
|
||||||
std::vector<std::shared_ptr<Player>> players_; // Vector con los jugadores
|
|
||||||
|
|
||||||
// Variables
|
// === Gestión de Texturas ===
|
||||||
Uint64 ticks_ = 0; // Contador de ticks para ajustar la velocidad del programa
|
SDL_Texture *text_texture_; // Textura con el texto
|
||||||
Uint32 counter_ = 0; // Contador para la lógica de la clase
|
SDL_Texture *canvas_; // Textura donde dibujarlo todo
|
||||||
Uint32 counter_pre_fade_ = 0; // Contador para activar el fundido final
|
|
||||||
Uint32 counter_prevent_endless_ = 0; // Contador para evitar que el juego se quede para siempre en los creditos
|
|
||||||
float black_bars_size_ = (param.game.game_area.rect.h - PLAY_AREA_HEIGHT) / 2; // Tamaño de las barras negras
|
|
||||||
int mini_logo_final_pos_ = 0; // Ubicación donde se detiene el minilogo
|
|
||||||
bool fading_ = false; // Indica si se está realizando el fade final
|
|
||||||
bool want_to_pass_ = false; // Indica si el jugador quiere saltarse los titulos de crédito
|
|
||||||
bool mini_logo_on_position_ = false; // Indica si el minilogo ya se ha quedado en su posición
|
|
||||||
int initial_volume_ = options.audio.music.volume; // Volumen actual al crear el objeto
|
|
||||||
int steps_ = 0; // Cantidad de pasos a dar para ir reduciendo el audio
|
|
||||||
|
|
||||||
// Rectangulos
|
// === Temporización y Contadores ===
|
||||||
SDL_FRect credits_rect_src_ = param.game.game_area.rect; // Rectangulo con el texto de los créditos (origen)
|
Uint64 ticks_ = 0; // Control de velocidad del programa
|
||||||
SDL_FRect credits_rect_dst_ = param.game.game_area.rect; // Rectangulo con el texto de los créditos (destino)
|
Uint32 counter_ = 0; // Contador principal de lógica
|
||||||
SDL_FRect mini_logo_rect_src_ = param.game.game_area.rect; // Rectangulo con el mini logo de JailGames y el texto de copyright (origen)
|
Uint32 counter_pre_fade_ = 0; // Activación del fundido final
|
||||||
SDL_FRect mini_logo_rect_dst_ = param.game.game_area.rect; // Rectangulo con el mini logo de JailGames y el texto de copyright (destino)
|
Uint32 counter_prevent_endless_ = 0; // Prevención de bucle infinito
|
||||||
|
|
||||||
|
// === Variables de Estado ===
|
||||||
|
bool fading_ = false; // Estado del fade final
|
||||||
|
bool want_to_pass_ = false; // Jugador quiere saltarse créditos
|
||||||
|
bool mini_logo_on_position_ = false; // Minilogo en posición final
|
||||||
|
|
||||||
|
// === Diseño y Posicionamiento ===
|
||||||
|
float black_bars_size_ = (param.game.game_area.rect.h - PLAY_AREA_HEIGHT) / 2;
|
||||||
|
int mini_logo_final_pos_ = 0; // Posición final del minilogo
|
||||||
|
|
||||||
|
// === Control de Audio ===
|
||||||
|
int initial_volume_ = options.audio.music.volume; // Volumen inicial
|
||||||
|
int steps_ = 0; // Pasos para reducir audio
|
||||||
|
|
||||||
|
// === Rectángulos de Renderizado ===
|
||||||
|
// Texto de créditos
|
||||||
|
SDL_FRect credits_rect_src_ = param.game.game_area.rect;
|
||||||
|
SDL_FRect credits_rect_dst_ = param.game.game_area.rect;
|
||||||
|
|
||||||
|
// Mini logo
|
||||||
|
SDL_FRect mini_logo_rect_src_ = param.game.game_area.rect;
|
||||||
|
SDL_FRect mini_logo_rect_dst_ = param.game.game_area.rect;
|
||||||
|
|
||||||
|
// Definición del área de juego
|
||||||
SDL_FRect play_area_ = {
|
SDL_FRect play_area_ = {
|
||||||
param.game.game_area.rect.x,
|
param.game.game_area.rect.x,
|
||||||
param.game.game_area.rect.y + black_bars_size_,
|
param.game.game_area.rect.y + black_bars_size_,
|
||||||
param.game.game_area.rect.w,
|
param.game.game_area.rect.w,
|
||||||
PLAY_AREA_HEIGHT}; // Area visible para los creditos
|
PLAY_AREA_HEIGHT};
|
||||||
SDL_FRect top_black_rect_ = {play_area_.x, param.game.game_area.rect.y, play_area_.w, black_bars_size_}; // Rectangulo negro superior
|
|
||||||
SDL_FRect bottom_black_rect_ = {play_area_.x, param.game.game_area.rect.h - black_bars_size_, play_area_.w, black_bars_size_}; // Rectangulo negro inferior
|
|
||||||
SDL_FRect left_black_rect_ = {play_area_.x, param.game.game_area.center_y - 1, 0, 2}; // Rectangulo negro situado a la izquierda
|
|
||||||
SDL_FRect right_black_rect_ = {play_area_.x + play_area_.w, param.game.game_area.center_y - 1, 0, 2}; // Rectangulo negro situado a la derecha
|
|
||||||
SDL_FRect red_rect = play_area_; // Rectangulo rojo para delimitar la ventana
|
|
||||||
|
|
||||||
// Actualiza las variables
|
// Barras negras para efecto letterbox
|
||||||
void update();
|
SDL_FRect top_black_rect_ = {
|
||||||
|
play_area_.x,
|
||||||
|
param.game.game_area.rect.y,
|
||||||
|
play_area_.w,
|
||||||
|
black_bars_size_};
|
||||||
|
SDL_FRect bottom_black_rect_ = {
|
||||||
|
play_area_.x,
|
||||||
|
param.game.game_area.rect.h - black_bars_size_,
|
||||||
|
play_area_.w,
|
||||||
|
black_bars_size_};
|
||||||
|
SDL_FRect left_black_rect_ = {
|
||||||
|
play_area_.x,
|
||||||
|
param.game.game_area.center_y - 1,
|
||||||
|
0,
|
||||||
|
2};
|
||||||
|
SDL_FRect right_black_rect_ = {
|
||||||
|
play_area_.x + play_area_.w,
|
||||||
|
param.game.game_area.center_y - 1,
|
||||||
|
0,
|
||||||
|
2};
|
||||||
|
|
||||||
// Dibuja en pantalla
|
// Borde para la ventana
|
||||||
void render();
|
SDL_FRect red_rect = play_area_; // Delimitador de ventana
|
||||||
|
|
||||||
// Comprueba el manejador de eventos
|
// === Métodos del Bucle Principal ===
|
||||||
void checkEvents();
|
void update(); // Actualización principal
|
||||||
|
void render(); // Renderizado
|
||||||
|
void checkEvents(); // Manejo de eventos
|
||||||
|
void checkInput(); // Procesamiento de entrada
|
||||||
|
|
||||||
// Comprueba las entradas
|
// === Métodos de Renderizado ===
|
||||||
void checkInput();
|
void fillTextTexture(); // Crear textura de texto
|
||||||
|
void fillCanvas(); // Renderizar todos los sprites
|
||||||
|
void updateTextureDstRects(); // Actualizar destinos de texturas
|
||||||
|
|
||||||
// Crea la textura con el texto
|
// === Métodos de Lógica del Juego ===
|
||||||
void fillTextTexture();
|
void throwBalloons(); // Lanzar globos al escenario
|
||||||
|
void initPlayers(); // Inicializar jugadores
|
||||||
|
void updateAllFades(); // Actualizar estados de fade
|
||||||
|
void cycleColors(); // Cambiar colores de fondo
|
||||||
|
|
||||||
// Dibuja todos los sprites en la textura
|
// === Métodos de Interfaz ===
|
||||||
void fillCanvas();
|
void updateBlackRects(); // Actualizar rectángulos negros
|
||||||
|
void updateRedRect(); // Actualizar rectángulo rojo
|
||||||
|
|
||||||
// Actualiza el destino de los rectangulos de las texturas
|
// === Métodos de Audio ===
|
||||||
void updateTextureDstRects();
|
void setVolume(int amount); // Establecer volumen
|
||||||
|
void resetVolume(); // Restablecer volumen
|
||||||
// Tira globos al escenario
|
|
||||||
void throwBalloons();
|
|
||||||
|
|
||||||
// Inicializa los jugadores
|
|
||||||
void initPlayers();
|
|
||||||
|
|
||||||
// Actualiza los rectangulos negros
|
|
||||||
void updateBlackRects();
|
|
||||||
|
|
||||||
// Actualiza el rectangulo rojo
|
|
||||||
void updateRedRect();
|
|
||||||
|
|
||||||
// Actualiza el estado de fade
|
|
||||||
void updateAllFades();
|
|
||||||
|
|
||||||
// Establece el nivel de volumen
|
|
||||||
void setVolume(int amount);
|
|
||||||
|
|
||||||
// Reestablece el nivel de volumen
|
|
||||||
void resetVolume();
|
|
||||||
|
|
||||||
// Cambia el color del fondo
|
|
||||||
void cycleColors();
|
|
||||||
|
|
||||||
public:
|
|
||||||
// Constructor
|
|
||||||
Credits();
|
|
||||||
|
|
||||||
// Destructor
|
|
||||||
~Credits();
|
|
||||||
|
|
||||||
// Bucle principal
|
|
||||||
void run();
|
|
||||||
};
|
};
|
||||||
@@ -85,7 +85,7 @@ bool DefineButtons::enable(int index)
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Comprueba si está habilitado
|
// Comprueba si está habilitado
|
||||||
bool DefineButtons::isEnabled() { return enabled_; }
|
bool DefineButtons::isEnabled() const { return enabled_; }
|
||||||
|
|
||||||
// Incrementa el indice de los botones
|
// Incrementa el indice de los botones
|
||||||
void DefineButtons::incIndexButton()
|
void DefineButtons::incIndexButton()
|
||||||
|
|||||||
@@ -2,76 +2,57 @@
|
|||||||
|
|
||||||
#include <SDL3/SDL_events.h> // Para SDL_Event, SDL_GamepadButtonEvent
|
#include <SDL3/SDL_events.h> // Para SDL_Event, SDL_GamepadButtonEvent
|
||||||
#include <SDL3/SDL_gamepad.h> // Para SDL_GamepadButton
|
#include <SDL3/SDL_gamepad.h> // Para SDL_GamepadButton
|
||||||
|
#include <memory> // Para std::shared_ptr
|
||||||
#include <stddef.h> // Para size_t
|
#include <stddef.h> // Para size_t
|
||||||
#include <memory> // Para shared_ptr
|
#include <string> // Para std::string
|
||||||
#include <string> // Para string
|
#include <vector> // Para std::vector
|
||||||
#include <vector> // Para vector
|
|
||||||
class Input; // lines 10-10
|
|
||||||
class Text; // lines 11-11
|
|
||||||
enum class InputAction : int; // lines 12-12
|
|
||||||
|
|
||||||
|
// Declaraciones adelantadas
|
||||||
|
class Input;
|
||||||
|
class Text;
|
||||||
|
enum class InputAction : int;
|
||||||
|
|
||||||
|
// Estructura para definir botones
|
||||||
struct DefineButtonsButton
|
struct DefineButtonsButton
|
||||||
{
|
{
|
||||||
std::string label; // Texto en pantalla para el botón
|
std::string label; // Texto en pantalla
|
||||||
InputAction input; // Input asociado
|
InputAction input; // Acción asociada
|
||||||
SDL_GamepadButton button; // Botón del mando correspondiente
|
SDL_GamepadButton button; // Botón del mando
|
||||||
|
|
||||||
// Constructor
|
|
||||||
DefineButtonsButton(const std::string &lbl, InputAction inp, SDL_GamepadButton btn)
|
DefineButtonsButton(const std::string &lbl, InputAction inp, SDL_GamepadButton btn)
|
||||||
: label(lbl), input(inp), button(btn) {}
|
: label(lbl), input(inp), button(btn) {}
|
||||||
};
|
};
|
||||||
|
|
||||||
// Clase Bullet
|
// Clase DefineButtons
|
||||||
class DefineButtons
|
class DefineButtons
|
||||||
{
|
{
|
||||||
private:
|
|
||||||
// Objetos
|
|
||||||
Input *input_; // Objeto pata gestionar la entrada
|
|
||||||
std::shared_ptr<Text> text_; // Objeto para escribir texto
|
|
||||||
|
|
||||||
// Variables
|
|
||||||
bool enabled_ = false; // Indica si el objeto está habilitado
|
|
||||||
int x_; // Posición donde dibujar el texto
|
|
||||||
int y_; // Posición donde dibujar el texto
|
|
||||||
std::vector<DefineButtonsButton> buttons_; // Vector con las nuevas definiciones de botones/acciones
|
|
||||||
size_t index_controller_ = 0; // Indice del controlador a reasignar
|
|
||||||
size_t index_button_ = 0; // Indice para saber qué botón se está definiendo
|
|
||||||
std::vector<std::string> controller_names_; // Nombres de los mandos
|
|
||||||
|
|
||||||
// Incrementa el indice de los botones
|
|
||||||
void incIndexButton();
|
|
||||||
|
|
||||||
// Comprueba el botón que se ha pulsado
|
|
||||||
void doControllerButtonDown(const SDL_GamepadButtonEvent &event);
|
|
||||||
|
|
||||||
// Asigna los botones definidos al input
|
|
||||||
void bindButtons();
|
|
||||||
|
|
||||||
// Guarda los cambios en las opciones
|
|
||||||
void saveBindingsToOptions();
|
|
||||||
|
|
||||||
// Comprueba que un botón no esté ya asignado
|
|
||||||
bool checkButtonNotInUse(SDL_GamepadButton button);
|
|
||||||
|
|
||||||
// Limpia la asignación de botones
|
|
||||||
void clearButtons();
|
|
||||||
|
|
||||||
public:
|
public:
|
||||||
// Constructor
|
|
||||||
DefineButtons();
|
DefineButtons();
|
||||||
|
|
||||||
// Destructor
|
|
||||||
~DefineButtons() = default;
|
~DefineButtons() = default;
|
||||||
|
|
||||||
// Dibuja el objeto en pantalla
|
void render(); // Dibuja el objeto en pantalla
|
||||||
void render();
|
void checkEvents(const SDL_Event &event); // Procesa los eventos
|
||||||
|
bool enable(int index_controller); // Habilita la redefinición de botones
|
||||||
|
bool isEnabled() const; // Comprueba si está habilitado
|
||||||
|
|
||||||
// Comprueba los eventos
|
private:
|
||||||
void checkEvents(const SDL_Event &event);
|
// Objetos
|
||||||
|
Input *input_ = nullptr; // Gestión de entrada
|
||||||
|
std::shared_ptr<Text> text_; // Renderizado de texto
|
||||||
|
|
||||||
// Habilita el objeto
|
// Variables
|
||||||
bool enable(int index);
|
bool enabled_ = false; // Indica si está activo
|
||||||
|
int x_ = 0, y_ = 0; // Coordenadas de texto
|
||||||
|
std::vector<DefineButtonsButton> buttons_; // Definiciones de botones
|
||||||
|
size_t index_controller_ = 0; // Índice del controlador asignado
|
||||||
|
size_t index_button_ = 0; // Índice del botón en proceso
|
||||||
|
std::vector<std::string> controller_names_; // Nombres de los mandos
|
||||||
|
|
||||||
// Comprueba si está habilitado
|
// Métodos internos
|
||||||
bool isEnabled();
|
void incIndexButton(); // Incrementa el índice de botones
|
||||||
};
|
void doControllerButtonDown(const SDL_GamepadButtonEvent &event); // Procesa pulsaciones
|
||||||
|
void bindButtons(); // Asigna botones al sistema de entrada
|
||||||
|
void saveBindingsToOptions(); // Guarda configuraciones
|
||||||
|
bool checkButtonNotInUse(SDL_GamepadButton button); // Verifica uso de botones
|
||||||
|
void clearButtons(); // Limpia asignaciones actuales
|
||||||
|
};
|
||||||
|
|||||||
@@ -1,63 +1,40 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
#include <string>
|
#include <array> // Para std::array
|
||||||
#include <array>
|
#include <string> // Para std::string
|
||||||
#include "utils.h"
|
#include "utils.h" // Archivo de utilidades
|
||||||
|
|
||||||
|
// Tamaño máximo del nombre
|
||||||
constexpr size_t NAME_SIZE = 3;
|
constexpr size_t NAME_SIZE = 3;
|
||||||
|
|
||||||
/*
|
|
||||||
Un array, "characterList", contiene la lista de caracteres
|
|
||||||
Un segundo array, "characterIndex", contiene el indice a "characterList" de cada una de las letras que conforman el nombre
|
|
||||||
"pos" es la posición de "characterIndex" que se está modificando
|
|
||||||
Izquierda o derecha modifican "pos", arriba o abajo modifican el índice de "characterIndex[pos]"
|
|
||||||
Pulsar cualquier botón, mueve "pos" a la derecha. Al pulsar el botón en la ´´ultima posición se finaliza la introducción de nombres
|
|
||||||
*/
|
|
||||||
|
|
||||||
// Clase EnterName
|
// Clase EnterName
|
||||||
class EnterName
|
class EnterName
|
||||||
{
|
{
|
||||||
private:
|
|
||||||
std::string character_list_; // Lista de todos los caracteres permitidos
|
|
||||||
std::string name_; // Nombre introducido
|
|
||||||
size_t position_ = 0; // Posición a editar del nombre
|
|
||||||
bool position_overflow_ = false; // Indica si hemos incrementado la posición más allá del límite
|
|
||||||
std::array<int, NAME_SIZE> character_index_; // Indice de la lista para cada uno de los caracteres que forman el nombre
|
|
||||||
|
|
||||||
// Actualiza el nombre a partir de la lista de índices
|
|
||||||
void updateNameFromCharacterIndex();
|
|
||||||
|
|
||||||
// Actualiza la variable
|
|
||||||
void initCharacterIndex(const std::string &name);
|
|
||||||
|
|
||||||
// Encuentra el indice de un caracter en "characterList"
|
|
||||||
int findIndex(char character) const;
|
|
||||||
|
|
||||||
public:
|
public:
|
||||||
// Constructor
|
|
||||||
EnterName();
|
EnterName();
|
||||||
|
|
||||||
// Destructor
|
|
||||||
~EnterName() = default;
|
~EnterName() = default;
|
||||||
|
|
||||||
// Inicializa el objeto
|
void init(const std::string &name = ""); // Inicializa con un nombre opcional
|
||||||
void init(const std::string &name = "");
|
|
||||||
|
|
||||||
// Incrementa la posición
|
void incPosition(); // Incrementa la posición del carácter actual
|
||||||
void incPosition();
|
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
|
||||||
|
|
||||||
// Decrementa la posición
|
std::string getFinalName() const { return trim(name_.substr(0, position_)); } // Obtiene el nombre final introducido
|
||||||
void decPosition();
|
std::string getCurrentName() const { return trim(name_); } // Obtiene el nombre actual en proceso
|
||||||
|
|
||||||
// Incrementa el índice
|
int getPosition() const { return position_; } // Posición actual del carácter editado
|
||||||
void incIndex();
|
bool getPositionOverflow() const { return position_overflow_; } // Indica si la posición excede el límite
|
||||||
|
|
||||||
// Decrementa el índice
|
private:
|
||||||
void decIndex();
|
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_`
|
||||||
|
|
||||||
// Getters
|
void updateNameFromCharacterIndex(); // Actualiza `name_` según `character_index_`
|
||||||
std::string getFinalName() const { return trim(name_.substr(0, position_)); }
|
void initCharacterIndex(const std::string &name); // Inicializa índices desde el nombre
|
||||||
std::string getCurrentName() const { return trim(name_); }
|
int findIndex(char character) const; // Busca el índice de un carácter en `character_list_`
|
||||||
int getPosition() const { return position_; }
|
|
||||||
bool getPositionOverflow() const { return position_overflow_; }
|
|
||||||
};
|
};
|
||||||
@@ -4,38 +4,26 @@
|
|||||||
#include <string> // Para string
|
#include <string> // Para string
|
||||||
#include <vector> // Para vector
|
#include <vector> // Para vector
|
||||||
#include "animated_sprite.h" // Para AnimatedSprite
|
#include "animated_sprite.h" // Para AnimatedSprite
|
||||||
class Texture; // lines 7-7
|
|
||||||
|
|
||||||
|
class Texture;
|
||||||
|
|
||||||
|
// Estructura para almacenar la información de una textura de explosión
|
||||||
struct ExplosionTexture
|
struct ExplosionTexture
|
||||||
{
|
{
|
||||||
int size; // Tamaño de la explosión
|
int size; // Tamaño de la explosión
|
||||||
std::shared_ptr<Texture> texture; // Textura para la explosión
|
std::shared_ptr<Texture> texture; // Textura para la explosión
|
||||||
std::vector<std::string> animation; // Animación para la textura
|
std::vector<std::string> animation; // Animación para la textura
|
||||||
|
|
||||||
// Constructor
|
|
||||||
ExplosionTexture(int sz, std::shared_ptr<Texture> tex, const std::vector<std::string> &anim)
|
ExplosionTexture(int sz, std::shared_ptr<Texture> tex, const std::vector<std::string> &anim)
|
||||||
: size(sz), texture(tex), animation(anim) {}
|
: size(sz), texture(tex), animation(anim) {}
|
||||||
};
|
};
|
||||||
|
|
||||||
// Clase explosions
|
// Clase Explosions
|
||||||
class Explosions
|
class Explosions
|
||||||
{
|
{
|
||||||
private:
|
|
||||||
// Variables
|
|
||||||
std::vector<ExplosionTexture> textures_; // Vector con las texturas a utilizar
|
|
||||||
std::vector<std::unique_ptr<AnimatedSprite>> explosions_; // Lista con todas las explosiones
|
|
||||||
|
|
||||||
// Vacia el vector de elementos finalizados
|
|
||||||
void freeExplosions();
|
|
||||||
|
|
||||||
// Busca una textura a partir del tamaño
|
|
||||||
int getIndexBySize(int size);
|
|
||||||
|
|
||||||
public:
|
public:
|
||||||
// Constructor
|
// Constructor y destructor
|
||||||
Explosions() = default;
|
Explosions() = default;
|
||||||
|
|
||||||
// Destructor
|
|
||||||
~Explosions() = default;
|
~Explosions() = default;
|
||||||
|
|
||||||
// Actualiza la lógica de la clase
|
// Actualiza la lógica de la clase
|
||||||
@@ -49,4 +37,17 @@ public:
|
|||||||
|
|
||||||
// Añade una explosión
|
// Añade una explosión
|
||||||
void add(int x, int y, int size);
|
void add(int x, int y, int size);
|
||||||
|
|
||||||
|
private:
|
||||||
|
// Vector con las texturas a utilizar
|
||||||
|
std::vector<ExplosionTexture> textures_;
|
||||||
|
|
||||||
|
// Lista con todas las explosiones
|
||||||
|
std::vector<std::unique_ptr<AnimatedSprite>> explosions_;
|
||||||
|
|
||||||
|
// Vacia el vector de elementos finalizados
|
||||||
|
void freeExplosions();
|
||||||
|
|
||||||
|
// Busca una textura a partir del tamaño
|
||||||
|
int getIndexBySize(int size);
|
||||||
};
|
};
|
||||||
110
source/fade.h
110
source/fade.h
@@ -1,9 +1,9 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
#include <SDL3/SDL_rect.h> // Para SDL_FRect
|
#include <SDL3/SDL_rect.h>
|
||||||
#include <SDL3/SDL_render.h> // Para SDL_Renderer, SDL_Texture
|
#include <SDL3/SDL_render.h>
|
||||||
#include <SDL3/SDL_stdinc.h> // Para Uint8, Uint16
|
#include <SDL3/SDL_stdinc.h>
|
||||||
#include <vector> // Para vector
|
#include <vector>
|
||||||
|
|
||||||
// Tipos de fundido
|
// Tipos de fundido
|
||||||
enum class FadeType : Uint8
|
enum class FadeType : Uint8
|
||||||
@@ -31,72 +31,62 @@ enum class FadeState : Uint8
|
|||||||
FINISHED = 4,
|
FINISHED = 4,
|
||||||
};
|
};
|
||||||
|
|
||||||
// Clase Fade
|
|
||||||
class Fade
|
class Fade
|
||||||
{
|
{
|
||||||
private:
|
|
||||||
// Objetos y punteros
|
|
||||||
SDL_Renderer *renderer_; // El renderizador de la ventana
|
|
||||||
SDL_Texture *backbuffer_; // Textura para usar como backbuffer con SDL_TEXTUREACCESS_TARGET
|
|
||||||
|
|
||||||
// Variables
|
|
||||||
FadeType type_; // Tipo de fade a realizar
|
|
||||||
FadeMode mode_; // Modo de fade a realizar
|
|
||||||
FadeState state_ = FadeState::NOT_ENABLED; // Estado actual del objeto
|
|
||||||
Uint16 counter_; // Contador interno
|
|
||||||
Uint8 r_, g_, b_, a_; // Colores para el fade
|
|
||||||
SDL_FRect rect1_; // Rectangulo usado para crear los efectos de transición
|
|
||||||
SDL_FRect rect2_; // Rectangulo usado para crear los efectos de transición
|
|
||||||
int num_squares_width_; // Cantidad total de cuadraditos en horizontal para el FadeType::RANDOM_SQUARE
|
|
||||||
int num_squares_height_; // Cantidad total de cuadraditos en vertical para el FadeType::RANDOM_SQUARE
|
|
||||||
std::vector<SDL_FRect> square_; // Vector con los indices de los cuadrados para el FadeType::RANDOM_SQUARE
|
|
||||||
int fade_random_squares_delay_; // Duración entre cada pintado de cuadrados
|
|
||||||
int fade_random_squares_mult_; // Cantidad de cuadrados que se pintaran cada vez
|
|
||||||
int post_duration_ = 0; // Duración posterior del fade tras finalizar
|
|
||||||
int post_counter_ = 0; // Contador para la duración posterior
|
|
||||||
int pre_duration_ = 0; // Duración previa del fade antes de iniciar
|
|
||||||
int pre_counter_ = 0; // Contador para la duración previa
|
|
||||||
int value_ = 0; // Estado actual del fade entre 0 y 100
|
|
||||||
|
|
||||||
// Inicializa las variables
|
|
||||||
void init();
|
|
||||||
|
|
||||||
// Limpia el backbuffer
|
|
||||||
void cleanBackbuffer(Uint8 r, Uint8 g, Uint8 b, Uint8 a);
|
|
||||||
|
|
||||||
// Calcula el valor del estado del fade
|
|
||||||
int calculateValue(int min, int max, int current);
|
|
||||||
|
|
||||||
public:
|
public:
|
||||||
// Constructor
|
// --- Constructores y destructor ---
|
||||||
Fade();
|
Fade();
|
||||||
|
|
||||||
// Destructor
|
|
||||||
~Fade();
|
~Fade();
|
||||||
|
|
||||||
// Resetea algunas variables para volver a hacer el fade sin perder ciertos parametros
|
// --- Métodos principales ---
|
||||||
void reset();
|
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
|
||||||
|
|
||||||
// Pinta una transición en pantalla
|
// --- Configuración ---
|
||||||
void render();
|
|
||||||
|
|
||||||
// Actualiza las variables internas
|
|
||||||
void update();
|
|
||||||
|
|
||||||
// Activa el fade
|
|
||||||
void activate();
|
|
||||||
|
|
||||||
// Establece el color del fade
|
|
||||||
void setColor(Uint8 r, Uint8 g, Uint8 b);
|
void setColor(Uint8 r, Uint8 g, Uint8 b);
|
||||||
|
|
||||||
// Getters
|
|
||||||
int getValue() const { return value_; }
|
|
||||||
bool isEnabled() const { return state_ != FadeState::NOT_ENABLED; }
|
|
||||||
bool hasEnded() const { return state_ == FadeState::FINISHED; }
|
|
||||||
|
|
||||||
// Setters
|
|
||||||
void setType(FadeType type) { type_ = type; }
|
void setType(FadeType type) { type_ = type; }
|
||||||
void setMode(FadeMode mode) { mode_ = mode; }
|
void setMode(FadeMode mode) { mode_ = mode; }
|
||||||
void setPostDuration(int value) { post_duration_ = value; }
|
void setPostDuration(int value) { post_duration_ = value; }
|
||||||
void setPreDuration(int value) { pre_duration_ = value; }
|
void setPreDuration(int value) { pre_duration_ = value; }
|
||||||
|
|
||||||
|
// --- Getters ---
|
||||||
|
int getValue() const { return value_; }
|
||||||
|
bool isEnabled() const { return state_ != FadeState::NOT_ENABLED; }
|
||||||
|
bool hasEnded() const { return state_ == FadeState::FINISHED; }
|
||||||
|
|
||||||
|
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
|
||||||
|
|
||||||
|
// --- 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
|
||||||
|
|
||||||
|
// --- 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)
|
||||||
|
|
||||||
|
// --- Métodos internos ---
|
||||||
|
void init(); // Inicializa variables
|
||||||
|
void cleanBackbuffer(Uint8 r, Uint8 g, Uint8 b, Uint8 a); // Limpia el backbuffer
|
||||||
|
int calculateValue(int min, int max, int current); // Calcula el valor del fade
|
||||||
};
|
};
|
||||||
412
source/game.h
412
source/game.h
@@ -10,23 +10,24 @@
|
|||||||
#include "options.h" // Para GameOptions, Options, options
|
#include "options.h" // Para GameOptions, Options, options
|
||||||
#include "player.h" // Para Player
|
#include "player.h" // Para Player
|
||||||
#include "utils.h" // Para Demo
|
#include "utils.h" // Para Demo
|
||||||
|
|
||||||
class Audio;
|
class Audio;
|
||||||
class Asset; // lines 14-14
|
class Asset;
|
||||||
class Background; // lines 15-15
|
class Background;
|
||||||
class BalloonManager; // lines 16-16
|
class BalloonManager;
|
||||||
class Bullet; // lines 18-18
|
class Tabe;
|
||||||
class Fade; // lines 19-19
|
class Bullet;
|
||||||
class Input; // lines 20-20
|
class Fade;
|
||||||
class Item; // lines 21-21
|
class Input;
|
||||||
class PathSprite; // lines 22-22
|
class Item;
|
||||||
class Scoreboard; // lines 23-23
|
class PathSprite;
|
||||||
class Screen; // lines 24-24
|
class Scoreboard;
|
||||||
class SmartSprite; // lines 25-25
|
class Screen;
|
||||||
class Tabe; // lines 17-17
|
class SmartSprite;
|
||||||
class Texture; // lines 26-26
|
class Texture;
|
||||||
enum class BulletType : Uint8; // lines 27-27
|
enum class BulletType : Uint8;
|
||||||
enum class ItemType; // lines 28-28
|
enum class ItemType;
|
||||||
struct Path; // lines 29-29
|
struct Path;
|
||||||
|
|
||||||
// Modo demo
|
// Modo demo
|
||||||
constexpr bool GAME_MODE_DEMO_OFF = false;
|
constexpr bool GAME_MODE_DEMO_OFF = false;
|
||||||
@@ -35,37 +36,21 @@ constexpr bool GAME_MODE_DEMO_ON = true;
|
|||||||
// Cantidad de elementos a escribir en los ficheros de datos
|
// Cantidad de elementos a escribir en los ficheros de datos
|
||||||
constexpr int TOTAL_SCORE_DATA = 3;
|
constexpr int TOTAL_SCORE_DATA = 3;
|
||||||
|
|
||||||
/*
|
|
||||||
Esta clase gestiona un estado del programa. Se encarga de toda la parte en la
|
|
||||||
que se está jugando.
|
|
||||||
|
|
||||||
Tiene:
|
|
||||||
- Cacheadas todas las texturas y animaciones que usaran los diferentes objetos.
|
|
||||||
Mediante el método loadMedia() almacena en vectores todos los recursos
|
|
||||||
- Tiene vectores con objetos: jugadores, enemigos, balas, explosiones, objetos y otros (sprites con los puntos al coger objetos)
|
|
||||||
- Se encarga de comprobar las colisiones entre los diferentes objetos, los marca como deshabilitados si es el caso y
|
|
||||||
luego revisa los vectores para eliminar los objetos deshabilitados
|
|
||||||
|
|
||||||
Utiliza:
|
|
||||||
- Un objeto para dibujar el fondo animado
|
|
||||||
- Un objeto para dibujar el marcador
|
|
||||||
|
|
||||||
La clase comprueba el nivel de amenaza que hay en pantalla contando el número de enemigos y su peligrosidad y actua en consecuencia:
|
|
||||||
- Generando items
|
|
||||||
- Generando nuevas oleadas enemigas
|
|
||||||
|
|
||||||
Mientras haya un jugador activo siempre puede unirse un segundo jugador. Cada vez que un jugador muere
|
|
||||||
aparece una cuenta atras para permitirle continuar. Si la cuenta atras de ambos jugadores llega a cero,
|
|
||||||
el juego termina. Cuando ambos jugadores han finalizado, se permite introducir nombre para la tabla de records
|
|
||||||
adjuntando la máxima puntuación obtenida en la partida, solo en caso de que hayan conseguido superar la
|
|
||||||
puntuación mínima.
|
|
||||||
*/
|
|
||||||
|
|
||||||
// Clase Game
|
// Clase Game
|
||||||
class Game
|
class Game
|
||||||
{
|
{
|
||||||
|
public:
|
||||||
|
// Constructor
|
||||||
|
Game(int playerID, int current_stage, bool demo);
|
||||||
|
|
||||||
|
// Destructor
|
||||||
|
~Game();
|
||||||
|
|
||||||
|
// Bucle principal del juego
|
||||||
|
void run();
|
||||||
|
|
||||||
private:
|
private:
|
||||||
// Enum
|
// --- Tipos internos ---
|
||||||
enum class GameState
|
enum class GameState
|
||||||
{
|
{
|
||||||
FADE_IN,
|
FADE_IN,
|
||||||
@@ -76,14 +61,12 @@ private:
|
|||||||
GAME_OVER,
|
GAME_OVER,
|
||||||
};
|
};
|
||||||
|
|
||||||
// Contadores
|
// --- Constantes internas ---
|
||||||
static constexpr int HELP_COUNTER_ = 1000;
|
static constexpr int HELP_COUNTER_ = 1000;
|
||||||
static constexpr int GAME_COMPLETED_START_FADE_ = 500;
|
static constexpr int GAME_COMPLETED_START_FADE_ = 500;
|
||||||
static constexpr int GAME_COMPLETED_END_ = 700;
|
static constexpr int GAME_COMPLETED_END_ = 700;
|
||||||
static constexpr int GAME_OVER_COUNTER_ = 350;
|
static constexpr int GAME_OVER_COUNTER_ = 350;
|
||||||
static constexpr int TIME_STOPPED_COUNTER_ = 360;
|
static constexpr int TIME_STOPPED_COUNTER_ = 360;
|
||||||
|
|
||||||
// Porcentaje de aparición de los objetos
|
|
||||||
static constexpr int ITEM_POINTS_1_DISK_ODDS_ = 10;
|
static constexpr int ITEM_POINTS_1_DISK_ODDS_ = 10;
|
||||||
static constexpr int ITEM_POINTS_2_GAVINA_ODDS_ = 6;
|
static constexpr int ITEM_POINTS_2_GAVINA_ODDS_ = 6;
|
||||||
static constexpr int ITEM_POINTS_3_PACMAR_ODDS_ = 3;
|
static constexpr int ITEM_POINTS_3_PACMAR_ODDS_ = 3;
|
||||||
@@ -92,7 +75,7 @@ private:
|
|||||||
static constexpr int ITEM_POWER_BALL_ODDS_ = 0;
|
static constexpr int ITEM_POWER_BALL_ODDS_ = 0;
|
||||||
static constexpr int ITEM_COFFEE_MACHINE_ODDS_ = 4;
|
static constexpr int ITEM_COFFEE_MACHINE_ODDS_ = 4;
|
||||||
|
|
||||||
// Estructuras
|
// --- Estructuras ---
|
||||||
struct Helper
|
struct Helper
|
||||||
{
|
{
|
||||||
bool need_coffee; // Indica si se necesitan cafes
|
bool need_coffee; // Indica si se necesitan cafes
|
||||||
@@ -106,7 +89,6 @@ private:
|
|||||||
int item_coffee_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
|
int item_coffee_machine_odds; // Probabilidad de aparición del objeto
|
||||||
|
|
||||||
// Constructor con valores predeterminados
|
|
||||||
Helper()
|
Helper()
|
||||||
: need_coffee(false),
|
: need_coffee(false),
|
||||||
need_coffee_machine(false),
|
need_coffee_machine(false),
|
||||||
@@ -120,7 +102,7 @@ private:
|
|||||||
item_coffee_machine_odds(ITEM_COFFEE_MACHINE_ODDS_) {}
|
item_coffee_machine_odds(ITEM_COFFEE_MACHINE_ODDS_) {}
|
||||||
};
|
};
|
||||||
|
|
||||||
// Objetos y punteros
|
// --- Objetos y punteros ---
|
||||||
SDL_Renderer *renderer_; // El renderizador de la ventana
|
SDL_Renderer *renderer_; // El renderizador de la ventana
|
||||||
Screen *screen_; // Objeto encargado de dibujar en pantalla
|
Screen *screen_; // Objeto encargado de dibujar en pantalla
|
||||||
Input *input_; // Manejador de entrada
|
Input *input_; // Manejador de entrada
|
||||||
@@ -134,11 +116,11 @@ private:
|
|||||||
std::vector<std::unique_ptr<Bullet>> bullets_; // Vector con las balas
|
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<Item>> items_; // Vector con los items
|
||||||
std::vector<std::unique_ptr<SmartSprite>> smart_sprites_; // Vector con los smartsprites
|
std::vector<std::unique_ptr<SmartSprite>> smart_sprites_; // Vector con los smartsprites
|
||||||
std::vector<std::unique_ptr<PathSprite>> path_sprites_; // Vector con los smartsprites
|
std::vector<std::unique_ptr<PathSprite>> path_sprites_; // Vector con los pathsprites
|
||||||
|
|
||||||
std::shared_ptr<Texture> bullet_texture_; // Textura para las balas
|
std::shared_ptr<Texture> bullet_texture_; // Textura para las balas
|
||||||
std::vector<std::shared_ptr<Texture>> item_textures_; // Vector con las texturas de los items
|
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::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
|
||||||
|
|
||||||
@@ -151,7 +133,7 @@ private:
|
|||||||
std::unique_ptr<Tabe> tabe_; // Objeto para gestionar el Tabe Volaor
|
std::unique_ptr<Tabe> tabe_; // Objeto para gestionar el Tabe Volaor
|
||||||
std::vector<Path> paths_; // Vector con los recorridos precalculados almacenados
|
std::vector<Path> paths_; // Vector con los recorridos precalculados almacenados
|
||||||
|
|
||||||
// Variables
|
// --- Variables de estado ---
|
||||||
HiScoreEntry hi_score_ = HiScoreEntry(
|
HiScoreEntry hi_score_ = HiScoreEntry(
|
||||||
options.game.hi_score_table[0].name,
|
options.game.hi_score_table[0].name,
|
||||||
options.game.hi_score_table[0].score); // Máxima puntuación y nombre de quien la ostenta
|
options.game.hi_score_table[0].score); // Máxima puntuación y nombre de quien la ostenta
|
||||||
@@ -172,6 +154,7 @@ private:
|
|||||||
int menace_current_ = 0; // Nivel de amenaza actual
|
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
|
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
|
GameState state_ = GameState::FADE_IN; // Estado
|
||||||
|
|
||||||
#ifdef DEBUG
|
#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
|
||||||
|
|
||||||
@@ -179,250 +162,87 @@ private:
|
|||||||
void checkDebugEvents(const SDL_Event &event);
|
void checkDebugEvents(const SDL_Event &event);
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
// Actualiza el juego
|
// --- Métodos internos ---
|
||||||
void update();
|
|
||||||
|
void update(); // Actualiza el juego
|
||||||
// Dibuja el juego
|
void render(); // Dibuja el juego
|
||||||
void render();
|
void checkEvents(); // Comprueba los eventos que hay en cola
|
||||||
|
void setResources(); // Asigna texturas y animaciones
|
||||||
// Comprueba los eventos que hay en cola
|
void updateHiScore(); // Actualiza el valor de HiScore en caso necesario
|
||||||
void checkEvents();
|
void updatePlayers(); // Actualiza las variables del jugador
|
||||||
|
void renderPlayers(); // Dibuja a los jugadores
|
||||||
// Asigna texturas y animaciones
|
void updateStage(); // Comprueba si hay cambio de fase y actualiza las variables
|
||||||
void setResources();
|
void updateGameStateGameOver(); // Actualiza el estado de fin de la partida
|
||||||
|
void destroyAllItems(); // Destruye todos los items
|
||||||
// Actualiza el valor de HiScore en caso necesario
|
bool checkPlayerBalloonCollision(std::shared_ptr<Player> &player); // Comprueba la colisión entre el jugador y los globos activos
|
||||||
void updateHiScore();
|
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
|
||||||
// Actualiza las variables del jugador
|
void updateBullets(); // Mueve las balas activas
|
||||||
void updatePlayers();
|
void renderBullets(); // Pinta las balas activas
|
||||||
|
void createBullet(int x, int y, BulletType kind, bool powered_up, int owner); // Crea un objeto bala
|
||||||
// Dibuja a los jugadores
|
void freeBullets(); // Vacia el vector de balas
|
||||||
void renderPlayers();
|
void updateItems(); // Actualiza los items
|
||||||
|
void renderItems(); // Pinta los items activos
|
||||||
// Comprueba si hay cambio de fase y actualiza las variables
|
ItemType dropItem(); // Devuelve un item en función del azar
|
||||||
void updateStage();
|
void createItem(ItemType type, float x, float y); // Crea un objeto item
|
||||||
|
void freeItems(); // Vacia el vector de items
|
||||||
// Actualiza el estado de fin de la partida
|
void createItemText(int x, std::shared_ptr<Texture> texture); // Crea un objeto PathSprite
|
||||||
void updateGameStateGameOver();
|
void createMessage(const std::vector<Path> &paths, std::shared_ptr<Texture> texture); // Crea un objeto PathSprite
|
||||||
|
void freeSmartSprites(); // Vacia el vector de smartsprites
|
||||||
// Destruye todos los items
|
void freePathSprites(); // Vacia el vector de pathsprites
|
||||||
void destroyAllItems();
|
void throwCoffee(int x, int y); // Crea un SpriteSmart para arrojar el item café al recibir un impacto
|
||||||
|
void updateSmartSprites(); // Actualiza los SpriteSmarts
|
||||||
// Comprueba la colisión entre el jugador y los globos activos
|
void renderSmartSprites(); // Pinta los SpriteSmarts activos
|
||||||
bool checkPlayerBalloonCollision(std::shared_ptr<Player> &player);
|
void updatePathSprites(); // Actualiza los PathSprites
|
||||||
|
void renderPathSprites(); // Pinta los PathSprites activos
|
||||||
// Comprueba la colisión entre el jugador y los items
|
void killPlayer(std::shared_ptr<Player> &player); // Acciones a realizar cuando el jugador muere
|
||||||
void checkPlayerItemCollision(std::shared_ptr<Player> &player);
|
void updateTimeStopped(); // Actualiza y comprueba el valor de la variable
|
||||||
|
void updateBackground(); // Actualiza el fondo
|
||||||
// Comprueba y procesa la colisión de las balas
|
void initPaths(); // Inicializa las variables que contienen puntos de ruta para mover objetos
|
||||||
void checkBulletCollision();
|
void enableTimeStopItem(); // Habilita el efecto del item de detener el tiempo
|
||||||
|
void disableTimeStopItem(); // Deshabilita el efecto del item de detener el tiempo
|
||||||
// Mueve las balas activas
|
void updateHelper(); // Actualiza las variables de ayuda
|
||||||
void updateBullets();
|
bool allPlayersAreWaitingOrGameOver(); // Comprueba si todos los jugadores han terminado de jugar
|
||||||
|
bool allPlayersAreGameOver(); // Comprueba si todos los jugadores han terminado de jugar
|
||||||
// Pinta las balas activas
|
bool allPlayersAreNotPlaying(); // Comprueba si todos los jugadores han terminado de jugar
|
||||||
void renderBullets();
|
void updateScoreboard(); // Actualiza el marcador
|
||||||
|
void fillCanvas(); // Dibuja los elementos de la zona de juego en su textura
|
||||||
// Crea un objeto bala
|
void pause(bool value); // Pausa el juego
|
||||||
void createBullet(int x, int y, BulletType kind, bool powered_up, int owner);
|
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
|
||||||
// Vacia el vector de balas
|
void checkPlayersStatusPlaying(); // Comprueba el estado de juego de los jugadores
|
||||||
void freeBullets();
|
std::shared_ptr<Player> getPlayer(int id); // Obtiene un jugador a partir de su "id"
|
||||||
|
int getController(int playerId); // Obtiene un controlador a partir del "id" del jugador
|
||||||
// Actualiza los items
|
void checkInput(); // Gestiona la entrada durante el juego
|
||||||
void updateItems();
|
void checkPauseInput(); // Verifica si alguno de los controladores ha solicitado una pausa y actualiza el estado de pausa del juego.
|
||||||
|
void handleDemoMode(); // Gestiona las entradas de los jugadores en el modo demo, incluyendo movimientos y disparos automáticos.
|
||||||
// Pinta los items activos
|
void handleDemoPlayerInput(const std::shared_ptr<Player> &player, int index); // Procesa las entradas para un jugador específico durante el modo demo.
|
||||||
void renderItems();
|
void handleFireInput(const std::shared_ptr<Player> &player, BulletType bulletType); // 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).
|
||||||
// Devuelve un item en función del azar
|
void handleNormalPlayerInput(const std::shared_ptr<Player> &player); // Maneja las entradas de movimiento y disparo para un jugador en modo normal.
|
||||||
ItemType dropItem();
|
void handleFireInputs(const std::shared_ptr<Player> &player, bool autofire, int controllerIndex); // 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.
|
||||||
// Crea un objeto item
|
void handleNameInput(const std::shared_ptr<Player> &player); // Procesa las entradas para la introducción del nombre del jugador.
|
||||||
void createItem(ItemType type, float x, float y);
|
void initDemo(int player_id); // Inicializa las variables para el modo DEMO
|
||||||
|
void setTotalPower(); // Calcula el poder total necesario para completar el juego
|
||||||
// Vacia el vector de items
|
void initScoreboard(); // Inicializa el marcador
|
||||||
void freeItems();
|
void initDifficultyVars(); // Inicializa las opciones relacionadas con la dificultad
|
||||||
|
void initPlayers(int player_id); // Inicializa los jugadores
|
||||||
// Crea un objeto PathSprite
|
void playMusic(); // Hace sonar la música
|
||||||
void createItemText(int x, std::shared_ptr<Texture> texture);
|
void stopMusic(); // Detiene la música
|
||||||
|
void updateDemo(); // Actualiza las variables durante el modo demo
|
||||||
// Crea un objeto PathSprite
|
|
||||||
void createMessage(const std::vector<Path> &paths, std::shared_ptr<Texture> texture);
|
|
||||||
|
|
||||||
// Vacia el vector de smartsprites
|
|
||||||
void freeSmartSprites();
|
|
||||||
|
|
||||||
// Vacia el vector de pathsprites
|
|
||||||
void freePathSprites();
|
|
||||||
|
|
||||||
// Crea un SpriteSmart para arrojar el item café al recibir un impacto
|
|
||||||
void throwCoffee(int x, int y);
|
|
||||||
|
|
||||||
// Actualiza los SpriteSmarts
|
|
||||||
void updateSmartSprites();
|
|
||||||
|
|
||||||
// Pinta los SpriteSmarts activos
|
|
||||||
void renderSmartSprites();
|
|
||||||
|
|
||||||
// Actualiza los PathSprites
|
|
||||||
void updatePathSprites();
|
|
||||||
|
|
||||||
// Pinta los PathSprites activos
|
|
||||||
void renderPathSprites();
|
|
||||||
|
|
||||||
// Acciones a realizar cuando el jugador muere
|
|
||||||
void killPlayer(std::shared_ptr<Player> &player);
|
|
||||||
|
|
||||||
// Actualiza y comprueba el valor de la variable
|
|
||||||
void updateTimeStopped();
|
|
||||||
|
|
||||||
// Actualiza el fondo
|
|
||||||
void updateBackground();
|
|
||||||
|
|
||||||
// Inicializa las variables que contienen puntos de ruta para mover objetos
|
|
||||||
void initPaths();
|
|
||||||
|
|
||||||
// Habilita el efecto del item de detener el tiempo
|
|
||||||
void enableTimeStopItem();
|
|
||||||
|
|
||||||
// Deshabilita el efecto del item de detener el tiempo
|
|
||||||
void disableTimeStopItem();
|
|
||||||
|
|
||||||
// Actualiza las variables de ayuda
|
|
||||||
void updateHelper();
|
|
||||||
|
|
||||||
// Comprueba si todos los jugadores han terminado de jugar
|
|
||||||
bool allPlayersAreWaitingOrGameOver();
|
|
||||||
|
|
||||||
// Comprueba si todos los jugadores han terminado de jugar
|
|
||||||
bool allPlayersAreGameOver();
|
|
||||||
|
|
||||||
// Comprueba si todos los jugadores han terminado de jugar
|
|
||||||
bool allPlayersAreNotPlaying();
|
|
||||||
|
|
||||||
// Actualiza el marcador
|
|
||||||
void updateScoreboard();
|
|
||||||
|
|
||||||
// Dibuja los elementos de la zona de juego en su textura
|
|
||||||
void fillCanvas();
|
|
||||||
|
|
||||||
// Pausa el juego
|
|
||||||
void pause(bool value);
|
|
||||||
|
|
||||||
// Añade una puntuación a la tabla de records
|
|
||||||
void addScoreToScoreBoard(const std::shared_ptr<Player> &player);
|
|
||||||
|
|
||||||
// Saca del estado de GAME OVER al jugador si el otro está activo
|
|
||||||
void checkAndUpdatePlayerStatus(int active_player_index, int inactive_player_index);
|
|
||||||
|
|
||||||
// Comprueba el estado de juego de los jugadores
|
|
||||||
void checkPlayersStatusPlaying();
|
|
||||||
|
|
||||||
// Obtiene un jugador a partir de su "id"
|
|
||||||
std::shared_ptr<Player> getPlayer(int id);
|
|
||||||
|
|
||||||
// Obtiene un controlador a partir del "id" del jugador
|
|
||||||
int getController(int playerId);
|
|
||||||
|
|
||||||
// Gestiona la entrada durante el juego
|
|
||||||
void checkInput();
|
|
||||||
|
|
||||||
// Verifica si alguno de los controladores ha solicitado una pausa y actualiza el estado de pausa del juego.
|
|
||||||
void checkPauseInput();
|
|
||||||
|
|
||||||
// Gestiona las entradas de los jugadores en el modo demo, incluyendo movimientos y disparos automáticos.
|
|
||||||
void handleDemoMode();
|
|
||||||
|
|
||||||
// Procesa las entradas para un jugador específico durante el modo demo.
|
|
||||||
void handleDemoPlayerInput(const std::shared_ptr<Player> &player, int index);
|
|
||||||
|
|
||||||
// Maneja el disparo de un jugador, incluyendo la creación de balas y la gestión del tiempo de espera entre disparos.
|
|
||||||
void handleFireInput(const std::shared_ptr<Player> &player, BulletType bulletType);
|
|
||||||
|
|
||||||
// Gestiona las entradas de todos los jugadores en el modo normal (fuera del modo demo).
|
|
||||||
void handlePlayersInput();
|
|
||||||
|
|
||||||
// Maneja las entradas de movimiento y disparo para un jugador en modo normal.
|
|
||||||
void handleNormalPlayerInput(const std::shared_ptr<Player> &player);
|
|
||||||
|
|
||||||
// Procesa las entradas de disparo del jugador, permitiendo disparos automáticos si está habilitado.
|
|
||||||
void handleFireInputs(const std::shared_ptr<Player> &player, bool autofire, int controllerIndex);
|
|
||||||
|
|
||||||
// Maneja la continuación del jugador cuando no está jugando, permitiendo que continúe si se pulsa el botón de inicio.
|
|
||||||
void handlePlayerContinue(const std::shared_ptr<Player> &player);
|
|
||||||
|
|
||||||
// Procesa las entradas para la introducción del nombre del jugador.
|
|
||||||
void handleNameInput(const std::shared_ptr<Player> &player);
|
|
||||||
|
|
||||||
// Inicializa las variables para el modo DEMO
|
|
||||||
void initDemo(int player_id);
|
|
||||||
|
|
||||||
// Calcula el poder total necesario para completar el juego
|
|
||||||
void setTotalPower();
|
|
||||||
|
|
||||||
// Inicializa el marcador
|
|
||||||
void initScoreboard();
|
|
||||||
|
|
||||||
// Inicializa las opciones relacionadas con la dificultad
|
|
||||||
void initDifficultyVars();
|
|
||||||
|
|
||||||
// Inicializa los jugadores
|
|
||||||
void initPlayers(int player_id);
|
|
||||||
|
|
||||||
// Hace sonar la música
|
|
||||||
void playMusic();
|
|
||||||
|
|
||||||
// Detiene la música
|
|
||||||
void stopMusic();
|
|
||||||
|
|
||||||
// Actualiza las variables durante el modo demo
|
|
||||||
void updateDemo();
|
|
||||||
#ifdef RECORDING
|
#ifdef RECORDING
|
||||||
// Actualiza las variables durante el modo de grabación
|
void updateRecording(); // Actualiza las variables durante el modo de grabación
|
||||||
void updateRecording();
|
|
||||||
#endif
|
#endif
|
||||||
// Actualiza las variables durante dicho estado
|
void updateGameStateFadeIn(); // Actualiza las variables durante dicho estado
|
||||||
void updateGameStateFadeIn();
|
void updateGameStateEnteringPlayer(); // Actualiza las variables durante dicho estado
|
||||||
|
void updateGameStateShowingGetReadyMessage(); // Actualiza las variables durante dicho estado
|
||||||
// Actualiza las variables durante dicho estado
|
void updateGameStatePlaying(); // Actualiza las variables durante el transcurso normal del juego
|
||||||
void updateGameStateEnteringPlayer();
|
void updateGameStateCompleted(); // Gestiona eventos para el estado del final del juego
|
||||||
|
void checkState(); // Comprueba el estado del juego
|
||||||
// Actualiza las variables durante dicho estado
|
void cleanVectors(); // Vacía los vectores de elementos deshabilitados
|
||||||
void updateGameStateShowingGetReadyMessage();
|
void updateMenace(); // Gestiona el nivel de amenaza
|
||||||
|
void evaluateAndSetMenace(); // Calcula y establece el valor de amenaza en funcion de los globos activos
|
||||||
// Actualiza las variables durante el transcurso normal del juego
|
void checkAndUpdateBalloonSpeed(); // Actualiza la velocidad de los globos en funcion del poder acumulado de la fase
|
||||||
void updateGameStatePlaying();
|
void setState(GameState state); // Cambia el estado del juego
|
||||||
|
|
||||||
// Gestiona eventos para el estado del final del juego
|
|
||||||
void updateGameStateCompleted();
|
|
||||||
|
|
||||||
// Comprueba el estado del juego
|
|
||||||
void checkState();
|
|
||||||
|
|
||||||
// Vacía los vectores de elementos deshabilitados
|
|
||||||
void cleanVectors();
|
|
||||||
|
|
||||||
// Gestiona el nivel de amenaza
|
|
||||||
void updateMenace();
|
|
||||||
|
|
||||||
// Calcula y establece el valor de amenaza en funcion de los globos activos
|
|
||||||
void evaluateAndSetMenace();
|
|
||||||
|
|
||||||
// Actualiza la velocidad de los globos en funcion del poder acumulado de la fase
|
|
||||||
void checkAndUpdateBalloonSpeed();
|
|
||||||
|
|
||||||
// Cambia el estado del juego
|
|
||||||
void setState(GameState state);
|
|
||||||
|
|
||||||
public:
|
|
||||||
// Constructor
|
|
||||||
Game(int playerID, int current_stage, bool demo);
|
|
||||||
|
|
||||||
// Destructor
|
|
||||||
~Game();
|
|
||||||
|
|
||||||
// Bucle para el juego
|
|
||||||
void run();
|
|
||||||
};
|
};
|
||||||
@@ -4,12 +4,27 @@
|
|||||||
#include "animated_sprite.h" // Para AnimatedSprite
|
#include "animated_sprite.h" // Para AnimatedSprite
|
||||||
#include "smart_sprite.h" // Para SmartSprite
|
#include "smart_sprite.h" // Para SmartSprite
|
||||||
#include "sprite.h" // Para Sprite
|
#include "sprite.h" // Para Sprite
|
||||||
class Texture; // lines 7-7
|
|
||||||
|
class Texture;
|
||||||
|
|
||||||
// Clase GameLogo
|
// Clase GameLogo
|
||||||
class GameLogo
|
class GameLogo
|
||||||
{
|
{
|
||||||
|
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
|
||||||
|
|
||||||
|
// --- Getters ---
|
||||||
|
bool hasFinished() const; // Indica si ha terminado la animación
|
||||||
|
|
||||||
private:
|
private:
|
||||||
|
// --- Tipos internos ---
|
||||||
enum class Status
|
enum class Status
|
||||||
{
|
{
|
||||||
DISABLED,
|
DISABLED,
|
||||||
@@ -25,16 +40,12 @@ private:
|
|||||||
int lenght = 8; // Cantidad de desplazamientos a realizar
|
int lenght = 8; // Cantidad de desplazamientos a realizar
|
||||||
int remaining = lenght; // Cantidad de desplazamientos pendientes a realizar
|
int remaining = lenght; // Cantidad de desplazamientos pendientes a realizar
|
||||||
int counter = delay; // Contador para el retraso
|
int counter = delay; // Contador para el retraso
|
||||||
int origin = 0; // Valor inicial de la pantalla para dejarla igual tras el desplazamiento
|
int origin = 0; // Valor inicial de la pantalla para dejarla igual tras el desplazamiento
|
||||||
|
|
||||||
// Constructor por defect
|
|
||||||
Shake() = default;
|
Shake() = default;
|
||||||
|
|
||||||
// Constructor
|
|
||||||
Shake(int d, int de, int l, int o)
|
Shake(int d, int de, int l, int o)
|
||||||
: desp(d), delay(de), lenght(l), remaining(l), counter(de), origin(o) {}
|
: desp(d), delay(de), lenght(l), remaining(l), counter(de), origin(o) {}
|
||||||
|
|
||||||
// Inicializa los miembros
|
|
||||||
void init(int d, int de, int l, int o)
|
void init(int d, int de, int l, int o)
|
||||||
{
|
{
|
||||||
desp = d;
|
desp = d;
|
||||||
@@ -46,52 +57,29 @@ private:
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// Objetos y punteros
|
// --- Objetos y punteros ---
|
||||||
std::shared_ptr<Texture> dust_texture_; // Textura con los graficos del polvo
|
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> coffee_texture_; // Textura con los graficos de la palabra "COFFEE"
|
||||||
std::shared_ptr<Texture> crisis_texture_; // Textura con los graficos de la plabra "CRISIS"
|
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::shared_ptr<Texture> arcade_edition_texture_; // Textura con los graficos de "Arcade Edition"
|
||||||
|
|
||||||
std::unique_ptr<AnimatedSprite> dust_left_sprite_; // Sprite con la el polvo que aparece al colisionar el texto de la pantalla de titulo
|
std::unique_ptr<AnimatedSprite> dust_left_sprite_; // Sprite del polvo (izquierda)
|
||||||
std::unique_ptr<AnimatedSprite> dust_right_sprite_; // Sprite con la el polvo que aparece al colisionar el texto de la pantalla de titulo
|
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<SmartSprite> coffee_sprite_; // Sprite con la palabra "COFFEE" para la pantalla de titulo
|
// --- Variables de estado ---
|
||||||
std::unique_ptr<SmartSprite> crisis_sprite_; // Sprite con la palabra "CRISIS" para la pantalla de titulo
|
float x_; // Posición X del logo
|
||||||
|
float y_; // Posición Y del logo
|
||||||
std::unique_ptr<Sprite> arcade_edition_sprite_; // Sprite con los graficos de "Arcade Edition"
|
|
||||||
|
|
||||||
// Variables
|
|
||||||
float x_; // Posición donde dibujar el logo
|
|
||||||
float y_; // Posición donde dibujar el logo
|
|
||||||
float zoom_ = 1.0f; // Zoom aplicado al texto "ARCADE EDITION"
|
float zoom_ = 1.0f; // Zoom aplicado al texto "ARCADE EDITION"
|
||||||
int post_finished_counter_ = 1; // Contador final una vez terminada las animaciones de los logos
|
int post_finished_counter_ = 1; // Contador final tras animaciones
|
||||||
|
|
||||||
Status coffee_crisis_status_ = Status::DISABLED; // Estado en el que se encuentra el texto "COFFEE CRISIS"
|
Status coffee_crisis_status_ = Status::DISABLED; // Estado de "COFFEE CRISIS"
|
||||||
Status arcade_edition_status_ = Status::DISABLED; // Estado en el que se encuentra el texto "ARCADE_EDITION"
|
Status arcade_edition_status_ = Status::DISABLED; // Estado de "ARCADE EDITION"
|
||||||
Shake shake_; // Estructura para generar el efecto de agitación
|
Shake shake_; // Efecto de agitación
|
||||||
|
|
||||||
// Inicializa las variables
|
// --- Métodos internos ---
|
||||||
void init();
|
void init(); // Inicializa las variables
|
||||||
|
int getInitialVerticalDesp(); // Calcula el desplazamiento vertical inicial
|
||||||
// Calcula el desplazamiento vertical inicial
|
|
||||||
int getInitialVerticalDesp();
|
|
||||||
|
|
||||||
public:
|
|
||||||
// Constructor
|
|
||||||
GameLogo(int x, int y);
|
|
||||||
|
|
||||||
// Destructor
|
|
||||||
~GameLogo() = default;
|
|
||||||
|
|
||||||
// Pinta la clase en pantalla
|
|
||||||
void render();
|
|
||||||
|
|
||||||
// Actualiza la lógica de la clase
|
|
||||||
void update();
|
|
||||||
|
|
||||||
// Activa la clase
|
|
||||||
void enable();
|
|
||||||
|
|
||||||
// Indica si ha terminado la animación
|
|
||||||
bool hasFinished() const;
|
|
||||||
};
|
};
|
||||||
@@ -7,17 +7,18 @@
|
|||||||
#include <string> // Para string
|
#include <string> // Para string
|
||||||
#include <vector> // Para vector
|
#include <vector> // Para vector
|
||||||
#include "utils.h"
|
#include "utils.h"
|
||||||
class Background; // lines 10-10
|
|
||||||
class Fade; // lines 11-11
|
class Background;
|
||||||
|
class Fade;
|
||||||
class PathSprite;
|
class PathSprite;
|
||||||
class Sprite;
|
class Sprite;
|
||||||
enum class FadeMode : Uint8; // lines 13-13
|
enum class FadeMode : Uint8;
|
||||||
struct Path;
|
struct Path;
|
||||||
|
|
||||||
/*
|
/*
|
||||||
Esta clase gestiona un estado del programa. Se encarga de mostrar la tabla con las puntuaciones
|
Esta clase gestiona un estado del programa. Se encarga de mostrar la tabla con las puntuaciones
|
||||||
más altas. Para ello utiliza un objeto que se encarga de pintar el fondo y una textura
|
más altas. Para ello utiliza un objeto que se encarga de pintar el fondo y una textura
|
||||||
sobre la que escribe las puntuacions. Esta textura se recorre modificando la ventana de vista
|
sobre la que escribe las puntuaciones. Esta textura se recorre modificando la ventana de vista
|
||||||
para dar el efecto de que la textura se mueve sobre la pantalla.
|
para dar el efecto de que la textura se mueve sobre la pantalla.
|
||||||
|
|
||||||
Para mejorar la legibilidad de los textos, el objeto que dibuja el fondo es capaz de modificar
|
Para mejorar la legibilidad de los textos, el objeto que dibuja el fondo es capaz de modificar
|
||||||
@@ -27,73 +28,6 @@ struct Path;
|
|||||||
// Clase HiScoreTable
|
// Clase HiScoreTable
|
||||||
class HiScoreTable
|
class HiScoreTable
|
||||||
{
|
{
|
||||||
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
|
|
||||||
|
|
||||||
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 spritres 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
|
|
||||||
|
|
||||||
// Actualiza las variables
|
|
||||||
void update();
|
|
||||||
|
|
||||||
// Pinta en pantalla
|
|
||||||
void render();
|
|
||||||
|
|
||||||
// Comprueba los eventos
|
|
||||||
void checkEvents();
|
|
||||||
|
|
||||||
// Comprueba las entradas
|
|
||||||
void checkInput();
|
|
||||||
|
|
||||||
// Convierte un entero a un string con separadores de miles
|
|
||||||
std::string format(int number);
|
|
||||||
|
|
||||||
// Dibuja los sprites en la textura
|
|
||||||
void fillTexture();
|
|
||||||
|
|
||||||
// Gestiona el fade
|
|
||||||
void updateFade();
|
|
||||||
|
|
||||||
// Crea los sprites con los textos
|
|
||||||
void createSprites();
|
|
||||||
|
|
||||||
// Actualiza las posiciones de los sprites de texto
|
|
||||||
void updateSprites();
|
|
||||||
|
|
||||||
// Inicializa el fade
|
|
||||||
void initFade();
|
|
||||||
|
|
||||||
// Inicializa el fondo
|
|
||||||
void initBackground();
|
|
||||||
|
|
||||||
// Obtiene un color del vector de colores de entradas
|
|
||||||
Color getEntryColor(int counter_);
|
|
||||||
|
|
||||||
// Inicializa los colores de las entradas
|
|
||||||
void iniEntryColors();
|
|
||||||
|
|
||||||
// Hace brillar los nombres de la tabla de records
|
|
||||||
void glowEntryNames();
|
|
||||||
|
|
||||||
// Gestiona el contador
|
|
||||||
void updateCounter();
|
|
||||||
|
|
||||||
public:
|
public:
|
||||||
// Constructor
|
// Constructor
|
||||||
HiScoreTable();
|
HiScoreTable();
|
||||||
@@ -103,4 +37,43 @@ public:
|
|||||||
|
|
||||||
// Bucle principal
|
// Bucle principal
|
||||||
void run();
|
void run();
|
||||||
|
|
||||||
|
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
|
||||||
|
|
||||||
|
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
|
||||||
|
|
||||||
|
// --- Métodos internos ---
|
||||||
|
void update(); // Actualiza las variables
|
||||||
|
void render(); // Pinta en pantalla
|
||||||
|
void checkEvents(); // Comprueba los eventos
|
||||||
|
void checkInput(); // Comprueba las entradas
|
||||||
|
std::string format(int number); // 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
|
||||||
|
Color getEntryColor(int counter_); // 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
|
||||||
};
|
};
|
||||||
115
source/input.h
115
source/input.h
@@ -8,14 +8,15 @@
|
|||||||
#include <vector> // Para vector
|
#include <vector> // Para vector
|
||||||
|
|
||||||
/*
|
/*
|
||||||
connectedControllers es un vector donde estan todos los mandos encontrados [0 .. n]
|
connectedControllers es un vector donde están todos los mandos encontrados [0 .. n]
|
||||||
checkInput requiere de un indice para comprobar las pulsaciónes de un controlador en concreto [0 .. n]
|
checkInput requiere de un índice para comprobar las pulsaciones de un controlador en concreto [0 .. n]
|
||||||
device contiene el tipo de dispositivo a comprobar:
|
device contiene el tipo de dispositivo a comprobar:
|
||||||
InputDeviceToUse::KEYBOARD solo mirará el teclado
|
InputDeviceToUse::KEYBOARD solo mirará el teclado
|
||||||
InputDeviceToUse::CONTROLLER solo mirará el controlador especificado (Si no se especifica, el primero)
|
InputDeviceToUse::CONTROLLER solo mirará el controlador especificado (Si no se especifica, el primero)
|
||||||
InputDeviceToUse::ANY mirará tanto el teclado como el PRIMER controlador
|
InputDeviceToUse::ANY mirará tanto el teclado como el PRIMER controlador
|
||||||
*/
|
*/
|
||||||
|
|
||||||
|
// Acciones de entrada posibles en el juego
|
||||||
enum class InputAction : int
|
enum class InputAction : int
|
||||||
{
|
{
|
||||||
// Inputs de movimiento
|
// Inputs de movimiento
|
||||||
@@ -56,6 +57,7 @@ enum class InputAction : int
|
|||||||
constexpr bool INPUT_ALLOW_REPEAT = true;
|
constexpr bool INPUT_ALLOW_REPEAT = true;
|
||||||
constexpr bool INPUT_DO_NOT_ALLOW_REPEAT = false;
|
constexpr bool INPUT_DO_NOT_ALLOW_REPEAT = false;
|
||||||
|
|
||||||
|
// Tipos de dispositivos de entrada
|
||||||
enum class InputDeviceToUse : int
|
enum class InputDeviceToUse : int
|
||||||
{
|
{
|
||||||
KEYBOARD = 0,
|
KEYBOARD = 0,
|
||||||
@@ -63,55 +65,9 @@ enum class InputDeviceToUse : int
|
|||||||
ANY = 2,
|
ANY = 2,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// Clase Input: gestiona la entrada de teclado y mandos (singleton)
|
||||||
class Input
|
class Input
|
||||||
{
|
{
|
||||||
private:
|
|
||||||
// [SINGLETON] Objeto privado
|
|
||||||
static Input *input_;
|
|
||||||
|
|
||||||
struct KeyBindings
|
|
||||||
{
|
|
||||||
Uint8 scancode; // Scancode asociado
|
|
||||||
bool active; // Indica si está activo
|
|
||||||
|
|
||||||
// Constructor
|
|
||||||
explicit KeyBindings(Uint8 sc = 0, bool act = false)
|
|
||||||
: scancode(sc), active(act) {}
|
|
||||||
};
|
|
||||||
|
|
||||||
struct ControllerBindings
|
|
||||||
{
|
|
||||||
SDL_GamepadButton button; // GameControllerButton asociado
|
|
||||||
bool active; // Indica si está activo
|
|
||||||
bool axis_active; // Estado del eje
|
|
||||||
|
|
||||||
// Constructor
|
|
||||||
explicit ControllerBindings(SDL_GamepadButton btn = SDL_GAMEPAD_BUTTON_INVALID, bool act = false, bool axis_act = false)
|
|
||||||
: button(btn), active(act), axis_active(axis_act) {}
|
|
||||||
};
|
|
||||||
|
|
||||||
// Variables
|
|
||||||
std::vector<SDL_Gamepad *> connected_controllers_; // Vector con todos los mandos conectados
|
|
||||||
std::vector<SDL_Joystick *> joysticks_; // Vector con todos los joysticks conectados
|
|
||||||
std::vector<KeyBindings> key_bindings_; // Vector con las teclas asociadas a los inputs predefinidos
|
|
||||||
std::vector<std::vector<ControllerBindings>> controller_bindings_; // Vector con los botones asociadas a los inputs predefinidos para cada mando
|
|
||||||
std::vector<std::string> controller_names_; // Vector con los nombres de los mandos
|
|
||||||
std::vector<InputAction> button_inputs_; // Inputs asignados al jugador y a botones, excluyendo direcciones
|
|
||||||
int num_joysticks_ = 0; // Número de joysticks conectados
|
|
||||||
int num_gamepads_ = 0; // Número de mandos conectados
|
|
||||||
std::string game_controller_db_path_; // Ruta al archivo gamecontrollerdb.txt
|
|
||||||
|
|
||||||
void initSDL();
|
|
||||||
|
|
||||||
// Comprueba el eje del mando
|
|
||||||
bool checkAxisInput(InputAction input, int controller_index, bool repeat);
|
|
||||||
|
|
||||||
// Constructor
|
|
||||||
explicit Input(const std::string &game_controller_db_path);
|
|
||||||
|
|
||||||
// Destructor
|
|
||||||
~Input() = default;
|
|
||||||
|
|
||||||
public:
|
public:
|
||||||
// [SINGLETON] Crearemos el objeto con esta función estática
|
// [SINGLETON] Crearemos el objeto con esta función estática
|
||||||
static void init(const std::string &game_controller_db_path);
|
static void init(const std::string &game_controller_db_path);
|
||||||
@@ -129,10 +85,10 @@ public:
|
|||||||
void bindGameControllerButton(int controller_index, InputAction input, SDL_GamepadButton button);
|
void bindGameControllerButton(int controller_index, InputAction input, SDL_GamepadButton button);
|
||||||
void bindGameControllerButton(int controller_index, InputAction inputTarget, InputAction inputSource);
|
void bindGameControllerButton(int controller_index, InputAction inputTarget, InputAction inputSource);
|
||||||
|
|
||||||
// Comprueba si un input esta activo
|
// Comprueba si un input está activo
|
||||||
bool checkInput(InputAction input, bool repeat = true, InputDeviceToUse device = InputDeviceToUse::ANY, int controller_index = 0);
|
bool checkInput(InputAction input, bool repeat = true, InputDeviceToUse device = InputDeviceToUse::ANY, int controller_index = 0);
|
||||||
|
|
||||||
// Comprueba si hay almenos un input activo
|
// Comprueba si hay al menos un input activo
|
||||||
bool checkAnyInput(InputDeviceToUse device = InputDeviceToUse::ANY, int controller_index = 0);
|
bool checkAnyInput(InputDeviceToUse device = InputDeviceToUse::ANY, int controller_index = 0);
|
||||||
|
|
||||||
// Comprueba si hay algún botón pulsado
|
// Comprueba si hay algún botón pulsado
|
||||||
@@ -141,16 +97,16 @@ public:
|
|||||||
// Busca si hay mandos conectados
|
// Busca si hay mandos conectados
|
||||||
bool discoverGameControllers();
|
bool discoverGameControllers();
|
||||||
|
|
||||||
// Comprueba si hay algun mando conectado
|
// Comprueba si hay algún mando conectado
|
||||||
bool gameControllerFound();
|
bool gameControllerFound();
|
||||||
|
|
||||||
// Obten el número de mandos conectados
|
// Obtiene el número de mandos conectados
|
||||||
int getNumControllers() const;
|
int getNumControllers() const;
|
||||||
|
|
||||||
// Obten el nombre de un mando de juego
|
// Obtiene el nombre de un mando de juego
|
||||||
std::string getControllerName(int controller_index) const;
|
std::string getControllerName(int controller_index) const;
|
||||||
|
|
||||||
// Obtiene el indice del controlador a partir de un event.id
|
// Obtiene el índice del controlador a partir de un event.id
|
||||||
int getJoyIndex(SDL_JoystickID id) const;
|
int getJoyIndex(SDL_JoystickID id) const;
|
||||||
|
|
||||||
// Muestra por consola los controles asignados
|
// Muestra por consola los controles asignados
|
||||||
@@ -165,6 +121,53 @@ public:
|
|||||||
// Convierte un std::string a InputAction
|
// Convierte un std::string a InputAction
|
||||||
InputAction to_inputs_e(const std::string &name) const;
|
InputAction to_inputs_e(const std::string &name) const;
|
||||||
|
|
||||||
// Obtiene el indice a partir del nombre del mando
|
// Obtiene el índice a partir del nombre del mando
|
||||||
int getIndexByName(const std::string &name) const;
|
int getIndexByName(const std::string &name) const;
|
||||||
|
|
||||||
|
private:
|
||||||
|
// [SINGLETON] Objeto privado
|
||||||
|
static Input *input_;
|
||||||
|
|
||||||
|
// Estructura para asociar teclas a acciones
|
||||||
|
struct KeyBindings
|
||||||
|
{
|
||||||
|
Uint8 scancode; // Scancode asociado
|
||||||
|
bool active; // Indica si está activo
|
||||||
|
|
||||||
|
KeyBindings(Uint8 sc = 0, bool act = false)
|
||||||
|
: scancode(sc), active(act) {}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Estructura para asociar botones de mando a acciones
|
||||||
|
struct ControllerBindings
|
||||||
|
{
|
||||||
|
SDL_GamepadButton button; // GameControllerButton asociado
|
||||||
|
bool active; // Indica si está activo
|
||||||
|
bool axis_active; // Estado del eje
|
||||||
|
|
||||||
|
ControllerBindings(SDL_GamepadButton btn = SDL_GAMEPAD_BUTTON_INVALID, bool act = false, bool axis_act = false)
|
||||||
|
: button(btn), active(act), axis_active(axis_act) {}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Variables internas
|
||||||
|
std::vector<SDL_Gamepad *> connected_controllers_; // Vector con todos los mandos conectados
|
||||||
|
std::vector<SDL_Joystick *> joysticks_; // Vector con todos los joysticks conectados
|
||||||
|
std::vector<KeyBindings> key_bindings_; // Vector con las teclas asociadas a los inputs predefinidos
|
||||||
|
std::vector<std::vector<ControllerBindings>> controller_bindings_; // Vector con los botones asociados a los inputs predefinidos para cada mando
|
||||||
|
std::vector<std::string> controller_names_; // Vector con los nombres de los mandos
|
||||||
|
std::vector<InputAction> button_inputs_; // Inputs asignados al jugador y a botones, excluyendo direcciones
|
||||||
|
int num_joysticks_ = 0; // Número de joysticks conectados
|
||||||
|
int num_gamepads_ = 0; // Número de mandos conectados
|
||||||
|
std::string game_controller_db_path_; // Ruta al archivo gamecontrollerdb.txt
|
||||||
|
|
||||||
|
void initSDL(); // Inicializa SDL para la gestión de mandos
|
||||||
|
|
||||||
|
// Comprueba el eje del mando
|
||||||
|
bool checkAxisInput(InputAction input, int controller_index, bool repeat);
|
||||||
|
|
||||||
|
// Constructor privado
|
||||||
|
explicit Input(const std::string &game_controller_db_path);
|
||||||
|
|
||||||
|
// Destructor
|
||||||
|
~Input() = default;
|
||||||
};
|
};
|
||||||
@@ -5,26 +5,27 @@
|
|||||||
#include <SDL3/SDL_stdinc.h> // Para Uint32
|
#include <SDL3/SDL_stdinc.h> // Para Uint32
|
||||||
#include <memory> // Para unique_ptr, shared_ptr
|
#include <memory> // Para unique_ptr, shared_ptr
|
||||||
#include <vector> // Para vector
|
#include <vector> // Para vector
|
||||||
class Fade; // lines 8-8
|
|
||||||
class Sprite; // lines 9-9
|
class Fade;
|
||||||
class Text; // lines 10-10
|
class Sprite;
|
||||||
class Texture; // lines 11-11
|
class Text;
|
||||||
class TiledBG; // lines 12-12
|
class Texture;
|
||||||
|
class TiledBG;
|
||||||
|
|
||||||
/*
|
/*
|
||||||
Esta clase gestiona un estado del programa. Se encarga de poner en pantalla
|
Esta clase gestiona un estado del programa. Se encarga de poner en pantalla
|
||||||
un texto explicativo para entender como se juega.
|
un texto explicativo para entender cómo se juega.
|
||||||
|
|
||||||
Ademas muestra algunos items y explica para qué sirven.
|
Además muestra algunos items y explica para qué sirven.
|
||||||
|
|
||||||
Utiliza dos texturas de apoyo, una con el texto ya escrito y otra donde se combina
|
Utiliza dos texturas de apoyo, una con el texto ya escrito y otra donde se combina
|
||||||
tanto el texto de la primera textura como los sprites de los items.
|
tanto el texto de la primera textura como los sprites de los items.
|
||||||
|
|
||||||
Finalmente, una ventana recorre la textura para dar el efecto de que todo se desplaza
|
Finalmente, una ventana recorre la textura para dar el efecto de que todo se desplaza
|
||||||
por la pantalla sobre el mosaico de fondo (gestionado por el correspondiente objeto)
|
por la pantalla sobre el mosaico de fondo (gestionado por el correspondiente objeto).
|
||||||
*/
|
*/
|
||||||
|
|
||||||
// Estructura para almacenar información de línea
|
// Estructura para almacenar información de línea animada
|
||||||
struct Line
|
struct Line
|
||||||
{
|
{
|
||||||
int y; // Coordenada Y de la línea
|
int y; // Coordenada Y de la línea
|
||||||
@@ -40,8 +41,18 @@ struct Line
|
|||||||
// Clase Instructions
|
// Clase Instructions
|
||||||
class Instructions
|
class Instructions
|
||||||
{
|
{
|
||||||
|
public:
|
||||||
|
// Constructor
|
||||||
|
Instructions();
|
||||||
|
|
||||||
|
// Destructor
|
||||||
|
~Instructions();
|
||||||
|
|
||||||
|
// Bucle principal
|
||||||
|
void run();
|
||||||
|
|
||||||
private:
|
private:
|
||||||
// Objetos y punteros
|
// --- Objetos y punteros ---
|
||||||
SDL_Renderer *renderer_; // El renderizador de la ventana
|
SDL_Renderer *renderer_; // El renderizador de la ventana
|
||||||
SDL_Texture *texture_; // Textura fija con el texto
|
SDL_Texture *texture_; // Textura fija con el texto
|
||||||
SDL_Texture *backbuffer_; // Textura para usar como backbuffer
|
SDL_Texture *backbuffer_; // Textura para usar como backbuffer
|
||||||
@@ -52,7 +63,7 @@ private:
|
|||||||
std::unique_ptr<TiledBG> tiled_bg_; // Objeto para dibujar el mosaico animado de fondo
|
std::unique_ptr<TiledBG> tiled_bg_; // Objeto para dibujar el mosaico animado de fondo
|
||||||
std::unique_ptr<Fade> fade_; // Objeto para renderizar fades
|
std::unique_ptr<Fade> fade_; // Objeto para renderizar fades
|
||||||
|
|
||||||
// Variables
|
// --- Variables ---
|
||||||
int counter_ = 0; // Contador para manejar el progreso en la pantalla de instrucciones
|
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
|
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_FRect view_; // Vista del backbuffer que se va a mostrar por pantalla
|
||||||
@@ -63,49 +74,17 @@ private:
|
|||||||
Uint32 start_delay_time_ = 0; // Tiempo de inicio del retraso para mover las líneas
|
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
|
bool start_delay_triggered_ = false; // Bandera para determinar si el retraso ha comenzado
|
||||||
|
|
||||||
// Actualiza las variables
|
// --- Métodos internos ---
|
||||||
void update();
|
void update(); // Actualiza las variables
|
||||||
|
void render(); // Pinta en pantalla
|
||||||
// Pinta en pantalla
|
void checkEvents(); // Comprueba los eventos
|
||||||
void render();
|
void checkInput(); // Comprueba las entradas
|
||||||
|
void fillTexture(); // Rellena la textura de texto
|
||||||
// Comprueba los eventos
|
void fillBackbuffer(); // Rellena el backbuffer
|
||||||
void checkEvents();
|
void iniSprites(); // Inicializa los sprites de los items
|
||||||
|
void updateSprites(); // Actualiza los sprites
|
||||||
// Comprueba las entradas
|
std::vector<Line> initializeLines(int height); // Inicializa las líneas animadas
|
||||||
void checkInput();
|
bool moveLines(std::vector<Line> &lines, int width, float duration, Uint32 startDelay); // Mueve las líneas
|
||||||
|
void renderLines(SDL_Renderer *renderer, SDL_Texture *texture, const std::vector<Line> &lines); // Renderiza las líneas
|
||||||
// Rellena la textura de texto
|
void updateBackbuffer(); // Gestiona la textura con los gráficos
|
||||||
void fillTexture();
|
|
||||||
|
|
||||||
// Rellena el backbuffer
|
|
||||||
void fillBackbuffer();
|
|
||||||
|
|
||||||
// Inicializa los sprites de los items
|
|
||||||
void iniSprites();
|
|
||||||
|
|
||||||
// Actualiza los sprites
|
|
||||||
void updateSprites();
|
|
||||||
|
|
||||||
// Método para inicializar las líneas
|
|
||||||
std::vector<Line> initializeLines(int height);
|
|
||||||
|
|
||||||
// Método para mover las líneas
|
|
||||||
bool moveLines(std::vector<Line> &lines, int width, float duration, Uint32 startDelay);
|
|
||||||
|
|
||||||
// Método para renderizar las líneas
|
|
||||||
void renderLines(SDL_Renderer *renderer, SDL_Texture *texture, const std::vector<Line> &lines);
|
|
||||||
|
|
||||||
// Gestiona la textura con los graficos
|
|
||||||
void updateBackbuffer();
|
|
||||||
|
|
||||||
public:
|
|
||||||
// Constructor
|
|
||||||
Instructions();
|
|
||||||
|
|
||||||
// Destructor
|
|
||||||
~Instructions();
|
|
||||||
|
|
||||||
// Bucle principal
|
|
||||||
void run();
|
|
||||||
};
|
};
|
||||||
@@ -9,13 +9,24 @@
|
|||||||
|
|
||||||
/*
|
/*
|
||||||
Esta clase gestiona un estado del programa. Se encarga de mostrar la secuencia
|
Esta clase gestiona un estado del programa. Se encarga de mostrar la secuencia
|
||||||
de introducción
|
de introducción.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
// Clase Intro
|
// Clase Intro
|
||||||
class Intro
|
class Intro
|
||||||
{
|
{
|
||||||
|
public:
|
||||||
|
// Constructor
|
||||||
|
Intro();
|
||||||
|
|
||||||
|
// Destructor
|
||||||
|
~Intro() = default;
|
||||||
|
|
||||||
|
// Bucle principal
|
||||||
|
void run();
|
||||||
|
|
||||||
private:
|
private:
|
||||||
|
// --- Estados internos ---
|
||||||
enum class IntroState
|
enum class IntroState
|
||||||
{
|
{
|
||||||
SCENES,
|
SCENES,
|
||||||
@@ -28,63 +39,31 @@ private:
|
|||||||
END,
|
END,
|
||||||
};
|
};
|
||||||
|
|
||||||
// Objetos
|
// --- Objetos ---
|
||||||
std::vector<std::unique_ptr<PathSprite>> sprites_; // Vector con los sprites inteligentes para los dibujos de la intro
|
std::vector<std::unique_ptr<PathSprite>> 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<PathSprite>> shadow_sprites_; // Vector con los sprites inteligentes para las sombras
|
||||||
std::vector<std::unique_ptr<Writer>> texts_; // Textos de la intro
|
std::vector<std::unique_ptr<Writer>> texts_; // Textos de la intro
|
||||||
std::unique_ptr<TiledBG> tiled_bg_;
|
std::unique_ptr<TiledBG> tiled_bg_; // Fondo en mosaico
|
||||||
|
|
||||||
// Variables
|
// --- Variables ---
|
||||||
Uint64 ticks_ = 0; // Contador de ticks para ajustar la velocidad del programa
|
Uint64 ticks_ = 0; // Contador de ticks para ajustar la velocidad del programa
|
||||||
int scene_ = 0; // Indica que escena está activa
|
int scene_ = 0; // Indica qué escena está activa
|
||||||
IntroState state_ = IntroState::SCENES; // Estado
|
IntroState state_ = IntroState::SCENES; // Estado principal de la intro
|
||||||
IntroPostState post_state_ = IntroPostState::STOP_BG; // Estado
|
IntroPostState post_state_ = IntroPostState::STOP_BG; // Estado POST
|
||||||
Uint32 state_start_time_;
|
Uint32 state_start_time_; // Tiempo de inicio del estado actual
|
||||||
Uint8 bg_color_ = 112;
|
Uint8 bg_color_ = 112; // Color de fondo
|
||||||
|
|
||||||
// Actualiza las variables del objeto
|
// --- Métodos internos ---
|
||||||
void update();
|
void update(); // Actualiza las variables del objeto
|
||||||
|
void render(); // Dibuja el objeto en pantalla
|
||||||
// Dibuja el objeto en pantalla
|
void checkEvents(); // Comprueba los eventos
|
||||||
void render();
|
void checkInput(); // Comprueba las entradas
|
||||||
|
void updateScenes(); // Actualiza las escenas de la intro
|
||||||
// Comprueba los eventos
|
void initSprites(); // Inicializa las imágenes
|
||||||
void checkEvents();
|
void initTexts(); // Inicializa los textos
|
||||||
|
void updateSprites(); // Actualiza los sprites
|
||||||
// Comprueba las entradas
|
void updateTexts(); // Actualiza los textos
|
||||||
void checkInput();
|
void renderSprites(); // Dibuja los sprites
|
||||||
|
void renderTexts(); // Dibuja los textos
|
||||||
// Actualiza las escenas de la intro
|
void updatePostState(); // Actualiza el estado POST
|
||||||
void updateScenes();
|
|
||||||
|
|
||||||
// Inicializa las imagens
|
|
||||||
void initSprites();
|
|
||||||
|
|
||||||
// Inicializa los textos
|
|
||||||
void initTexts();
|
|
||||||
|
|
||||||
// Actualiza los sprites
|
|
||||||
void updateSprites();
|
|
||||||
|
|
||||||
// Actualiza los textos
|
|
||||||
void updateTexts();
|
|
||||||
|
|
||||||
// Dibuja los sprites
|
|
||||||
void renderSprites();
|
|
||||||
|
|
||||||
// Dibuja los textos
|
|
||||||
void renderTexts();
|
|
||||||
|
|
||||||
// Actualiza el estado POST
|
|
||||||
void updatePostState();
|
|
||||||
|
|
||||||
public:
|
|
||||||
// Constructor
|
|
||||||
Intro();
|
|
||||||
|
|
||||||
// Destructor
|
|
||||||
~Intro() = default;
|
|
||||||
|
|
||||||
// Bucle principal
|
|
||||||
void run();
|
|
||||||
};
|
};
|
||||||
|
|||||||
176
source/item.h
176
source/item.h
@@ -5,143 +5,49 @@
|
|||||||
#include <memory> // Para shared_ptr, unique_ptr
|
#include <memory> // Para shared_ptr, unique_ptr
|
||||||
#include <string> // Para string
|
#include <string> // Para string
|
||||||
#include <vector> // Para vector
|
#include <vector> // Para vector
|
||||||
#include "animated_sprite.h" // Para SpriteAnimated
|
#include "animated_sprite.h" // Para AnimatedSprite
|
||||||
#include "utils.h" // Para Circle
|
#include "utils.h" // Para Circle
|
||||||
|
|
||||||
class Texture;
|
class Texture;
|
||||||
|
|
||||||
/**
|
// Tipos de objetos disponibles en el juego.
|
||||||
* @brief Tipos de objetos disponibles en el juego.
|
// Define los diferentes tipos de objetos que pueden existir en el juego.
|
||||||
*
|
|
||||||
* Esta enumeración define los diferentes tipos de objetos que pueden existir en el juego,
|
|
||||||
* cada uno con un identificador único.
|
|
||||||
*/
|
|
||||||
enum class ItemType : int
|
enum class ItemType : int
|
||||||
{
|
{
|
||||||
DISK = 1, /**< Disco */
|
DISK = 1, // Disco
|
||||||
GAVINA = 2, /**< Gavina */
|
GAVINA = 2, // Gavina
|
||||||
PACMAR = 3, /**< Pacman */
|
PACMAR = 3, // Pacman
|
||||||
CLOCK = 4, /**< Reloj */
|
CLOCK = 4, // Reloj
|
||||||
COFFEE = 5, /**< Café */
|
COFFEE = 5, // Café
|
||||||
DEBIAN = 6, /**< Debian */
|
DEBIAN = 6, // Debian
|
||||||
COFFEE_MACHINE = 7, /**< Máquina de café */
|
COFFEE_MACHINE = 7, // Máquina de café
|
||||||
NONE = 8, /**< Ninguno */
|
NONE = 8, // Ninguno
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
// Clase Item.
|
||||||
* @brief Clase Item.
|
// Representa un objeto en el juego, con sus propiedades y métodos para gestionar su comportamiento.
|
||||||
*
|
|
||||||
* Esta clase representa un objeto en el juego, con sus propiedades y métodos para gestionar su comportamiento.
|
|
||||||
*/
|
|
||||||
class Item
|
class Item
|
||||||
{
|
{
|
||||||
private:
|
|
||||||
// Objetos y punteros
|
|
||||||
std::unique_ptr<AnimatedSprite> sprite_; /**< Sprite con los gráficos del objeto */
|
|
||||||
|
|
||||||
// Variables
|
|
||||||
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_; /**< Especifica el tipo de objeto que es */
|
|
||||||
bool enabled_ = true; /**< Especifica 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; /**< Temporizador con el tiempo que el objeto está presente */
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @brief Alinea el círculo de colisión con la posición del objeto.
|
|
||||||
*
|
|
||||||
* Esta función ajusta la posición del círculo de colisión para que coincida con la posición del objeto.
|
|
||||||
* Actualiza las coordenadas X e Y del colisionador basándose en las coordenadas del objeto.
|
|
||||||
*/
|
|
||||||
void shiftColliders();
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @brief Coloca el sprite en la posición del objeto.
|
|
||||||
*
|
|
||||||
* Esta función ajusta la posición del sprite para que coincida con la posición del objeto.
|
|
||||||
* Actualiza las coordenadas X e Y del sprite basándose en las coordenadas del objeto.
|
|
||||||
*/
|
|
||||||
void shiftSprite();
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @brief Actualiza la posición y estados del objeto.
|
|
||||||
*
|
|
||||||
* Esta función actualiza la posición del objeto basándose en su velocidad y aceleración.
|
|
||||||
* Controla las colisiones con los límites del área de juego, ajustando la posición y la velocidad en consecuencia.
|
|
||||||
* También actualiza la posición del sprite y el colisionador del objeto.
|
|
||||||
*/
|
|
||||||
void move();
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @brief Actualiza el contador de tiempo de vida del objeto.
|
|
||||||
*
|
|
||||||
* Esta función decrementa el contador de tiempo de vida del objeto.
|
|
||||||
* Si el tiempo de vida es mayor a 0, se decrementa en 1.
|
|
||||||
* Si el tiempo de vida es 0 o menos, se desactiva el objeto llamando a la función `disable()`.
|
|
||||||
*/
|
|
||||||
void updateTimeToLive();
|
|
||||||
|
|
||||||
public:
|
public:
|
||||||
/**
|
// Constructor. Inicializa un objeto Item con el tipo, posición, área de juego, textura y animación.
|
||||||
* @brief Constructor de la clase Item.
|
|
||||||
*
|
|
||||||
* Este constructor inicializa un objeto Item con el tipo especificado, posición inicial, área de juego, textura y animación.
|
|
||||||
*
|
|
||||||
* @param type El tipo de objeto (ItemType).
|
|
||||||
* @param x La posición X inicial del objeto.
|
|
||||||
* @param y La posición Y inicial del objeto.
|
|
||||||
* @param play_area El área de juego donde el objeto se moverá.
|
|
||||||
* @param texture La textura del objeto.
|
|
||||||
* @param animation La animación asociada al objeto.
|
|
||||||
*/
|
|
||||||
Item(ItemType type, float x, float y, SDL_FRect &play_area, std::shared_ptr<Texture> texture, const std::vector<std::string> &animation);
|
Item(ItemType type, float x, float y, SDL_FRect &play_area, std::shared_ptr<Texture> texture, const std::vector<std::string> &animation);
|
||||||
|
|
||||||
/**
|
// Destructor.
|
||||||
* @brief Destructor de la clase Item.
|
|
||||||
*
|
|
||||||
* Este destructor libera los recursos asociados con el objeto Item.
|
|
||||||
*/
|
|
||||||
~Item() = default;
|
~Item() = default;
|
||||||
|
|
||||||
/**
|
// Centra el objeto en la posición X indicada, asegurando que no se salga del área de juego.
|
||||||
* @brief Centra el objeto en la posición X.
|
|
||||||
*
|
|
||||||
* Esta función ajusta la posición X del objeto para que esté centrado en la posición X especificada.
|
|
||||||
* Además, asegura que el objeto no se salga de los límites del área de juego.
|
|
||||||
*
|
|
||||||
* @param x La posición X en la que se desea centrar el objeto.
|
|
||||||
*/
|
|
||||||
void alignTo(int x);
|
void alignTo(int x);
|
||||||
|
|
||||||
/**
|
// Renderiza el objeto en pantalla si está habilitado.
|
||||||
* @brief Pinta el objeto en la pantalla.
|
// 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.
|
||||||
* Esta función renderiza el objeto en la pantalla si está habilitado.
|
|
||||||
* Si el tiempo de vida (`time_to_live_`) es mayor que 200, renderiza el sprite.
|
|
||||||
* Si el tiempo de vida es menor o igual a 200, renderiza el sprite de forma intermitente, basándose en un cálculo de módulo.
|
|
||||||
*/
|
|
||||||
void render();
|
void render();
|
||||||
|
|
||||||
/**
|
// Desactiva el objeto estableciendo su estado enabled_ a false.
|
||||||
* @brief Pone a cero todos los valores del objeto.
|
|
||||||
*
|
|
||||||
* Esta función desactiva el objeto estableciendo su estado `enabled_` a `false`.
|
|
||||||
*/
|
|
||||||
void disable();
|
void disable();
|
||||||
|
|
||||||
/**
|
// Actualiza la posición, animación y contadores del objeto.
|
||||||
* @brief Actualiza el objeto a su posición, animación y controla los contadores.
|
// Llama a move(), sprite_->update() y updateTimeToLive().
|
||||||
*
|
|
||||||
* Esta función mueve el objeto, actualiza su animación y controla el contador de tiempo de vida.
|
|
||||||
* Llama a las funciones `move()`, `sprite_->update()` y `updateTimeToLive()`.
|
|
||||||
*/
|
|
||||||
void update();
|
void update();
|
||||||
|
|
||||||
// Getters
|
// Getters
|
||||||
@@ -153,4 +59,40 @@ public:
|
|||||||
bool isEnabled() const { return enabled_; }
|
bool isEnabled() const { return enabled_; }
|
||||||
bool isOnFloor() const { return floor_collision_; }
|
bool isOnFloor() const { return floor_collision_; }
|
||||||
Circle &getCollider() { return collider_; }
|
Circle &getCollider() { return collider_; }
|
||||||
|
|
||||||
|
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
|
||||||
|
|
||||||
|
// 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();
|
||||||
|
|
||||||
|
// 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();
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ namespace lang
|
|||||||
std::vector<std::string> texts; // Vector con los textos
|
std::vector<std::string> texts; // Vector con los textos
|
||||||
|
|
||||||
// Inicializa los textos del juego en el idioma seleccionado
|
// Inicializa los textos del juego en el idioma seleccionado
|
||||||
bool loadFromFile(std::string file_path)
|
bool loadFromFile(const std::string &file_path)
|
||||||
{
|
{
|
||||||
texts.clear();
|
texts.clear();
|
||||||
|
|
||||||
|
|||||||
@@ -1,22 +1,23 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
#include <string> // Para string
|
#include <string> // Para std::string
|
||||||
|
|
||||||
namespace lang
|
namespace lang
|
||||||
{
|
{
|
||||||
|
// --- Códigos de idioma soportados ---
|
||||||
enum class Code : int
|
enum class Code : int
|
||||||
{
|
{
|
||||||
es_ES = 0,
|
es_ES = 0, // Español
|
||||||
ba_BA = 1,
|
ba_BA = 1, // Bable/Asturiano
|
||||||
en_UK = 2,
|
en_UK = 2, // Inglés (Reino Unido)
|
||||||
};
|
};
|
||||||
|
|
||||||
// Inicializa los textos del juego en el idioma seleccionado
|
// Inicializa los textos del juego en el idioma seleccionado
|
||||||
bool loadFromFile(std::string file_path);
|
bool loadFromFile(const std::string &file_path);
|
||||||
|
|
||||||
// Obtiene la cadena de texto del indice
|
// Obtiene la cadena de texto correspondiente al índice
|
||||||
std::string getText(int index);
|
std::string getText(int index);
|
||||||
|
|
||||||
// Obtiene el codigo del idioma del siguiente idioma
|
// Obtiene el código del siguiente idioma disponible
|
||||||
Code getNextLangCode(Code lang);
|
Code getNextLangCode(Code lang);
|
||||||
}
|
}
|
||||||
@@ -1,65 +1,25 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
#include <SDL3/SDL_rect.h> // Para SDL_FPoint
|
#include <SDL3/SDL_rect.h> // Para SDL_FPoint
|
||||||
#include <SDL3/SDL_stdinc.h> // Para Uint32
|
#include <SDL3/SDL_stdinc.h> // Para Uint64
|
||||||
#include <memory> // Para shared_ptr, unique_ptr
|
#include <memory> // Para shared_ptr, unique_ptr
|
||||||
#include <vector> // Para vector
|
#include <vector> // Para vector
|
||||||
class Sprite; // lines 8-8
|
|
||||||
class Texture; // lines 9-9
|
class Sprite;
|
||||||
struct Color; // lines 10-10
|
class Texture;
|
||||||
|
struct Color;
|
||||||
|
|
||||||
/*
|
/*
|
||||||
Esta clase gestiona un estado del programa. Se encarga de dibujar por pantalla el
|
Esta clase gestiona un estado del programa. Se encarga de dibujar por pantalla el
|
||||||
logo de "JAILGAMES" utilizando un sencillo efecto consistente en generar un sprite por
|
logo de "JAILGAMES" utilizando un sencillo efecto consistente en generar un sprite por
|
||||||
cada linea del bitmap que forma la palabra "JAILGAMES". Posteriormente realiza una
|
cada línea del bitmap que forma la palabra "JAILGAMES". Posteriormente realiza una
|
||||||
modulación de color sobre la textura para simular un fade to black al estilo
|
modulación de color sobre la textura para simular un fade to black al estilo
|
||||||
ZX Spectrum
|
ZX Spectrum.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
// Clase Logo
|
// --- Clase Logo ---
|
||||||
class Logo
|
class Logo
|
||||||
{
|
{
|
||||||
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 maximo
|
|
||||||
static constexpr int SPEED = 8; // Velocidad de desplazamiento de cada linea
|
|
||||||
|
|
||||||
// Objetos y punteros
|
|
||||||
std::shared_ptr<Texture> since_texture_; // Textura con los graficos "Since 1998"
|
|
||||||
std::unique_ptr<Sprite> since_sprite_; // Sprite para manejar la sinceTexture
|
|
||||||
std::shared_ptr<Texture> jail_texture_; // Textura con los graficos "JAILGAMES"
|
|
||||||
std::vector<std::unique_ptr<Sprite>> jail_sprite_; // Vector con los sprites de cada linea 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 X donde dibujar el logo
|
|
||||||
|
|
||||||
// Actualiza las variables
|
|
||||||
void update();
|
|
||||||
|
|
||||||
// Dibuja en pantalla
|
|
||||||
void render();
|
|
||||||
|
|
||||||
// Comprueba el manejador de eventos
|
|
||||||
void checkEvents();
|
|
||||||
|
|
||||||
// Comprueba las entradas
|
|
||||||
void checkInput();
|
|
||||||
|
|
||||||
// Gestiona el logo de JAILGAMES
|
|
||||||
void updateJAILGAMES();
|
|
||||||
|
|
||||||
// Renderiza el logo de JAILGAMES
|
|
||||||
void renderJAILGAMES();
|
|
||||||
|
|
||||||
// Gestiona el color de las texturas
|
|
||||||
void updateTextureColors();
|
|
||||||
|
|
||||||
public:
|
public:
|
||||||
// Constructor
|
// Constructor
|
||||||
Logo();
|
Logo();
|
||||||
@@ -69,4 +29,33 @@ public:
|
|||||||
|
|
||||||
// Bucle principal
|
// Bucle principal
|
||||||
void run();
|
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
|
||||||
|
|
||||||
|
// --- 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
|
||||||
|
|
||||||
|
// --- Métodos internos ---
|
||||||
|
void update(); // Actualiza las variables
|
||||||
|
void render(); // Dibuja en pantalla
|
||||||
|
void checkEvents(); // Comprueba el manejador de eventos
|
||||||
|
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
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,17 +1,17 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
#include <string> // Para string
|
#include <string> // Para std::string
|
||||||
#include <vector> // Para vector
|
#include <vector> // Para std::vector
|
||||||
|
|
||||||
/*
|
/*
|
||||||
Esta clase sirve para añadir elementos hiScoreEntry_r a un vector (tabla), de manera
|
Esta clase sirve para añadir elementos HiScoreEntry a un vector (tabla), de manera
|
||||||
que la tabla siempre está ordenada.
|
que la tabla siempre está ordenada.
|
||||||
|
|
||||||
Además tiene un método para dejar la tabla con sus valores iniciales y métodos para
|
Además tiene un método para dejar la tabla con sus valores iniciales y métodos para
|
||||||
leer y escribir la tabla a un fichero
|
leer y escribir la tabla a un fichero.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
// Estructura para las entradas de la tabla de recirds
|
// --- Estructura para las entradas de la tabla de records ---
|
||||||
struct HiScoreEntry
|
struct HiScoreEntry
|
||||||
{
|
{
|
||||||
std::string name; // Nombre
|
std::string name; // Nombre
|
||||||
@@ -23,16 +23,9 @@ struct HiScoreEntry
|
|||||||
: name(n.substr(0, 6)), score(s), one_credit_complete(occ) {}
|
: name(n.substr(0, 6)), score(s), one_credit_complete(occ) {}
|
||||||
};
|
};
|
||||||
|
|
||||||
// Clase ManageHiScoreTable
|
// --- Clase ManageHiScoreTable ---
|
||||||
class ManageHiScoreTable
|
class ManageHiScoreTable
|
||||||
{
|
{
|
||||||
private:
|
|
||||||
// Variables
|
|
||||||
std::vector<HiScoreEntry> &table_; // Tabla con los records
|
|
||||||
|
|
||||||
// Ordena la tabla
|
|
||||||
void sort();
|
|
||||||
|
|
||||||
public:
|
public:
|
||||||
// Constructor
|
// Constructor
|
||||||
explicit ManageHiScoreTable(std::vector<HiScoreEntry> &table)
|
explicit ManageHiScoreTable(std::vector<HiScoreEntry> &table)
|
||||||
@@ -44,7 +37,7 @@ public:
|
|||||||
// Resetea la tabla a los valores por defecto
|
// Resetea la tabla a los valores por defecto
|
||||||
void clear();
|
void clear();
|
||||||
|
|
||||||
// Añade un elemento a la tabla
|
// Añade un elemento a la tabla (devuelve la posición en la que se inserta)
|
||||||
int add(const HiScoreEntry &entry);
|
int add(const HiScoreEntry &entry);
|
||||||
|
|
||||||
// Carga la tabla con los datos de un fichero
|
// Carga la tabla con los datos de un fichero
|
||||||
@@ -52,4 +45,11 @@ public:
|
|||||||
|
|
||||||
// Guarda la tabla en un fichero
|
// Guarda la tabla en un fichero
|
||||||
bool saveToFile(const std::string &file_path);
|
bool saveToFile(const std::string &file_path);
|
||||||
|
|
||||||
|
private:
|
||||||
|
// Referencia a la tabla con los records
|
||||||
|
std::vector<HiScoreEntry> &table_;
|
||||||
|
|
||||||
|
// Ordena la tabla internamente
|
||||||
|
void sort();
|
||||||
};
|
};
|
||||||
@@ -5,10 +5,12 @@
|
|||||||
|
|
||||||
namespace Mouse
|
namespace Mouse
|
||||||
{
|
{
|
||||||
extern Uint32 cursor_hide_time; // Tiempo en milisegundos para ocultar el cursor
|
// --- Variables de estado del cursor ---
|
||||||
extern Uint32 last_mouse_move_time; // Última vez que el ratón se movió
|
extern Uint32 cursor_hide_time; // Tiempo en milisegundos para ocultar el cursor tras inactividad
|
||||||
extern bool cursor_visible; // Estado del cursor
|
extern Uint32 last_mouse_move_time; // Última vez (en ms) que el ratón se movió
|
||||||
|
extern bool cursor_visible; // Indica si el cursor está visible
|
||||||
|
|
||||||
void handleEvent(const SDL_Event &event);
|
// --- Gestión de eventos y visibilidad ---
|
||||||
void updateCursorVisibility();
|
void handleEvent(const SDL_Event &event); // Procesa eventos de ratón (movimiento, clic, etc.)
|
||||||
|
void updateCursorVisibility(); // Actualiza la visibilidad del cursor según la inactividad
|
||||||
}
|
}
|
||||||
@@ -2,70 +2,41 @@
|
|||||||
|
|
||||||
#include <SDL3/SDL_rect.h> // Para SDL_FPoint, SDL_FRect
|
#include <SDL3/SDL_rect.h> // Para SDL_FPoint, SDL_FRect
|
||||||
#include <SDL3/SDL_surface.h> // Para SDL_FlipMode
|
#include <SDL3/SDL_surface.h> // Para SDL_FlipMode
|
||||||
#include <algorithm> // Para max
|
#include <algorithm> // Para std::max
|
||||||
#include <memory> // Para shared_ptr
|
#include <memory> // Para shared_ptr
|
||||||
#include "sprite.h" // Para Sprite
|
#include "sprite.h" // Para Sprite
|
||||||
class Texture; // lines 8-8
|
|
||||||
|
class Texture;
|
||||||
|
|
||||||
// Clase MovingSprite. Añade movimiento y efectos de rotación, zoom y flip al sprite
|
// Clase MovingSprite. Añade movimiento y efectos de rotación, zoom y flip al sprite
|
||||||
class MovingSprite : public Sprite
|
class MovingSprite : public Sprite
|
||||||
{
|
{
|
||||||
public:
|
public:
|
||||||
|
// --- Estructura para la rotación ---
|
||||||
struct Rotate
|
struct Rotate
|
||||||
{
|
{
|
||||||
bool enabled; // Indica si ha de rotar
|
bool enabled; // Indica si ha de rotar
|
||||||
int counter; // Contador
|
int counter; // Contador
|
||||||
int speed; // Velocidad de giro
|
int speed; // Velocidad de giro
|
||||||
double angle; // Angulo para dibujarlo
|
double angle; // Ángulo para dibujarlo
|
||||||
float amount; // Cantidad de grados a girar en cada iteración
|
float amount; // Cantidad de grados a girar en cada iteración
|
||||||
SDL_FPoint center; // Centro de rotación
|
SDL_FPoint center; // Centro de rotación
|
||||||
|
|
||||||
Rotate() : enabled(false), counter(0), speed(1), angle(0.0), amount(0.0f), center({0.0f, 0.0f}) {}
|
Rotate() : enabled(false), counter(0), speed(1), angle(0.0), amount(0.0f), center({0.0f, 0.0f}) {}
|
||||||
};
|
};
|
||||||
|
|
||||||
protected:
|
// --- Constructores y destructor ---
|
||||||
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 pixeles a desplazarse
|
|
||||||
float vy_ = 0.0f; // Velocidad en el eje Y. Cantidad de pixeles 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
|
|
||||||
|
|
||||||
Rotate rotate_; // Variables usada 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 como se voltea el sprite
|
|
||||||
|
|
||||||
// Incrementa el valor del ángulo
|
|
||||||
void updateAngle() { rotate_.angle += rotate_.amount; }
|
|
||||||
|
|
||||||
// Mueve el sprite
|
|
||||||
void move();
|
|
||||||
|
|
||||||
// Rota el sprite
|
|
||||||
void rotate();
|
|
||||||
|
|
||||||
public:
|
|
||||||
// Constructor
|
|
||||||
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, MovingSprite::Rotate rotate, float zoom_w, float zoom_h, SDL_FlipMode flip);
|
||||||
MovingSprite(std::shared_ptr<Texture> texture, SDL_FRect pos);
|
MovingSprite(std::shared_ptr<Texture> texture, SDL_FRect pos);
|
||||||
explicit MovingSprite(std::shared_ptr<Texture> texture);
|
explicit MovingSprite(std::shared_ptr<Texture> texture);
|
||||||
|
|
||||||
// Destructor
|
|
||||||
virtual ~MovingSprite() override = default;
|
virtual ~MovingSprite() override = default;
|
||||||
|
|
||||||
// Actualiza las variables internas del objeto
|
// --- Métodos principales ---
|
||||||
virtual void update();
|
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
|
||||||
|
|
||||||
// Reinicia todas las variables a cero
|
// --- Getters de posición y movimiento ---
|
||||||
void clear() override;
|
|
||||||
|
|
||||||
// Muestra el sprite por pantalla
|
|
||||||
void render() override;
|
|
||||||
|
|
||||||
// Obtiene la variable
|
|
||||||
float getPosX() const { return x_; }
|
float getPosX() const { return x_; }
|
||||||
float getPosY() const { return y_; }
|
float getPosY() const { return y_; }
|
||||||
float getVelX() const { return vx_; }
|
float getVelX() const { return vx_; }
|
||||||
@@ -73,51 +44,53 @@ public:
|
|||||||
float getAccelX() const { return ax_; }
|
float getAccelX() const { return ax_; }
|
||||||
float getAccelY() const { return ay_; }
|
float getAccelY() const { return ay_; }
|
||||||
|
|
||||||
// Establece la variable
|
// --- Setters de movimiento ---
|
||||||
void setVelX(float value) { vx_ = value; }
|
void setVelX(float value) { vx_ = value; }
|
||||||
void setVelY(float value) { vy_ = value; }
|
void setVelY(float value) { vy_ = value; }
|
||||||
void setAccelX(float value) { ax_ = value; }
|
void setAccelX(float value) { ax_ = value; }
|
||||||
void setAccelY(float value) { ay_ = value; }
|
void setAccelY(float value) { ay_ = value; }
|
||||||
|
|
||||||
// Obten el valor de la variable
|
// --- Rotación ---
|
||||||
bool isRotating() const { return rotate_.enabled; }
|
bool isRotating() const { return rotate_.enabled; }
|
||||||
|
|
||||||
// Establece el valor de la variable
|
|
||||||
void setZoomW(float value) { zoom_w_ = value; }
|
void setZoomW(float value) { zoom_w_ = value; }
|
||||||
void setZoomH(float value) { zoom_h_ = value; }
|
void setZoomH(float value) { zoom_h_ = value; }
|
||||||
|
|
||||||
// Establece el valor de la variable
|
|
||||||
void setAngle(double value) { rotate_.angle = value; }
|
void setAngle(double value) { rotate_.angle = value; }
|
||||||
void setRotatingCenter(SDL_FPoint point) { rotate_.center = point; }
|
void setRotatingCenter(SDL_FPoint point) { rotate_.center = point; }
|
||||||
|
void setRotate(bool enable); // Activa o desactiva el efecto de rotación
|
||||||
// Activa o desactiva el efecto de rotación
|
|
||||||
void setRotate(bool enable);
|
|
||||||
|
|
||||||
// Establece el valor de la variable
|
|
||||||
void setRotateSpeed(int value) { rotate_.speed = std::max(1, value); }
|
void setRotateSpeed(int value) { rotate_.speed = std::max(1, value); }
|
||||||
void setRotateAmount(double value) { rotate_.amount = value; }
|
void setRotateAmount(double value) { rotate_.amount = value; }
|
||||||
|
void switchRotate() { rotate_.amount *= -1; } // Cambia el sentido de la rotación
|
||||||
|
|
||||||
// Cambia el sentido de la rotación
|
// --- Flip ---
|
||||||
void switchRotate() { rotate_.amount *= -1; }
|
|
||||||
|
|
||||||
// Establece el valor de la variable
|
|
||||||
void setFlip(SDL_FlipMode flip) { flip_ = flip; }
|
void setFlip(SDL_FlipMode flip) { flip_ = flip; }
|
||||||
|
|
||||||
// Gira el sprite horizontalmente
|
|
||||||
void flip() { flip_ = (flip_ == SDL_FLIP_HORIZONTAL) ? SDL_FLIP_NONE : SDL_FLIP_HORIZONTAL; }
|
void flip() { flip_ = (flip_ == SDL_FLIP_HORIZONTAL) ? SDL_FLIP_NONE : SDL_FLIP_HORIZONTAL; }
|
||||||
|
|
||||||
// Obtiene el valor de la variable
|
|
||||||
SDL_FlipMode getFlip() { return flip_; }
|
SDL_FlipMode getFlip() { return flip_; }
|
||||||
|
|
||||||
// Establece la posición y_ el tamaño del objeto
|
// --- Posición y tamaño ---
|
||||||
void setPos(SDL_FRect rect);
|
void setPos(SDL_FRect rect); // Establece la posición y el tamaño del objeto
|
||||||
|
void setPos(float x, float y); // Establece la posición del objeto
|
||||||
|
void setPosX(float value); // Establece la posición X
|
||||||
|
void setPosY(float value); // Establece la posición Y
|
||||||
|
|
||||||
// Establece el valor de las variables
|
protected:
|
||||||
void setPos(float x, float y);
|
// --- 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
|
||||||
|
|
||||||
// Establece el valor de la variable
|
float vx_ = 0.0f; // Velocidad en el eje X. Cantidad de píxeles a desplazarse
|
||||||
void setPosX(float value);
|
float vy_ = 0.0f; // Velocidad en el eje Y. Cantidad de píxeles a desplazarse
|
||||||
|
|
||||||
// Establece el valor de la variable
|
float ax_ = 0.0f; // Aceleración en el eje X. Variación de la velocidad
|
||||||
void setPosY(float value);
|
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
|
||||||
|
|
||||||
|
// --- 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
|
||||||
};
|
};
|
||||||
@@ -3,19 +3,50 @@
|
|||||||
#include <SDL3/SDL_rect.h> // Para SDL_FRect
|
#include <SDL3/SDL_rect.h> // Para SDL_FRect
|
||||||
#include <SDL3/SDL_render.h> // Para SDL_Renderer
|
#include <SDL3/SDL_render.h> // Para SDL_Renderer
|
||||||
#include <memory> // Para shared_ptr
|
#include <memory> // Para shared_ptr
|
||||||
#include <string> // Para string, basic_string
|
#include <string> // Para string
|
||||||
#include <vector> // Para vector
|
#include <vector> // Para vector
|
||||||
#include "utils.h" // Para Color
|
#include "utils.h" // Para Color
|
||||||
class Sprite; // lines 9-9
|
|
||||||
class Text; // lines 10-10
|
|
||||||
class Texture; // lines 11-11
|
|
||||||
|
|
||||||
|
class Sprite;
|
||||||
|
class Text;
|
||||||
|
class Texture;
|
||||||
|
|
||||||
|
// --- Clase Notifier: gestiona las notificaciones en pantalla (singleton) ---
|
||||||
class Notifier
|
class Notifier
|
||||||
{
|
{
|
||||||
|
public:
|
||||||
|
// [SINGLETON] Crearemos el objeto con esta función estática
|
||||||
|
static void init(const std::string &icon_file, std::shared_ptr<Text> text);
|
||||||
|
|
||||||
|
// [SINGLETON] Destruiremos el objeto con esta función estática
|
||||||
|
static void destroy();
|
||||||
|
|
||||||
|
// [SINGLETON] Con este método obtenemos el objeto y podemos trabajar con él
|
||||||
|
static Notifier *get();
|
||||||
|
|
||||||
|
// Dibuja las notificaciones por pantalla
|
||||||
|
void render();
|
||||||
|
|
||||||
|
// Actualiza el estado de las notificaciones
|
||||||
|
void update();
|
||||||
|
|
||||||
|
// Muestra una notificación de texto por pantalla
|
||||||
|
void show(std::vector<std::string> texts, int icon = -1, const std::string &code = std::string());
|
||||||
|
|
||||||
|
// Indica si hay notificaciones activas
|
||||||
|
bool isActive() const { return !notifications_.empty(); }
|
||||||
|
|
||||||
|
// Obtiene los códigos de las notificaciones activas
|
||||||
|
std::vector<std::string> getCodes();
|
||||||
|
|
||||||
|
// Comprueba si hay alguna notificación con un código concreto
|
||||||
|
bool checkCode(const std::string &code) { return stringInVector(getCodes(), code); }
|
||||||
|
|
||||||
private:
|
private:
|
||||||
// [SINGLETON] Objeto notifier
|
// [SINGLETON] Objeto notifier
|
||||||
static Notifier *notifier_;
|
static Notifier *notifier_;
|
||||||
|
|
||||||
|
// --- Tipos internos ---
|
||||||
enum class NotificationStatus
|
enum class NotificationStatus
|
||||||
{
|
{
|
||||||
RISING,
|
RISING,
|
||||||
@@ -30,18 +61,19 @@ private:
|
|||||||
SQUARED,
|
SQUARED,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// --- Estructura Notification ---
|
||||||
struct Notification
|
struct Notification
|
||||||
{
|
{
|
||||||
std::shared_ptr<Texture> texture;
|
std::shared_ptr<Texture> texture; // Textura de la notificación
|
||||||
std::shared_ptr<Sprite> sprite;
|
std::shared_ptr<Sprite> sprite; // Sprite asociado
|
||||||
std::vector<std::string> texts;
|
std::vector<std::string> texts; // Textos a mostrar
|
||||||
int counter;
|
int counter; // Contador de tiempo
|
||||||
NotificationStatus state;
|
NotificationStatus state; // Estado de la notificación
|
||||||
NotificationShape shape;
|
NotificationShape shape; // Forma de la notificación
|
||||||
SDL_FRect rect;
|
SDL_FRect rect; // Rectángulo de la notificación
|
||||||
int y;
|
int y; // Posición vertical
|
||||||
int travel_dist;
|
int travel_dist; // Distancia a recorrer
|
||||||
std::string code; // Permite asignar un código a la notificación
|
std::string code; // Código identificador de la notificación
|
||||||
|
|
||||||
// Constructor
|
// Constructor
|
||||||
explicit Notification()
|
explicit Notification()
|
||||||
@@ -49,58 +81,23 @@ private:
|
|||||||
shape(NotificationShape::SQUARED), rect{0, 0, 0, 0}, y(0), travel_dist(0), code("") {}
|
shape(NotificationShape::SQUARED), rect{0, 0, 0, 0}, y(0), travel_dist(0), code("") {}
|
||||||
};
|
};
|
||||||
|
|
||||||
// Objetos y punteros
|
// --- Objetos y punteros ---
|
||||||
SDL_Renderer *renderer_; // El renderizador de la ventana
|
SDL_Renderer *renderer_; // El renderizador de la ventana
|
||||||
|
|
||||||
std::shared_ptr<Texture> icon_texture_; // Textura para los iconos de las notificaciones
|
std::shared_ptr<Texture> icon_texture_; // Textura para los iconos de las notificaciones
|
||||||
std::shared_ptr<Text> text_; // Objeto para dibujar texto
|
std::shared_ptr<Text> text_; // Objeto para dibujar texto
|
||||||
|
|
||||||
// Variables
|
// --- Variables de estado ---
|
||||||
Color bg_color_; // Color de fondo de las notificaciones
|
Color bg_color_; // Color de fondo de las notificaciones
|
||||||
int wait_time_; // Tiempo que se ve la notificación
|
int wait_time_; // Tiempo que se ve la notificación
|
||||||
std::vector<Notification> notifications_; // La lista de notificaciones activas
|
std::vector<Notification> notifications_; // Lista de notificaciones activas
|
||||||
bool stack_; // Indica si las notificaciones se apilan
|
bool stack_; // Indica si las notificaciones se apilan
|
||||||
bool has_icons_; // Indica si el notificador tiene textura para iconos
|
bool has_icons_; // Indica si el notificador tiene textura para iconos
|
||||||
|
|
||||||
// Elimina las notificaciones finalizadas
|
// --- Métodos internos ---
|
||||||
void clearFinishedNotifications();
|
void clearFinishedNotifications(); // Elimina las notificaciones finalizadas
|
||||||
|
void clearAllNotifications(); // Finaliza y elimina todas las notificaciones activas
|
||||||
|
|
||||||
// Finaliza y elimnina todas las notificaciones activas
|
// [SINGLETON] Constructor y destructor privados
|
||||||
void clearAllNotifications();
|
|
||||||
|
|
||||||
// [SINGLETON] Ahora el constructor y el destructor son privados, para no poder crear objetos notifier desde fuera
|
|
||||||
|
|
||||||
// Constructor
|
|
||||||
Notifier(std::string icon_file, std::shared_ptr<Text> text);
|
Notifier(std::string icon_file, std::shared_ptr<Text> text);
|
||||||
|
|
||||||
// Destructor
|
|
||||||
~Notifier() = default;
|
~Notifier() = default;
|
||||||
|
|
||||||
public:
|
|
||||||
// [SINGLETON] Crearemos el objeto con esta función estática
|
|
||||||
static void init(const std::string &icon_file, std::shared_ptr<Text> text);
|
|
||||||
|
|
||||||
// [SINGLETON] Destruiremos el objeto con esta función estática
|
|
||||||
static void destroy();
|
|
||||||
|
|
||||||
// [SINGLETON] Con este método obtenemos el objeto y podemos trabajar con él
|
|
||||||
static Notifier *get();
|
|
||||||
|
|
||||||
// Dibuja las notificaciones por pantalla
|
|
||||||
void render();
|
|
||||||
|
|
||||||
// Actualiza el estado de las notificaiones
|
|
||||||
void update();
|
|
||||||
|
|
||||||
// Muestra una notificación de texto por pantalla
|
|
||||||
void show(std::vector<std::string> texts, int icon = -1, const std::string &code = std::string());
|
|
||||||
|
|
||||||
// Indica si hay notificaciones activas
|
|
||||||
bool isActive() { return !notifications_.empty(); }
|
|
||||||
|
|
||||||
// Obtiene los códigos de las notificaciones
|
|
||||||
std::vector<std::string> getCodes();
|
|
||||||
|
|
||||||
// Comprueba si hay alguna notificacion con un código
|
|
||||||
bool checkCode(const std::string &code) { return stringInVector(getCodes(), code); }
|
|
||||||
};
|
};
|
||||||
|
|||||||
103
source/options.h
103
source/options.h
@@ -2,16 +2,17 @@
|
|||||||
|
|
||||||
#include <SDL3/SDL_gamepad.h> // Para SDL_GamepadButton
|
#include <SDL3/SDL_gamepad.h> // Para SDL_GamepadButton
|
||||||
#include <SDL3/SDL_surface.h> // Para SDL_ScaleMode
|
#include <SDL3/SDL_surface.h> // Para SDL_ScaleMode
|
||||||
#include <string> // Para string
|
#include <string> // Para std::string
|
||||||
#include <vector> // Para vector
|
#include <vector> // Para std::vector
|
||||||
#include "input.h" // Para InputAction, InputDeviceToUse
|
#include "input.h" // Para InputAction, InputDeviceToUse
|
||||||
#include "manage_hiscore_table.h" // Para HiScoreEntry
|
#include "manage_hiscore_table.h" // Para HiScoreEntry
|
||||||
|
|
||||||
namespace lang
|
namespace lang
|
||||||
{
|
{
|
||||||
enum class Code : int;
|
enum class Code : int;
|
||||||
} // lines 11-11
|
}
|
||||||
|
|
||||||
// Dificultad del juego
|
// --- Dificultad del juego ---
|
||||||
enum class GameDifficulty
|
enum class GameDifficulty
|
||||||
{
|
{
|
||||||
EASY = 0,
|
EASY = 0,
|
||||||
@@ -19,58 +20,58 @@ enum class GameDifficulty
|
|||||||
HARD = 2,
|
HARD = 2,
|
||||||
};
|
};
|
||||||
|
|
||||||
// Estructura para las opciones de la ventana
|
// --- Opciones de la ventana ---
|
||||||
struct WindowOptions
|
struct WindowOptions
|
||||||
{
|
{
|
||||||
std::string caption; // Texto que aparece en la barra de titulo de la ventana
|
std::string caption; // Texto que aparece en la barra de título de la ventana
|
||||||
int zoom = 1; // Contiene el valor por el que se multiplica el tamaño de la ventana
|
int zoom = 1; // Valor por el que se multiplica el tamaño de la ventana
|
||||||
int max_zoom = 1; // Tamaño máximo para que el tamaño de la ventana no sea mayor que el tamaño de la pantalla
|
int max_zoom = 1; // Tamaño máximo para que la ventana no sea mayor que la pantalla
|
||||||
};
|
};
|
||||||
|
|
||||||
// Estructura con opciones para el video
|
// --- Opciones de vídeo ---
|
||||||
struct VideoOptions
|
struct VideoOptions
|
||||||
{
|
{
|
||||||
SDL_ScaleMode scale_mode; // Filtro usado para el escalado de la imagen
|
SDL_ScaleMode scale_mode; // Filtro usado para el escalado de la imagen
|
||||||
bool fullscreen; // Contiene el valor del modo de pantalla completa
|
bool fullscreen; // Indica si se usa pantalla completa
|
||||||
bool v_sync; // Indica si se quiere usar vsync o no
|
bool v_sync; // Indica si se usa vsync
|
||||||
bool integer_scale; // Indica si se va a usar el escalado entero
|
bool integer_scale; // Indica si se usa escalado entero
|
||||||
bool shaders; // Indica si se van a usar shaders para los filtros de video
|
bool shaders; // Indica si se usan shaders para los filtros de vídeo
|
||||||
std::string info; // Información sobre el modo de video
|
std::string info; // Información sobre el modo de vídeo
|
||||||
};
|
};
|
||||||
|
|
||||||
// Estructura para las opciones de musica
|
// --- Opciones de música ---
|
||||||
struct MusicOptions
|
struct MusicOptions
|
||||||
{
|
{
|
||||||
bool enabled; // Indica si la musica suena o no
|
bool enabled; // Indica si la música suena o no
|
||||||
int volume; // Volumen al que suena la música
|
int volume; // Volumen de la música
|
||||||
};
|
};
|
||||||
|
|
||||||
// Estructura para las opciones de sonido
|
// --- Opciones de sonido ---
|
||||||
struct SoundOptions
|
struct SoundOptions
|
||||||
{
|
{
|
||||||
bool enabled; // Indica si los sonidos suenan o no
|
bool enabled; // Indica si los sonidos suenan o no
|
||||||
int volume; // Volumen al que suenan los sonidos
|
int volume; // Volumen de los sonidos
|
||||||
};
|
};
|
||||||
|
|
||||||
// Estructura para las opciones de audio
|
// --- Opciones de audio ---
|
||||||
struct AudioOptions
|
struct AudioOptions
|
||||||
{
|
{
|
||||||
MusicOptions music; // Opciones para la música
|
MusicOptions music; // Opciones para la música
|
||||||
SoundOptions sound; // Opciones para los efectos de sonido
|
SoundOptions sound; // Opciones para los efectos de sonido
|
||||||
bool enabled; // Indica si el audio está activo o no
|
bool enabled; // Indica si el audio está activo o no
|
||||||
int volume; // Volumen al que suenan el audio
|
int volume; // Volumen general del audio
|
||||||
};
|
};
|
||||||
|
|
||||||
// Estructura para las opciones del juego
|
// --- Opciones del juego ---
|
||||||
struct GameOptions
|
struct GameOptions
|
||||||
{
|
{
|
||||||
GameDifficulty difficulty; // Dificultad del juego
|
GameDifficulty difficulty; // Dificultad del juego
|
||||||
lang::Code language; // Idioma usado en el juego
|
lang::Code language; // Idioma usado en el juego
|
||||||
bool autofire; // Indicador de autofire
|
bool autofire; // Indicador de autofire
|
||||||
std::vector<HiScoreEntry> hi_score_table; // Tabla de mejores puntuaciones
|
std::vector<HiScoreEntry> hi_score_table; // Tabla de mejores puntuaciones
|
||||||
std::vector<int> last_hi_score_entry = {-1, -1}; // Inicialización directa con dos elementos en -1
|
std::vector<int> last_hi_score_entry = {-1, -1}; // Últimas posiciones de entrada en la tabla
|
||||||
|
|
||||||
// Método para reiniciar las últimas entradas de puntuación
|
// Reinicia las últimas entradas de puntuación
|
||||||
void clear_last_hi_score_entries()
|
void clear_last_hi_score_entries()
|
||||||
{
|
{
|
||||||
last_hi_score_entry[0] = -1;
|
last_hi_score_entry[0] = -1;
|
||||||
@@ -78,16 +79,16 @@ struct GameOptions
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// Estructura para los controles del juego
|
// --- Opciones de mando ---
|
||||||
struct GamepadOptions
|
struct GamepadOptions
|
||||||
{
|
{
|
||||||
int index; // Indice en el vector de mandos
|
int index; // Índice en el vector de mandos
|
||||||
int player_id; // Jugador asociado al mando
|
int player_id; // Jugador asociado al mando
|
||||||
InputDeviceToUse type; // Indica si se utilizará teclado o mando o ambos
|
InputDeviceToUse type; // Indica si se usará teclado, mando o ambos
|
||||||
std::string name; // Nombre del dispositivo
|
std::string name; // Nombre del dispositivo
|
||||||
bool plugged; // Indica si el mando se encuentra conectado
|
bool plugged; // Indica si el mando está conectado
|
||||||
std::vector<InputAction> inputs; // Listado de inputs
|
std::vector<InputAction> inputs; // Listado de acciones asignadas
|
||||||
std::vector<SDL_GamepadButton> buttons; // Listado de botones asignados a cada input
|
std::vector<SDL_GamepadButton> buttons; // Listado de botones asignados a cada acción
|
||||||
|
|
||||||
// Constructor por defecto
|
// Constructor por defecto
|
||||||
GamepadOptions()
|
GamepadOptions()
|
||||||
@@ -96,36 +97,24 @@ struct GamepadOptions
|
|||||||
buttons{SDL_GAMEPAD_BUTTON_WEST, SDL_GAMEPAD_BUTTON_NORTH, SDL_GAMEPAD_BUTTON_EAST, SDL_GAMEPAD_BUTTON_START, SDL_GAMEPAD_BUTTON_BACK} {}
|
buttons{SDL_GAMEPAD_BUTTON_WEST, SDL_GAMEPAD_BUTTON_NORTH, SDL_GAMEPAD_BUTTON_EAST, SDL_GAMEPAD_BUTTON_START, SDL_GAMEPAD_BUTTON_BACK} {}
|
||||||
};
|
};
|
||||||
|
|
||||||
// Estructura con todas las opciones de configuración del programa
|
// --- Opciones generales del programa ---
|
||||||
struct Options
|
struct Options
|
||||||
{
|
{
|
||||||
WindowOptions window; // Opciones para la ventana del programa
|
WindowOptions window; // Opciones de la ventana
|
||||||
GameOptions game; // Opciones para el propio juego
|
GameOptions game; // Opciones del juego
|
||||||
VideoOptions video; // Opciones relativas a la clase screen
|
VideoOptions video; // Opciones de vídeo
|
||||||
AudioOptions audio; // Opciones para el audio
|
AudioOptions audio; // Opciones de audio
|
||||||
std::vector<GamepadOptions> controllers; // Opciones con las asignaciones del mando para cada jugador
|
std::vector<GamepadOptions> controllers; // Opciones de mando para cada jugador
|
||||||
};
|
};
|
||||||
|
|
||||||
// Variables
|
// --- Variables globales ---
|
||||||
extern Options options;
|
extern Options options;
|
||||||
|
|
||||||
// Inicializa las opciones del programa
|
// --- Funciones de configuración ---
|
||||||
void initOptions();
|
void initOptions(); // Inicializa las opciones del programa
|
||||||
|
bool loadOptionsFile(std::string file_path); // Carga el fichero de configuración
|
||||||
// Carga el fichero de configuración
|
bool saveOptionsFile(std::string file_path); // Guarda el fichero de configuración
|
||||||
bool loadOptionsFile(std::string file_path);
|
void setKeyboardToPlayer(int player_id); // Asigna el teclado al jugador
|
||||||
|
void swapOptionsKeyboard(); // Intercambia el teclado de jugador
|
||||||
// Guarda el fichero de configuración
|
void swapOptionsControllers(); // Intercambia los jugadores asignados a los dos primeros mandos
|
||||||
bool saveOptionsFile(std::string file_path);
|
int getPlayerWhoUsesKeyboard(); // Averigua quién está usando el teclado
|
||||||
|
|
||||||
// Asigna el teclado al jugador
|
|
||||||
void setKeyboardToPlayer(int player_id);
|
|
||||||
|
|
||||||
// Intercambia el teclado de jugador
|
|
||||||
void swapOptionsKeyboard();
|
|
||||||
|
|
||||||
// Intercambia los jugadores asignados a los dos primeros mandos
|
|
||||||
void swapOptionsControllers();
|
|
||||||
|
|
||||||
// Averigua quien está usando el teclado
|
|
||||||
int getPlayerWhoUsesKeyboard();
|
|
||||||
@@ -2,88 +2,91 @@
|
|||||||
|
|
||||||
#include <SDL3/SDL_rect.h> // Para SDL_FRect
|
#include <SDL3/SDL_rect.h> // Para SDL_FRect
|
||||||
#include <SDL3/SDL_stdinc.h> // Para Uint32
|
#include <SDL3/SDL_stdinc.h> // Para Uint32
|
||||||
#include <string> // Para string
|
#include <string> // Para std::string
|
||||||
#include <vector> // Para vector
|
#include <vector> // Para std::vector
|
||||||
#include "utils.h" // Para Color, Zone
|
#include "utils.h" // Para Color, Zone, NotifyPosition
|
||||||
|
|
||||||
// param.game
|
// --- Parámetros del juego ---
|
||||||
struct ParamGame
|
struct ParamGame
|
||||||
{
|
{
|
||||||
float width; // Ancho de la resolucion nativa del juego
|
float width; // Ancho de la resolución nativa del juego
|
||||||
float height; // Alto de la resolucion nativa del juego
|
float height; // Alto de la resolución nativa del juego
|
||||||
float item_size; // Tamaño de los items del juego
|
float item_size; // Tamaño de los ítems del juego
|
||||||
float coffee_machine_w; // Ancho de la máquina de café
|
float coffee_machine_w; // Ancho de la máquina de café
|
||||||
float coffee_machine_h; // Alto de la máquina de café
|
float coffee_machine_h; // Alto de la máquina de café
|
||||||
Zone play_area; // Rectangulo con la posición de la zona de juego
|
Zone play_area; // Rectángulo con la posición de la zona de juego
|
||||||
Zone game_area; // Rectangulo con las dimensiones del juego
|
Zone game_area; // Rectángulo con las dimensiones del juego
|
||||||
int enter_name_seconds; // Duración en segundos para introducir el nombre al finalizar la partida
|
int enter_name_seconds; // Duración en segundos para introducir el nombre al finalizar la partida
|
||||||
Uint32 speed; // Velocidad a la que transcurre el juego
|
Uint32 speed; // Velocidad a la que transcurre el juego
|
||||||
};
|
};
|
||||||
|
|
||||||
// param.fade
|
// --- Parámetros del fade ---
|
||||||
struct ParamFade
|
struct ParamFade
|
||||||
{
|
{
|
||||||
float num_squares_width; // Cantidad total de cuadraditos en horizontal para el FadeType::RANDOM_SQUARE
|
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
|
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_delay; // Duración entre cada pintado de cuadrados
|
||||||
int random_squares_mult; // Cantidad de cuadrados que se pintaran cada vez
|
int random_squares_mult; // Cantidad de cuadrados que se pintarán cada vez
|
||||||
int post_duration; // Duración final del fade
|
int post_duration; // Duración final del fade
|
||||||
float venetian_size; // Altura de los rectangulos para FadeType::VENETIAN
|
float venetian_size; // Altura de los rectángulos para FadeType::VENETIAN
|
||||||
};
|
};
|
||||||
|
|
||||||
// param.title
|
// --- Parámetros de la pantalla de título ---
|
||||||
struct ParamTitle
|
struct ParamTitle
|
||||||
{
|
{
|
||||||
int press_start_position; // Posición del texto para empezar a jugar
|
int press_start_position; // Posición del texto para empezar a jugar
|
||||||
int title_duration; // Tiempo de inactividad del titulo
|
int title_duration; // Tiempo de inactividad del título
|
||||||
int arcade_edition_position; // Posición del bitmap
|
int arcade_edition_position; // Posición del bitmap "Arcade Edition"
|
||||||
int title_c_c_position; // Posición del bitmap
|
int title_c_c_position; // Posición del bitmap "Coffee Crisis"
|
||||||
};
|
};
|
||||||
|
|
||||||
// param.background
|
// --- Parámetros del fondo ---
|
||||||
struct ParamBackground
|
struct ParamBackground
|
||||||
{
|
{
|
||||||
Color attenuate_color;
|
Color attenuate_color; // Color para atenuar el fondo
|
||||||
int attenuate_alpha;
|
int attenuate_alpha; // Alpha para la atenuación
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// --- Parámetros de los globos (balloons) ---
|
||||||
struct ParamBalloon
|
struct ParamBalloon
|
||||||
{
|
{
|
||||||
float grav; // Aceleración en el eje Y. Modifica la velocidad
|
float grav; // Aceleración en el eje Y. Modifica la velocidad
|
||||||
float vel; // Velocidad inicial que tienen al rebotar contra el suelo
|
float vel; // Velocidad inicial al rebotar contra el suelo
|
||||||
|
|
||||||
// Constructor
|
// Constructor
|
||||||
explicit ParamBalloon(float grav_val = 0.0f, float vel_val = 0.0f)
|
explicit ParamBalloon(float grav_val = 0.0f, float vel_val = 0.0f)
|
||||||
: grav(grav_val), vel(vel_val) {}
|
: grav(grav_val), vel(vel_val) {}
|
||||||
};
|
};
|
||||||
|
|
||||||
// Estructura para las opciones de las notificaciones
|
// --- Parámetros de las notificaciones ---
|
||||||
struct ParamNotification
|
struct ParamNotification
|
||||||
{
|
{
|
||||||
NotifyPosition pos_h; // Ubicación de las notificaciones en pantalla
|
NotifyPosition pos_h; // Ubicación horizontal de las notificaciones en pantalla
|
||||||
NotifyPosition pos_v; // Ubicación de las notificaciones en pantalla
|
NotifyPosition pos_v; // Ubicación vertical de las notificaciones en pantalla
|
||||||
bool sound; // Indica si las notificaciones suenan
|
bool sound; // Indica si las notificaciones suenan
|
||||||
Color color; // Color de las notificaciones
|
Color color; // Color de las notificaciones
|
||||||
};
|
};
|
||||||
|
|
||||||
// Estructura para almacenar todos los parámetros del juego
|
// --- Estructura principal para almacenar todos los parámetros del juego ---
|
||||||
struct Param
|
struct Param
|
||||||
{
|
{
|
||||||
ParamGame game;
|
ParamGame game; // Parámetros del juego
|
||||||
ParamFade fade;
|
ParamFade fade; // Parámetros del fade
|
||||||
SDL_FRect scoreboard;
|
SDL_FRect scoreboard; // Rectángulo del marcador
|
||||||
ParamTitle title;
|
ParamTitle title; // Parámetros de la pantalla de título
|
||||||
ParamBackground background;
|
ParamBackground background; // Parámetros del fondo
|
||||||
std::vector<ParamBalloon> balloon;
|
std::vector<ParamBalloon> balloon; // Parámetros de los globos
|
||||||
ParamNotification notification;
|
ParamNotification notification; // Parámetros de las notificaciones
|
||||||
|
|
||||||
|
// Constructor
|
||||||
Param() : game(), fade(), scoreboard(), title(), background(), notification()
|
Param() : game(), fade(), scoreboard(), title(), background(), notification()
|
||||||
{
|
{
|
||||||
balloon.reserve(4);
|
balloon.reserve(4);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// --- Variable global con los parámetros del juego ---
|
||||||
extern Param param;
|
extern Param param;
|
||||||
|
|
||||||
// Establece valores para los parametros a partir de un fichero de texto
|
// --- Funciones globales ---
|
||||||
void loadParamsFromFile(const std::string &file_path);
|
void loadParamsFromFile(const std::string &file_path); // Establece valores para los parámetros a partir de un fichero de texto
|
||||||
@@ -1,18 +1,21 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
#include <SDL3/SDL_rect.h> // Para SDL_FPoint
|
#include <SDL3/SDL_rect.h> // Para SDL_FPoint
|
||||||
#include <functional> // Para function
|
#include <functional> // Para std::function
|
||||||
#include <memory> // Para shared_ptr
|
#include <memory> // Para shared_ptr
|
||||||
#include <vector> // Para vector
|
#include <vector> // Para vector
|
||||||
#include "sprite.h" // Para Sprite
|
#include "sprite.h" // Para Sprite
|
||||||
class Texture; // lines 8-8
|
|
||||||
|
|
||||||
|
class Texture;
|
||||||
|
|
||||||
|
// --- Tipos de recorrido ---
|
||||||
enum class PathType
|
enum class PathType
|
||||||
{
|
{
|
||||||
VERTICAL,
|
VERTICAL,
|
||||||
HORIZONTAL,
|
HORIZONTAL,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// --- Centrado del recorrido ---
|
||||||
enum class PathCentered
|
enum class PathCentered
|
||||||
{
|
{
|
||||||
ON_X,
|
ON_X,
|
||||||
@@ -20,7 +23,7 @@ enum class PathCentered
|
|||||||
NONE,
|
NONE,
|
||||||
};
|
};
|
||||||
|
|
||||||
// Estructuras
|
// --- Estructura Path: define un recorrido para el sprite ---
|
||||||
struct Path
|
struct Path
|
||||||
{
|
{
|
||||||
std::vector<SDL_FPoint> spots; // Puntos por los que se desplazará el sprite
|
std::vector<SDL_FPoint> spots; // Puntos por los que se desplazará el sprite
|
||||||
@@ -37,47 +40,39 @@ struct Path
|
|||||||
// Devuelve un vector con los puntos que conforman la ruta
|
// Devuelve un vector con los puntos que conforman la ruta
|
||||||
std::vector<SDL_FPoint> createPath(float start, float end, PathType type, float fixed_pos, int steps, const std::function<double(double)> &easingFunction);
|
std::vector<SDL_FPoint> createPath(float start, float end, PathType type, float fixed_pos, int steps, const std::function<double(double)> &easingFunction);
|
||||||
|
|
||||||
// Clase PathSprite
|
// --- Clase PathSprite: Sprite que sigue uno o varios recorridos ---
|
||||||
class PathSprite : public Sprite
|
class PathSprite : public Sprite
|
||||||
{
|
{
|
||||||
private:
|
|
||||||
// Variables
|
|
||||||
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; // Path que se está recorriendo actualmente
|
|
||||||
std::vector<Path> paths_; // Caminos a recorrer por el sprite
|
|
||||||
|
|
||||||
// Coloca el sprite en los diferentes puntos del recorrido
|
|
||||||
void moveThroughCurrentPath();
|
|
||||||
|
|
||||||
// Cambia de recorrido o finaliza
|
|
||||||
void goToNextPathOrDie();
|
|
||||||
|
|
||||||
public:
|
public:
|
||||||
// Constructor
|
// --- Constructor y destructor ---
|
||||||
explicit PathSprite(std::shared_ptr<Texture> texture)
|
explicit PathSprite(std::shared_ptr<Texture> texture)
|
||||||
: Sprite(texture) {}
|
: Sprite(texture) {}
|
||||||
|
|
||||||
// Destructor
|
|
||||||
~PathSprite() override = default;
|
~PathSprite() override = default;
|
||||||
|
|
||||||
// Actualiza la posición del sprite
|
// --- Métodos principales ---
|
||||||
void update();
|
void update(); // Actualiza la posición del sprite según el recorrido
|
||||||
|
void render() override; // Muestra el sprite por pantalla
|
||||||
|
|
||||||
// Muestra el sprite por pantalla
|
// --- Gestión de recorridos ---
|
||||||
void render() override;
|
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)> &easingFunction, int waiting_counter = 0); // Añade un recorrido generado
|
||||||
|
|
||||||
// Añade un recorrido
|
// --- Estado y control ---
|
||||||
void addPath(Path path, bool centered = false);
|
void enable(); // Habilita el objeto
|
||||||
void addPath(std::vector<SDL_FPoint> spots, int waiting_counter = 0);
|
bool hasFinished(); // Indica si ha terminado todos los recorridos
|
||||||
void addPath(int start, int end, PathType type, int fixed_pos, int steps, const std::function<double(double)> &easingFunction, int waiting_counter = 0);
|
|
||||||
|
|
||||||
// Habilita el objeto
|
// --- Getters ---
|
||||||
void enable();
|
int getCurrentPath() const { return current_path_; } // Devuelve el índice del recorrido actual
|
||||||
|
|
||||||
// Indica si ha terminado todos los recorridos
|
private:
|
||||||
bool hasFinished();
|
// --- 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
|
||||||
|
|
||||||
// Getters
|
// --- Métodos internos ---
|
||||||
int getCurrentPath() const { return current_path_; }
|
void moveThroughCurrentPath(); // Coloca el sprite en los diferentes puntos del recorrido
|
||||||
|
void goToNextPathOrDie(); // Cambia de recorrido o finaliza
|
||||||
};
|
};
|
||||||
409
source/player.h
409
source/player.h
@@ -1,257 +1,210 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
#include <SDL3/SDL_rect.h> // Para SDL_FRect
|
#include <SDL3/SDL_rect.h> // Para SDL_FRect
|
||||||
#include <SDL3/SDL_stdinc.h> // Para Uint32
|
#include <SDL3/SDL_stdinc.h> // Para Uint32
|
||||||
#include <memory> // Para unique_ptr, shared_ptr
|
#include <memory> // Para unique_ptr, shared_ptr
|
||||||
#include <string> // Para string
|
#include <string> // Para string
|
||||||
#include <vector> // Para vector
|
#include <vector> // Para vector
|
||||||
#include "animated_sprite.h" // Para AnimatedSprite
|
#include "animated_sprite.h" // Para AnimatedSprite
|
||||||
#include "enter_name.h" // Para EnterName
|
#include "enter_name.h" // Para EnterName
|
||||||
#include "manage_hiscore_table.h" // Para HiScoreEntry
|
#include "manage_hiscore_table.h" // Para HiScoreEntry
|
||||||
#include "options.h" // Para Options, OptionsGame, options
|
#include "options.h" // Para Options, OptionsGame, options
|
||||||
#include "utils.h" // Para Circle
|
#include "utils.h" // Para Circle
|
||||||
class Texture; // lines 13-13
|
|
||||||
enum class InputAction : int; // lines 14-14
|
|
||||||
enum class ScoreboardMode; // lines 15-15
|
|
||||||
|
|
||||||
// Estados del jugador
|
class Texture;
|
||||||
|
enum class InputAction : int;
|
||||||
|
enum class ScoreboardMode;
|
||||||
|
|
||||||
|
// --- Estados del jugador ---
|
||||||
enum class PlayerState
|
enum class PlayerState
|
||||||
{
|
{
|
||||||
WALKING_LEFT,
|
WALKING_LEFT,
|
||||||
WALKING_RIGHT,
|
WALKING_RIGHT,
|
||||||
WALKING_STOP,
|
WALKING_STOP,
|
||||||
|
|
||||||
FIRING_UP,
|
FIRING_UP,
|
||||||
FIRING_LEFT,
|
FIRING_LEFT,
|
||||||
FIRING_RIGHT,
|
FIRING_RIGHT,
|
||||||
FIRING_NONE,
|
FIRING_NONE,
|
||||||
|
|
||||||
COOLING_UP,
|
COOLING_UP,
|
||||||
COOLING_LEFT,
|
COOLING_LEFT,
|
||||||
COOLING_RIGHT,
|
COOLING_RIGHT,
|
||||||
|
|
||||||
PLAYING, // Está jugando
|
PLAYING, // Está jugando
|
||||||
CONTINUE, // Está con la cuenta atras para continuar
|
CONTINUE, // Cuenta atrás para continuar
|
||||||
WAITING, // No está jugando pero puede entrar a jugar
|
WAITING, // No está jugando pero puede entrar a jugar
|
||||||
ENTERING_NAME, // Introduciendo nombre
|
ENTERING_NAME, // Introduciendo nombre
|
||||||
SHOWING_NAME, // Mostrando el nombre introducido
|
SHOWING_NAME, // Mostrando el nombre introducido
|
||||||
DYING, // El cadaver está volando por ahi
|
DYING, // El cadáver está volando por ahí
|
||||||
DIED, // El cadaver ha desaparecido por el fondo
|
DIED, // El cadáver ha desaparecido por el fondo
|
||||||
GAME_OVER, // No está jugando y no puede entrar a jugar
|
GAME_OVER, // No está jugando y no puede entrar a jugar
|
||||||
CELEBRATING, // Poniendo pose de victoria
|
CELEBRATING, // Poniendo pose de victoria
|
||||||
ENTERING_NAME_GAME_COMPLETED, // Poniendo nombre en el tramo final del juego
|
ENTERING_NAME_GAME_COMPLETED, // Poniendo nombre en el tramo final del juego
|
||||||
LEAVING_SCREEN, // Moviendose fuera de la pantalla
|
LEAVING_SCREEN, // Moviéndose fuera de la pantalla
|
||||||
ENTERING_SCREEN, // Entando a la pantalla
|
ENTERING_SCREEN, // Entrando a la pantalla
|
||||||
CREDITS, // Estado para los creditos del juego
|
CREDITS, // Estado para los créditos del juego
|
||||||
};
|
};
|
||||||
|
|
||||||
// Clase Player
|
// --- Clase Player ---
|
||||||
class Player
|
class Player
|
||||||
{
|
{
|
||||||
private:
|
|
||||||
// Constantes
|
|
||||||
static constexpr int POWERUP_COUNTER_ = 1500; // Duración del estado PowerUp
|
|
||||||
static constexpr int INVULNERABLE_COUNTER_ = 200; // Duración del estado invulnerable
|
|
||||||
static constexpr int WIDTH_ = 30; // Anchura
|
|
||||||
static constexpr int HEIGHT_ = 30; // Altura
|
|
||||||
static constexpr float BASE_SPEED_ = 1.5f; // Velocidad base del jugador
|
|
||||||
|
|
||||||
// Objetos y punteros
|
|
||||||
std::unique_ptr<AnimatedSprite> player_sprite_; // Sprite para dibujar el jugador
|
|
||||||
std::unique_ptr<AnimatedSprite> power_sprite_; // Sprite para dibujar el aura del jugador con el poder a tope
|
|
||||||
std::unique_ptr<EnterName> enter_name_; // Clase utilizada para introducir el nombre
|
|
||||||
|
|
||||||
// Variables
|
|
||||||
int id_; // Numero de identificación para el jugador. Player1 = 1, Player2 = 2
|
|
||||||
SDL_FRect play_area_; // Rectangulo con la zona de juego
|
|
||||||
float pos_x_ = 0.0f; // Posicion en el eje X
|
|
||||||
int pos_y_ = 0; // Posicion en el eje Y
|
|
||||||
float default_pos_x_; // Posición inicial para el jugador
|
|
||||||
int default_pos_y_; // Posición inicial para el jugador
|
|
||||||
float vel_x_ = 0.0f; // Cantidad de pixeles a desplazarse en el eje X
|
|
||||||
int vel_y_ = 0.0f; // Cantidad de pixeles a desplazarse en el eje Y
|
|
||||||
int cool_down_ = 0; // Contador durante el cual no puede disparar
|
|
||||||
int cooling_state_counter_ = 0; // Contador para la animación del estado cooling
|
|
||||||
int score_ = 0; // Puntos del jugador
|
|
||||||
float score_multiplier_ = 1.0f; // Multiplicador de puntos
|
|
||||||
PlayerState walking_state_ = PlayerState::WALKING_STOP; // Estado del jugador al moverse
|
|
||||||
PlayerState firing_state_ = PlayerState::FIRING_NONE; // Estado del jugador al disparar
|
|
||||||
PlayerState playing_state_ = PlayerState::WAITING; // Estado del jugador en el juego
|
|
||||||
bool invulnerable_ = true; // Indica si el jugador es invulnerable
|
|
||||||
int invulnerable_counter_ = INVULNERABLE_COUNTER_; // Contador para la invulnerabilidad
|
|
||||||
bool extra_hit_ = false; // Indica si el jugador tiene un toque extra
|
|
||||||
int coffees_ = 0; // Indica cuantos cafes lleva acumulados
|
|
||||||
bool power_up_ = false; // Indica si el jugador tiene activo el modo PowerUp
|
|
||||||
int power_up_counter_ = POWERUP_COUNTER_; // Temporizador para el modo PowerUp
|
|
||||||
int power_up_desp_x_ = 0; // Desplazamiento del sprite de PowerUp respecto al sprite del jugador
|
|
||||||
Circle collider_ = Circle(0, 0, 9); // Circulo de colisión del jugador
|
|
||||||
int continue_counter_ = 10; // Contador para poder continuar
|
|
||||||
Uint32 continue_ticks_ = 0; // Variable para poder cambiar el contador de continue en función del tiempo
|
|
||||||
int scoreboard_panel_ = 0; // Panel del marcador asociado al jugador
|
|
||||||
std::string name_; // Nombre del jugador
|
|
||||||
int controller_index_ = 0; // Indice del array de mandos que utilizará para moverse
|
|
||||||
bool demo_; // Para que el jugador sepa si está en el modo demostración
|
|
||||||
int enter_name_counter_; // Contador para poner nombre
|
|
||||||
Uint32 enter_name_ticks_ = 0; // Variable para poder cambiar el contador de poner nombre en función del tiempo
|
|
||||||
Uint32 showing_name_ticks_ = 0; // Tiempo en el que se entra al estado SHOWING_NAME
|
|
||||||
int step_counter_ = 0; // Cuenta los pasos para los estados en los que camina automáticamente
|
|
||||||
bool game_completed_ = false; // Indica si ha completado el juego
|
|
||||||
int credits_used_ = 1; // Indica el numero de veces que ha continuado
|
|
||||||
std::string last_enter_name_; // Ultimo nombre introducido en la tabla de puntuaciones
|
|
||||||
|
|
||||||
// Actualiza el circulo de colisión a la posición del jugador
|
|
||||||
void shiftColliders();
|
|
||||||
|
|
||||||
// Recoloca el sprite
|
|
||||||
void shiftSprite();
|
|
||||||
|
|
||||||
// Monitoriza el estado
|
|
||||||
void updateInvulnerable();
|
|
||||||
|
|
||||||
// Actualiza el contador de continue
|
|
||||||
void updateContinueCounter();
|
|
||||||
|
|
||||||
// Actualiza el contador de entrar nombre
|
|
||||||
void updateEnterNameCounter();
|
|
||||||
|
|
||||||
// Actualiza el estado de SHOWING_NAME
|
|
||||||
void updateShowingName();
|
|
||||||
|
|
||||||
// Decrementa el contador de entrar nombre
|
|
||||||
void decEnterNameCounter();
|
|
||||||
|
|
||||||
// Actualiza el panel del marcador
|
|
||||||
void updateScoreboard();
|
|
||||||
|
|
||||||
// Cambia el modo del marcador
|
|
||||||
void setScoreboardMode(ScoreboardMode mode);
|
|
||||||
|
|
||||||
// Hace sonar un ruido al azar
|
|
||||||
void playRandomBubbleSound();
|
|
||||||
|
|
||||||
// Getters
|
|
||||||
bool isRenderable() const { return !isWaiting() && !isGameOver(); }
|
|
||||||
|
|
||||||
public:
|
public:
|
||||||
// Constructor
|
// --- Constructor y destructor ---
|
||||||
Player(int id, float x, int y, bool demo, SDL_FRect &play_area, std::vector<std::shared_ptr<Texture>> texture, const std::vector<std::vector<std::string>> &animations);
|
Player(int id, float x, int y, bool demo, SDL_FRect &play_area, std::vector<std::shared_ptr<Texture>> texture, const std::vector<std::vector<std::string>> &animations);
|
||||||
|
~Player() = default;
|
||||||
|
|
||||||
// Destructor
|
// --- Inicialización y ciclo de vida ---
|
||||||
~Player() = default;
|
void init(); // Inicializa el jugador
|
||||||
|
void update(); // Actualiza estado, animación y contadores
|
||||||
|
void render(); // Dibuja el jugador en pantalla
|
||||||
|
|
||||||
// Iniciador
|
// --- Entrada y control ---
|
||||||
void init();
|
void setInput(InputAction input); // Procesa entrada general
|
||||||
|
void setInputPlaying(InputAction input); // Procesa entrada en modo jugando
|
||||||
|
void setInputEnteringName(InputAction input); // Procesa entrada al introducir nombre
|
||||||
|
|
||||||
// Actualiza al jugador a su posicion, animación y controla los contadores
|
// --- Movimiento y animación ---
|
||||||
void update();
|
void move(); // Mueve el jugador
|
||||||
|
void setAnimation(); // Establece la animación según el estado
|
||||||
|
|
||||||
// Pinta el jugador en pantalla
|
// --- Texturas y animaciones ---
|
||||||
void render();
|
void setPlayerTextures(const std::vector<std::shared_ptr<Texture>> &texture); // Cambia las texturas del jugador
|
||||||
|
|
||||||
// Pone las texturas del jugador
|
// --- Estados y contadores ---
|
||||||
void setPlayerTextures(const std::vector<std::shared_ptr<Texture>> &texture);
|
void updateCooldown(); // Actualiza el cooldown de disparo
|
||||||
|
|
||||||
// Actua en consecuencia de la entrada recibida
|
// --- Puntuación y marcador ---
|
||||||
void setInput(InputAction input);
|
void addScore(int score); // Añade puntos
|
||||||
|
void incScoreMultiplier(); // Incrementa el multiplicador
|
||||||
|
void decScoreMultiplier(); // Decrementa el multiplicador
|
||||||
|
|
||||||
// Procesa inputs para cuando está jugando
|
// --- Estados de juego ---
|
||||||
void setInputPlaying(InputAction input);
|
void setPlayingState(PlayerState state); // Cambia el estado de juego
|
||||||
|
void setInvulnerable(bool value); // Establece el valor del estado de invulnerabilidad
|
||||||
|
void setPowerUp(); // Activa el modo PowerUp
|
||||||
|
void updatePowerUp(); // Actualiza el valor de PowerUp
|
||||||
|
void giveExtraHit(); // Concede un toque extra al jugador
|
||||||
|
void removeExtraHit(); // Quita el toque extra al jugador
|
||||||
|
void decContinueCounter(); // Decrementa el contador de continuar
|
||||||
|
|
||||||
// Procesa inputs para cuando está introduciendo el nombre
|
// --- Getters y comprobaciones de estado ---
|
||||||
void setInputEnteringName(InputAction input);
|
int getRecordNamePos() const; // Obtiene la posición que se está editando del nombre del jugador para la tabla de mejores puntuaciones
|
||||||
|
|
||||||
// Mueve el jugador a la posición y animación que le corresponde
|
// Comprobación de playing_state
|
||||||
void move();
|
bool hasDied() const { return playing_state_ == PlayerState::DIED; }
|
||||||
|
bool isCelebrating() const { return playing_state_ == PlayerState::CELEBRATING; }
|
||||||
|
bool isContinue() const { return playing_state_ == PlayerState::CONTINUE; }
|
||||||
|
bool isDying() const { return playing_state_ == PlayerState::DYING; }
|
||||||
|
bool isEnteringName() const { return playing_state_ == PlayerState::ENTERING_NAME; }
|
||||||
|
bool isShowingName() const { return playing_state_ == PlayerState::SHOWING_NAME; }
|
||||||
|
bool isEnteringNameGameCompleted() const { return playing_state_ == PlayerState::ENTERING_NAME_GAME_COMPLETED; }
|
||||||
|
bool isLeavingScreen() const { return playing_state_ == PlayerState::LEAVING_SCREEN; }
|
||||||
|
bool isGameOver() const { return playing_state_ == PlayerState::GAME_OVER; }
|
||||||
|
bool isPlaying() const { return playing_state_ == PlayerState::PLAYING; }
|
||||||
|
bool isWaiting() const { return playing_state_ == PlayerState::WAITING; }
|
||||||
|
|
||||||
// Establece la animación correspondiente al estado
|
// Getters
|
||||||
void setAnimation();
|
bool canFire() const { return cool_down_ <= 0; }
|
||||||
|
bool hasExtraHit() const { return extra_hit_; }
|
||||||
|
bool isCooling() const { return firing_state_ == PlayerState::COOLING_LEFT || firing_state_ == PlayerState::COOLING_UP || firing_state_ == PlayerState::COOLING_RIGHT; }
|
||||||
|
bool IsEligibleForHighScore() const { return score_ > options.game.hi_score_table.back().score; }
|
||||||
|
bool isInvulnerable() const { return invulnerable_; }
|
||||||
|
bool isPowerUp() const { return power_up_; }
|
||||||
|
Circle &getCollider() { return collider_; }
|
||||||
|
float getScoreMultiplier() const { return score_multiplier_; }
|
||||||
|
int getCoffees() const { return coffees_; }
|
||||||
|
int getContinueCounter() const { return continue_counter_; }
|
||||||
|
int getController() const { return controller_index_; }
|
||||||
|
int getHeight() const { return HEIGHT_; }
|
||||||
|
int getId() const { return id_; }
|
||||||
|
int getInvulnerableCounter() const { return invulnerable_counter_; }
|
||||||
|
int getPosX() const { return static_cast<int>(pos_x_); }
|
||||||
|
int getPosY() const { return pos_y_; }
|
||||||
|
int getPowerUpCounter() const { return power_up_counter_; }
|
||||||
|
std::string getRecordName() const { return enter_name_ ? enter_name_->getFinalName() : ""; }
|
||||||
|
int getScore() const { return score_; }
|
||||||
|
int getScoreBoardPanel() const { return scoreboard_panel_; }
|
||||||
|
int getWidth() const { return WIDTH_; }
|
||||||
|
PlayerState getPlayingState() const { return playing_state_; }
|
||||||
|
const std::string &getName() const { return name_; }
|
||||||
|
bool get1CC() const { return game_completed_ && credits_used_ == 1; }
|
||||||
|
bool getEnterNamePositionOverflow() const { return enter_name_ ? enter_name_->getPositionOverflow() : false; }
|
||||||
|
|
||||||
// Actualiza el valor de la variable
|
// Setters inline
|
||||||
void updateCooldown();
|
void setController(int index) { controller_index_ = index; }
|
||||||
|
void setFireCooldown(int time) { cool_down_ = time; }
|
||||||
|
void setFiringState(PlayerState state) { firing_state_ = state; }
|
||||||
|
void setInvulnerableCounter(int value) { invulnerable_counter_ = value; }
|
||||||
|
void setName(const std::string &name) { name_ = name; }
|
||||||
|
void setPowerUpCounter(int value) { power_up_counter_ = value; }
|
||||||
|
void setScore(int score) { score_ = score; }
|
||||||
|
void setScoreBoardPanel(int panel) { scoreboard_panel_ = panel; }
|
||||||
|
void setScoreMultiplier(float value) { score_multiplier_ = value; }
|
||||||
|
void setWalkingState(PlayerState state) { walking_state_ = state; }
|
||||||
|
void addCredit() { ++credits_used_; }
|
||||||
|
|
||||||
// Incrementa la puntuación del jugador
|
private:
|
||||||
void addScore(int score);
|
// --- Constantes ---
|
||||||
|
static constexpr int POWERUP_COUNTER_ = 1500; // Duración del estado PowerUp
|
||||||
|
static constexpr int INVULNERABLE_COUNTER_ = 200; // Duración del estado invulnerable
|
||||||
|
static constexpr int WIDTH_ = 30; // Anchura
|
||||||
|
static constexpr int HEIGHT_ = 30; // Altura
|
||||||
|
static constexpr float BASE_SPEED_ = 1.5f; // Velocidad base del jugador
|
||||||
|
|
||||||
// Establece el estado del jugador en el juego
|
// --- Objetos y punteros ---
|
||||||
void setPlayingState(PlayerState state);
|
std::unique_ptr<AnimatedSprite> player_sprite_; // Sprite para dibujar el jugador
|
||||||
|
std::unique_ptr<AnimatedSprite> power_sprite_; // Sprite para dibujar el aura del jugador con el poder a tope
|
||||||
|
std::unique_ptr<EnterName> enter_name_; // Clase utilizada para introducir el nombre
|
||||||
|
|
||||||
// Aumenta el valor de la variable hasta un máximo
|
// --- Variables de estado ---
|
||||||
void incScoreMultiplier();
|
int id_; // Número de identificación para el jugador. Player1 = 1, Player2 = 2
|
||||||
|
SDL_FRect play_area_; // Rectángulo con la zona de juego
|
||||||
|
float pos_x_ = 0.0f; // Posición en el eje X
|
||||||
|
int pos_y_ = 0; // Posición en el eje Y
|
||||||
|
float default_pos_x_; // Posición inicial para el jugador
|
||||||
|
int default_pos_y_; // Posición inicial para el jugador
|
||||||
|
float vel_x_ = 0.0f; // Cantidad de píxeles a desplazarse en el eje X
|
||||||
|
int vel_y_ = 0.0f; // Cantidad de píxeles a desplazarse en el eje Y
|
||||||
|
int cool_down_ = 0; // Contador durante el cual no puede disparar
|
||||||
|
int cooling_state_counter_ = 0; // Contador para la animación del estado cooling
|
||||||
|
int score_ = 0; // Puntos del jugador
|
||||||
|
float score_multiplier_ = 1.0f; // Multiplicador de puntos
|
||||||
|
PlayerState walking_state_ = PlayerState::WALKING_STOP; // Estado del jugador al moverse
|
||||||
|
PlayerState firing_state_ = PlayerState::FIRING_NONE; // Estado del jugador al disparar
|
||||||
|
PlayerState playing_state_ = PlayerState::WAITING; // Estado del jugador en el juego
|
||||||
|
bool invulnerable_ = true; // Indica si el jugador es invulnerable
|
||||||
|
int invulnerable_counter_ = INVULNERABLE_COUNTER_; // Contador para la invulnerabilidad
|
||||||
|
bool extra_hit_ = false; // Indica si el jugador tiene un toque extra
|
||||||
|
int coffees_ = 0; // Indica cuántos cafés lleva acumulados
|
||||||
|
bool power_up_ = false; // Indica si el jugador tiene activo el modo PowerUp
|
||||||
|
int power_up_counter_ = POWERUP_COUNTER_; // Temporizador para el modo PowerUp
|
||||||
|
int power_up_desp_x_ = 0; // Desplazamiento del sprite de PowerUp respecto al sprite del jugador
|
||||||
|
Circle collider_ = Circle(0, 0, 9); // Círculo de colisión del jugador
|
||||||
|
int continue_counter_ = 10; // Contador para poder continuar
|
||||||
|
Uint32 continue_ticks_ = 0; // Variable para poder cambiar el contador de continue en función del tiempo
|
||||||
|
int scoreboard_panel_ = 0; // Panel del marcador asociado al jugador
|
||||||
|
std::string name_; // Nombre del jugador
|
||||||
|
int controller_index_ = 0; // Índice del array de mandos que utilizará para moverse
|
||||||
|
bool demo_; // Para que el jugador sepa si está en el modo demostración
|
||||||
|
int enter_name_counter_; // Contador para poner nombre
|
||||||
|
Uint32 enter_name_ticks_ = 0; // Variable para poder cambiar el contador de poner nombre en función del tiempo
|
||||||
|
Uint32 showing_name_ticks_ = 0; // Tiempo en el que se entra al estado SHOWING_NAME
|
||||||
|
int step_counter_ = 0; // Cuenta los pasos para los estados en los que camina automáticamente
|
||||||
|
bool game_completed_ = false; // Indica si ha completado el juego
|
||||||
|
int credits_used_ = 1; // Indica el número de veces que ha continuado
|
||||||
|
std::string last_enter_name_; // Último nombre introducido en la tabla de puntuaciones
|
||||||
|
|
||||||
// Decrementa el valor de la variable hasta un mínimo
|
// --- Métodos internos ---
|
||||||
void decScoreMultiplier();
|
void shiftColliders(); // Actualiza el círculo de colisión a la posición del jugador
|
||||||
|
void shiftSprite(); // Recoloca el sprite
|
||||||
// Establece el valor del estado
|
void updateInvulnerable(); // Monitoriza el estado de invulnerabilidad
|
||||||
void setInvulnerable(bool value);
|
void updateContinueCounter(); // Actualiza el contador de continue
|
||||||
|
void updateEnterNameCounter();// Actualiza el contador de entrar nombre
|
||||||
// Establece el valor de la variable a verdadero
|
void updateShowingName(); // Actualiza el estado SHOWING_NAME
|
||||||
void setPowerUp();
|
void decEnterNameCounter(); // Decrementa el contador de entrar nombre
|
||||||
|
void updateScoreboard(); // Actualiza el panel del marcador
|
||||||
// Actualiza el valor de la variable
|
void setScoreboardMode(ScoreboardMode mode); // Cambia el modo del marcador
|
||||||
void updatePowerUp();
|
void playRandomBubbleSound(); // Hace sonar un sonido aleatorio
|
||||||
|
bool isRenderable() const { return !isWaiting() && !isGameOver(); }
|
||||||
// Concede un toque extra al jugador
|
};
|
||||||
void giveExtraHit();
|
|
||||||
|
|
||||||
// Quita el toque extra al jugador
|
|
||||||
void removeExtraHit();
|
|
||||||
|
|
||||||
// Decrementa el contador de continuar
|
|
||||||
void decContinueCounter();
|
|
||||||
|
|
||||||
// Obtiene la posición que se está editando del nombre del jugador para la tabla de mejores puntuaciones
|
|
||||||
int getRecordNamePos() const;
|
|
||||||
|
|
||||||
// Comprobación de playing_state
|
|
||||||
bool hasDied() const { return playing_state_ == PlayerState::DIED; }
|
|
||||||
bool isCelebrating() const { return playing_state_ == PlayerState::CELEBRATING; }
|
|
||||||
bool isContinue() const { return playing_state_ == PlayerState::CONTINUE; }
|
|
||||||
bool isDying() const { return playing_state_ == PlayerState::DYING; }
|
|
||||||
bool isEnteringName() const { return playing_state_ == PlayerState::ENTERING_NAME; }
|
|
||||||
bool isShowingName() const { return playing_state_ == PlayerState::SHOWING_NAME; }
|
|
||||||
bool isEnteringNameGameCompleted() const { return playing_state_ == PlayerState::ENTERING_NAME_GAME_COMPLETED; }
|
|
||||||
bool isLeavingScreen() const { return playing_state_ == PlayerState::LEAVING_SCREEN; }
|
|
||||||
bool isGameOver() const { return playing_state_ == PlayerState::GAME_OVER; }
|
|
||||||
bool isPlaying() const { return playing_state_ == PlayerState::PLAYING; }
|
|
||||||
bool isWaiting() const { return playing_state_ == PlayerState::WAITING; }
|
|
||||||
|
|
||||||
// Getters
|
|
||||||
bool canFire() const { return cool_down_ > 0 ? false : true; }
|
|
||||||
bool hasExtraHit() const { return extra_hit_; }
|
|
||||||
bool isCooling() const { return firing_state_ == PlayerState::COOLING_LEFT || firing_state_ == PlayerState::COOLING_UP || firing_state_ == PlayerState::COOLING_RIGHT; }
|
|
||||||
bool IsEligibleForHighScore() const { return score_ > options.game.hi_score_table.back().score; }
|
|
||||||
bool isInvulnerable() const { return invulnerable_; }
|
|
||||||
bool isPowerUp() const { return power_up_; }
|
|
||||||
Circle &getCollider() { return collider_; }
|
|
||||||
float getScoreMultiplier() const { return score_multiplier_; }
|
|
||||||
int getCoffees() const { return coffees_; }
|
|
||||||
int getContinueCounter() const { return continue_counter_; }
|
|
||||||
int getController() const { return controller_index_; }
|
|
||||||
int getHeight() const { return HEIGHT_; }
|
|
||||||
int getId() const { return id_; }
|
|
||||||
int getInvulnerableCounter() const { return invulnerable_counter_; }
|
|
||||||
int getPosX() const { return static_cast<int>(pos_x_); }
|
|
||||||
int getPosY() const { return pos_y_; }
|
|
||||||
int getPowerUpCounter() const { return power_up_counter_; }
|
|
||||||
std::string getRecordName() const { return enter_name_->getFinalName(); }
|
|
||||||
int getScore() const { return score_; }
|
|
||||||
int getScoreBoardPanel() const { return scoreboard_panel_; }
|
|
||||||
int getWidth() const { return WIDTH_; }
|
|
||||||
PlayerState getPlayingState() const { return playing_state_; }
|
|
||||||
const std::string &getName() const { return name_; }
|
|
||||||
bool get1CC() const { return game_completed_ && credits_used_ == 1; }
|
|
||||||
bool getEnterNamePositionOverflow() const { return enter_name_->getPositionOverflow(); }
|
|
||||||
|
|
||||||
// Setters
|
|
||||||
void setController(int index) { controller_index_ = index; }
|
|
||||||
void setFireCooldown(int time) { cool_down_ = time; }
|
|
||||||
void setFiringState(PlayerState state) { firing_state_ = state; }
|
|
||||||
void setInvulnerableCounter(int value) { invulnerable_counter_ = value; }
|
|
||||||
void setName(const std::string &name) { name_ = name; }
|
|
||||||
void setPowerUpCounter(int value) { power_up_counter_ = value; }
|
|
||||||
void setScore(int score) { score_ = score; }
|
|
||||||
void setScoreBoardPanel(int panel) { scoreboard_panel_ = panel; }
|
|
||||||
void setScoreMultiplier(float value) { score_multiplier_ = value; }
|
|
||||||
void setWalkingState(PlayerState state) { walking_state_ = state; }
|
|
||||||
void addCredit() { ++credits_used_; }
|
|
||||||
};
|
|
||||||
@@ -4,173 +4,126 @@
|
|||||||
#include <string> // Para string
|
#include <string> // Para string
|
||||||
#include <vector> // Para vector
|
#include <vector> // Para vector
|
||||||
#include "animated_sprite.h" // Para AnimationsFileBuffer
|
#include "animated_sprite.h" // Para AnimationsFileBuffer
|
||||||
#include "text.h" // Para TextFile
|
#include "text.h" // Para TextFile, Text
|
||||||
#include "texture.h" // Para Texture
|
#include "texture.h" // Para Texture
|
||||||
#include "utils.h" // Para DemoData
|
#include "utils.h" // Para DemoData
|
||||||
|
|
||||||
struct JA_Music_t;
|
struct JA_Music_t;
|
||||||
struct JA_Sound_t;
|
struct JA_Sound_t;
|
||||||
|
|
||||||
// Estructura para almacenar ficheros de sonido y su nombre
|
// --- Estructuras para recursos individuales ---
|
||||||
|
|
||||||
|
// Sonido
|
||||||
struct ResourceSound
|
struct ResourceSound
|
||||||
{
|
{
|
||||||
std::string name; // Nombre del sonido
|
std::string name; // Nombre del sonido
|
||||||
JA_Sound_t *sound; // Objeto con el sonido
|
JA_Sound_t *sound; // Objeto con el sonido
|
||||||
|
|
||||||
// Constructor
|
|
||||||
ResourceSound(const std::string &name, JA_Sound_t *sound)
|
ResourceSound(const std::string &name, JA_Sound_t *sound)
|
||||||
: name(name), sound(sound) {}
|
: name(name), sound(sound) {}
|
||||||
};
|
};
|
||||||
|
|
||||||
// Estructura para almacenar ficheros musicales y su nombre
|
// Música
|
||||||
struct ResourceMusic
|
struct ResourceMusic
|
||||||
{
|
{
|
||||||
std::string name; // Nombre de la musica
|
std::string name; // Nombre de la música
|
||||||
JA_Music_t *music; // Objeto con la música
|
JA_Music_t *music; // Objeto con la música
|
||||||
|
|
||||||
// Constructor
|
|
||||||
ResourceMusic(const std::string &name, JA_Music_t *music)
|
ResourceMusic(const std::string &name, JA_Music_t *music)
|
||||||
: name(name), music(music) {}
|
: name(name), music(music) {}
|
||||||
};
|
};
|
||||||
|
|
||||||
// Estructura para almacenar objetos Texture y su nombre
|
// Textura
|
||||||
struct ResourceTexture
|
struct ResourceTexture
|
||||||
{
|
{
|
||||||
std::string name; // Nombre de la textura
|
std::string name; // Nombre de la textura
|
||||||
std::shared_ptr<Texture> texture; // Objeto con la textura
|
std::shared_ptr<Texture> texture; // Objeto con la textura
|
||||||
|
|
||||||
// Constructor
|
|
||||||
ResourceTexture(const std::string &name, std::shared_ptr<Texture> texture)
|
ResourceTexture(const std::string &name, std::shared_ptr<Texture> texture)
|
||||||
: name(name), texture(texture) {}
|
: name(name), texture(texture) {}
|
||||||
};
|
};
|
||||||
|
|
||||||
// Estructura para almacenar ficheros TextFile y su nombre
|
// Fichero de texto (fuente)
|
||||||
struct ResourceTextFile
|
struct ResourceTextFile
|
||||||
{
|
{
|
||||||
std::string name; // Nombre del fichero
|
std::string name; // Nombre del fichero
|
||||||
std::shared_ptr<TextFile> text_file; // Objeto con los descriptores de la fuente de texto
|
std::shared_ptr<TextFile> text_file; // Objeto con los descriptores de la fuente de texto
|
||||||
|
|
||||||
// Constructor
|
|
||||||
ResourceTextFile(const std::string &name, std::shared_ptr<TextFile> text_file)
|
ResourceTextFile(const std::string &name, std::shared_ptr<TextFile> text_file)
|
||||||
: name(name), text_file(text_file) {}
|
: name(name), text_file(text_file) {}
|
||||||
};
|
};
|
||||||
|
|
||||||
// Estructura para almacenar objetos Text y su nombre
|
// Objeto de texto
|
||||||
struct ResourceText
|
struct ResourceText
|
||||||
{
|
{
|
||||||
std::string name; // Nombre del objeto
|
std::string name; // Nombre del objeto
|
||||||
std::shared_ptr<Text> text; // Objeto
|
std::shared_ptr<Text> text; // Objeto
|
||||||
|
|
||||||
// Constructor
|
|
||||||
ResourceText(const std::string &name, std::shared_ptr<Text> text)
|
ResourceText(const std::string &name, std::shared_ptr<Text> text)
|
||||||
: name(name), text(text) {}
|
: name(name), text(text) {}
|
||||||
};
|
};
|
||||||
|
|
||||||
// Estructura para almacenar ficheros animaciones y su nombre
|
// Animación
|
||||||
struct ResourceAnimation
|
struct ResourceAnimation
|
||||||
{
|
{
|
||||||
std::string name; // Nombre del fichero
|
std::string name; // Nombre del fichero
|
||||||
AnimationsFileBuffer animation; // Objeto con las animaciones
|
AnimationsFileBuffer animation; // Objeto con las animaciones
|
||||||
|
|
||||||
// Constructor
|
|
||||||
ResourceAnimation(const std::string &name, const AnimationsFileBuffer &animation)
|
ResourceAnimation(const std::string &name, const AnimationsFileBuffer &animation)
|
||||||
: name(name), animation(animation) {}
|
: name(name), animation(animation) {}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// --- Clase Resource: gestiona todos los recursos del juego (singleton) ---
|
||||||
class Resource
|
class Resource
|
||||||
{
|
{
|
||||||
|
public:
|
||||||
|
// --- Métodos de singleton ---
|
||||||
|
static void init(); // Inicializa el objeto Resource
|
||||||
|
static void destroy(); // Libera el objeto Resource
|
||||||
|
static Resource *get(); // Obtiene el puntero al objeto Resource
|
||||||
|
|
||||||
|
// --- Métodos de acceso a recursos ---
|
||||||
|
JA_Sound_t *getSound(const std::string &name); // Obtiene el sonido por nombre
|
||||||
|
JA_Music_t *getMusic(const std::string &name); // Obtiene la música por nombre
|
||||||
|
std::shared_ptr<Texture> getTexture(const std::string &name); // Obtiene la textura por nombre
|
||||||
|
std::shared_ptr<TextFile> getTextFile(const std::string &name); // Obtiene el fichero de texto por nombre
|
||||||
|
std::shared_ptr<Text> getText(const std::string &name); // Obtiene el objeto de texto por nombre
|
||||||
|
AnimationsFileBuffer &getAnimation(const std::string &name); // Obtiene la animación por nombre
|
||||||
|
DemoData &getDemoData(int index); // Obtiene los datos de demo por índice
|
||||||
|
|
||||||
|
// --- Recarga de recursos ---
|
||||||
|
void reload(); // Recarga todos los recursos
|
||||||
|
void reloadTextures(); // Recarga solo las texturas
|
||||||
|
|
||||||
private:
|
private:
|
||||||
// [SINGLETON] Objeto resource privado
|
// --- Singleton ---
|
||||||
static Resource *resource_;
|
static Resource *resource_;
|
||||||
|
|
||||||
|
// --- Vectores de recursos ---
|
||||||
std::vector<ResourceSound> sounds_; // Vector con los sonidos
|
std::vector<ResourceSound> sounds_; // Vector con los sonidos
|
||||||
std::vector<ResourceMusic> musics_; // Vector con las musicas
|
std::vector<ResourceMusic> musics_; // Vector con las músicas
|
||||||
std::vector<ResourceTexture> textures_; // Vector con las musicas
|
std::vector<ResourceTexture> textures_; // Vector con las texturas
|
||||||
std::vector<ResourceTextFile> text_files_; // Vector con los ficheros de texto
|
std::vector<ResourceTextFile> text_files_; // Vector con los ficheros de texto
|
||||||
std::vector<ResourceText> texts_; // Vector con los objetos de texto
|
std::vector<ResourceText> texts_; // Vector con los objetos de texto
|
||||||
std::vector<ResourceAnimation> animations_; // Vector con las animaciones
|
std::vector<ResourceAnimation> animations_; // Vector con las animaciones
|
||||||
std::vector<DemoData> demos_; // Vector con los ficheros de datos para el modo demostración
|
std::vector<DemoData> demos_; // Vector con los ficheros de datos para el modo demostración
|
||||||
|
|
||||||
// Carga los sonidos
|
// --- Métodos internos de carga y gestión ---
|
||||||
void loadSounds();
|
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
|
||||||
|
|
||||||
// Carga las musicas
|
// --- Constructores y destructor privados (singleton) ---
|
||||||
void loadMusics();
|
Resource(); // Constructor privado
|
||||||
|
~Resource() = default; // Destructor privado
|
||||||
// Carga las texturas
|
|
||||||
void loadTextures();
|
|
||||||
|
|
||||||
// Carga los ficheros de texto
|
|
||||||
void loadTextFiles();
|
|
||||||
|
|
||||||
// Carga las animaciones
|
|
||||||
void loadAnimations();
|
|
||||||
|
|
||||||
// Carga los datos para el modo demostración
|
|
||||||
void loadDemoData();
|
|
||||||
|
|
||||||
// Añade paletas a las texturas
|
|
||||||
void addPalettes();
|
|
||||||
|
|
||||||
// Crea texturas
|
|
||||||
void createTextures();
|
|
||||||
|
|
||||||
// Crea los objetos de texto
|
|
||||||
void createText();
|
|
||||||
|
|
||||||
// Vacia todos los vectores de recursos
|
|
||||||
void clear();
|
|
||||||
|
|
||||||
// Carga todos los recursos
|
|
||||||
void load();
|
|
||||||
|
|
||||||
// Vacía el vector de sonidos
|
|
||||||
void clearSounds();
|
|
||||||
|
|
||||||
// Vacía el vector de musicas
|
|
||||||
void clearMusics();
|
|
||||||
|
|
||||||
// [SINGLETON] Ahora el constructor y el destructor son privados, para no poder crear objetos resource desde fuera
|
|
||||||
|
|
||||||
// Constructor
|
|
||||||
Resource();
|
|
||||||
|
|
||||||
// Destructor
|
|
||||||
~Resource() = default;
|
|
||||||
|
|
||||||
public:
|
|
||||||
// [SINGLETON] Crearemos el objeto resource con esta función estática
|
|
||||||
static void init();
|
|
||||||
|
|
||||||
// [SINGLETON] Destruiremos el objeto resource con esta función estática
|
|
||||||
static void destroy();
|
|
||||||
|
|
||||||
// [SINGLETON] Con este método obtenemos el objeto resource y podemos trabajar con él
|
|
||||||
static Resource *get();
|
|
||||||
|
|
||||||
// Obtiene el sonido a partir de un nombre
|
|
||||||
JA_Sound_t *getSound(const std::string &name);
|
|
||||||
|
|
||||||
// Obtiene la música a partir de un nombre
|
|
||||||
JA_Music_t *getMusic(const std::string &name);
|
|
||||||
|
|
||||||
// Obtiene la textura a partir de un nombre
|
|
||||||
std::shared_ptr<Texture> getTexture(const std::string &name);
|
|
||||||
|
|
||||||
// Obtiene el fichero de texto a partir de un nombre
|
|
||||||
std::shared_ptr<TextFile> getTextFile(const std::string &name);
|
|
||||||
|
|
||||||
// Obtiene el objeto de texto a partir de un nombre
|
|
||||||
std::shared_ptr<Text> getText(const std::string &name);
|
|
||||||
|
|
||||||
// Obtiene la animación a partir de un nombre
|
|
||||||
AnimationsFileBuffer &getAnimation(const std::string &name);
|
|
||||||
|
|
||||||
// Obtiene el fichero con los datos para el modo demostración a partir de un çindice
|
|
||||||
DemoData &getDemoData(int index);
|
|
||||||
|
|
||||||
// Recarga todos los recursos
|
|
||||||
void reload();
|
|
||||||
|
|
||||||
// Recarga las texturas
|
|
||||||
void reloadTextures();
|
|
||||||
};
|
};
|
||||||
@@ -9,17 +9,18 @@
|
|||||||
#include <string> // Para string
|
#include <string> // Para string
|
||||||
#include <vector> // Para vector
|
#include <vector> // Para vector
|
||||||
#include "utils.h" // Para Color
|
#include "utils.h" // Para Color
|
||||||
class Sprite; // lines 11-11
|
|
||||||
class Text; // lines 12-12
|
|
||||||
class Texture; // lines 13-13
|
|
||||||
|
|
||||||
// Defines
|
class Sprite;
|
||||||
|
class Text;
|
||||||
|
class Texture;
|
||||||
|
|
||||||
|
// --- Defines ---
|
||||||
constexpr int SCOREBOARD_LEFT_PANEL = 0;
|
constexpr int SCOREBOARD_LEFT_PANEL = 0;
|
||||||
constexpr int SCOREBOARD_CENTER_PANEL = 1;
|
constexpr int SCOREBOARD_CENTER_PANEL = 1;
|
||||||
constexpr int SCOREBOARD_RIGHT_PANEL = 2;
|
constexpr int SCOREBOARD_RIGHT_PANEL = 2;
|
||||||
constexpr int SCOREBOARD_MAX_PANELS = 3;
|
constexpr int SCOREBOARD_MAX_PANELS = 3;
|
||||||
|
|
||||||
// Enums
|
// --- Enums ---
|
||||||
enum class ScoreboardMode : int
|
enum class ScoreboardMode : int
|
||||||
{
|
{
|
||||||
SCORE,
|
SCORE,
|
||||||
@@ -34,32 +35,55 @@ enum class ScoreboardMode : int
|
|||||||
NUM_MODES,
|
NUM_MODES,
|
||||||
};
|
};
|
||||||
|
|
||||||
// Structs
|
// --- Structs ---
|
||||||
struct Panel
|
struct Panel
|
||||||
{
|
{
|
||||||
ScoreboardMode mode; // Modo en el que se encuentra el panel
|
ScoreboardMode mode; // Modo en el que se encuentra el panel
|
||||||
SDL_FRect pos; // Posición donde dibujar el panel dentro del marcador
|
SDL_FRect pos; // Posición donde dibujar el panel dentro del marcador
|
||||||
};
|
};
|
||||||
|
|
||||||
// Clase Scoreboard
|
// --- Clase Scoreboard ---
|
||||||
class Scoreboard
|
class Scoreboard
|
||||||
{
|
{
|
||||||
|
public:
|
||||||
|
// --- Métodos de singleton ---
|
||||||
|
static void init(); // Crea el objeto Scoreboard
|
||||||
|
static void destroy(); // Libera el objeto Scoreboard
|
||||||
|
static Scoreboard *get(); // Obtiene el puntero al objeto Scoreboard
|
||||||
|
|
||||||
|
// --- Métodos principales ---
|
||||||
|
void update(); // Actualiza la lógica del marcador
|
||||||
|
void render(); // Pinta el marcador
|
||||||
|
|
||||||
|
// --- Setters ---
|
||||||
|
void setColor(Color color); // Establece el color del marcador
|
||||||
|
void setPos(SDL_FRect rect); // Establece la posición y tamaño del marcador
|
||||||
|
void setContinue(int panel, int continue_counter) { continue_counter_[panel] = continue_counter; }
|
||||||
|
void setHiScore(int hi_score) { hi_score_ = hi_score; }
|
||||||
|
void setHiScoreName(const std::string &name) { hi_score_name_ = name; }
|
||||||
|
void setMode(int index, ScoreboardMode mode) { panel_[index].mode = mode; }
|
||||||
|
void setMult(int panel, float mult) { mult_[panel] = mult; }
|
||||||
|
void setName(int panel, const std::string &name) { name_[panel] = name; }
|
||||||
|
void setPower(float power) { power_ = power; }
|
||||||
|
void setRecordName(int panel, const std::string &record_name) { record_name_[panel] = record_name; }
|
||||||
|
void setScore(int panel, int score) { score_[panel] = score; }
|
||||||
|
void setSelectorPos(int panel, int pos) { selector_pos_[panel] = pos; }
|
||||||
|
void setStage(int stage) { stage_ = stage; }
|
||||||
|
|
||||||
private:
|
private:
|
||||||
// [SINGLETON] Objeto scoreboard privado
|
// --- Singleton ---
|
||||||
static Scoreboard *scoreboard_;
|
static Scoreboard *scoreboard_;
|
||||||
|
|
||||||
// Objetos y punteros
|
// --- Objetos y punteros ---
|
||||||
SDL_Renderer *renderer_; // El renderizador de la ventana
|
SDL_Renderer *renderer_; // El renderizador de la ventana
|
||||||
|
|
||||||
std::shared_ptr<Texture> game_power_meter_texture_; // Textura con el marcador de poder de la fase
|
std::shared_ptr<Texture> game_power_meter_texture_; // Textura con el marcador de poder de la fase
|
||||||
std::unique_ptr<Sprite> power_meter_sprite_; // Sprite para el medidor de poder de la fase
|
std::unique_ptr<Sprite> power_meter_sprite_; // Sprite para el medidor de poder de la fase
|
||||||
std::shared_ptr<Text> text_scoreboard_; // Fuente para el marcador del juego
|
std::shared_ptr<Text> text_scoreboard_; // Fuente para el marcador del juego
|
||||||
|
SDL_Texture *background_ = nullptr; // Textura para dibujar el marcador
|
||||||
|
std::vector<SDL_Texture *> panel_texture_; // Texturas para dibujar cada panel
|
||||||
|
|
||||||
SDL_Texture *background_ = nullptr; // Textura para dibujar el marcador
|
// --- Variables de estado ---
|
||||||
std::vector<SDL_Texture *> panel_texture_; // Texturas para dibujar cada panel
|
std::string name_[SCOREBOARD_MAX_PANELS] = {}; // Nombre de cada jugador
|
||||||
|
|
||||||
// Variables
|
|
||||||
std::string name_[SCOREBOARD_MAX_PANELS] = {}; // Nom de cada jugador
|
|
||||||
std::string record_name_[SCOREBOARD_MAX_PANELS] = {}; // Nombre introducido para la tabla de records
|
std::string record_name_[SCOREBOARD_MAX_PANELS] = {}; // Nombre introducido para la tabla de records
|
||||||
size_t selector_pos_[SCOREBOARD_MAX_PANELS] = {}; // Posición del selector de letra para introducir el nombre
|
size_t selector_pos_[SCOREBOARD_MAX_PANELS] = {}; // Posición del selector de letra para introducir el nombre
|
||||||
int score_[SCOREBOARD_MAX_PANELS] = {}; // Puntuación de los jugadores
|
int score_[SCOREBOARD_MAX_PANELS] = {}; // Puntuación de los jugadores
|
||||||
@@ -72,81 +96,27 @@ private:
|
|||||||
std::string hi_score_name_ = std::string(); // Nombre del jugador con la máxima puntuación
|
std::string hi_score_name_ = std::string(); // Nombre del jugador con la máxima puntuación
|
||||||
Color color_ = Color(); // Color del marcador
|
Color color_ = Color(); // Color del marcador
|
||||||
SDL_FRect rect_ = {0, 0, 320, 40}; // Posición y dimensiones 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_GetTiks()
|
Uint64 ticks_ = SDL_GetTicks(); // Variable donde almacenar el valor de SDL_GetTicks()
|
||||||
int time_counter_ = 0; // Contador de segundos
|
int time_counter_ = 0; // Contador de segundos
|
||||||
int loop_counter_ = 0; // Contador de bucle
|
int loop_counter_ = 0; // Contador de bucle
|
||||||
std::vector<Color> name_colors_; // Colores para destacar el nombre una vez introducido
|
std::vector<Color> name_colors_; // Colores para destacar el nombre una vez introducido
|
||||||
|
|
||||||
// Puntos predefinidos para colocar elementos en los paneles
|
// --- Puntos predefinidos para colocar elementos en los paneles ---
|
||||||
SDL_FPoint slot4_1_, slot4_2_, slot4_3_, slot4_4_;
|
SDL_FPoint slot4_1_, slot4_2_, slot4_3_, slot4_4_;
|
||||||
SDL_FPoint enter_name_pos_;
|
SDL_FPoint enter_name_pos_;
|
||||||
|
|
||||||
// Recalcula las anclas de los elementos
|
// --- Métodos internos ---
|
||||||
void recalculateAnchors();
|
void recalculateAnchors(); // Recalcula las anclas de los elementos
|
||||||
|
std::string updateScoreText(int num); // 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
|
||||||
|
|
||||||
// Transforma un valor numérico en una cadena de 7 cifras
|
// --- Constructor y destructor privados (singleton) ---
|
||||||
std::string updateScoreText(int num);
|
|
||||||
|
|
||||||
// Crea la textura de fondo
|
|
||||||
void createBackgroundTexture();
|
|
||||||
|
|
||||||
// Crea las texturas de los paneles
|
|
||||||
void createPanelTextures();
|
|
||||||
|
|
||||||
// Rellena los diferentes paneles del marcador
|
|
||||||
void fillPanelTextures();
|
|
||||||
|
|
||||||
// Rellena la textura de fondo
|
|
||||||
void fillBackgroundTexture();
|
|
||||||
|
|
||||||
// Actualiza el contador
|
|
||||||
void updateTimeCounter();
|
|
||||||
|
|
||||||
// Dibuja la linea que separa la zona de juego del marcador
|
|
||||||
void renderSeparator();
|
|
||||||
|
|
||||||
// Inicializa el vector de colores para el nombre
|
|
||||||
void iniNameColors();
|
|
||||||
|
|
||||||
// [SINGLETON] Ahora el constructor y el destructor son privados
|
|
||||||
|
|
||||||
// Constructor
|
|
||||||
Scoreboard();
|
Scoreboard();
|
||||||
|
|
||||||
// Destructor
|
|
||||||
~Scoreboard();
|
~Scoreboard();
|
||||||
|
|
||||||
public:
|
|
||||||
// [SINGLETON] Crearemos el objeto scoreboard con esta función estática
|
|
||||||
static void init();
|
|
||||||
|
|
||||||
// [SINGLETON] Destruiremos el objeto scoreboard con esta función estática
|
|
||||||
static void destroy();
|
|
||||||
|
|
||||||
// [SINGLETON] Con este método obtenemos el objeto scoreboard y podemos trabajar con él
|
|
||||||
static Scoreboard *get();
|
|
||||||
|
|
||||||
// Actualiza la lógica del marcador
|
|
||||||
void update();
|
|
||||||
|
|
||||||
// Pinta el marcador
|
|
||||||
void render();
|
|
||||||
|
|
||||||
// Establece el valor de la variable
|
|
||||||
void setColor(Color color);
|
|
||||||
|
|
||||||
// Establece el valor de la variable
|
|
||||||
void setPos(SDL_FRect rect);
|
|
||||||
|
|
||||||
void setContinue(int panel, int continue_counter) { continue_counter_[panel] = continue_counter; }
|
|
||||||
void setHiScore(int hi_score) { hi_score_ = hi_score; }
|
|
||||||
void setHiScoreName(const std::string &name) { hi_score_name_ = name; }
|
|
||||||
void setMode(int index, ScoreboardMode mode) { panel_[index].mode = mode; }
|
|
||||||
void setMult(int panel, float mult) { mult_[panel] = mult; }
|
|
||||||
void setName(int panel, const std::string &name) { name_[panel] = name; }
|
|
||||||
void setPower(float power) { power_ = power; }
|
|
||||||
void setRecordName(int panel, const std::string &record_name) { record_name_[panel] = record_name; }
|
|
||||||
void setScore(int panel, int score) { score_[panel] = score; }
|
|
||||||
void setSelectorPos(int panel, int pos) { selector_pos_[panel] = pos; }
|
|
||||||
void setStage(int stage) { stage_ = stage; }
|
|
||||||
};
|
};
|
||||||
|
|||||||
262
source/screen.h
262
source/screen.h
@@ -1,10 +1,10 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
#include <SDL3/SDL_rect.h> // Para SDL_FRect
|
#include <SDL3/SDL_rect.h> // Para SDL_FRect
|
||||||
#include <SDL3/SDL_render.h> // Para SDL_Renderer, SDL_SetRenderLogicalPrese...
|
#include <SDL3/SDL_render.h> // Para SDL_Renderer, SDL_SetRenderLogicalPresentation
|
||||||
#include <SDL3/SDL_stdinc.h> // Para Uint32
|
#include <SDL3/SDL_stdinc.h> // Para Uint32
|
||||||
#include <SDL3/SDL_video.h> // Para SDL_Window, SDL_HideWindow, SDL_ShowWindow
|
#include <SDL3/SDL_video.h> // Para SDL_Window, SDL_HideWindow, SDL_ShowWindow
|
||||||
#include <SDL3/SDL_log.h> // Para SDL_LogCategory, SDL_LogError, SDL_L...
|
#include <SDL3/SDL_log.h> // Para SDL_LogCategory, SDL_LogError, SDL_Log
|
||||||
#include <string> // Para string
|
#include <string> // Para string
|
||||||
#include <memory> // Para shared_ptr
|
#include <memory> // Para shared_ptr
|
||||||
#include "options.h" // Para Options, VideoOptions, options
|
#include "options.h" // Para Options, VideoOptions, options
|
||||||
@@ -16,98 +16,116 @@
|
|||||||
#include "resource.h"
|
#include "resource.h"
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
|
// Clase Screen: gestiona la ventana, el renderizador y los efectos visuales globales
|
||||||
class Screen
|
class Screen
|
||||||
{
|
{
|
||||||
|
public:
|
||||||
|
// --- Métodos de singleton ---
|
||||||
|
static void init(); // Inicializa el objeto Screen
|
||||||
|
static void destroy(); // Libera el objeto Screen
|
||||||
|
static Screen *get(); // Obtiene el puntero al objeto Screen
|
||||||
|
|
||||||
|
// --- Métodos principales ---
|
||||||
|
void update(); // Actualiza la lógica de la clase
|
||||||
|
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
|
||||||
|
|
||||||
|
// --- Configuración de ventana y render ---
|
||||||
|
void setFullscreenMode(bool mode = options.video.fullscreen); // Establece el modo de video
|
||||||
|
void toggleFullscreen(); // Cambia entre pantalla completa y ventana
|
||||||
|
void setWindowZoom(int size); // Cambia el tamaño de la ventana
|
||||||
|
bool decWindowZoom(); // Reduce el tamaño de la ventana
|
||||||
|
bool incWindowZoom(); // Aumenta el tamaño de la ventana
|
||||||
|
|
||||||
|
// --- Efectos visuales ---
|
||||||
|
void shake() { shake_effect_.enable(src_rect_, dst_rect_); } // 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() { options.video.shaders = !options.video.shaders; } // Activa/desactiva los shaders
|
||||||
|
void toggleIntegerScale(); // Activa/desactiva el escalado entero
|
||||||
|
void toggleVSync(); // Activa/desactiva el vsync
|
||||||
|
void attenuate(bool value) { attenuate_effect_ = value; } // Atenúa la pantalla
|
||||||
|
|
||||||
|
// --- Getters ---
|
||||||
|
SDL_Renderer *getRenderer() { return renderer_; } // Obtiene el renderizador
|
||||||
|
void show() { SDL_ShowWindow(window_); } // Muestra la ventana
|
||||||
|
void hide() { SDL_HideWindow(window_); } // Oculta la ventana
|
||||||
|
|
||||||
|
#ifdef DEBUG
|
||||||
|
// --- Debug ---
|
||||||
|
void toggleDebugInfo() { debug_info_.show = !debug_info_.show; }
|
||||||
|
void setDebugInfoEnabled(bool value) { debug_info_.show = value; }
|
||||||
|
void initDebugInfo() { debug_info_.init(); }
|
||||||
|
#endif
|
||||||
|
|
||||||
private:
|
private:
|
||||||
// Constantes
|
// --- Constantes ---
|
||||||
static constexpr int WINDOWS_DECORATIONS_ = 35;
|
static constexpr int WINDOWS_DECORATIONS_ = 35;
|
||||||
|
|
||||||
// Estructura para gestionar los fotogramas por segundo
|
// --- Estructuras internas ---
|
||||||
struct FPS
|
struct FPS
|
||||||
{
|
{
|
||||||
Uint32 ticks; // Tiempo en milisegundos desde que se comenzó a contar.
|
Uint32 ticks; // Tiempo en milisegundos desde que se comenzó a contar.
|
||||||
int frameCount; // Número acumulado de frames en el intervalo.
|
int frameCount; // Número acumulado de frames en el intervalo.
|
||||||
int lastValue; // Número de frames calculado en el último segundo.
|
int lastValue; // Número de frames calculado en el último segundo.
|
||||||
|
|
||||||
// Constructor para inicializar la estructura.
|
|
||||||
FPS() : ticks(0), frameCount(0), lastValue(0) {}
|
FPS() : ticks(0), frameCount(0), lastValue(0) {}
|
||||||
|
void increment() { frameCount++; }
|
||||||
// Incrementador que se llama en cada frame.
|
|
||||||
void increment()
|
|
||||||
{
|
|
||||||
frameCount++;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Método para calcular y devolver el valor de FPS.
|
|
||||||
int calculate(Uint32 currentTicks)
|
int calculate(Uint32 currentTicks)
|
||||||
{
|
{
|
||||||
if (currentTicks - ticks >= 1000) // Si ha pasado un segundo o más.
|
if (currentTicks - ticks >= 1000)
|
||||||
{
|
{
|
||||||
lastValue = frameCount; // Actualizamos el valor del último FPS.
|
lastValue = frameCount;
|
||||||
frameCount = 0; // Reiniciamos el contador de frames.
|
frameCount = 0;
|
||||||
ticks = currentTicks; // Actualizamos el tiempo base.
|
ticks = currentTicks;
|
||||||
}
|
}
|
||||||
return lastValue;
|
return lastValue;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// Estructura para gestionar el efecto de flash en la pantalla
|
|
||||||
struct FlashEffect
|
struct FlashEffect
|
||||||
{
|
{
|
||||||
bool enabled; // Indica si el efecto está activo
|
bool enabled;
|
||||||
int lenght; // Duración del efecto
|
int lenght;
|
||||||
int delay; // Frames iniciales en los que no se aplica
|
int delay;
|
||||||
int counter; // Contador para el efecto
|
int counter;
|
||||||
Color color; // Color del efecto
|
Color color;
|
||||||
|
|
||||||
// Constructor
|
|
||||||
explicit FlashEffect(bool enabled = false, int lenght = 0, int delay = 0, Color color = Color(0xFF, 0xFF, 0xFF))
|
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) {}
|
: enabled(enabled), lenght(lenght), delay(delay), counter(lenght), color(color) {}
|
||||||
|
|
||||||
// Actualiza
|
|
||||||
void update() { (enabled && counter > 0) ? counter-- : enabled = false; }
|
void update() { (enabled && counter > 0) ? counter-- : enabled = false; }
|
||||||
|
|
||||||
// Indica si se pude dibujar
|
|
||||||
bool isRendarable() { return enabled && counter < lenght - delay; }
|
bool isRendarable() { return enabled && counter < lenght - delay; }
|
||||||
};
|
};
|
||||||
|
|
||||||
// Estructura para agitar la pantalla
|
|
||||||
struct ShakeEffect
|
struct ShakeEffect
|
||||||
{
|
{
|
||||||
int desp; // Pixels de desplazamiento para agitar la pantalla en el eje x
|
int desp;
|
||||||
int delay; // Retraso entre cada desplazamiento de la pantalla al agitarse
|
int delay;
|
||||||
int counter; // Contador para el retraso
|
int counter;
|
||||||
int lenght; // Cantidad de desplazamientos a realizar
|
int lenght;
|
||||||
int remaining; // Cantidad de desplazamientos pendientes a realizar
|
int remaining;
|
||||||
int original_pos; // Posición inicial de la pantalla para dejarla igual tras el desplazamiento
|
int original_pos;
|
||||||
int original_width; // Anchura inicial de la pantalla para dejarla igual tras el desplazamiento
|
int original_width;
|
||||||
bool enabled; // Indica si el efecto está activo
|
bool enabled;
|
||||||
|
|
||||||
// Constructor
|
|
||||||
explicit ShakeEffect(bool en = false, int dp = 2, int dl = 3, int cnt = 0, int len = 8, int rem = 0, int origPos = 0, int origWidth = 800)
|
explicit ShakeEffect(bool en = false, int dp = 2, int dl = 3, int cnt = 0, int len = 8, int rem = 0, int origPos = 0, int origWidth = 800)
|
||||||
: desp(dp), delay(dl), counter(cnt), lenght(len), remaining(rem), original_pos(origPos), original_width(origWidth), enabled(en) {}
|
: desp(dp), delay(dl), counter(cnt), lenght(len), remaining(rem), original_pos(origPos), original_width(origWidth), enabled(en) {}
|
||||||
|
|
||||||
// Método para habilitar el efecto
|
|
||||||
void enable(SDL_FRect &src_rect, SDL_FRect &dst_rect)
|
void enable(SDL_FRect &src_rect, SDL_FRect &dst_rect)
|
||||||
{
|
{
|
||||||
if (!enabled)
|
if (!enabled)
|
||||||
{
|
{
|
||||||
// Configurar el estado inicial si el efecto no está activo
|
|
||||||
enabled = true;
|
enabled = true;
|
||||||
original_pos = src_rect.x;
|
original_pos = src_rect.x;
|
||||||
original_width = src_rect.w;
|
original_width = src_rect.w;
|
||||||
|
|
||||||
// Acortar los anchos iniciales durante el efecto
|
|
||||||
src_rect.w -= desp;
|
src_rect.w -= desp;
|
||||||
dst_rect.w = src_rect.w;
|
dst_rect.w = src_rect.w;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Renovar contadores y duración del efecto
|
|
||||||
remaining = lenght;
|
remaining = lenght;
|
||||||
counter = delay;
|
counter = delay;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Método para actualizar el efecto de movimiento/agitación
|
|
||||||
void update(SDL_FRect &src_rect, SDL_FRect &dst_rect)
|
void update(SDL_FRect &src_rect, SDL_FRect &dst_rect)
|
||||||
{
|
{
|
||||||
if (enabled)
|
if (enabled)
|
||||||
@@ -119,19 +137,13 @@ private:
|
|||||||
else
|
else
|
||||||
{
|
{
|
||||||
counter = delay;
|
counter = delay;
|
||||||
|
|
||||||
// Calcular desplazamientos según el estado de la agitación
|
|
||||||
const auto SRC_DESP = (remaining % 2 == 0) ? 0 : desp;
|
const auto SRC_DESP = (remaining % 2 == 0) ? 0 : desp;
|
||||||
const auto DST_DESP = (remaining % 2 == 1) ? 0 : desp;
|
const auto DST_DESP = (remaining % 2 == 1) ? 0 : desp;
|
||||||
|
|
||||||
src_rect.x = original_pos + SRC_DESP;
|
src_rect.x = original_pos + SRC_DESP;
|
||||||
dst_rect.x = original_pos + DST_DESP;
|
dst_rect.x = original_pos + DST_DESP;
|
||||||
|
|
||||||
remaining--;
|
remaining--;
|
||||||
|
|
||||||
if (remaining == -1)
|
if (remaining == -1)
|
||||||
{
|
{
|
||||||
// Restaurar posición y dimensiones originales
|
|
||||||
enabled = false;
|
enabled = false;
|
||||||
src_rect.x = original_pos;
|
src_rect.x = original_pos;
|
||||||
src_rect.w = original_width;
|
src_rect.w = original_width;
|
||||||
@@ -142,19 +154,14 @@ private:
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Método para comprobar si el efecto está activo
|
bool isEnabled() const { return enabled; }
|
||||||
bool isEnabled() const
|
|
||||||
{
|
|
||||||
return enabled;
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
#ifdef DEBUG
|
#ifdef DEBUG
|
||||||
// Estructura pra mostrar la información de debug
|
|
||||||
struct Debug
|
struct Debug
|
||||||
{
|
{
|
||||||
std::shared_ptr<Text> text = nullptr; // Objeto de texto para escribir
|
std::shared_ptr<Text> text = nullptr;
|
||||||
bool show = false; // Indica si se ha de mostrar la informacion por pantalla
|
bool show = false;
|
||||||
|
|
||||||
void init()
|
void init()
|
||||||
{
|
{
|
||||||
if (Resource::get())
|
if (Resource::get())
|
||||||
@@ -169,133 +176,42 @@ private:
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
#endif
|
#endif
|
||||||
// [SINGLETON] Objeto privado
|
|
||||||
|
// --- Singleton ---
|
||||||
static Screen *screen_;
|
static Screen *screen_;
|
||||||
|
|
||||||
// Objetos y punteros
|
// --- Objetos y punteros ---
|
||||||
SDL_Window *window_; // Ventana de la aplicación
|
SDL_Window *window_; // Ventana de la aplicación
|
||||||
SDL_Renderer *renderer_; // El renderizador de la ventana
|
SDL_Renderer *renderer_; // El renderizador de la ventana
|
||||||
SDL_Texture *game_canvas_; // Textura donde se dibuja todo antes de volcarse al renderizador
|
SDL_Texture *game_canvas_; // Textura donde se dibuja todo antes de volcarse al renderizador
|
||||||
|
|
||||||
// Variables
|
// --- Variables de estado ---
|
||||||
SDL_FRect src_rect_; // Coordenadas de donde va a pillar la textura del juego para dibujarla
|
SDL_FRect src_rect_; // Coordenadas de origen para dibujar la textura del juego
|
||||||
SDL_FRect dst_rect_; // Coordenadas donde se va a dibujar la textura del juego sobre la pantalla o ventana
|
SDL_FRect dst_rect_; // Coordenadas destino para dibujar la textura del juego
|
||||||
FPS fps_; // Variable para gestionar los frames por segundo
|
FPS fps_; // Gestión de frames por segundo
|
||||||
std::string shader_source_; // Almacena el contenido del archivo GLSL
|
std::string shader_source_; // Almacena el contenido del archivo GLSL
|
||||||
FlashEffect flash_effect_; // Variable para gestionar el efecto de flash
|
FlashEffect flash_effect_; // Efecto de flash en pantalla
|
||||||
ShakeEffect shake_effect_; // Variable para gestionar el efecto de agitar la pantalla
|
ShakeEffect shake_effect_; // Efecto de agitar la pantalla
|
||||||
bool attenuate_effect_ = false; // Indica si la pantalla ha de estar atenuada
|
bool attenuate_effect_ = false; // Indica si la pantalla ha de estar atenuada
|
||||||
#ifdef DEBUG
|
#ifdef DEBUG
|
||||||
Debug debug_info_; // Variable para gestionar la informaciçón de debug
|
Debug debug_info_; // Información de debug
|
||||||
#endif
|
#endif
|
||||||
// Arranca SDL VIDEO y crea la ventana
|
|
||||||
bool initSDL();
|
|
||||||
|
|
||||||
// Dibuja el efecto de flash en la pantalla
|
// --- Métodos internos ---
|
||||||
void renderFlash();
|
bool initSDL(); // Arranca SDL VIDEO y crea la ventana
|
||||||
|
void renderFlash(); // Dibuja el efecto de flash en la pantalla
|
||||||
// Aplica el efecto de agitar la pantalla
|
void renderShake(); // Aplica el efecto de agitar la pantalla
|
||||||
void renderShake();
|
void renderInfo(); // Muestra información por pantalla
|
||||||
|
void renderScreen(); // Selecciona y ejecuta el método de renderizado adecuado
|
||||||
// Muestra información por pantalla
|
void loadShaders(); // Carga el contenido del archivo GLSL
|
||||||
void renderInfo();
|
void initShaders(); // Inicializa los shaders
|
||||||
|
void adjustWindowSize(); // Calcula el tamaño de la ventana
|
||||||
// Selecciona y ejecuta el método de renderizado adecuado basado en la configuración de shaders
|
|
||||||
void renderScreen();
|
|
||||||
|
|
||||||
// Carga el contenido del archivo GLSL
|
|
||||||
void loadShaders();
|
|
||||||
|
|
||||||
// Inicializa los shaders
|
|
||||||
void initShaders();
|
|
||||||
|
|
||||||
// Calcula el tamaño de la ventana
|
|
||||||
void adjustWindowSize();
|
|
||||||
|
|
||||||
// Ajusta el tamaño lógico del renderizador
|
|
||||||
void adjustRenderLogicalSize() { SDL_SetRenderLogicalPresentation(renderer_, param.game.width, param.game.height, SDL_LOGICAL_PRESENTATION_INTEGER_SCALE); }
|
void adjustRenderLogicalSize() { SDL_SetRenderLogicalPresentation(renderer_, param.game.width, param.game.height, SDL_LOGICAL_PRESENTATION_INTEGER_SCALE); }
|
||||||
|
void getDisplayInfo(); // Obtiene información sobre la pantalla
|
||||||
|
void renderOverlays(); // Renderiza todos los overlays y efectos
|
||||||
|
void renderAttenuate(); // Atenúa la pantalla
|
||||||
|
|
||||||
// Obtiene información sobre la pantalla
|
// --- Constructores y destructor ---
|
||||||
void getDisplayInfo();
|
|
||||||
|
|
||||||
// Renderiza todos los overlays y efectos
|
|
||||||
void renderOverlays();
|
|
||||||
|
|
||||||
// Atenua la pantalla
|
|
||||||
void renderAttenuate();
|
|
||||||
|
|
||||||
// Constructor
|
|
||||||
Screen();
|
Screen();
|
||||||
|
|
||||||
// Destructor
|
|
||||||
~Screen();
|
~Screen();
|
||||||
|
|
||||||
public:
|
|
||||||
// [SINGLETON] Crearemos el objeto con esta función estática
|
|
||||||
static void init();
|
|
||||||
|
|
||||||
// [SINGLETON] Destruiremos el objeto con esta función estática
|
|
||||||
static void destroy();
|
|
||||||
|
|
||||||
// [SINGLETON] Con este método obtenemos el objeto y podemos trabajar con él
|
|
||||||
static Screen *get();
|
|
||||||
|
|
||||||
// Actualiza la lógica de la clase
|
|
||||||
void update();
|
|
||||||
|
|
||||||
// Limpia la pantalla
|
|
||||||
void clean(Color color = Color(0x00, 0x00, 0x00));
|
|
||||||
|
|
||||||
// Prepara para empezar a dibujar en la textura de juego
|
|
||||||
void start();
|
|
||||||
|
|
||||||
// Vuelca el contenido del renderizador en pantalla
|
|
||||||
void render();
|
|
||||||
|
|
||||||
// Establece el modo de video
|
|
||||||
void setFullscreenMode(bool mode = options.video.fullscreen);
|
|
||||||
|
|
||||||
// Cambia entre pantalla completa y ventana
|
|
||||||
void toggleFullscreen();
|
|
||||||
|
|
||||||
// Cambia el tamaño de la ventana
|
|
||||||
void setWindowZoom(int size);
|
|
||||||
|
|
||||||
// Reduce el tamaño de la ventana
|
|
||||||
bool decWindowZoom();
|
|
||||||
|
|
||||||
// Aumenta el tamaño de la ventana
|
|
||||||
bool incWindowZoom();
|
|
||||||
|
|
||||||
// Agita la pantalla
|
|
||||||
void shake() { shake_effect_.enable(src_rect_, dst_rect_); }
|
|
||||||
|
|
||||||
// Pone la pantalla de color
|
|
||||||
void flash(Color color, int lenght = 10, int delay = 0) { flash_effect_ = FlashEffect(true, lenght, delay, color); }
|
|
||||||
|
|
||||||
// Activa / desactiva los shaders
|
|
||||||
void toggleShaders() { options.video.shaders = !options.video.shaders; }
|
|
||||||
#ifdef DEBUG
|
|
||||||
// Activa / desactiva la información de debug
|
|
||||||
void toggleDebugInfo() { debug_info_.show = !debug_info_.show; }
|
|
||||||
void setDebugInfoEnabled(bool value) { debug_info_.show = value; }
|
|
||||||
void initDebugInfo() { debug_info_.init(); }
|
|
||||||
#endif
|
|
||||||
// Activa / desactiva el escalado entero
|
|
||||||
void toggleIntegerScale();
|
|
||||||
|
|
||||||
// Activa / desactiva el vsync
|
|
||||||
void toggleVSync();
|
|
||||||
|
|
||||||
// Getters
|
|
||||||
SDL_Renderer *getRenderer() { return renderer_; }
|
|
||||||
|
|
||||||
// Muestra la ventana
|
|
||||||
void show() { SDL_ShowWindow(window_); }
|
|
||||||
|
|
||||||
// Oculta la ventana
|
|
||||||
void hide() { SDL_HideWindow(window_); }
|
|
||||||
|
|
||||||
// Atenua la pantalla
|
|
||||||
void attenuate(bool value) { attenuate_effect_ = value; }
|
|
||||||
};
|
};
|
||||||
@@ -1,46 +1,53 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
|
/*
|
||||||
|
Namespace section: define los estados/secciones principales del programa,
|
||||||
|
así como las opciones y modos especiales (como el Attract Mode).
|
||||||
|
Proporciona variables globales para gestionar el flujo entre secciones.
|
||||||
|
*/
|
||||||
|
|
||||||
namespace section
|
namespace section
|
||||||
{
|
{
|
||||||
// Secciones del programa
|
// --- Enumeraciones de secciones del programa ---
|
||||||
enum class Name
|
enum class Name
|
||||||
{
|
{
|
||||||
INIT,
|
INIT, // Inicialización
|
||||||
LOGO,
|
LOGO, // Pantalla de logo
|
||||||
INTRO,
|
INTRO, // Introducción
|
||||||
TITLE,
|
TITLE, // Pantalla de título/menú principal
|
||||||
GAME,
|
GAME, // Juego principal
|
||||||
HI_SCORE_TABLE,
|
HI_SCORE_TABLE, // Tabla de récords
|
||||||
GAME_DEMO,
|
GAME_DEMO, // Modo demo
|
||||||
INSTRUCTIONS,
|
INSTRUCTIONS, // Instrucciones
|
||||||
CREDITS,
|
CREDITS, // Créditos
|
||||||
QUIT,
|
QUIT, // Salir del juego
|
||||||
};
|
};
|
||||||
|
|
||||||
// Opciones para la sección
|
// --- Opciones para la sección actual ---
|
||||||
enum class Options
|
enum class Options
|
||||||
{
|
{
|
||||||
GAME_PLAY_1P,
|
GAME_PLAY_1P, // Jugar 1 jugador
|
||||||
GAME_PLAY_2P,
|
GAME_PLAY_2P, // Jugar 2 jugadores
|
||||||
TITLE_TIME_OUT,
|
TITLE_TIME_OUT, // Timeout en el título
|
||||||
TITLE_1,
|
TITLE_1, // Opción 1 en el título
|
||||||
TITLE_2,
|
TITLE_2, // Opción 2 en el título
|
||||||
QUIT_WITH_KEYBOARD,
|
QUIT_WITH_KEYBOARD, // Salir con teclado
|
||||||
QUIT_WITH_CONTROLLER,
|
QUIT_WITH_CONTROLLER, // Salir con mando
|
||||||
QUIT_FROM_EVENT,
|
QUIT_FROM_EVENT, // Salir por evento
|
||||||
RELOAD,
|
RELOAD, // Recargar sección
|
||||||
HI_SCORE_AFTER_PLAYING,
|
HI_SCORE_AFTER_PLAYING, // Mostrar récord tras jugar
|
||||||
NONE,
|
NONE, // Sin opción
|
||||||
};
|
};
|
||||||
|
|
||||||
// Variables para el Attract Mode
|
// --- Modos para el Attract Mode ---
|
||||||
enum class AttractMode
|
enum class AttractMode
|
||||||
{
|
{
|
||||||
TITLE_TO_DEMO,
|
TITLE_TO_DEMO, // Pasar de título a demo
|
||||||
TITLE_TO_LOGO,
|
TITLE_TO_LOGO, // Pasar de título a logo
|
||||||
};
|
};
|
||||||
|
|
||||||
extern Name name;
|
// --- Variables globales de estado ---
|
||||||
extern Options options;
|
extern Name name; // Sección actual
|
||||||
extern AttractMode attract_mode;
|
extern Options options; // Opción seleccionada en la sección
|
||||||
|
extern AttractMode attract_mode; // Estado del Attract Mode
|
||||||
}
|
}
|
||||||
@@ -1,50 +1,45 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
#include <memory> // Para shared_ptr
|
#include <memory> // Para shared_ptr
|
||||||
#include "animated_sprite.h" // Para SpriteAnimated
|
#include "animated_sprite.h" // Para AnimatedSprite
|
||||||
|
|
||||||
class Texture;
|
class Texture;
|
||||||
|
|
||||||
// Clase SpriteSmart
|
// Clase SmartSprite: Sprite animado que se mueve hacia un destino y puede deshabilitarse automáticamente
|
||||||
class SmartSprite : public AnimatedSprite
|
class SmartSprite : public AnimatedSprite
|
||||||
{
|
{
|
||||||
|
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
|
||||||
|
|
||||||
|
// --- Getters ---
|
||||||
|
int getDestX() const { return dest_x_; } // Obtiene la posición de destino en X
|
||||||
|
int getDestY() const { return dest_y_; } // Obtiene la posición de destino en Y
|
||||||
|
bool isOnDestination() const { return on_destination_; } // Indica si está en el destino
|
||||||
|
bool hasFinished() const { 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
|
||||||
|
|
||||||
private:
|
private:
|
||||||
// Variables
|
// --- Variables internas ---
|
||||||
bool on_destination_ = false; // Indica si está en el destino
|
bool on_destination_ = false; // Indica si está en el destino
|
||||||
int dest_x_ = 0; // Posicion de destino en el eje X
|
int dest_x_ = 0; // Posición de destino en el eje X
|
||||||
int dest_y_ = 0; // Posicion de destino en el eje Y
|
int dest_y_ = 0; // Posición de destino en el eje Y
|
||||||
int finished_counter_ = 0; // Contador para deshabilitarlo
|
int finished_counter_ = 0; // Contador para deshabilitarlo
|
||||||
bool finished_ = false; // Indica si ya ha terminado
|
bool finished_ = false; // Indica si ya ha terminado
|
||||||
bool enabled_ = false; // Indica si el objeto está habilitado
|
bool enabled_ = false; // Indica si el objeto está habilitado
|
||||||
|
|
||||||
// Comprueba si ha terminado
|
// --- Métodos internos ---
|
||||||
void checkFinished();
|
void checkFinished(); // Comprueba si ha terminado
|
||||||
|
void checkMove(); // Comprueba el movimiento
|
||||||
// Comprueba el movimiento
|
|
||||||
void checkMove();
|
|
||||||
|
|
||||||
public:
|
|
||||||
// Constructor
|
|
||||||
explicit SmartSprite(std::shared_ptr<Texture> texture)
|
|
||||||
: AnimatedSprite(texture) {}
|
|
||||||
|
|
||||||
// Destructor
|
|
||||||
~SmartSprite() override = default;
|
|
||||||
|
|
||||||
// Actualiza la posición y comprueba si ha llegado a su destino
|
|
||||||
void update() override;
|
|
||||||
|
|
||||||
// Dibuja el sprite
|
|
||||||
void render() override;
|
|
||||||
|
|
||||||
// Getters
|
|
||||||
int getDestX() const { return dest_x_; }
|
|
||||||
int getDestY() const { return dest_y_; }
|
|
||||||
bool isOnDestination() const { return on_destination_; }
|
|
||||||
bool hasFinished() const { return finished_; }
|
|
||||||
|
|
||||||
// Setters
|
|
||||||
void setFinishedCounter(int value) { finished_counter_ = value; }
|
|
||||||
void setDestX(int x) { dest_x_ = x; }
|
|
||||||
void setDestY(int y) { dest_y_ = y; }
|
|
||||||
void setEnabled(bool value) { enabled_ = value; }
|
|
||||||
};
|
};
|
||||||
@@ -2,71 +2,60 @@
|
|||||||
|
|
||||||
#include <SDL3/SDL_rect.h> // Para SDL_FRect, SDL_FPoint
|
#include <SDL3/SDL_rect.h> // Para SDL_FRect, SDL_FPoint
|
||||||
#include <memory> // Para shared_ptr
|
#include <memory> // Para shared_ptr
|
||||||
|
|
||||||
class Texture;
|
class Texture;
|
||||||
|
|
||||||
// Clase sprite
|
// Clase Sprite: representa un objeto gráfico básico con posición, tamaño y textura
|
||||||
class Sprite
|
class Sprite
|
||||||
{
|
{
|
||||||
protected:
|
|
||||||
// Variables
|
|
||||||
std::shared_ptr<Texture> texture_; // Textura donde estan todos los dibujos del sprite
|
|
||||||
SDL_FRect pos_; // Posición y tamaño donde dibujar el sprite
|
|
||||||
SDL_FRect sprite_clip_; // Rectangulo de origen de la textura que se dibujará en pantalla
|
|
||||||
double zoom_ = 1.0f; // Zoom aplicado a la textura
|
|
||||||
|
|
||||||
public:
|
public:
|
||||||
// Constructor
|
// --- Constructores y destructor ---
|
||||||
Sprite(std::shared_ptr<Texture>, float x, float y, float w, float h);
|
Sprite(std::shared_ptr<Texture> texture, float x, float y, float w, float h);
|
||||||
Sprite(std::shared_ptr<Texture>, SDL_FRect rect);
|
Sprite(std::shared_ptr<Texture> texture, SDL_FRect rect);
|
||||||
explicit Sprite(std::shared_ptr<Texture>);
|
explicit Sprite(std::shared_ptr<Texture> texture);
|
||||||
|
|
||||||
// Destructor
|
|
||||||
virtual ~Sprite() = default;
|
virtual ~Sprite() = default;
|
||||||
|
|
||||||
// Muestra el sprite por pantalla
|
// --- Renderizado y control ---
|
||||||
virtual void render();
|
virtual void render(); // Muestra el sprite por pantalla
|
||||||
|
virtual void clear(); // Reinicia las variables a cero
|
||||||
|
|
||||||
// Reinicia las variables a cero
|
// --- Getters de posición y tamaño ---
|
||||||
virtual void clear();
|
|
||||||
|
|
||||||
// Obtiene la posición y el tamaño
|
|
||||||
float getX() const { return pos_.x; }
|
float getX() const { return pos_.x; }
|
||||||
float getY() const { return pos_.y; }
|
float getY() const { return pos_.y; }
|
||||||
float getWidth() const { return pos_.w; }
|
float getWidth() const { return pos_.w; }
|
||||||
float getHeight() const { return pos_.h; }
|
float getHeight() const { return pos_.h; }
|
||||||
|
|
||||||
// Devuelve el rectangulo donde está el sprite
|
|
||||||
SDL_FRect getPosition() const { return pos_; }
|
SDL_FRect getPosition() const { return pos_; }
|
||||||
SDL_FRect &getRect() { return pos_; }
|
SDL_FRect &getRect() { return pos_; }
|
||||||
|
|
||||||
// Establece la posición y el tamaño
|
// --- Setters de posición y tamaño ---
|
||||||
void setX(float x) { pos_.x = x; }
|
void setX(float x) { pos_.x = x; }
|
||||||
void setY(float y) { pos_.y = y; }
|
void setY(float y) { pos_.y = y; }
|
||||||
void setWidth(float w) { pos_.w = w; }
|
void setWidth(float w) { pos_.w = w; }
|
||||||
void setHeight(float h) { pos_.h = h; }
|
void setHeight(float h) { pos_.h = h; }
|
||||||
|
|
||||||
// Establece la posición del objeto
|
|
||||||
void setPosition(float x, float y);
|
void setPosition(float x, float y);
|
||||||
void setPosition(SDL_FPoint p);
|
void setPosition(SDL_FPoint p);
|
||||||
void setPosition(SDL_FRect r) { pos_ = r; }
|
void setPosition(SDL_FRect r) { pos_ = r; }
|
||||||
|
|
||||||
// Establece el nivel de zoom
|
// --- Zoom ---
|
||||||
void setZoom(float zoom) { zoom_ = zoom; }
|
void setZoom(float zoom) { zoom_ = zoom; }
|
||||||
|
|
||||||
// Aumenta o disminuye la posición
|
// --- Modificación de posición ---
|
||||||
void incX(float value) { pos_.x += value; }
|
void incX(float value) { pos_.x += value; }
|
||||||
void incY(float value) { pos_.y += value; }
|
void incY(float value) { pos_.y += value; }
|
||||||
|
|
||||||
// Obtiene el rectangulo que se dibuja de la textura
|
// --- Sprite clip ---
|
||||||
SDL_FRect getSpriteClip() const { return sprite_clip_; }
|
SDL_FRect getSpriteClip() const { return sprite_clip_; }
|
||||||
|
|
||||||
// Establece el rectangulo que se dibuja de la textura
|
|
||||||
void setSpriteClip(SDL_FRect rect) { sprite_clip_ = rect; }
|
void setSpriteClip(SDL_FRect rect) { sprite_clip_ = rect; }
|
||||||
void setSpriteClip(float x, float y, float w, float h) { sprite_clip_ = (SDL_FRect){x, y, w, h}; }
|
void setSpriteClip(float x, float y, float w, float h) { sprite_clip_ = SDL_FRect{x, y, w, h}; }
|
||||||
|
|
||||||
// Obtiene un puntero a la textura
|
// --- Textura ---
|
||||||
std::shared_ptr<Texture> getTexture() const { return texture_; }
|
std::shared_ptr<Texture> getTexture() const { return texture_; }
|
||||||
|
|
||||||
// Establece la textura a utilizar
|
|
||||||
void setTexture(std::shared_ptr<Texture> texture) { texture_ = 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
|
||||||
};
|
};
|
||||||
@@ -2,8 +2,14 @@
|
|||||||
|
|
||||||
#include <vector>
|
#include <vector>
|
||||||
|
|
||||||
|
/*
|
||||||
|
Namespace Stage: gestiona los datos y operaciones de las fases del juego.
|
||||||
|
Permite consultar y modificar el poder necesario, la amenaza y el estado de cada fase.
|
||||||
|
*/
|
||||||
|
|
||||||
namespace Stage
|
namespace Stage
|
||||||
{
|
{
|
||||||
|
// --- Estructura con los datos de una fase ---
|
||||||
struct Stage
|
struct Stage
|
||||||
{
|
{
|
||||||
int power_to_complete; // Cantidad de poder que se necesita para completar la fase
|
int power_to_complete; // Cantidad de poder que se necesita para completar la fase
|
||||||
@@ -15,18 +21,15 @@ namespace Stage
|
|||||||
: power_to_complete(power_to_complete), min_menace(min_menace), max_menace(max_menace) {}
|
: power_to_complete(power_to_complete), min_menace(min_menace), max_menace(max_menace) {}
|
||||||
};
|
};
|
||||||
|
|
||||||
extern std::vector<Stage> stages; // Variable con los datos de cada pantalla
|
// --- Variables globales del estado de las fases ---
|
||||||
extern int power; // Poder acumulado en la fase
|
extern std::vector<Stage> stages; // Vector con los datos de cada pantalla
|
||||||
|
extern int power; // Poder acumulado en la fase actual
|
||||||
extern int total_power; // Poder total necesario para completar el juego
|
extern int total_power; // Poder total necesario para completar el juego
|
||||||
extern int number; // Fase actual
|
extern int number; // Índice de la fase actual
|
||||||
extern bool power_can_be_added; // Indica si se puede añadir poder a la fase
|
extern bool power_can_be_added; // Indica si se puede añadir poder a la fase
|
||||||
|
|
||||||
// Devuelve una fase
|
// --- Funciones principales ---
|
||||||
Stage get(int index);
|
Stage get(int index); // Devuelve una fase por índice
|
||||||
|
void init(); // Inicializa las variables del namespace Stage
|
||||||
// Inicializa las variables del namespace Stage
|
void addPower(int amount); // Añade poder a la fase actual
|
||||||
void init();
|
|
||||||
|
|
||||||
// Añade poder
|
|
||||||
void addPower(int amount);
|
|
||||||
}
|
}
|
||||||
102
source/tabe.h
102
source/tabe.h
@@ -7,6 +7,7 @@
|
|||||||
#include <memory> // Para unique_ptr
|
#include <memory> // Para unique_ptr
|
||||||
#include "animated_sprite.h" // Para AnimatedSprite
|
#include "animated_sprite.h" // Para AnimatedSprite
|
||||||
|
|
||||||
|
// --- Enumeraciones para dirección y estado ---
|
||||||
enum class TabeDirection : int
|
enum class TabeDirection : int
|
||||||
{
|
{
|
||||||
TO_THE_LEFT = 0,
|
TO_THE_LEFT = 0,
|
||||||
@@ -19,6 +20,7 @@ enum class TabeState : int
|
|||||||
HIT = 1,
|
HIT = 1,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// --- Estructura para el temporizador del Tabe ---
|
||||||
struct TabeTimer
|
struct TabeTimer
|
||||||
{
|
{
|
||||||
Uint32 time_until_next_spawn; // Tiempo restante para la próxima aparición
|
Uint32 time_until_next_spawn; // Tiempo restante para la próxima aparición
|
||||||
@@ -68,76 +70,54 @@ struct TabeTimer
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// Clase Tabe
|
// --- Clase Tabe ---
|
||||||
class Tabe
|
class Tabe
|
||||||
{
|
{
|
||||||
|
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
|
||||||
|
bool tryToGetBonus(); // Intenta obtener el bonus
|
||||||
|
|
||||||
|
// --- Getters ---
|
||||||
|
SDL_FRect &getCollider() { return sprite_->getRect(); } // Obtiene el área de colisión
|
||||||
|
bool isEnabled() const { return enabled_; } // Indica si el objeto está activo
|
||||||
|
|
||||||
private:
|
private:
|
||||||
// Constantes
|
// --- Constantes ---
|
||||||
static constexpr int WIDTH_ = 32;
|
static constexpr int WIDTH_ = 32;
|
||||||
static constexpr int HEIGHT_ = 32;
|
static constexpr int HEIGHT_ = 32;
|
||||||
|
|
||||||
// Punteros
|
// --- Objetos y punteros ---
|
||||||
std::unique_ptr<AnimatedSprite> sprite_; // Sprite con los graficos y animaciones
|
std::unique_ptr<AnimatedSprite> sprite_; // Sprite con los gráficos y animaciones
|
||||||
|
|
||||||
// Variables
|
// --- Variables de estado ---
|
||||||
float x_ = 0; // Posición del objeto
|
float x_ = 0; // Posición X
|
||||||
float y_ = 0; // Posición del objeto
|
float y_ = 0; // Posición Y
|
||||||
float speed_ = 0.0f; // Velocidad de movimiento del objeto
|
float speed_ = 0.0f; // Velocidad de movimiento
|
||||||
float accel_ = 0.0f; // Aceleración del objeto
|
float accel_ = 0.0f; // Aceleración
|
||||||
int fly_distance_ = 0; // Distancia de vuelo
|
int fly_distance_ = 0; // Distancia de vuelo
|
||||||
int waiting_counter_ = 0; // Tiempo que pasa quieto el objeto
|
int waiting_counter_ = 0; // Tiempo que pasa quieto
|
||||||
bool enabled_ = false; // Indica si el objeto está activo
|
bool enabled_ = false; // Indica si el objeto está activo
|
||||||
TabeDirection direction_ = TabeDirection::TO_THE_LEFT; // Dirección del objeto
|
TabeDirection direction_ = TabeDirection::TO_THE_LEFT; // Dirección actual
|
||||||
TabeDirection destiny_ = TabeDirection::TO_THE_LEFT; // Destino del objeto
|
TabeDirection destiny_ = TabeDirection::TO_THE_LEFT; // Destino
|
||||||
TabeState state_ = TabeState::FLY; // Estado
|
TabeState state_ = TabeState::FLY; // Estado actual
|
||||||
int hit_counter_ = 0; // Contador para el estado HIT
|
int hit_counter_ = 0; // Contador para el estado HIT
|
||||||
int number_of_hits_ = 0; // Cantidad de disparos que ha recibido
|
int number_of_hits_ = 0; // Cantidad de disparos recibidos
|
||||||
bool has_bonus_ = true; // Indica si el Tabe aun tiene el bonus para soltar
|
bool has_bonus_ = true; // Indica si aún tiene el bonus para soltar
|
||||||
TabeTimer timer_; // Temporizador para gestionar la aparición del Tabe
|
TabeTimer timer_; // Temporizador para gestionar la aparición
|
||||||
|
|
||||||
// Mueve el objeto
|
// --- Métodos internos ---
|
||||||
void move();
|
void move(); // Mueve el objeto
|
||||||
|
void shiftSprite() { sprite_->setPos(x_, y_); } // Actualiza la posición del sprite
|
||||||
// Actualiza la posición del sprite
|
void setRandomFlyPath(TabeDirection direction, int lenght); // Establece un vuelo aleatorio
|
||||||
void shiftSprite() { sprite_->setPos(x_, y_); }
|
void updateState(); // Actualiza el estado
|
||||||
|
void updateTimer(); // Actualiza el temporizador
|
||||||
// Establece un vuelo aleatorio
|
void disable(); // Deshabilita el objeto
|
||||||
void setRandomFlyPath(TabeDirection direction, int lenght);
|
|
||||||
|
|
||||||
// Actualiza el estado
|
|
||||||
void updateState();
|
|
||||||
|
|
||||||
// Actualiza el temporizador
|
|
||||||
void updateTimer();
|
|
||||||
|
|
||||||
// Deshabilita el objeto
|
|
||||||
void disable();
|
|
||||||
|
|
||||||
public:
|
|
||||||
// Constructor
|
|
||||||
Tabe();
|
|
||||||
|
|
||||||
// Destructor
|
|
||||||
~Tabe() = default;
|
|
||||||
|
|
||||||
// Actualiza la lógica
|
|
||||||
void update();
|
|
||||||
|
|
||||||
// Dibuja el objeto
|
|
||||||
void render();
|
|
||||||
|
|
||||||
// Habilita el objeto
|
|
||||||
void enable();
|
|
||||||
|
|
||||||
// Establece el estado
|
|
||||||
void setState(TabeState state);
|
|
||||||
|
|
||||||
// Intenta obtener el bonus
|
|
||||||
bool tryToGetBonus();
|
|
||||||
|
|
||||||
// Obtiene el area de colisión
|
|
||||||
SDL_FRect &getCollider() { return sprite_->getRect(); }
|
|
||||||
|
|
||||||
// Getters
|
|
||||||
bool isEnabled() const { return enabled_; }
|
|
||||||
};
|
};
|
||||||
@@ -5,13 +5,16 @@
|
|||||||
#include <string> // Para string
|
#include <string> // Para string
|
||||||
#include "sprite.h" // Para Sprite
|
#include "sprite.h" // Para Sprite
|
||||||
#include "utils.h" // Para Color
|
#include "utils.h" // Para Color
|
||||||
class Texture; // lines 9-9
|
|
||||||
|
|
||||||
|
class Texture;
|
||||||
|
|
||||||
|
// --- Constantes para flags de texto ---
|
||||||
constexpr int TEXT_COLOR = 1;
|
constexpr int TEXT_COLOR = 1;
|
||||||
constexpr int TEXT_SHADOW = 2;
|
constexpr int TEXT_SHADOW = 2;
|
||||||
constexpr int TEXT_CENTER = 4;
|
constexpr int TEXT_CENTER = 4;
|
||||||
constexpr int TEXT_STROKE = 8;
|
constexpr int TEXT_STROKE = 8;
|
||||||
|
|
||||||
|
// --- Estructuras auxiliares ---
|
||||||
struct TextOffset
|
struct TextOffset
|
||||||
{
|
{
|
||||||
int x, y, w;
|
int x, y, w;
|
||||||
@@ -24,61 +27,47 @@ struct TextFile
|
|||||||
TextOffset offset[128]; // Vector con las posiciones y ancho de cada letra
|
TextOffset offset[128]; // Vector con las posiciones y ancho de cada letra
|
||||||
};
|
};
|
||||||
|
|
||||||
// Llena una estructuta TextFile desde un fichero
|
// Llena una estructura TextFile desde un fichero
|
||||||
std::shared_ptr<TextFile> loadTextFile(const std::string &file_path);
|
std::shared_ptr<TextFile> loadTextFile(const std::string &file_path);
|
||||||
|
|
||||||
// Clase texto. Pinta texto en pantalla a partir de un bitmap
|
// --- Clase Text: pinta texto en pantalla a partir de un bitmap ---
|
||||||
class Text
|
class Text
|
||||||
{
|
{
|
||||||
private:
|
public:
|
||||||
// Objetos y punteros
|
// --- Constructores y destructor ---
|
||||||
std::unique_ptr<Sprite> sprite_ = nullptr; // Objeto con los graficos para el texto
|
Text(std::shared_ptr<Texture> texture, const std::string &text_file);
|
||||||
|
Text(std::shared_ptr<Texture> texture, std::shared_ptr<TextFile> text_file);
|
||||||
|
~Text() = default;
|
||||||
|
|
||||||
// Variables
|
// --- Métodos de escritura en pantalla ---
|
||||||
|
void write(int x, int y, const std::string &text, int kerning = 1, int lenght = -1); // Escribe el texto en pantalla
|
||||||
|
void write2X(int x, int y, const std::string &text, int kerning = 1); // Escribe el texto al doble de tamaño
|
||||||
|
|
||||||
|
// --- Escritura en textura ---
|
||||||
|
std::shared_ptr<Texture> writeToTexture(const std::string &text, int zoom = 1, int kerning = 1); // Escribe el texto en una textura
|
||||||
|
std::shared_ptr<Texture> writeDXToTexture(Uint8 flags, const std::string &text, int kerning = 1, Color textColor = Color(), Uint8 shadow_distance = 1, Color shadow_color = Color(), int lenght = -1); // Escribe el texto con extras en una textura
|
||||||
|
|
||||||
|
// --- Métodos de escritura avanzada ---
|
||||||
|
void writeColored(int x, int y, const std::string &text, Color color, int kerning = 1, int lenght = -1); // Escribe el texto con colores
|
||||||
|
void writeShadowed(int x, int y, const std::string &text, Color color, Uint8 shadow_distance = 1, int kerning = 1, int lenght = -1); // Escribe el texto con sombra
|
||||||
|
void writeCentered(int x, int y, const std::string &text, int kerning = 1, int lenght = -1); // Escribe el texto centrado en un punto x
|
||||||
|
void writeDX(Uint8 flags, int x, int y, const std::string &text, int kerning = 1, Color textColor = Color(), Uint8 shadow_distance = 1, Color shadow_color = Color(), int lenght = -1); // Escribe texto con extras
|
||||||
|
|
||||||
|
// --- Utilidades ---
|
||||||
|
int lenght(const std::string &text, int kerning = 1) const; // Obtiene la longitud en pixels de una cadena
|
||||||
|
int getCharacterSize() const; // Devuelve el tamaño de caracter actual
|
||||||
|
|
||||||
|
// --- Configuración ---
|
||||||
|
void setFixedWidth(bool value); // Establece si se usa un tamaño fijo de letra
|
||||||
|
void setPalette(int number); // Establece una paleta
|
||||||
|
|
||||||
|
private:
|
||||||
|
// --- Objetos y punteros ---
|
||||||
|
std::unique_ptr<Sprite> sprite_ = nullptr; // Objeto con los gráficos para el texto
|
||||||
|
|
||||||
|
// --- Variables ---
|
||||||
int box_width_ = 0; // Anchura de la caja de cada caracter en el png
|
int box_width_ = 0; // Anchura de la caja de cada caracter en el png
|
||||||
int box_height_ = 0; // Altura de la caja de cada caracter en el png
|
int box_height_ = 0; // Altura de la caja de cada caracter en el png
|
||||||
bool fixed_width_ = false; // Indica si el texto se ha de escribir con longitud fija en todas las letras
|
bool fixed_width_ = false; // Indica si el texto se ha de escribir con longitud fija en todas las letras
|
||||||
TextOffset offset_[128] = {}; // Vector con las posiciones y ancho de cada letra
|
TextOffset offset_[128] = {}; // Vector con las posiciones y ancho de cada letra
|
||||||
|
|
||||||
public:
|
|
||||||
// Constructor
|
|
||||||
Text(std::shared_ptr<Texture> texture, const std::string &text_file);
|
|
||||||
Text(std::shared_ptr<Texture> texture, std::shared_ptr<TextFile> text_file);
|
|
||||||
|
|
||||||
// Destructor
|
|
||||||
~Text() = default;
|
|
||||||
|
|
||||||
// Escribe el texto en pantalla
|
|
||||||
void write(int x, int y, const std::string &text, int kerning = 1, int lenght = -1);
|
|
||||||
void write2X(int x, int y, const std::string &text, int kerning = 1);
|
|
||||||
|
|
||||||
// Escribe el texto en una textura
|
|
||||||
std::shared_ptr<Texture> writeToTexture(const std::string &text, int zoom = 1, int kerning = 1);
|
|
||||||
|
|
||||||
// Escribe el texto con extras en una textura
|
|
||||||
std::shared_ptr<Texture> writeDXToTexture(Uint8 flags, const std::string &text, int kerning = 1, Color textColor = Color(), Uint8 shadow_distance = 1, Color shadow_color = Color(), int lenght = -1);
|
|
||||||
|
|
||||||
// Escribe el texto con colores
|
|
||||||
void writeColored(int x, int y, const std::string &text, Color color, int kerning = 1, int lenght = -1);
|
|
||||||
|
|
||||||
// Escribe el texto con sombra
|
|
||||||
void writeShadowed(int x, int y, const std::string &text, Color color, Uint8 shadow_distance = 1, int kerning = 1, int lenght = -1);
|
|
||||||
|
|
||||||
// Escribe el texto centrado en un punto x
|
|
||||||
void writeCentered(int x, int y, const std::string &text, int kerning = 1, int lenght = -1);
|
|
||||||
|
|
||||||
// Escribe texto con extras
|
|
||||||
void writeDX(Uint8 flags, int x, int y, const std::string &text, int kerning = 1, Color textColor = Color(), Uint8 shadow_distance = 1, Color shadow_color = Color(), int lenght = -1);
|
|
||||||
|
|
||||||
// Obtiene la longitud en pixels de una cadena
|
|
||||||
int lenght(const std::string &text, int kerning = 1) const;
|
|
||||||
|
|
||||||
// Devuelve el valor de la variable
|
|
||||||
int getCharacterSize() const;
|
|
||||||
|
|
||||||
// Establece si se usa un tamaño fijo de letra
|
|
||||||
void setFixedWidth(bool value);
|
|
||||||
|
|
||||||
// Establece una paleta
|
|
||||||
void setPalette(int number);
|
|
||||||
};
|
};
|
||||||
120
source/texture.h
120
source/texture.h
@@ -3,15 +3,16 @@
|
|||||||
#include <SDL3/SDL_blendmode.h> // Para SDL_BlendMode
|
#include <SDL3/SDL_blendmode.h> // Para SDL_BlendMode
|
||||||
#include <SDL3/SDL_pixels.h> // Para SDL_PixelFormat
|
#include <SDL3/SDL_pixels.h> // Para SDL_PixelFormat
|
||||||
#include <SDL3/SDL_rect.h> // Para SDL_FPoint, SDL_FRect
|
#include <SDL3/SDL_rect.h> // Para SDL_FPoint, SDL_FRect
|
||||||
#include <SDL3/SDL_render.h> // Para SDL_Renderer, SDL_TextureAccess, SDL...
|
#include <SDL3/SDL_render.h> // Para SDL_Renderer, SDL_TextureAccess, SDL_Texture
|
||||||
#include <SDL3/SDL_stdinc.h> // Para Uint8, Uint16, Uint32
|
#include <SDL3/SDL_stdinc.h> // Para Uint8, Uint16, Uint32
|
||||||
#include <SDL3/SDL_surface.h> // Para SDL_FlipMode
|
#include <SDL3/SDL_surface.h> // Para SDL_FlipMode
|
||||||
#include <memory> // Para shared_ptr
|
#include <memory> // Para shared_ptr
|
||||||
#include <string> // Para string
|
#include <string> // Para string
|
||||||
#include <vector> // Para vector
|
#include <vector> // Para vector
|
||||||
struct Color; // lines 11-11
|
|
||||||
|
|
||||||
// Definiciones de tipos
|
struct Color;
|
||||||
|
|
||||||
|
// Definición de Surface para imágenes con paleta
|
||||||
struct Surface
|
struct Surface
|
||||||
{
|
{
|
||||||
std::shared_ptr<Uint8[]> data;
|
std::shared_ptr<Uint8[]> data;
|
||||||
@@ -22,86 +23,57 @@ struct Surface
|
|||||||
: data(pixels), w(width), h(height) {}
|
: data(pixels), w(width), h(height) {}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// Clase Texture: gestiona texturas, paletas y renderizado
|
||||||
class Texture
|
class Texture
|
||||||
{
|
{
|
||||||
|
public:
|
||||||
|
// --- Constructores y destructor ---
|
||||||
|
explicit Texture(SDL_Renderer *renderer, const std::string &path = std::string());
|
||||||
|
~Texture();
|
||||||
|
|
||||||
|
// --- Carga y creación ---
|
||||||
|
bool loadFromFile(const std::string &path); // Carga una imagen desde un fichero
|
||||||
|
bool createBlank(int width, int height, SDL_PixelFormat format = SDL_PIXELFORMAT_RGBA8888, SDL_TextureAccess access = SDL_TEXTUREACCESS_STREAMING); // Crea una textura en blanco
|
||||||
|
bool reLoad(); // Recarga la textura
|
||||||
|
|
||||||
|
// --- Renderizado ---
|
||||||
|
void render(int x, int y, SDL_FRect *clip = nullptr, float zoomW = 1, float zoomH = 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
|
||||||
|
|
||||||
|
// --- Paletas ---
|
||||||
|
void addPaletteFromFile(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(int palette); // Cambia la paleta de la textura
|
||||||
|
|
||||||
|
// --- Getters ---
|
||||||
|
int getWidth(); // Obtiene el ancho de la imagen
|
||||||
|
int getHeight(); // Obtiene el alto de la imagen
|
||||||
|
SDL_Texture *getSDLTexture(); // Obtiene la textura SDL
|
||||||
|
SDL_Renderer *getRenderer(); // Obtiene el renderizador
|
||||||
|
|
||||||
private:
|
private:
|
||||||
// Objetos y punteros
|
// --- Objetos y punteros ---
|
||||||
SDL_Renderer *renderer_; // Renderizador donde dibujar la textura
|
SDL_Renderer *renderer_; // Renderizador donde dibujar la textura
|
||||||
SDL_Texture *texture_ = nullptr; // La textura
|
SDL_Texture *texture_ = nullptr; // La textura
|
||||||
std::shared_ptr<Surface> surface_ = nullptr; // Surface para usar imagenes en formato gif con paleta
|
std::shared_ptr<Surface> surface_ = nullptr; // Surface para usar imágenes en formato gif con paleta
|
||||||
|
|
||||||
// Variables
|
// --- Variables ---
|
||||||
std::string path_; // Ruta de la imagen de la textura
|
std::string path_; // Ruta de la imagen de la textura
|
||||||
int width_ = 0; // Ancho de la imagen
|
int width_ = 0; // Ancho de la imagen
|
||||||
int height_ = 0; // Alto de la imagen
|
int height_ = 0; // Alto de la imagen
|
||||||
std::vector<std::vector<Uint32>> palettes_; // Vector con las diferentes paletas
|
std::vector<std::vector<Uint32>> palettes_; // Vector con las diferentes paletas
|
||||||
int current_palette_ = 0; // Indice de la paleta en uso
|
int current_palette_ = 0; // Índice de la paleta en uso
|
||||||
|
|
||||||
// Crea una surface desde un fichero .gif
|
// --- Métodos internos ---
|
||||||
std::shared_ptr<Surface> loadSurface(const std::string &file_name);
|
std::shared_ptr<Surface> loadSurface(const std::string &file_name); // Crea una surface desde un fichero .gif
|
||||||
|
void flipSurface(); // Vuelca la surface en la textura
|
||||||
// Vuelca la surface en la textura
|
std::vector<Uint32> loadPaletteFromFile(const std::string &file_name); // Carga una paleta desde un fichero
|
||||||
void flipSurface();
|
void unloadTexture(); // Libera la memoria de la textura
|
||||||
|
void unloadSurface(); // Libera la surface actual
|
||||||
// Carga una paleta desde un fichero
|
|
||||||
std::vector<Uint32> loadPaletteFromFile(const std::string &file_name);
|
|
||||||
|
|
||||||
// Libera la memoria de la textura
|
|
||||||
void unloadTexture();
|
|
||||||
|
|
||||||
// Desencadenar la superficie actual
|
|
||||||
void unloadSurface();
|
|
||||||
|
|
||||||
public:
|
|
||||||
// Constructor
|
|
||||||
explicit Texture(SDL_Renderer *renderer, const std::string &path = std::string());
|
|
||||||
|
|
||||||
// Destructor
|
|
||||||
~Texture();
|
|
||||||
|
|
||||||
// Carga una imagen desde un fichero
|
|
||||||
bool loadFromFile(const std::string &path);
|
|
||||||
|
|
||||||
// Crea una textura en blanco
|
|
||||||
bool createBlank(int width, int height, SDL_PixelFormat format = SDL_PIXELFORMAT_RGBA8888, SDL_TextureAccess = SDL_TEXTUREACCESS_STREAMING);
|
|
||||||
|
|
||||||
// Establece el color para la modulacion
|
|
||||||
void setColor(Uint8 red, Uint8 green, Uint8 blue);
|
|
||||||
void setColor(Color color);
|
|
||||||
|
|
||||||
// Establece el blending
|
|
||||||
void setBlendMode(SDL_BlendMode blending);
|
|
||||||
|
|
||||||
// Establece el alpha para la modulación
|
|
||||||
void setAlpha(Uint8 alpha);
|
|
||||||
|
|
||||||
// Renderiza la textura en un punto específico
|
|
||||||
void render(int x, int y, SDL_FRect *clip = nullptr, float zoomW = 1, float zoomH = 1, double angle = 0.0, SDL_FPoint *center = nullptr, SDL_FlipMode flip = SDL_FLIP_NONE);
|
|
||||||
|
|
||||||
// Establece la textura como objetivo de renderizado
|
|
||||||
void setAsRenderTarget(SDL_Renderer *renderer);
|
|
||||||
|
|
||||||
// Obtiene el ancho de la imagen
|
|
||||||
int getWidth();
|
|
||||||
|
|
||||||
// Obtiene el alto de la imagen
|
|
||||||
int getHeight();
|
|
||||||
|
|
||||||
// Recarga la textura
|
|
||||||
bool reLoad();
|
|
||||||
|
|
||||||
// Obtiene la textura
|
|
||||||
SDL_Texture *getSDLTexture();
|
|
||||||
|
|
||||||
// Añade una paleta a la lista
|
|
||||||
void addPaletteFromFile(const std::string &path);
|
|
||||||
|
|
||||||
// Establece un color de la paleta
|
|
||||||
void setPaletteColor(int palette, int index, Uint32 color);
|
|
||||||
|
|
||||||
// Cambia la paleta de la textura
|
|
||||||
void setPalette(int palette);
|
|
||||||
|
|
||||||
// Obtiene el renderizador
|
|
||||||
SDL_Renderer *getRenderer();
|
|
||||||
};
|
};
|
||||||
@@ -15,62 +15,50 @@ enum class TiledBGMode : int
|
|||||||
|
|
||||||
/*
|
/*
|
||||||
Esta clase dibuja un tileado de fondo. Para ello se sirve de una textura "canvas", que rellena con los tiles.
|
Esta clase dibuja un tileado de fondo. Para ello se sirve de una textura "canvas", que rellena con los tiles.
|
||||||
El rectangulo "window" recorre la textura de diferentes formas para generar el efecto de movimiento de la
|
El rectángulo "window" recorre la textura de diferentes formas para generar el efecto de movimiento de la
|
||||||
textura en pantalla
|
textura en pantalla.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
// Clase TiledBG
|
// Clase TiledBG
|
||||||
class TiledBG
|
class 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
|
||||||
|
|
||||||
|
// --- 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 ---
|
||||||
|
bool isStopped() const { return speed_ == 0.0f; } // Indica si está parado
|
||||||
|
|
||||||
private:
|
private:
|
||||||
// Constantes
|
// --- Constantes ---
|
||||||
static constexpr int TILE_WIDTH_ = 64; // Ancho del tile
|
static constexpr int TILE_WIDTH_ = 64; // Ancho del tile
|
||||||
static constexpr int TILE_HEIGHT_ = 64; // Alto del tile
|
static constexpr int TILE_HEIGHT_ = 64; // Alto del tile
|
||||||
|
|
||||||
// Objetos y punteros
|
// --- Objetos y punteros ---
|
||||||
SDL_Renderer *renderer_; // El renderizador de la ventana
|
SDL_Renderer *renderer_; // El renderizador de la ventana
|
||||||
SDL_Texture *canvas_; // Textura donde dibujar el fondo formado por tiles
|
SDL_Texture *canvas_; // Textura donde dibujar el fondo formado por tiles
|
||||||
|
|
||||||
// Variables
|
// --- Variables de estado ---
|
||||||
SDL_FRect pos_; // Posición y tamaño del mosaico
|
SDL_FRect pos_; // Posición y tamaño del mosaico
|
||||||
SDL_FRect window_; // Ventana visible para la textura de fondo del titulo
|
SDL_FRect window_; // Ventana visible para la textura de fondo del título
|
||||||
TiledBGMode mode_; // Tipo de movimiento del mosaico
|
TiledBGMode mode_; // Tipo de movimiento del mosaico
|
||||||
double sin_[360]; // Vector con los valores del seno precalculados
|
double sin_[360]; // Vector con los valores del seno precalculados
|
||||||
float desp_ = 0.0f; // Desplazamiento aplicado
|
float desp_ = 0.0f; // Desplazamiento aplicado
|
||||||
float speed_ = 1.0f; // Incremento que se añade al desplazamiento a cada bucle
|
float speed_ = 1.0f; // Incremento que se añade al desplazamiento a cada bucle
|
||||||
bool stopping_ = false; // Indica si se está deteniendo
|
bool stopping_ = false; // Indica si se está deteniendo
|
||||||
|
|
||||||
// Rellena la textura con el contenido
|
// --- Métodos internos ---
|
||||||
void fillTexture();
|
void fillTexture(); // Rellena la textura con el contenido
|
||||||
|
void updateDesp() { desp_ += speed_; } // Actualiza el desplazamiento
|
||||||
// Actualiza el desplazamiento
|
void updateStop(); // Detiene el desplazamiento de forma ordenada
|
||||||
void updateDesp() { desp_ += speed_; }
|
|
||||||
|
|
||||||
// Detiene el desplazamiento de forma ordenada
|
|
||||||
void updateStop();
|
|
||||||
|
|
||||||
public:
|
|
||||||
// Constructor
|
|
||||||
TiledBG(SDL_FRect pos, TiledBGMode mode);
|
|
||||||
|
|
||||||
// Destructor
|
|
||||||
~TiledBG();
|
|
||||||
|
|
||||||
// Pinta la clase en pantalla
|
|
||||||
void render();
|
|
||||||
|
|
||||||
// Actualiza la lógica de la clase
|
|
||||||
void update();
|
|
||||||
|
|
||||||
// Establece la velocidad
|
|
||||||
void setSpeed(float speed) { speed_ = speed; }
|
|
||||||
|
|
||||||
// Detiene el desplazamiento de forma ordenada
|
|
||||||
void stopGracefully() { stopping_ = true; }
|
|
||||||
|
|
||||||
// Cambia el color de la textura
|
|
||||||
void setColor(Color color) { SDL_SetTextureColorMod(canvas_, color.r, color.g, color.b); }
|
|
||||||
|
|
||||||
// Indica si está parado
|
|
||||||
bool isStopped() const { return speed_ == 0.0f; }
|
|
||||||
};
|
};
|
||||||
129
source/title.h
129
source/title.h
@@ -3,12 +3,13 @@
|
|||||||
#include <SDL3/SDL_stdinc.h> // Para Uint32
|
#include <SDL3/SDL_stdinc.h> // Para Uint32
|
||||||
#include <memory> // Para unique_ptr, shared_ptr
|
#include <memory> // Para unique_ptr, shared_ptr
|
||||||
#include "section.h" // Para Options
|
#include "section.h" // Para Options
|
||||||
class DefineButtons; // lines 5-5
|
|
||||||
class Fade; // lines 6-6
|
class DefineButtons;
|
||||||
class GameLogo; // lines 7-7
|
class Fade;
|
||||||
class Sprite; // lines 8-8
|
class GameLogo;
|
||||||
class Text; // lines 9-9
|
class Sprite;
|
||||||
class TiledBG; // lines 11-11
|
class Text;
|
||||||
|
class TiledBG;
|
||||||
|
|
||||||
// Textos
|
// Textos
|
||||||
constexpr const char TEXT_COPYRIGHT[] = "@2020,2025 JailDesigner";
|
constexpr const char TEXT_COPYRIGHT[] = "@2020,2025 JailDesigner";
|
||||||
@@ -17,86 +18,56 @@ constexpr const char TEXT_COPYRIGHT[] = "@2020,2025 JailDesigner";
|
|||||||
constexpr bool ALLOW_TITLE_ANIMATION_SKIP = false;
|
constexpr bool ALLOW_TITLE_ANIMATION_SKIP = false;
|
||||||
|
|
||||||
/*
|
/*
|
||||||
Esta clase gestiona un estado del programa. Se encarga de la parte del titulo o menu
|
Clase que gestiona el estado de título/menú principal del juego.
|
||||||
que sirve para empezar a jugar. Utiliza otras clases para:
|
Responsable de mostrar el logo, el fondo animado y gestionar la entrada para comenzar la partida.
|
||||||
- Mostrar el logo del juego
|
No permite saltar la animación del título salvo que se cambie el define.
|
||||||
- Dibujar el tileado de fondo
|
|
||||||
- Redifinir los botones de los mandos de juego
|
|
||||||
|
|
||||||
Esta clase tiene tres estados:
|
|
||||||
- El titulo está animandose, con el fondo estático
|
|
||||||
- El titulo ya está en su sitio y el fondo se está animando
|
|
||||||
- Se ha pulsado el botón de start
|
|
||||||
|
|
||||||
Por razones de diseño, no se permite saltarse la animación del titulo, aunque es
|
|
||||||
configurable mediante un define
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
// Clase Title
|
// Clase Title
|
||||||
class Title
|
class Title
|
||||||
{
|
{
|
||||||
private:
|
|
||||||
// Enumeraciones
|
|
||||||
enum class TitleState
|
|
||||||
{
|
|
||||||
LOGO_ANIMATING,
|
|
||||||
LOGO_FINISHED,
|
|
||||||
START_HAS_BEEN_PRESSED,
|
|
||||||
};
|
|
||||||
|
|
||||||
// Objetos y punteros
|
|
||||||
std::shared_ptr<Text> text_; // Objeto de texto para poder escribir textos en pantalla
|
|
||||||
std::unique_ptr<Fade> fade_; // Objeto para realizar fundidos en pantalla
|
|
||||||
std::unique_ptr<TiledBG> tiled_bg_; // Objeto para dibujar el mosaico animado de fondo
|
|
||||||
std::unique_ptr<GameLogo> game_logo_; // Objeto para dibujar el logo con el título del juego
|
|
||||||
std::unique_ptr<Sprite> mini_logo_sprite_; // Sprite con el logo de JailGames mini
|
|
||||||
std::unique_ptr<DefineButtons> define_buttons_; // Objeto para definir los botones del joystic
|
|
||||||
|
|
||||||
// Variable
|
|
||||||
int counter_ = 0; // Temporizador para la pantalla de titulo
|
|
||||||
Uint64 ticks_ = 0; // Contador de ticks para ajustar la velocidad del programa
|
|
||||||
section::Name next_section_; // Indica cual es la siguiente sección a cargar cuando termine el contador del titulo
|
|
||||||
section::Options selection_ = section::Options::TITLE_TIME_OUT; // Opción elegida en el titulo
|
|
||||||
int num_controllers_; // Número de mandos conectados
|
|
||||||
TitleState state_; // Estado en el que se encuentra la sección
|
|
||||||
|
|
||||||
// Actualiza las variables del objeto
|
|
||||||
void update();
|
|
||||||
|
|
||||||
// Dibuja el objeto en pantalla
|
|
||||||
void render();
|
|
||||||
|
|
||||||
// Comprueba los eventos
|
|
||||||
void checkEvents();
|
|
||||||
|
|
||||||
// Comprueba las entradas
|
|
||||||
void checkInput();
|
|
||||||
|
|
||||||
// Reinicia el contador interno
|
|
||||||
void resetCounter();
|
|
||||||
|
|
||||||
// Intercambia la asignación de mandos a los jugadores
|
|
||||||
void swapControllers();
|
|
||||||
|
|
||||||
// Intercambia el teclado de jugador
|
|
||||||
void swapKeyboard();
|
|
||||||
|
|
||||||
// Muestra información sobre los controles y los jugadores
|
|
||||||
void showControllers();
|
|
||||||
|
|
||||||
// Actualiza el fade
|
|
||||||
void updateFade();
|
|
||||||
|
|
||||||
// Actualiza el estado
|
|
||||||
void updateState();
|
|
||||||
|
|
||||||
public:
|
public:
|
||||||
// Constructor
|
// --- Constructores y destructor ---
|
||||||
Title();
|
Title();
|
||||||
|
|
||||||
// Destructor
|
|
||||||
~Title();
|
~Title();
|
||||||
|
|
||||||
// Bucle para el titulo del juego
|
// --- Método principal ---
|
||||||
void run();
|
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
|
||||||
|
};
|
||||||
|
|
||||||
|
// --- 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
|
||||||
|
|
||||||
|
// --- 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
|
||||||
|
|
||||||
|
// --- 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
|
||||||
|
void swapKeyboard(); // Intercambia el teclado de jugador
|
||||||
|
void showControllers(); // Muestra información sobre los controles y los jugadores
|
||||||
|
void updateFade(); // Actualiza el fade
|
||||||
|
void updateState(); // Actualiza el estado
|
||||||
};
|
};
|
||||||
156
source/utils.h
156
source/utils.h
@@ -8,33 +8,27 @@
|
|||||||
#include <string> // Para string
|
#include <string> // Para string
|
||||||
#include <vector> // Para vector
|
#include <vector> // Para vector
|
||||||
|
|
||||||
// Constantes
|
// --- Constantes ---
|
||||||
constexpr int BLOCK = 8;
|
constexpr int BLOCK = 8;
|
||||||
constexpr int TOTAL_DEMO_DATA = 2000;
|
constexpr int TOTAL_DEMO_DATA = 2000;
|
||||||
|
|
||||||
// Variables para que los argumentos del programa tengan mas peso que los definidos en otros lugares
|
// --- Estructuras y tipos ---
|
||||||
struct Overrides
|
struct Overrides
|
||||||
{
|
{
|
||||||
std::string param_file; // Fichero de parametros a utilizar
|
std::string param_file; // Fichero de parametros a utilizar
|
||||||
bool clear_hi_score_table; // Reinicia la tabla de records
|
bool clear_hi_score_table; // Reinicia la tabla de records
|
||||||
bool set_v_sync; // Establece el vsync
|
bool set_v_sync; // Establece el vsync
|
||||||
|
|
||||||
// Constructor por defecto
|
|
||||||
Overrides()
|
Overrides()
|
||||||
: param_file(""), clear_hi_score_table(false), set_v_sync(false) {}
|
: param_file(""), clear_hi_score_table(false), set_v_sync(false) {}
|
||||||
};
|
};
|
||||||
|
|
||||||
extern Overrides overrides;
|
extern Overrides overrides;
|
||||||
|
|
||||||
// Estructura para definir un circulo
|
// Estructura para definir un circulo
|
||||||
struct Circle
|
struct Circle
|
||||||
{
|
{
|
||||||
int x, y, r;
|
int x, y, r;
|
||||||
|
|
||||||
// Constructor por defecto
|
|
||||||
Circle() : x(0), y(0), r(0) {}
|
Circle() : x(0), y(0), r(0) {}
|
||||||
|
|
||||||
// Constructor
|
|
||||||
Circle(int xCoord, int yCoord, int radius)
|
Circle(int xCoord, int yCoord, int radius)
|
||||||
: x(xCoord), y(yCoord), r(radius) {}
|
: x(xCoord), y(yCoord), r(radius) {}
|
||||||
};
|
};
|
||||||
@@ -46,13 +40,7 @@ struct Color
|
|||||||
constexpr Color() : r(0), g(0), b(0) {}
|
constexpr Color() : r(0), g(0), b(0) {}
|
||||||
explicit constexpr Color(int red, int green, int blue) : r(red), g(green), b(blue) {}
|
explicit constexpr Color(int red, int green, int blue) : r(red), g(green), b(blue) {}
|
||||||
|
|
||||||
// Método para obtener el color inverso
|
constexpr Color getInverse() const { return Color(255 - r, 255 - g, 255 - b); }
|
||||||
constexpr Color getInverse() const
|
|
||||||
{
|
|
||||||
return Color(255 - r, 255 - g, 255 - b);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Método para aclarar el color
|
|
||||||
Color lighten(int amount = 50) const
|
Color lighten(int amount = 50) const
|
||||||
{
|
{
|
||||||
return Color(
|
return Color(
|
||||||
@@ -60,8 +48,6 @@ struct Color
|
|||||||
std::min(255, g + amount),
|
std::min(255, g + amount),
|
||||||
std::min(255, b + amount));
|
std::min(255, b + amount));
|
||||||
}
|
}
|
||||||
|
|
||||||
// Método para oscurecer el color
|
|
||||||
Color darken(int amount = 50) const
|
Color darken(int amount = 50) const
|
||||||
{
|
{
|
||||||
return Color(
|
return Color(
|
||||||
@@ -81,6 +67,7 @@ enum class NotifyPosition
|
|||||||
RIGHT,
|
RIGHT,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// Estructura para datos de la demo
|
||||||
struct DemoKeys
|
struct DemoKeys
|
||||||
{
|
{
|
||||||
Uint8 left;
|
Uint8 left;
|
||||||
@@ -90,7 +77,6 @@ struct DemoKeys
|
|||||||
Uint8 fire_left;
|
Uint8 fire_left;
|
||||||
Uint8 fire_right;
|
Uint8 fire_right;
|
||||||
|
|
||||||
// Constructor que inicializa todos los campos
|
|
||||||
explicit DemoKeys(Uint8 l = 0, Uint8 r = 0, Uint8 ni = 0, Uint8 f = 0, Uint8 fl = 0, Uint8 fr = 0)
|
explicit DemoKeys(Uint8 l = 0, Uint8 r = 0, Uint8 ni = 0, Uint8 f = 0, Uint8 fl = 0, Uint8 fr = 0)
|
||||||
: left(l), right(r), no_input(ni), fire(f), fire_left(fl), fire_right(fr) {}
|
: left(l), right(r), no_input(ni), fire(f), fire_left(fl), fire_right(fr) {}
|
||||||
};
|
};
|
||||||
@@ -105,10 +91,7 @@ struct Demo
|
|||||||
DemoKeys keys; // Variable con las pulsaciones de teclas del modo demo
|
DemoKeys keys; // Variable con las pulsaciones de teclas del modo demo
|
||||||
std::vector<DemoData> data; // Vector con diferentes sets de datos con los movimientos para la demo
|
std::vector<DemoData> data; // Vector con diferentes sets de datos con los movimientos para la demo
|
||||||
|
|
||||||
// Constructor por defecto
|
|
||||||
Demo() : enabled(false), recording(false), counter(0), keys(), data() {}
|
Demo() : enabled(false), recording(false), counter(0), keys(), data() {}
|
||||||
|
|
||||||
// Constructor con parámetros
|
|
||||||
Demo(bool e, bool r, int c, const DemoKeys &k, const std::vector<DemoData> &d)
|
Demo(bool e, bool r, int c, const DemoKeys &k, const std::vector<DemoData> &d)
|
||||||
: enabled(e), recording(r), counter(c), keys(k), data(d) {}
|
: enabled(e), recording(r), counter(c), keys(k), data(d) {}
|
||||||
};
|
};
|
||||||
@@ -122,83 +105,10 @@ struct Zone
|
|||||||
float third_quarter_x; // Anclaje al 75% del eje X
|
float third_quarter_x; // Anclaje al 75% del eje X
|
||||||
float center_y; // Anclaje al 50% del eje Y
|
float center_y; // Anclaje al 50% del eje Y
|
||||||
float first_quarter_y; // Anclaje al 25% del eje Y
|
float first_quarter_y; // Anclaje al 25% del eje Y
|
||||||
float third_quarter_y; // Anclaje al 75% del eje X
|
float third_quarter_y; // Anclaje al 75% del eje Y
|
||||||
};
|
};
|
||||||
|
|
||||||
// Obtiene un color del vector de colores imitando al Coche Fantástico
|
// --- Funciones utilitarias ---
|
||||||
Color getColorLikeKnightRider(const std::vector<Color> &colors, int counter_);
|
|
||||||
|
|
||||||
// Calcula el cuadrado de la distancia entre dos puntos
|
|
||||||
double distanceSquared(int x1, int y1, int x2, int y2);
|
|
||||||
|
|
||||||
// Detector de colisiones entre dos circulos
|
|
||||||
bool checkCollision(const Circle &a, const Circle &b);
|
|
||||||
|
|
||||||
// Detector de colisiones entre un circulo y un rectangulo
|
|
||||||
bool checkCollision(const Circle &a, const SDL_FRect &b);
|
|
||||||
|
|
||||||
// Detector de colisiones entre un dos rectangulos
|
|
||||||
bool checkCollision(const SDL_FRect &a, const SDL_FRect &b);
|
|
||||||
|
|
||||||
// Detector de colisiones entre un punto y un rectangulo
|
|
||||||
bool checkCollision(const SDL_FPoint &p, const SDL_FRect &r);
|
|
||||||
|
|
||||||
// Convierte una cadena en un valor booleano
|
|
||||||
bool stringToBool(const std::string &str);
|
|
||||||
|
|
||||||
// Convierte un valor booleano en una cadena
|
|
||||||
std::string boolToString(bool value);
|
|
||||||
|
|
||||||
// Convierte un valor booleano en una cadena "on" o "off"
|
|
||||||
std::string boolToOnOff(bool value);
|
|
||||||
|
|
||||||
// Convierte una cadena a minusculas
|
|
||||||
std::string toLower(const std::string &str);
|
|
||||||
|
|
||||||
// Dibuja un circulo
|
|
||||||
void DrawCircle(SDL_Renderer *renderer, int32_t centerX, int32_t centerY, int32_t radius);
|
|
||||||
|
|
||||||
// Aclara el color
|
|
||||||
Color lightenColor(const Color &color, int amount);
|
|
||||||
|
|
||||||
// Oscurece el color
|
|
||||||
Color DarkenColor(const Color &color, int amount);
|
|
||||||
|
|
||||||
// Quita los espacioes en un string
|
|
||||||
std::string trim(const std::string &str);
|
|
||||||
|
|
||||||
// Función de suavizado
|
|
||||||
double easeOutQuint(double t);
|
|
||||||
double easeInQuint(double t);
|
|
||||||
double easeInOutQuint(double t);
|
|
||||||
double easeInQuad(double t);
|
|
||||||
double easeOutQuad(double t);
|
|
||||||
double easeInOutSine(double t);
|
|
||||||
double easeInOut(double t);
|
|
||||||
double easeInOutExpo(double t);
|
|
||||||
double easeOutBounce(double t);
|
|
||||||
double easeOutElastic(double t);
|
|
||||||
double easeInElastic(double t);
|
|
||||||
|
|
||||||
// Comprueba si una vector contiene una cadena
|
|
||||||
bool stringInVector(const std::vector<std::string> &vec, const std::string &str);
|
|
||||||
|
|
||||||
// Imprime por pantalla una linea de texto de tamaño fijo rellena con puntos
|
|
||||||
void printWithDots(const std::string &text1, const std::string &text2, const std::string &text3);
|
|
||||||
|
|
||||||
// Carga el fichero de datos para la demo
|
|
||||||
DemoData loadDemoDataFromFile(const std::string &file_path);
|
|
||||||
|
|
||||||
#ifdef RECORDING
|
|
||||||
// Guarda el fichero de datos para la demo
|
|
||||||
bool saveDemoFile(const std::string &file_path, const DemoData &dd);
|
|
||||||
#endif
|
|
||||||
|
|
||||||
// Obtiene el nombre de un fichero a partir de una ruta
|
|
||||||
std::string getFileName(const std::string &path);
|
|
||||||
|
|
||||||
// Obtiene la ruta eliminando el nombre del fichero
|
|
||||||
std::string getPath(const std::string &full_path);
|
|
||||||
|
|
||||||
// Colores
|
// Colores
|
||||||
extern const Color BG_COLOR;
|
extern const Color BG_COLOR;
|
||||||
@@ -215,4 +125,56 @@ extern const Color ORANGE_SOFT_COLOR;
|
|||||||
extern const Color GREEN_COLOR;
|
extern const Color GREEN_COLOR;
|
||||||
extern const Color BLUE_SKY_COLOR;
|
extern const Color BLUE_SKY_COLOR;
|
||||||
extern const Color PINK_SKY_COLOR;
|
extern const Color PINK_SKY_COLOR;
|
||||||
extern const Color GREEN_SKY_COLOR;
|
extern const Color GREEN_SKY_COLOR;
|
||||||
|
|
||||||
|
// Colores y gráficos
|
||||||
|
Color getColorLikeKnightRider(const std::vector<Color> &colors, int counter_);
|
||||||
|
|
||||||
|
// Colisiones y geometría
|
||||||
|
double distanceSquared(int x1, int y1, int x2, int y2);
|
||||||
|
bool checkCollision(const Circle &a, const Circle &b);
|
||||||
|
bool checkCollision(const Circle &a, const SDL_FRect &b);
|
||||||
|
bool checkCollision(const SDL_FRect &a, const SDL_FRect &b);
|
||||||
|
bool checkCollision(const SDL_FPoint &p, const SDL_FRect &r);
|
||||||
|
|
||||||
|
// Conversión y manipulación de cadenas
|
||||||
|
bool stringToBool(const std::string &str);
|
||||||
|
std::string boolToString(bool value);
|
||||||
|
std::string boolToOnOff(bool value);
|
||||||
|
std::string toLower(const std::string &str);
|
||||||
|
std::string trim(const std::string &str);
|
||||||
|
|
||||||
|
// Dibujo
|
||||||
|
void DrawCircle(SDL_Renderer *renderer, int32_t centerX, int32_t centerY, int32_t radius);
|
||||||
|
|
||||||
|
// Manipulación de color
|
||||||
|
Color lightenColor(const Color &color, int amount);
|
||||||
|
Color DarkenColor(const Color &color, int amount);
|
||||||
|
|
||||||
|
// Funciones de suavizado (easing)
|
||||||
|
double easeOutQuint(double t);
|
||||||
|
double easeInQuint(double t);
|
||||||
|
double easeInOutQuint(double t);
|
||||||
|
double easeInQuad(double t);
|
||||||
|
double easeOutQuad(double t);
|
||||||
|
double easeInOutSine(double t);
|
||||||
|
double easeInOut(double t);
|
||||||
|
double easeInOutExpo(double t);
|
||||||
|
double easeOutBounce(double t);
|
||||||
|
double easeOutElastic(double t);
|
||||||
|
double easeInElastic(double t);
|
||||||
|
|
||||||
|
// Utilidades varias
|
||||||
|
bool stringInVector(const std::vector<std::string> &vec, const std::string &str); // Comprueba si un vector contiene una cadena
|
||||||
|
void printWithDots(const std::string &text1, const std::string &text2, const std::string &text3); // Imprime una línea con puntos
|
||||||
|
|
||||||
|
// Demo
|
||||||
|
DemoData loadDemoDataFromFile(const std::string &file_path);
|
||||||
|
|
||||||
|
#ifdef RECORDING
|
||||||
|
bool saveDemoFile(const std::string &file_path, const DemoData &dd);
|
||||||
|
#endif
|
||||||
|
|
||||||
|
// Ficheros y rutas
|
||||||
|
std::string getFileName(const std::string &path); // Obtiene el nombre de un fichero a partir de una ruta
|
||||||
|
std::string getPath(const std::string &full_path); // Obtiene la ruta eliminando el nombre del fichero
|
||||||
@@ -7,24 +7,6 @@ class Text;
|
|||||||
// Clase Writer. Pinta texto en pantalla letra a letra a partir de una cadena y un objeto Text
|
// Clase Writer. Pinta texto en pantalla letra a letra a partir de una cadena y un objeto Text
|
||||||
class Writer
|
class Writer
|
||||||
{
|
{
|
||||||
private:
|
|
||||||
// Objetos y punteros
|
|
||||||
std::shared_ptr<Text> text_; // Objeto encargado de escribir el texto
|
|
||||||
|
|
||||||
// Variables
|
|
||||||
int pos_x_ = 0; // Posicion en el eje X donde empezar a escribir el texto
|
|
||||||
int pos_y_ = 0; // Posicion en el eje Y donde empezar a escribir el texto
|
|
||||||
int kerning_ = 0; // Kerning del texto, es decir, espaciado entre caracteres
|
|
||||||
std::string caption_ = std::string(); // 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
|
|
||||||
|
|
||||||
public:
|
public:
|
||||||
// Constructor
|
// Constructor
|
||||||
explicit Writer(std::shared_ptr<Text> text)
|
explicit Writer(std::shared_ptr<Text> text)
|
||||||
@@ -39,33 +21,37 @@ public:
|
|||||||
// Dibuja el objeto en pantalla
|
// Dibuja el objeto en pantalla
|
||||||
void render() const;
|
void render() const;
|
||||||
|
|
||||||
// Establece el valor de la variable
|
// Setters
|
||||||
void setPosX(int value);
|
void setPosX(int value); // Establece la posición X
|
||||||
|
void setPosY(int value); // Establece la posición Y
|
||||||
// Establece el valor de la variable
|
void setKerning(int value); // Establece el kerning (espaciado entre caracteres)
|
||||||
void setPosY(int value);
|
void setCaption(const std::string &text); // Establece el texto a escribir
|
||||||
|
void setSpeed(int value); // Establece la velocidad de escritura
|
||||||
// Establece el valor de la variable
|
void setEnabled(bool value); // Habilita o deshabilita el objeto
|
||||||
void setKerning(int value);
|
void setFinishedCounter(int time); // Establece el temporizador para deshabilitar el objeto
|
||||||
|
|
||||||
// Establece el valor de la variable
|
|
||||||
void setCaption(const std::string &text);
|
|
||||||
|
|
||||||
// Establece el valor de la variable
|
|
||||||
void setSpeed(int value);
|
|
||||||
|
|
||||||
// Establece el valor de la variable
|
|
||||||
void setEnabled(bool value);
|
|
||||||
|
|
||||||
// Obtiene el valor de la variable
|
|
||||||
bool IsEnabled() const;
|
|
||||||
|
|
||||||
// Establece el valor de la variable
|
|
||||||
void setFinishedCounter(int time);
|
|
||||||
|
|
||||||
// Centra la cadena de texto a un punto X
|
// Centra la cadena de texto a un punto X
|
||||||
void center(int x);
|
void center(int x);
|
||||||
|
|
||||||
// Obtiene el valor de la variable
|
// Getters
|
||||||
bool hasFinished() const;
|
bool IsEnabled() const; // Indica si el objeto está habilitado
|
||||||
|
bool hasFinished() const; // Indica si ya ha terminado
|
||||||
|
|
||||||
|
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_ = std::string(); // 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