revisió de capçaleres
This commit is contained in:
@@ -1,18 +1,22 @@
|
||||
#pragma once
|
||||
|
||||
#include <SDL3/SDL_rect.h> // Para SDL_FRect
|
||||
#include <memory> // Para shared_ptr
|
||||
#include <string> // Para string
|
||||
#include <vector> // Para vector
|
||||
#include "moving_sprite.h" // Para MovingSprite
|
||||
#include <SDL3/SDL_rect.h>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "moving_sprite.h"
|
||||
|
||||
// Declaraciones adelantadas
|
||||
class Texture;
|
||||
|
||||
// === Estructura de Animación ===
|
||||
struct Animation
|
||||
{
|
||||
std::string name; // Nombre de la animación
|
||||
std::vector<SDL_FRect> frames; // Frames que componen la animació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
|
||||
int current_frame; // Frame actual en reproducció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) {}
|
||||
};
|
||||
|
||||
// === Alias de Tipos ===
|
||||
using AnimationsFileBuffer = std::vector<std::string>;
|
||||
|
||||
// === Funciones Globales ===
|
||||
// Carga las animaciones desde un fichero en un vector
|
||||
AnimationsFileBuffer loadAnimationsFromFile(const std::string &file_path);
|
||||
|
||||
class AnimatedSprite : public MovingSprite
|
||||
{
|
||||
public:
|
||||
// Constructor
|
||||
// Constructores
|
||||
AnimatedSprite(std::shared_ptr<Texture> texture, const std::string &file_path);
|
||||
AnimatedSprite(std::shared_ptr<Texture> texture, const AnimationsFileBuffer &animations);
|
||||
explicit AnimatedSprite(std::shared_ptr<Texture> texture)
|
||||
: MovingSprite(texture) {}
|
||||
explicit AnimatedSprite(std::shared_ptr<Texture> texture) : MovingSprite(texture) {}
|
||||
|
||||
// Destructor
|
||||
virtual ~AnimatedSprite() override = default;
|
||||
|
||||
// Actualización del objeto
|
||||
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
|
||||
// === Actualización ===
|
||||
void update() override; // Actualiza la animación
|
||||
|
||||
// Manipulación de animaciones
|
||||
void setCurrentAnimation(const std::string &name = "default"); // Establece animación por nombre
|
||||
void setCurrentAnimation(int index = 0); // Establece animación por índice
|
||||
void resetAnimation(); // Reinicia la animación
|
||||
// === Control de Animaciones ===
|
||||
void setCurrentAnimation(const std::string &name = "default"); // Establecer por nombre
|
||||
void setCurrentAnimation(int index = 0); // Establecer por índice
|
||||
void resetAnimation(); // Reiniciar la animación
|
||||
|
||||
// === Consultas ===
|
||||
bool animationIsCompleted(); // Comprobar si ha terminado
|
||||
int getIndex(const std::string &name); // Obtener índice por nombre
|
||||
|
||||
protected:
|
||||
// Almacenamiento de animaciones
|
||||
// === Datos de Animación ===
|
||||
std::vector<Animation> animations_; // Vector de animaciones disponibles
|
||||
int current_animation_ = 0; // Índice de la animación activa
|
||||
|
||||
// Procesos internos
|
||||
void animate(); // Calcula el frame actual de la animación
|
||||
void loadFromAnimationsFileBuffer(const AnimationsFileBuffer &source); // Carga animaciones desde un buffer
|
||||
};
|
||||
// === Métodos Internos ===
|
||||
void animate(); // Calcular el frame actual de la animación
|
||||
void loadFromAnimationsFileBuffer(const AnimationsFileBuffer &source); // Cargar desde buffer
|
||||
};
|
||||
@@ -1,9 +1,11 @@
|
||||
#pragma once
|
||||
|
||||
#include <string> // Para manejar cadenas de texto
|
||||
#include <vector> // Para estructuras dinámicas de datos
|
||||
#include "utils.h" // Para la función getPath
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "utils.h"
|
||||
|
||||
// === Enumeraciones ===
|
||||
enum class AssetType : int
|
||||
{
|
||||
BITMAP,
|
||||
@@ -18,57 +20,52 @@ enum class AssetType : int
|
||||
MAX_ASSET_TYPE,
|
||||
};
|
||||
|
||||
// Clase Asset
|
||||
class Asset
|
||||
{
|
||||
public:
|
||||
// Obtención de la instancia única (*Meyers Singleton*)
|
||||
static Asset &get()
|
||||
// === Singleton ===
|
||||
static Asset &get() // Obtención de la instancia única (Meyers Singleton)
|
||||
{
|
||||
static Asset instance;
|
||||
return instance;
|
||||
}
|
||||
|
||||
// === Inicialización ===
|
||||
void init(const std::string &executable_path)
|
||||
{
|
||||
executable_path_ = getPath(executable_path);
|
||||
}
|
||||
|
||||
// Manejo de archivos
|
||||
void add(const std::string &file, AssetType type, bool required = true, bool absolute = false); // Añade un recurso
|
||||
std::string get(const std::string &text) const; // Devuelve la ruta completa de un recurso
|
||||
bool check() const; // Verifica la existencia de todos los elementos
|
||||
std::vector<std::string> getListByType(AssetType type) const; // Obtiene lista de recursos de un tipo específico
|
||||
// === Gestión de Recursos ===
|
||||
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; // Obtener ruta completa
|
||||
bool check() const; // Verificar existencia
|
||||
std::vector<std::string> getListByType(AssetType type) const; // Lista por tipo
|
||||
|
||||
private:
|
||||
// Estructura para definir un recurso
|
||||
// === Estructura Interna ===
|
||||
struct AssetItem
|
||||
{
|
||||
std::string file; // Ruta del fichero desde la raíz del directorio
|
||||
AssetType type; // Tipo de recurso
|
||||
bool required; // Indica si el fichero es obligatorio
|
||||
|
||||
// Constructor
|
||||
AssetItem(const std::string &filePath, AssetType assetType, bool isRequired)
|
||||
: file(filePath), type(assetType), required(isRequired) {}
|
||||
};
|
||||
|
||||
// Variables internas
|
||||
int longest_name_ = 0; // Longitud del nombre de archivo más largo
|
||||
std::vector<AssetItem> file_list_; // Lista con todas las rutas de los archivos
|
||||
// === Variables Internas ===
|
||||
int longest_name_ = 0; // Longitud del nombre más largo
|
||||
std::vector<AssetItem> file_list_; // Lista con todas las rutas
|
||||
std::string executable_path_; // Ruta del ejecutable
|
||||
|
||||
// Métodos internos
|
||||
bool checkFile(const std::string &path) const; // Verifica si un archivo existe
|
||||
std::string getTypeName(AssetType type) const; // Obtiene el nombre textual del tipo de recurso
|
||||
// === Métodos Internos ===
|
||||
bool checkFile(const std::string &path) const; // Verificar si archivo existe
|
||||
std::string getTypeName(AssetType type) const; // Obtener nombre textual del tipo
|
||||
|
||||
// Constructor privado
|
||||
Asset() = default;
|
||||
|
||||
// Destructor privado
|
||||
~Asset() = default;
|
||||
|
||||
// Evita copia y asignación
|
||||
Asset(const Asset &) = delete;
|
||||
Asset &operator=(const Asset &) = delete;
|
||||
};
|
||||
// === Patrón Singleton ===
|
||||
Asset() = default; // Constructor privado
|
||||
~Asset() = default; // Destructor privado
|
||||
Asset(const Asset &) = delete; // Evitar copia
|
||||
Asset &operator=(const Asset &) = delete; // Evitar asignación
|
||||
};
|
||||
@@ -1,61 +1,60 @@
|
||||
#pragma once
|
||||
|
||||
#include <string>
|
||||
|
||||
#include "audio.h"
|
||||
|
||||
class Audio
|
||||
{
|
||||
public:
|
||||
// Obtención de la instancia única (*Meyers Singleton*)
|
||||
static Audio &get()
|
||||
// === Singleton ===
|
||||
static Audio &get() // Obtención de la instancia única (Meyers Singleton)
|
||||
{
|
||||
static Audio instance;
|
||||
return instance;
|
||||
}
|
||||
|
||||
// Manejo de reproducción de música
|
||||
void playMusic(const std::string &name, int loop = -1); // Reproduce música en bucle
|
||||
void pauseMusic(); // Pausa la reproducción de música
|
||||
void stopMusic(); // Detiene la música completamente
|
||||
void fadeOutMusic(int milliseconds); // Fundido de salida de la música
|
||||
// === Control de Música ===
|
||||
void playMusic(const std::string &name, int loop = -1); // Reproducir en bucle
|
||||
void pauseMusic(); // Pausar reproducción
|
||||
void stopMusic(); // Detener completamente
|
||||
void fadeOutMusic(int milliseconds); // Fundido de salida
|
||||
|
||||
// Manejo de efectos de sonido
|
||||
void playSound(const std::string &name); // Reproduce un sonido puntual
|
||||
void stopAllSounds(); // Detiene todos los sonidos activos
|
||||
// === Control de Sonidos ===
|
||||
void playSound(const std::string &name); // Reproducir sonido puntual
|
||||
void stopAllSounds(); // Detener todos los sonidos
|
||||
|
||||
// Configuración de audio general
|
||||
void enable() { enabled_ = true; } // Habilita el audio
|
||||
void disable() { enabled_ = false; } // Deshabilita el audio
|
||||
void enable(bool value) { enabled_ = value; } // Establece estado del audio
|
||||
void toggleEnabled() { enabled_ = !enabled_; } // Alterna estado del audio
|
||||
// === Configuración General ===
|
||||
void enable() { enabled_ = true; } // Habilitar audio
|
||||
void disable() { enabled_ = false; } // Deshabilitar audio
|
||||
void enable(bool value) { enabled_ = value; } // Establecer estado
|
||||
void toggleEnabled() { enabled_ = !enabled_; } // Alternar estado
|
||||
|
||||
// Configuración de sonido
|
||||
void enableSound() { sound_enabled_ = true; } // Habilita los sonidos
|
||||
void disableSound() { sound_enabled_ = false; } // Deshabilita los sonidos
|
||||
void enableSound(bool value) { sound_enabled_ = value; } // Establece estado de sonidos
|
||||
void toggleSound() { sound_enabled_ = !sound_enabled_; } // Alterna estado de sonidos
|
||||
// === Configuración de Sonidos ===
|
||||
void enableSound() { sound_enabled_ = true; } // Habilitar sonidos
|
||||
void disableSound() { sound_enabled_ = false; } // Deshabilitar sonidos
|
||||
void enableSound(bool value) { sound_enabled_ = value; } // Establecer estado
|
||||
void toggleSound() { sound_enabled_ = !sound_enabled_; } // Alternar estado
|
||||
|
||||
// Configuración de música
|
||||
void enableMusic() { music_enabled_ = true; } // Habilita la música
|
||||
void disableMusic() { music_enabled_ = false; } // Deshabilita la música
|
||||
void enableMusic(bool value) { music_enabled_ = value; } // Establece estado de música
|
||||
void toggleMusic() { music_enabled_ = !music_enabled_; } // Alterna estado de música
|
||||
// === Configuración de Música ===
|
||||
void enableMusic() { music_enabled_ = true; } // Habilitar música
|
||||
void disableMusic() { music_enabled_ = false; } // Deshabilitar música
|
||||
void enableMusic(bool value) { music_enabled_ = value; } // Establecer estado
|
||||
void toggleMusic() { music_enabled_ = !music_enabled_; } // Alternar estado
|
||||
|
||||
// Control de volumen
|
||||
void setSoundVolume(int volume); // Ajusta volumen de efectos de sonido
|
||||
void setMusicVolume(int volume); // Ajusta volumen de música
|
||||
// === Control de Volumen ===
|
||||
void setSoundVolume(int volume); // Ajustar volumen de efectos
|
||||
void setMusicVolume(int volume); // Ajustar volumen de música
|
||||
|
||||
private:
|
||||
// Variables internas
|
||||
// === Variables de Estado ===
|
||||
bool enabled_ = true; // Estado general del audio
|
||||
bool sound_enabled_ = true; // Estado de los efectos de sonido
|
||||
bool music_enabled_ = true; // Estado de la música
|
||||
|
||||
// Constructor privado (Meyers Singleton)
|
||||
Audio();
|
||||
~Audio();
|
||||
|
||||
// Prevención de copia y asignación
|
||||
Audio(const Audio &) = delete;
|
||||
Audio &operator=(const Audio &) = delete;
|
||||
};
|
||||
// === Patrón Singleton ===
|
||||
Audio(); // Constructor privado
|
||||
~Audio(); // Destructor privado
|
||||
Audio(const Audio &) = delete; // Evitar copia
|
||||
Audio &operator=(const Audio &) = delete; // Evitar asignación
|
||||
};
|
||||
215
source/balloon.h
215
source/balloon.h
@@ -7,19 +7,18 @@
|
||||
#include <vector> // Para vector
|
||||
#include "animated_sprite.h" // Para AnimatedSprite
|
||||
#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
|
||||
constexpr int MAX_BOUNCE = 10;
|
||||
class Texture;
|
||||
|
||||
// --- 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_POWER[] = {1, 3, 7, 15};
|
||||
constexpr int BALLOON_MENACE[] = {1, 2, 4, 8};
|
||||
constexpr int BALLOON_SIZE[] = {10, 16, 26, 48, 49};
|
||||
const std::string BALLOON_SOUND[] = {"bubble1.wav", "bubble2.wav", "bubble3.wav", "bubble4.wav"};
|
||||
|
||||
// Tamaños de globo
|
||||
enum class BalloonSize : Uint8
|
||||
{
|
||||
SIZE1 = 0,
|
||||
@@ -28,7 +27,6 @@ enum class BalloonSize : Uint8
|
||||
SIZE4 = 3,
|
||||
};
|
||||
|
||||
// Clases de globo
|
||||
enum class BalloonType : Uint8
|
||||
{
|
||||
BALLOON = 0,
|
||||
@@ -36,116 +34,23 @@ enum class BalloonType : Uint8
|
||||
POWERBALL = 2,
|
||||
};
|
||||
|
||||
// Velocidad del globo
|
||||
constexpr float BALLOON_VELX_POSITIVE = 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_POP_ANIMATION = 1;
|
||||
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};
|
||||
|
||||
// PowerBall
|
||||
constexpr int POWERBALL_SCREENPOWER_MINIMUM = 10;
|
||||
constexpr int POWERBALL_COUNTER = 8;
|
||||
|
||||
// Clase Balloon
|
||||
// --- Clase 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:
|
||||
// Constructor
|
||||
// --- Constructores y destructor ---
|
||||
Balloon(
|
||||
float x,
|
||||
float y,
|
||||
@@ -157,35 +62,21 @@ public:
|
||||
SDL_FRect play_area,
|
||||
std::shared_ptr<Texture> texture,
|
||||
const std::vector<std::string> &animation);
|
||||
|
||||
// Destructor
|
||||
~Balloon() = default;
|
||||
|
||||
// Centra el globo en la posición X
|
||||
void alignTo(int x);
|
||||
// --- Métodos principales ---
|
||||
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
|
||||
void render();
|
||||
// --- Métodos de color ---
|
||||
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
|
||||
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
|
||||
// --- Getters ---
|
||||
float getPosX() const { return x_; }
|
||||
float getPosY() const { return y_; }
|
||||
int getWidth() const { return w_; }
|
||||
@@ -204,10 +95,80 @@ public:
|
||||
bool isUsingReversedColor() { return use_reversed_colors_; }
|
||||
bool canBePopped() const { return !isBeingCreated(); }
|
||||
|
||||
// Setters
|
||||
// --- Setters ---
|
||||
void setVelY(float vel_y) { vy_ = vel_y; }
|
||||
void setSpeed(float speed) { speed_ = speed; }
|
||||
void setInvulnerable(bool value) { invulnerable_ = value; }
|
||||
void setSound(bool value) { sound_enabled_ = value; }
|
||||
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 <vector>
|
||||
|
||||
// Constantes de configuración
|
||||
// --- Constantes de configuración ---
|
||||
constexpr int NUMBER_OF_BALLOON_FORMATIONS = 100;
|
||||
constexpr int MAX_NUMBER_OF_BALLOONS_IN_A_FORMATION = 50;
|
||||
constexpr int NUMBER_OF_SETS_PER_POOL = 10;
|
||||
constexpr int NUMBER_OF_STAGES = 10;
|
||||
|
||||
// Estructuras de datos
|
||||
// --- Estructuras de datos ---
|
||||
struct BalloonFormationParams
|
||||
{
|
||||
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 *>;
|
||||
|
||||
// Clase BalloonFormations
|
||||
// --- Clase BalloonFormations ---
|
||||
class BalloonFormations
|
||||
{
|
||||
public:
|
||||
// Constructor
|
||||
// --- Constructor y destructor ---
|
||||
BalloonFormations()
|
||||
{
|
||||
initBalloonFormations();
|
||||
initBalloonFormationPools();
|
||||
}
|
||||
|
||||
// Destructor
|
||||
~BalloonFormations() = default;
|
||||
|
||||
// Getters
|
||||
// --- Getters ---
|
||||
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 set) const { return balloon_formation_.at(set); }
|
||||
|
||||
private:
|
||||
// --- Datos ---
|
||||
std::vector<BalloonFormationUnit> balloon_formation_; // Vector con todas las formaciones enemigas
|
||||
std::vector<BalloonFormationPool> balloon_formation_pool_; // Conjuntos de formaciones enemigas
|
||||
|
||||
// Métodos internos de inicialización
|
||||
// --- Métodos internos de inicialización ---
|
||||
void initBalloonFormations();
|
||||
void initBalloonFormationPools();
|
||||
};
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
#include <memory> // Para shared_ptr, unique_ptr
|
||||
#include "sprite.h" // Para Sprite
|
||||
#include "utils.h" // Para Circle
|
||||
class Texture; // lines 8-8
|
||||
class Texture;
|
||||
|
||||
// Tipos de balas
|
||||
enum class BulletType : Uint8
|
||||
@@ -25,6 +25,23 @@ enum class BulletMoveStatus : Uint8
|
||||
// Clase 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:
|
||||
// Constantes
|
||||
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_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_y_; // Posición en el eje Y
|
||||
float vel_x_; // Velocidad en el eje X
|
||||
|
||||
BulletType bullet_type_; // Tipo de objeto
|
||||
int owner_; // Identificador del dueño del objeto
|
||||
Circle collider_; // Círculo de colisión del objeto
|
||||
BulletType bullet_type_; // Tipo de bala
|
||||
int owner_; // Identificador del dueño
|
||||
Circle collider_; // Círculo de colisión
|
||||
|
||||
void shiftColliders(); // Alinea el círculo de colisión con el objeto
|
||||
void shiftSprite(); // Alinea el sprite con el objeto
|
||||
|
||||
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();
|
||||
// Métodos internos
|
||||
void shiftColliders(); // Ajusta el círculo de colisión
|
||||
void shiftSprite(); // Ajusta el sprite
|
||||
};
|
||||
|
||||
@@ -33,11 +33,11 @@ constexpr const char TEXT_COPYRIGHT[] = "@2020,2025 JailDesigner";
|
||||
// Constructor
|
||||
Credits::Credits()
|
||||
: 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)),
|
||||
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_)
|
||||
{
|
||||
|
||||
194
source/credits.h
194
source/credits.h
@@ -1,113 +1,125 @@
|
||||
#pragma once
|
||||
|
||||
#include <SDL3/SDL_rect.h> // Para SDL_FRect
|
||||
#include <SDL3/SDL_render.h> // Para SDL_Texture
|
||||
#include <SDL3/SDL_stdinc.h> // Para Uint32
|
||||
#include <memory> // Para unique_ptr, shared_ptr
|
||||
#include <vector> // Para vector
|
||||
#include "options.h" // Para Options, OptionsAudio, OptionsMusic
|
||||
#include "param.h" // Para Param, ParamGame, param
|
||||
#include "utils.h" // Para Zone
|
||||
class BalloonManager; // lines 8-8
|
||||
class Fade; // lines 11-11
|
||||
class Player; // lines 10-10
|
||||
class TiledBG; // lines 9-9
|
||||
#include <SDL3/SDL_rect.h>
|
||||
#include <SDL3/SDL_render.h>
|
||||
#include <SDL3/SDL_stdinc.h>
|
||||
#include <memory>
|
||||
#include <vector>
|
||||
|
||||
#include "options.h"
|
||||
#include "param.h"
|
||||
#include "utils.h"
|
||||
|
||||
// Declaraciones adelantadas
|
||||
class BalloonManager;
|
||||
class Fade;
|
||||
class Player;
|
||||
class TiledBG;
|
||||
|
||||
constexpr int PLAY_AREA_HEIGHT = 200;
|
||||
|
||||
class Credits
|
||||
{
|
||||
public:
|
||||
Credits();
|
||||
~Credits();
|
||||
|
||||
void run(); // Bucle principal
|
||||
|
||||
private:
|
||||
// Objetos
|
||||
std::unique_ptr<BalloonManager> balloon_manager_; // Objeto para gestionar los globos
|
||||
SDL_Texture *text_texture_; // Textura con el texto
|
||||
SDL_Texture *canvas_; // Textura donde dibujarlo todo
|
||||
std::unique_ptr<TiledBG> tiled_bg_; // Objeto para dibujar el mosaico animado de fondo
|
||||
std::unique_ptr<Fade> fade_in_; // Objeto para realizar el fundido de entrada
|
||||
std::unique_ptr<Fade> fade_out_; // Objeto para realizar el fundido de salida
|
||||
std::vector<std::shared_ptr<Player>> players_; // Vector con los jugadores
|
||||
// === Objetos Principales ===
|
||||
std::unique_ptr<BalloonManager> balloon_manager_; // Gestión de globos
|
||||
std::unique_ptr<TiledBG> tiled_bg_; // Mosaico animado de fondo
|
||||
std::unique_ptr<Fade> fade_in_; // Fundido de entrada
|
||||
std::unique_ptr<Fade> fade_out_; // Fundido de salida
|
||||
std::vector<std::shared_ptr<Player>> players_; // Vector de jugadores
|
||||
|
||||
// Variables
|
||||
Uint64 ticks_ = 0; // Contador de ticks para ajustar la velocidad del programa
|
||||
Uint32 counter_ = 0; // Contador para la lógica de la clase
|
||||
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
|
||||
// === Gestión de Texturas ===
|
||||
SDL_Texture *text_texture_; // Textura con el texto
|
||||
SDL_Texture *canvas_; // Textura donde dibujarlo todo
|
||||
|
||||
// Rectangulos
|
||||
SDL_FRect credits_rect_src_ = param.game.game_area.rect; // Rectangulo con el texto de los créditos (origen)
|
||||
SDL_FRect credits_rect_dst_ = param.game.game_area.rect; // Rectangulo con el texto de los créditos (destino)
|
||||
SDL_FRect mini_logo_rect_src_ = param.game.game_area.rect; // Rectangulo con el mini logo de JailGames y el texto de copyright (origen)
|
||||
SDL_FRect mini_logo_rect_dst_ = param.game.game_area.rect; // Rectangulo con el mini logo de JailGames y el texto de copyright (destino)
|
||||
// === Temporización y Contadores ===
|
||||
Uint64 ticks_ = 0; // Control de velocidad del programa
|
||||
Uint32 counter_ = 0; // Contador principal de lógica
|
||||
Uint32 counter_pre_fade_ = 0; // Activación del fundido final
|
||||
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_ = {
|
||||
param.game.game_area.rect.x,
|
||||
param.game.game_area.rect.y + black_bars_size_,
|
||||
param.game.game_area.rect.w,
|
||||
PLAY_AREA_HEIGHT}; // Area visible para los creditos
|
||||
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
|
||||
PLAY_AREA_HEIGHT};
|
||||
|
||||
// Actualiza las variables
|
||||
void update();
|
||||
// Barras negras para efecto letterbox
|
||||
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
|
||||
void render();
|
||||
// Borde para la ventana
|
||||
SDL_FRect red_rect = play_area_; // Delimitador de ventana
|
||||
|
||||
// Comprueba el manejador de eventos
|
||||
void checkEvents();
|
||||
// === Métodos del Bucle Principal ===
|
||||
void update(); // Actualización principal
|
||||
void render(); // Renderizado
|
||||
void checkEvents(); // Manejo de eventos
|
||||
void checkInput(); // Procesamiento de entrada
|
||||
|
||||
// Comprueba las entradas
|
||||
void checkInput();
|
||||
// === Métodos de Renderizado ===
|
||||
void fillTextTexture(); // Crear textura de texto
|
||||
void fillCanvas(); // Renderizar todos los sprites
|
||||
void updateTextureDstRects(); // Actualizar destinos de texturas
|
||||
|
||||
// Crea la textura con el texto
|
||||
void fillTextTexture();
|
||||
// === Métodos de Lógica del Juego ===
|
||||
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
|
||||
void fillCanvas();
|
||||
// === Métodos de Interfaz ===
|
||||
void updateBlackRects(); // Actualizar rectángulos negros
|
||||
void updateRedRect(); // Actualizar rectángulo rojo
|
||||
|
||||
// Actualiza el destino de los rectangulos de las texturas
|
||||
void updateTextureDstRects();
|
||||
|
||||
// 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();
|
||||
// === Métodos de Audio ===
|
||||
void setVolume(int amount); // Establecer volumen
|
||||
void resetVolume(); // Restablecer volumen
|
||||
};
|
||||
@@ -85,7 +85,7 @@ bool DefineButtons::enable(int index)
|
||||
}
|
||||
|
||||
// Comprueba si está habilitado
|
||||
bool DefineButtons::isEnabled() { return enabled_; }
|
||||
bool DefineButtons::isEnabled() const { return enabled_; }
|
||||
|
||||
// Incrementa el indice de los botones
|
||||
void DefineButtons::incIndexButton()
|
||||
|
||||
@@ -2,76 +2,57 @@
|
||||
|
||||
#include <SDL3/SDL_events.h> // Para SDL_Event, SDL_GamepadButtonEvent
|
||||
#include <SDL3/SDL_gamepad.h> // Para SDL_GamepadButton
|
||||
#include <memory> // Para std::shared_ptr
|
||||
#include <stddef.h> // Para size_t
|
||||
#include <memory> // Para shared_ptr
|
||||
#include <string> // Para string
|
||||
#include <vector> // Para vector
|
||||
class Input; // lines 10-10
|
||||
class Text; // lines 11-11
|
||||
enum class InputAction : int; // lines 12-12
|
||||
#include <string> // Para std::string
|
||||
#include <vector> // Para std::vector
|
||||
|
||||
// Declaraciones adelantadas
|
||||
class Input;
|
||||
class Text;
|
||||
enum class InputAction : int;
|
||||
|
||||
// Estructura para definir botones
|
||||
struct DefineButtonsButton
|
||||
{
|
||||
std::string label; // Texto en pantalla para el botón
|
||||
InputAction input; // Input asociado
|
||||
SDL_GamepadButton button; // Botón del mando correspondiente
|
||||
std::string label; // Texto en pantalla
|
||||
InputAction input; // Acción asociada
|
||||
SDL_GamepadButton button; // Botón del mando
|
||||
|
||||
// Constructor
|
||||
DefineButtonsButton(const std::string &lbl, InputAction inp, SDL_GamepadButton btn)
|
||||
: label(lbl), input(inp), button(btn) {}
|
||||
};
|
||||
|
||||
// Clase Bullet
|
||||
// Clase 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:
|
||||
// Constructor
|
||||
DefineButtons();
|
||||
|
||||
// Destructor
|
||||
~DefineButtons() = default;
|
||||
|
||||
// Dibuja el objeto en pantalla
|
||||
void render();
|
||||
void render(); // Dibuja el objeto en pantalla
|
||||
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
|
||||
void checkEvents(const SDL_Event &event);
|
||||
private:
|
||||
// Objetos
|
||||
Input *input_ = nullptr; // Gestión de entrada
|
||||
std::shared_ptr<Text> text_; // Renderizado de texto
|
||||
|
||||
// Habilita el objeto
|
||||
bool enable(int index);
|
||||
// Variables
|
||||
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
|
||||
bool isEnabled();
|
||||
};
|
||||
// Métodos internos
|
||||
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
|
||||
|
||||
#include <string>
|
||||
#include <array>
|
||||
#include "utils.h"
|
||||
#include <array> // Para std::array
|
||||
#include <string> // Para std::string
|
||||
#include "utils.h" // Archivo de utilidades
|
||||
|
||||
// Tamaño máximo del nombre
|
||||
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
|
||||
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:
|
||||
// Constructor
|
||||
EnterName();
|
||||
|
||||
// Destructor
|
||||
~EnterName() = default;
|
||||
|
||||
// Inicializa el objeto
|
||||
void init(const std::string &name = "");
|
||||
void init(const std::string &name = ""); // Inicializa con un nombre opcional
|
||||
|
||||
// Incrementa la posición
|
||||
void incPosition();
|
||||
void incPosition(); // Incrementa la posición del carácter actual
|
||||
void decPosition(); // Decrementa la posición del carácter actual
|
||||
void incIndex(); // Incrementa el índice del carácter en la lista
|
||||
void decIndex(); // Decrementa el índice del carácter en la lista
|
||||
|
||||
// Decrementa la posición
|
||||
void decPosition();
|
||||
std::string getFinalName() const { return trim(name_.substr(0, position_)); } // Obtiene el nombre final introducido
|
||||
std::string getCurrentName() const { return trim(name_); } // Obtiene el nombre actual en proceso
|
||||
|
||||
// Incrementa el índice
|
||||
void incIndex();
|
||||
int getPosition() const { return position_; } // Posición actual del carácter editado
|
||||
bool getPositionOverflow() const { return position_overflow_; } // Indica si la posición excede el límite
|
||||
|
||||
// Decrementa el índice
|
||||
void decIndex();
|
||||
private:
|
||||
std::string character_list_; // Lista de caracteres permitidos
|
||||
std::string name_; // Nombre en proceso
|
||||
size_t position_ = 0; // Índice del carácter que se edita
|
||||
bool position_overflow_ = false; // Flag para exceder límite
|
||||
std::array<int, NAME_SIZE> character_index_; // Índices a `character_list_`
|
||||
|
||||
// Getters
|
||||
std::string getFinalName() const { return trim(name_.substr(0, position_)); }
|
||||
std::string getCurrentName() const { return trim(name_); }
|
||||
int getPosition() const { return position_; }
|
||||
bool getPositionOverflow() const { return position_overflow_; }
|
||||
void updateNameFromCharacterIndex(); // Actualiza `name_` según `character_index_`
|
||||
void initCharacterIndex(const std::string &name); // Inicializa índices desde el nombre
|
||||
int findIndex(char character) const; // Busca el índice de un carácter en `character_list_`
|
||||
};
|
||||
@@ -4,38 +4,26 @@
|
||||
#include <string> // Para string
|
||||
#include <vector> // Para vector
|
||||
#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
|
||||
{
|
||||
int size; // Tamaño de la explosión
|
||||
std::shared_ptr<Texture> texture; // Textura para la explosión
|
||||
std::vector<std::string> animation; // Animación para la textura
|
||||
|
||||
// Constructor
|
||||
ExplosionTexture(int sz, std::shared_ptr<Texture> tex, const std::vector<std::string> &anim)
|
||||
: size(sz), texture(tex), animation(anim) {}
|
||||
};
|
||||
|
||||
// Clase explosions
|
||||
// Clase 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:
|
||||
// Constructor
|
||||
// Constructor y destructor
|
||||
Explosions() = default;
|
||||
|
||||
// Destructor
|
||||
~Explosions() = default;
|
||||
|
||||
// Actualiza la lógica de la clase
|
||||
@@ -49,4 +37,17 @@ public:
|
||||
|
||||
// Añade una explosión
|
||||
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
|
||||
|
||||
#include <SDL3/SDL_rect.h> // Para SDL_FRect
|
||||
#include <SDL3/SDL_render.h> // Para SDL_Renderer, SDL_Texture
|
||||
#include <SDL3/SDL_stdinc.h> // Para Uint8, Uint16
|
||||
#include <vector> // Para vector
|
||||
#include <SDL3/SDL_rect.h>
|
||||
#include <SDL3/SDL_render.h>
|
||||
#include <SDL3/SDL_stdinc.h>
|
||||
#include <vector>
|
||||
|
||||
// Tipos de fundido
|
||||
enum class FadeType : Uint8
|
||||
@@ -31,72 +31,62 @@ enum class FadeState : Uint8
|
||||
FINISHED = 4,
|
||||
};
|
||||
|
||||
// Clase 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:
|
||||
// Constructor
|
||||
// --- Constructores y destructor ---
|
||||
Fade();
|
||||
|
||||
// Destructor
|
||||
~Fade();
|
||||
|
||||
// Resetea algunas variables para volver a hacer el fade sin perder ciertos parametros
|
||||
void reset();
|
||||
// --- Métodos principales ---
|
||||
void reset(); // Resetea variables para reutilizar el fade
|
||||
void render(); // Dibuja la transición en pantalla
|
||||
void update(); // Actualiza el estado interno
|
||||
void activate(); // Activa el fade
|
||||
|
||||
// Pinta una transición en pantalla
|
||||
void render();
|
||||
|
||||
// Actualiza las variables internas
|
||||
void update();
|
||||
|
||||
// Activa el fade
|
||||
void activate();
|
||||
|
||||
// Establece el color del fade
|
||||
// --- Configuración ---
|
||||
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 setMode(FadeMode mode) { mode_ = mode; }
|
||||
void setPostDuration(int value) { post_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 "player.h" // Para Player
|
||||
#include "utils.h" // Para Demo
|
||||
|
||||
class Audio;
|
||||
class Asset; // lines 14-14
|
||||
class Background; // lines 15-15
|
||||
class BalloonManager; // lines 16-16
|
||||
class Bullet; // lines 18-18
|
||||
class Fade; // lines 19-19
|
||||
class Input; // lines 20-20
|
||||
class Item; // lines 21-21
|
||||
class PathSprite; // lines 22-22
|
||||
class Scoreboard; // lines 23-23
|
||||
class Screen; // lines 24-24
|
||||
class SmartSprite; // lines 25-25
|
||||
class Tabe; // lines 17-17
|
||||
class Texture; // lines 26-26
|
||||
enum class BulletType : Uint8; // lines 27-27
|
||||
enum class ItemType; // lines 28-28
|
||||
struct Path; // lines 29-29
|
||||
class Asset;
|
||||
class Background;
|
||||
class BalloonManager;
|
||||
class Tabe;
|
||||
class Bullet;
|
||||
class Fade;
|
||||
class Input;
|
||||
class Item;
|
||||
class PathSprite;
|
||||
class Scoreboard;
|
||||
class Screen;
|
||||
class SmartSprite;
|
||||
class Texture;
|
||||
enum class BulletType : Uint8;
|
||||
enum class ItemType;
|
||||
struct Path;
|
||||
|
||||
// Modo demo
|
||||
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
|
||||
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
|
||||
class Game
|
||||
{
|
||||
public:
|
||||
// Constructor
|
||||
Game(int playerID, int current_stage, bool demo);
|
||||
|
||||
// Destructor
|
||||
~Game();
|
||||
|
||||
// Bucle principal del juego
|
||||
void run();
|
||||
|
||||
private:
|
||||
// Enum
|
||||
// --- Tipos internos ---
|
||||
enum class GameState
|
||||
{
|
||||
FADE_IN,
|
||||
@@ -76,14 +61,12 @@ private:
|
||||
GAME_OVER,
|
||||
};
|
||||
|
||||
// Contadores
|
||||
// --- Constantes internas ---
|
||||
static constexpr int HELP_COUNTER_ = 1000;
|
||||
static constexpr int GAME_COMPLETED_START_FADE_ = 500;
|
||||
static constexpr int GAME_COMPLETED_END_ = 700;
|
||||
static constexpr int GAME_OVER_COUNTER_ = 350;
|
||||
static constexpr int TIME_STOPPED_COUNTER_ = 360;
|
||||
|
||||
// Porcentaje de aparición de los objetos
|
||||
static constexpr int ITEM_POINTS_1_DISK_ODDS_ = 10;
|
||||
static constexpr int ITEM_POINTS_2_GAVINA_ODDS_ = 6;
|
||||
static constexpr int ITEM_POINTS_3_PACMAR_ODDS_ = 3;
|
||||
@@ -92,7 +75,7 @@ private:
|
||||
static constexpr int ITEM_POWER_BALL_ODDS_ = 0;
|
||||
static constexpr int ITEM_COFFEE_MACHINE_ODDS_ = 4;
|
||||
|
||||
// Estructuras
|
||||
// --- Estructuras ---
|
||||
struct Helper
|
||||
{
|
||||
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_machine_odds; // Probabilidad de aparición del objeto
|
||||
|
||||
// Constructor con valores predeterminados
|
||||
Helper()
|
||||
: need_coffee(false),
|
||||
need_coffee_machine(false),
|
||||
@@ -120,7 +102,7 @@ private:
|
||||
item_coffee_machine_odds(ITEM_COFFEE_MACHINE_ODDS_) {}
|
||||
};
|
||||
|
||||
// Objetos y punteros
|
||||
// --- Objetos y punteros ---
|
||||
SDL_Renderer *renderer_; // El renderizador de la ventana
|
||||
Screen *screen_; // Objeto encargado de dibujar en pantalla
|
||||
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<Item>> items_; // Vector con los items
|
||||
std::vector<std::unique_ptr<SmartSprite>> smart_sprites_; // Vector con los smartsprites
|
||||
std::vector<std::unique_ptr<PathSprite>> path_sprites_; // Vector con los smartsprites
|
||||
std::vector<std::unique_ptr<PathSprite>> path_sprites_; // Vector con los pathsprites
|
||||
|
||||
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::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
|
||||
|
||||
@@ -151,7 +133,7 @@ private:
|
||||
std::unique_ptr<Tabe> tabe_; // Objeto para gestionar el Tabe Volaor
|
||||
std::vector<Path> paths_; // Vector con los recorridos precalculados almacenados
|
||||
|
||||
// Variables
|
||||
// --- Variables de estado ---
|
||||
HiScoreEntry hi_score_ = HiScoreEntry(
|
||||
options.game.hi_score_table[0].name,
|
||||
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_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
|
||||
|
||||
#ifdef DEBUG
|
||||
bool auto_pop_balloons_ = false; // Si es true, incrementa automaticamente los globos explotados
|
||||
|
||||
@@ -179,250 +162,87 @@ private:
|
||||
void checkDebugEvents(const SDL_Event &event);
|
||||
#endif
|
||||
|
||||
// Actualiza el juego
|
||||
void update();
|
||||
|
||||
// Dibuja el juego
|
||||
void render();
|
||||
|
||||
// Comprueba los eventos que hay en cola
|
||||
void checkEvents();
|
||||
|
||||
// Asigna texturas y animaciones
|
||||
void setResources();
|
||||
|
||||
// Actualiza el valor de HiScore en caso necesario
|
||||
void updateHiScore();
|
||||
|
||||
// Actualiza las variables del jugador
|
||||
void updatePlayers();
|
||||
|
||||
// Dibuja a los jugadores
|
||||
void renderPlayers();
|
||||
|
||||
// Comprueba si hay cambio de fase y actualiza las variables
|
||||
void updateStage();
|
||||
|
||||
// Actualiza el estado de fin de la partida
|
||||
void updateGameStateGameOver();
|
||||
|
||||
// Destruye todos los items
|
||||
void destroyAllItems();
|
||||
|
||||
// Comprueba la colisión entre el jugador y los globos activos
|
||||
bool checkPlayerBalloonCollision(std::shared_ptr<Player> &player);
|
||||
|
||||
// Comprueba la colisión entre el jugador y los items
|
||||
void checkPlayerItemCollision(std::shared_ptr<Player> &player);
|
||||
|
||||
// Comprueba y procesa la colisión de las balas
|
||||
void checkBulletCollision();
|
||||
|
||||
// Mueve las balas activas
|
||||
void updateBullets();
|
||||
|
||||
// Pinta las balas activas
|
||||
void renderBullets();
|
||||
|
||||
// Crea un objeto bala
|
||||
void createBullet(int x, int y, BulletType kind, bool powered_up, int owner);
|
||||
|
||||
// Vacia el vector de balas
|
||||
void freeBullets();
|
||||
|
||||
// Actualiza los items
|
||||
void updateItems();
|
||||
|
||||
// Pinta los items activos
|
||||
void renderItems();
|
||||
|
||||
// Devuelve un item en función del azar
|
||||
ItemType dropItem();
|
||||
|
||||
// Crea un objeto item
|
||||
void createItem(ItemType type, float x, float y);
|
||||
|
||||
// Vacia el vector de items
|
||||
void freeItems();
|
||||
|
||||
// Crea un objeto PathSprite
|
||||
void createItemText(int x, std::shared_ptr<Texture> texture);
|
||||
|
||||
// Crea un objeto PathSprite
|
||||
void createMessage(const std::vector<Path> &paths, std::shared_ptr<Texture> texture);
|
||||
|
||||
// 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();
|
||||
// --- Métodos internos ---
|
||||
|
||||
void update(); // Actualiza el juego
|
||||
void render(); // Dibuja el juego
|
||||
void checkEvents(); // Comprueba los eventos que hay en cola
|
||||
void setResources(); // Asigna texturas y animaciones
|
||||
void updateHiScore(); // Actualiza el valor de HiScore en caso necesario
|
||||
void updatePlayers(); // Actualiza las variables del jugador
|
||||
void renderPlayers(); // Dibuja a los jugadores
|
||||
void updateStage(); // Comprueba si hay cambio de fase y actualiza las variables
|
||||
void updateGameStateGameOver(); // Actualiza el estado de fin de la partida
|
||||
void destroyAllItems(); // Destruye todos los items
|
||||
bool checkPlayerBalloonCollision(std::shared_ptr<Player> &player); // Comprueba la colisión entre el jugador y los globos activos
|
||||
void checkPlayerItemCollision(std::shared_ptr<Player> &player); // Comprueba la colisión entre el jugador y los items
|
||||
void checkBulletCollision(); // Comprueba y procesa la colisión de las balas
|
||||
void updateBullets(); // Mueve las balas activas
|
||||
void renderBullets(); // Pinta las balas activas
|
||||
void createBullet(int x, int y, BulletType kind, bool powered_up, int owner); // Crea un objeto bala
|
||||
void freeBullets(); // Vacia el vector de balas
|
||||
void updateItems(); // Actualiza los items
|
||||
void renderItems(); // Pinta los items activos
|
||||
ItemType dropItem(); // Devuelve un item en función del azar
|
||||
void createItem(ItemType type, float x, float y); // Crea un objeto item
|
||||
void freeItems(); // Vacia el vector de items
|
||||
void createItemText(int x, std::shared_ptr<Texture> texture); // Crea un objeto PathSprite
|
||||
void createMessage(const std::vector<Path> &paths, std::shared_ptr<Texture> texture); // Crea un objeto PathSprite
|
||||
void freeSmartSprites(); // Vacia el vector de smartsprites
|
||||
void freePathSprites(); // Vacia el vector de pathsprites
|
||||
void throwCoffee(int x, int y); // Crea un SpriteSmart para arrojar el item café al recibir un impacto
|
||||
void updateSmartSprites(); // Actualiza los SpriteSmarts
|
||||
void renderSmartSprites(); // Pinta los SpriteSmarts activos
|
||||
void updatePathSprites(); // Actualiza los PathSprites
|
||||
void renderPathSprites(); // Pinta los PathSprites activos
|
||||
void killPlayer(std::shared_ptr<Player> &player); // Acciones a realizar cuando el jugador muere
|
||||
void updateTimeStopped(); // Actualiza y comprueba el valor de la variable
|
||||
void updateBackground(); // Actualiza el fondo
|
||||
void initPaths(); // Inicializa las variables que contienen puntos de ruta para mover objetos
|
||||
void enableTimeStopItem(); // Habilita el efecto del item de detener el tiempo
|
||||
void disableTimeStopItem(); // Deshabilita el efecto del item de detener el tiempo
|
||||
void updateHelper(); // Actualiza las variables de ayuda
|
||||
bool allPlayersAreWaitingOrGameOver(); // Comprueba si todos los jugadores han terminado de jugar
|
||||
bool allPlayersAreGameOver(); // Comprueba si todos los jugadores han terminado de jugar
|
||||
bool allPlayersAreNotPlaying(); // Comprueba si todos los jugadores han terminado de jugar
|
||||
void updateScoreboard(); // Actualiza el marcador
|
||||
void fillCanvas(); // Dibuja los elementos de la zona de juego en su textura
|
||||
void pause(bool value); // Pausa el juego
|
||||
void addScoreToScoreBoard(const std::shared_ptr<Player> &player); // Añade una puntuación a la tabla de records
|
||||
void checkAndUpdatePlayerStatus(int active_player_index, int inactive_player_index); // Saca del estado de GAME OVER al jugador si el otro está activo
|
||||
void checkPlayersStatusPlaying(); // Comprueba el estado de juego de los jugadores
|
||||
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
|
||||
void checkInput(); // Gestiona la entrada durante el juego
|
||||
void checkPauseInput(); // Verifica si alguno de los controladores ha solicitado una pausa y actualiza el estado de pausa del juego.
|
||||
void handleDemoMode(); // Gestiona las entradas de los jugadores en el modo demo, incluyendo movimientos y disparos automáticos.
|
||||
void handleDemoPlayerInput(const std::shared_ptr<Player> &player, int index); // Procesa las entradas para un jugador específico durante el modo demo.
|
||||
void handleFireInput(const std::shared_ptr<Player> &player, BulletType 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).
|
||||
void handleNormalPlayerInput(const std::shared_ptr<Player> &player); // Maneja las entradas de movimiento y disparo para un jugador en modo normal.
|
||||
void handleFireInputs(const std::shared_ptr<Player> &player, bool autofire, int 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.
|
||||
void handleNameInput(const std::shared_ptr<Player> &player); // Procesa las entradas para la introducción del nombre del jugador.
|
||||
void initDemo(int player_id); // Inicializa las variables para el modo DEMO
|
||||
void setTotalPower(); // Calcula el poder total necesario para completar el juego
|
||||
void initScoreboard(); // Inicializa el marcador
|
||||
void initDifficultyVars(); // Inicializa las opciones relacionadas con la dificultad
|
||||
void initPlayers(int player_id); // Inicializa los jugadores
|
||||
void playMusic(); // Hace sonar la música
|
||||
void stopMusic(); // Detiene la música
|
||||
void updateDemo(); // Actualiza las variables durante el modo demo
|
||||
#ifdef RECORDING
|
||||
// Actualiza las variables durante el modo de grabación
|
||||
void updateRecording();
|
||||
void updateRecording(); // Actualiza las variables durante el modo de grabación
|
||||
#endif
|
||||
// Actualiza las variables durante dicho estado
|
||||
void updateGameStateFadeIn();
|
||||
|
||||
// Actualiza las variables durante dicho estado
|
||||
void updateGameStateEnteringPlayer();
|
||||
|
||||
// Actualiza las variables durante dicho estado
|
||||
void updateGameStateShowingGetReadyMessage();
|
||||
|
||||
// Actualiza las variables durante el transcurso normal del juego
|
||||
void updateGameStatePlaying();
|
||||
|
||||
// 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();
|
||||
void updateGameStateFadeIn(); // Actualiza las variables durante dicho estado
|
||||
void updateGameStateEnteringPlayer(); // Actualiza las variables durante dicho estado
|
||||
void updateGameStateShowingGetReadyMessage(); // Actualiza las variables durante dicho estado
|
||||
void updateGameStatePlaying(); // Actualiza las variables durante el transcurso normal del juego
|
||||
void updateGameStateCompleted(); // Gestiona eventos para el estado del final del juego
|
||||
void checkState(); // Comprueba el estado del juego
|
||||
void cleanVectors(); // Vacía los vectores de elementos deshabilitados
|
||||
void updateMenace(); // Gestiona el nivel de amenaza
|
||||
void evaluateAndSetMenace(); // Calcula y establece el valor de amenaza en funcion de los globos activos
|
||||
void checkAndUpdateBalloonSpeed(); // Actualiza la velocidad de los globos en funcion del poder acumulado de la fase
|
||||
void setState(GameState state); // Cambia el estado del juego
|
||||
};
|
||||
@@ -4,12 +4,27 @@
|
||||
#include "animated_sprite.h" // Para AnimatedSprite
|
||||
#include "smart_sprite.h" // Para SmartSprite
|
||||
#include "sprite.h" // Para Sprite
|
||||
class Texture; // lines 7-7
|
||||
|
||||
class Texture;
|
||||
|
||||
// Clase 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:
|
||||
// --- Tipos internos ---
|
||||
enum class Status
|
||||
{
|
||||
DISABLED,
|
||||
@@ -25,16 +40,12 @@ private:
|
||||
int lenght = 8; // Cantidad de desplazamientos a realizar
|
||||
int remaining = lenght; // Cantidad de desplazamientos pendientes a realizar
|
||||
int counter = delay; // Contador para el retraso
|
||||
int origin = 0; // Valor inicial de la pantalla para dejarla igual tras el desplazamiento
|
||||
int origin = 0; // Valor inicial de la pantalla para dejarla igual tras el desplazamiento
|
||||
|
||||
// Constructor por defect
|
||||
Shake() = default;
|
||||
|
||||
// Constructor
|
||||
Shake(int d, int de, int l, int 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)
|
||||
{
|
||||
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> 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::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_right_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 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
|
||||
std::unique_ptr<SmartSprite> crisis_sprite_; // Sprite con la palabra "CRISIS" para la pantalla de titulo
|
||||
|
||||
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
|
||||
// --- Variables de estado ---
|
||||
float x_; // Posición X del logo
|
||||
float y_; // Posición Y del logo
|
||||
float zoom_ = 1.0f; // Zoom aplicado al texto "ARCADE EDITION"
|
||||
int post_finished_counter_ = 1; // Contador final 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 arcade_edition_status_ = Status::DISABLED; // Estado en el que se encuentra el texto "ARCADE_EDITION"
|
||||
Shake shake_; // Estructura para generar el efecto de agitación
|
||||
Status coffee_crisis_status_ = Status::DISABLED; // Estado de "COFFEE CRISIS"
|
||||
Status arcade_edition_status_ = Status::DISABLED; // Estado de "ARCADE EDITION"
|
||||
Shake shake_; // Efecto de agitación
|
||||
|
||||
// Inicializa las variables
|
||||
void init();
|
||||
|
||||
// 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;
|
||||
// --- Métodos internos ---
|
||||
void init(); // Inicializa las variables
|
||||
int getInitialVerticalDesp(); // Calcula el desplazamiento vertical inicial
|
||||
};
|
||||
@@ -7,17 +7,18 @@
|
||||
#include <string> // Para string
|
||||
#include <vector> // Para vector
|
||||
#include "utils.h"
|
||||
class Background; // lines 10-10
|
||||
class Fade; // lines 11-11
|
||||
|
||||
class Background;
|
||||
class Fade;
|
||||
class PathSprite;
|
||||
class Sprite;
|
||||
enum class FadeMode : Uint8; // lines 13-13
|
||||
enum class FadeMode : Uint8;
|
||||
struct Path;
|
||||
|
||||
/*
|
||||
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
|
||||
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 mejorar la legibilidad de los textos, el objeto que dibuja el fondo es capaz de modificar
|
||||
@@ -27,73 +28,6 @@ struct Path;
|
||||
// Clase 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:
|
||||
// Constructor
|
||||
HiScoreTable();
|
||||
@@ -103,4 +37,43 @@ public:
|
||||
|
||||
// Bucle principal
|
||||
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
|
||||
|
||||
/*
|
||||
connectedControllers es un vector donde estan todos los mandos encontrados [0 .. n]
|
||||
checkInput requiere de un indice para comprobar las pulsaciónes de un controlador en concreto [0 .. n]
|
||||
connectedControllers es un vector donde están todos los mandos encontrados [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:
|
||||
InputDeviceToUse::KEYBOARD solo mirará el teclado
|
||||
InputDeviceToUse::CONTROLLER solo mirará el controlador especificado (Si no se especifica, el primero)
|
||||
InputDeviceToUse::ANY mirará tanto el teclado como el PRIMER controlador
|
||||
*/
|
||||
|
||||
// Acciones de entrada posibles en el juego
|
||||
enum class InputAction : int
|
||||
{
|
||||
// Inputs de movimiento
|
||||
@@ -56,6 +57,7 @@ enum class InputAction : int
|
||||
constexpr bool INPUT_ALLOW_REPEAT = true;
|
||||
constexpr bool INPUT_DO_NOT_ALLOW_REPEAT = false;
|
||||
|
||||
// Tipos de dispositivos de entrada
|
||||
enum class InputDeviceToUse : int
|
||||
{
|
||||
KEYBOARD = 0,
|
||||
@@ -63,55 +65,9 @@ enum class InputDeviceToUse : int
|
||||
ANY = 2,
|
||||
};
|
||||
|
||||
// Clase Input: gestiona la entrada de teclado y mandos (singleton)
|
||||
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:
|
||||
// [SINGLETON] Crearemos el objeto con esta función estática
|
||||
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 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);
|
||||
|
||||
// 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);
|
||||
|
||||
// Comprueba si hay algún botón pulsado
|
||||
@@ -141,16 +97,16 @@ public:
|
||||
// Busca si hay mandos conectados
|
||||
bool discoverGameControllers();
|
||||
|
||||
// Comprueba si hay algun mando conectado
|
||||
// Comprueba si hay algún mando conectado
|
||||
bool gameControllerFound();
|
||||
|
||||
// Obten el número de mandos conectados
|
||||
// Obtiene el número de mandos conectados
|
||||
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;
|
||||
|
||||
// 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;
|
||||
|
||||
// Muestra por consola los controles asignados
|
||||
@@ -165,6 +121,53 @@ public:
|
||||
// Convierte un std::string a InputAction
|
||||
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;
|
||||
|
||||
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 <memory> // Para unique_ptr, shared_ptr
|
||||
#include <vector> // Para vector
|
||||
class Fade; // lines 8-8
|
||||
class Sprite; // lines 9-9
|
||||
class Text; // lines 10-10
|
||||
class Texture; // lines 11-11
|
||||
class TiledBG; // lines 12-12
|
||||
|
||||
class Fade;
|
||||
class Sprite;
|
||||
class Text;
|
||||
class Texture;
|
||||
class TiledBG;
|
||||
|
||||
/*
|
||||
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
|
||||
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
|
||||
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
|
||||
{
|
||||
int y; // Coordenada Y de la línea
|
||||
@@ -40,8 +41,18 @@ struct Line
|
||||
// Clase Instructions
|
||||
class Instructions
|
||||
{
|
||||
public:
|
||||
// Constructor
|
||||
Instructions();
|
||||
|
||||
// Destructor
|
||||
~Instructions();
|
||||
|
||||
// Bucle principal
|
||||
void run();
|
||||
|
||||
private:
|
||||
// Objetos y punteros
|
||||
// --- Objetos y punteros ---
|
||||
SDL_Renderer *renderer_; // El renderizador de la ventana
|
||||
SDL_Texture *texture_; // Textura fija con el texto
|
||||
SDL_Texture *backbuffer_; // Textura para usar como backbuffer
|
||||
@@ -52,7 +63,7 @@ private:
|
||||
std::unique_ptr<TiledBG> tiled_bg_; // Objeto para dibujar el mosaico animado de fondo
|
||||
std::unique_ptr<Fade> fade_; // Objeto para renderizar fades
|
||||
|
||||
// Variables
|
||||
// --- Variables ---
|
||||
int counter_ = 0; // Contador para manejar el progreso en la pantalla de instrucciones
|
||||
Uint64 ticks_ = 0; // Contador de ticks para ajustar la velocidad del programa
|
||||
SDL_FRect view_; // Vista del backbuffer que se va a mostrar por pantalla
|
||||
@@ -63,49 +74,17 @@ private:
|
||||
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
|
||||
|
||||
// Actualiza las variables
|
||||
void update();
|
||||
|
||||
// Pinta en pantalla
|
||||
void render();
|
||||
|
||||
// Comprueba los eventos
|
||||
void checkEvents();
|
||||
|
||||
// Comprueba las entradas
|
||||
void checkInput();
|
||||
|
||||
// Rellena la textura de texto
|
||||
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();
|
||||
// --- Métodos internos ---
|
||||
void update(); // Actualiza las variables
|
||||
void render(); // Pinta en pantalla
|
||||
void checkEvents(); // Comprueba los eventos
|
||||
void checkInput(); // Comprueba las entradas
|
||||
void fillTexture(); // Rellena la textura de texto
|
||||
void fillBackbuffer(); // Rellena el backbuffer
|
||||
void iniSprites(); // Inicializa los sprites de los items
|
||||
void updateSprites(); // Actualiza los sprites
|
||||
std::vector<Line> initializeLines(int height); // Inicializa las líneas animadas
|
||||
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
|
||||
void updateBackbuffer(); // Gestiona la textura con los gráficos
|
||||
};
|
||||
@@ -9,13 +9,24 @@
|
||||
|
||||
/*
|
||||
Esta clase gestiona un estado del programa. Se encarga de mostrar la secuencia
|
||||
de introducción
|
||||
de introducción.
|
||||
*/
|
||||
|
||||
// Clase Intro
|
||||
class Intro
|
||||
{
|
||||
public:
|
||||
// Constructor
|
||||
Intro();
|
||||
|
||||
// Destructor
|
||||
~Intro() = default;
|
||||
|
||||
// Bucle principal
|
||||
void run();
|
||||
|
||||
private:
|
||||
// --- Estados internos ---
|
||||
enum class IntroState
|
||||
{
|
||||
SCENES,
|
||||
@@ -28,63 +39,31 @@ private:
|
||||
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>> shadow_sprites_; // Vector con los sprites inteligentes para las sombras
|
||||
std::vector<std::unique_ptr<Writer>> texts_; // Textos de la intro
|
||||
std::unique_ptr<TiledBG> tiled_bg_;
|
||||
std::unique_ptr<TiledBG> tiled_bg_; // Fondo en mosaico
|
||||
|
||||
// Variables
|
||||
// --- Variables ---
|
||||
Uint64 ticks_ = 0; // Contador de ticks para ajustar la velocidad del programa
|
||||
int scene_ = 0; // Indica que escena está activa
|
||||
IntroState state_ = IntroState::SCENES; // Estado
|
||||
IntroPostState post_state_ = IntroPostState::STOP_BG; // Estado
|
||||
Uint32 state_start_time_;
|
||||
Uint8 bg_color_ = 112;
|
||||
int scene_ = 0; // Indica qué escena está activa
|
||||
IntroState state_ = IntroState::SCENES; // Estado principal de la intro
|
||||
IntroPostState post_state_ = IntroPostState::STOP_BG; // Estado POST
|
||||
Uint32 state_start_time_; // Tiempo de inicio del estado actual
|
||||
Uint8 bg_color_ = 112; // Color de fondo
|
||||
|
||||
// Actualiza las variables del objeto
|
||||
void update();
|
||||
|
||||
// Dibuja el objeto en pantalla
|
||||
void render();
|
||||
|
||||
// Comprueba los eventos
|
||||
void checkEvents();
|
||||
|
||||
// Comprueba las entradas
|
||||
void checkInput();
|
||||
|
||||
// Actualiza las escenas de la intro
|
||||
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();
|
||||
// --- 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 updateScenes(); // Actualiza las escenas de la intro
|
||||
void initSprites(); // Inicializa las imágenes
|
||||
void initTexts(); // Inicializa los textos
|
||||
void updateSprites(); // Actualiza los sprites
|
||||
void updateTexts(); // Actualiza los textos
|
||||
void renderSprites(); // Dibuja los sprites
|
||||
void renderTexts(); // Dibuja los textos
|
||||
void updatePostState(); // Actualiza el estado POST
|
||||
};
|
||||
|
||||
176
source/item.h
176
source/item.h
@@ -5,143 +5,49 @@
|
||||
#include <memory> // Para shared_ptr, unique_ptr
|
||||
#include <string> // Para string
|
||||
#include <vector> // Para vector
|
||||
#include "animated_sprite.h" // Para SpriteAnimated
|
||||
#include "animated_sprite.h" // Para AnimatedSprite
|
||||
#include "utils.h" // Para Circle
|
||||
|
||||
class Texture;
|
||||
|
||||
/**
|
||||
* @brief Tipos de objetos disponibles en el juego.
|
||||
*
|
||||
* Esta enumeración define los diferentes tipos de objetos que pueden existir en el juego,
|
||||
* cada uno con un identificador único.
|
||||
*/
|
||||
// Tipos de objetos disponibles en el juego.
|
||||
// Define los diferentes tipos de objetos que pueden existir en el juego.
|
||||
enum class ItemType : int
|
||||
{
|
||||
DISK = 1, /**< Disco */
|
||||
GAVINA = 2, /**< Gavina */
|
||||
PACMAR = 3, /**< Pacman */
|
||||
CLOCK = 4, /**< Reloj */
|
||||
COFFEE = 5, /**< Café */
|
||||
DEBIAN = 6, /**< Debian */
|
||||
COFFEE_MACHINE = 7, /**< Máquina de café */
|
||||
NONE = 8, /**< Ninguno */
|
||||
DISK = 1, // Disco
|
||||
GAVINA = 2, // Gavina
|
||||
PACMAR = 3, // Pacman
|
||||
CLOCK = 4, // Reloj
|
||||
COFFEE = 5, // Café
|
||||
DEBIAN = 6, // Debian
|
||||
COFFEE_MACHINE = 7, // Máquina de café
|
||||
NONE = 8, // Ninguno
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief Clase Item.
|
||||
*
|
||||
* Esta clase representa un objeto en el juego, con sus propiedades y métodos para gestionar su comportamiento.
|
||||
*/
|
||||
// Clase Item.
|
||||
// Representa un objeto en el juego, con sus propiedades y métodos para gestionar su comportamiento.
|
||||
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:
|
||||
/**
|
||||
* @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.
|
||||
*/
|
||||
// Constructor. Inicializa un objeto Item con el tipo, posición, área de juego, textura y animación.
|
||||
Item(ItemType type, float x, float y, SDL_FRect &play_area, std::shared_ptr<Texture> texture, const std::vector<std::string> &animation);
|
||||
|
||||
/**
|
||||
* @brief Destructor de la clase Item.
|
||||
*
|
||||
* Este destructor libera los recursos asociados con el objeto Item.
|
||||
*/
|
||||
// Destructor.
|
||||
~Item() = default;
|
||||
|
||||
/**
|
||||
* @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.
|
||||
*/
|
||||
// Centra el objeto en la posición X indicada, asegurando que no se salga del área de juego.
|
||||
void alignTo(int x);
|
||||
|
||||
/**
|
||||
* @brief Pinta el objeto en la pantalla.
|
||||
*
|
||||
* 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.
|
||||
*/
|
||||
// Renderiza el objeto en pantalla si está habilitado.
|
||||
// Si el tiempo de vida es mayor que 200, renderiza el sprite.
|
||||
// Si es menor o igual a 200, renderiza el sprite de forma intermitente.
|
||||
void render();
|
||||
|
||||
/**
|
||||
* @brief Pone a cero todos los valores del objeto.
|
||||
*
|
||||
* Esta función desactiva el objeto estableciendo su estado `enabled_` a `false`.
|
||||
*/
|
||||
// Desactiva el objeto estableciendo su estado enabled_ a false.
|
||||
void disable();
|
||||
|
||||
/**
|
||||
* @brief Actualiza el objeto a su posición, animación y controla los contadores.
|
||||
*
|
||||
* 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()`.
|
||||
*/
|
||||
// Actualiza la posición, animación y contadores del objeto.
|
||||
// Llama a move(), sprite_->update() y updateTimeToLive().
|
||||
void update();
|
||||
|
||||
// Getters
|
||||
@@ -153,4 +59,40 @@ public:
|
||||
bool isEnabled() const { return enabled_; }
|
||||
bool isOnFloor() const { return floor_collision_; }
|
||||
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
|
||||
|
||||
// Inicializa los textos del juego en el idioma seleccionado
|
||||
bool loadFromFile(std::string file_path)
|
||||
bool loadFromFile(const std::string &file_path)
|
||||
{
|
||||
texts.clear();
|
||||
|
||||
|
||||
@@ -1,22 +1,23 @@
|
||||
#pragma once
|
||||
|
||||
#include <string> // Para string
|
||||
#include <string> // Para std::string
|
||||
|
||||
namespace lang
|
||||
{
|
||||
// --- Códigos de idioma soportados ---
|
||||
enum class Code : int
|
||||
{
|
||||
es_ES = 0,
|
||||
ba_BA = 1,
|
||||
en_UK = 2,
|
||||
es_ES = 0, // Español
|
||||
ba_BA = 1, // Bable/Asturiano
|
||||
en_UK = 2, // Inglés (Reino Unido)
|
||||
};
|
||||
|
||||
// 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);
|
||||
|
||||
// Obtiene el codigo del idioma del siguiente idioma
|
||||
// Obtiene el código del siguiente idioma disponible
|
||||
Code getNextLangCode(Code lang);
|
||||
}
|
||||
@@ -1,65 +1,25 @@
|
||||
#pragma once
|
||||
|
||||
#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 <vector> // Para vector
|
||||
class Sprite; // lines 8-8
|
||||
class Texture; // lines 9-9
|
||||
struct Color; // lines 10-10
|
||||
|
||||
class Sprite;
|
||||
class Texture;
|
||||
struct Color;
|
||||
|
||||
/*
|
||||
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
|
||||
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
|
||||
ZX Spectrum
|
||||
ZX Spectrum.
|
||||
*/
|
||||
|
||||
// Clase Logo
|
||||
// --- Clase 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:
|
||||
// Constructor
|
||||
Logo();
|
||||
@@ -69,4 +29,33 @@ public:
|
||||
|
||||
// Bucle principal
|
||||
void run();
|
||||
|
||||
private:
|
||||
// --- Constantes ---
|
||||
static constexpr int SHOW_SINCE_SPRITE_COUNTER_MARK = 70; // Tiempo del contador en el que empieza a verse el sprite de "SINCE 1998"
|
||||
static constexpr int INIT_FADE_COUNTER_MARK = 300; // Tiempo del contador cuando inicia el fade a negro
|
||||
static constexpr int END_LOGO_COUNTER_MARK = 400; // Tiempo del contador para terminar el logo
|
||||
static constexpr int POST_LOGO_DURATION = 20; // Tiempo que dura el logo con el fade al máximo
|
||||
static constexpr int SPEED = 8; // Velocidad de desplazamiento de cada línea
|
||||
|
||||
// --- 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
|
||||
|
||||
#include <string> // Para string
|
||||
#include <vector> // Para vector
|
||||
#include <string> // Para std::string
|
||||
#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.
|
||||
|
||||
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
|
||||
{
|
||||
std::string name; // Nombre
|
||||
@@ -23,16 +23,9 @@ struct HiScoreEntry
|
||||
: name(n.substr(0, 6)), score(s), one_credit_complete(occ) {}
|
||||
};
|
||||
|
||||
// Clase ManageHiScoreTable
|
||||
// --- Clase ManageHiScoreTable ---
|
||||
class ManageHiScoreTable
|
||||
{
|
||||
private:
|
||||
// Variables
|
||||
std::vector<HiScoreEntry> &table_; // Tabla con los records
|
||||
|
||||
// Ordena la tabla
|
||||
void sort();
|
||||
|
||||
public:
|
||||
// Constructor
|
||||
explicit ManageHiScoreTable(std::vector<HiScoreEntry> &table)
|
||||
@@ -44,7 +37,7 @@ public:
|
||||
// Resetea la tabla a los valores por defecto
|
||||
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);
|
||||
|
||||
// Carga la tabla con los datos de un fichero
|
||||
@@ -52,4 +45,11 @@ public:
|
||||
|
||||
// Guarda la tabla en un fichero
|
||||
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
|
||||
{
|
||||
extern Uint32 cursor_hide_time; // Tiempo en milisegundos para ocultar el cursor
|
||||
extern Uint32 last_mouse_move_time; // Última vez que el ratón se movió
|
||||
extern bool cursor_visible; // Estado del cursor
|
||||
// --- Variables de estado del cursor ---
|
||||
extern Uint32 cursor_hide_time; // Tiempo en milisegundos para ocultar el cursor tras inactividad
|
||||
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);
|
||||
void updateCursorVisibility();
|
||||
// --- Gestión de eventos y visibilidad ---
|
||||
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_surface.h> // Para SDL_FlipMode
|
||||
#include <algorithm> // Para max
|
||||
#include <algorithm> // Para std::max
|
||||
#include <memory> // Para shared_ptr
|
||||
#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
|
||||
class MovingSprite : public Sprite
|
||||
{
|
||||
public:
|
||||
// --- Estructura para la rotación ---
|
||||
struct Rotate
|
||||
{
|
||||
bool enabled; // Indica si ha de rotar
|
||||
int counter; // Contador
|
||||
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
|
||||
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}) {}
|
||||
};
|
||||
|
||||
protected:
|
||||
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
|
||||
// --- Constructores y destructor ---
|
||||
MovingSprite(std::shared_ptr<Texture> texture, SDL_FRect pos, MovingSprite::Rotate rotate, float zoom_w, float zoom_h, SDL_FlipMode flip);
|
||||
MovingSprite(std::shared_ptr<Texture> texture, SDL_FRect pos);
|
||||
explicit MovingSprite(std::shared_ptr<Texture> texture);
|
||||
|
||||
// Destructor
|
||||
virtual ~MovingSprite() override = default;
|
||||
|
||||
// Actualiza las variables internas del objeto
|
||||
virtual void update();
|
||||
// --- Métodos principales ---
|
||||
virtual void update(); // Actualiza las variables internas del objeto
|
||||
void clear() override; // Reinicia todas las variables a cero
|
||||
void render() override; // Muestra el sprite por pantalla
|
||||
|
||||
// Reinicia todas las variables a cero
|
||||
void clear() override;
|
||||
|
||||
// Muestra el sprite por pantalla
|
||||
void render() override;
|
||||
|
||||
// Obtiene la variable
|
||||
// --- Getters de posición y movimiento ---
|
||||
float getPosX() const { return x_; }
|
||||
float getPosY() const { return y_; }
|
||||
float getVelX() const { return vx_; }
|
||||
@@ -73,51 +44,53 @@ public:
|
||||
float getAccelX() const { return ax_; }
|
||||
float getAccelY() const { return ay_; }
|
||||
|
||||
// Establece la variable
|
||||
// --- Setters de movimiento ---
|
||||
void setVelX(float value) { vx_ = value; }
|
||||
void setVelY(float value) { vy_ = value; }
|
||||
void setAccelX(float value) { ax_ = value; }
|
||||
void setAccelY(float value) { ay_ = value; }
|
||||
|
||||
// Obten el valor de la variable
|
||||
// --- Rotación ---
|
||||
bool isRotating() const { return rotate_.enabled; }
|
||||
|
||||
// Establece el valor de la variable
|
||||
void setZoomW(float value) { zoom_w_ = value; }
|
||||
void setZoomH(float value) { zoom_h_ = value; }
|
||||
|
||||
// Establece el valor de la variable
|
||||
void setAngle(double value) { rotate_.angle = value; }
|
||||
void setRotatingCenter(SDL_FPoint point) { rotate_.center = point; }
|
||||
|
||||
// Activa o desactiva el efecto de rotación
|
||||
void setRotate(bool enable);
|
||||
|
||||
// Establece el valor de la variable
|
||||
void setRotate(bool enable); // Activa o desactiva el efecto de rotación
|
||||
void setRotateSpeed(int value) { rotate_.speed = std::max(1, value); }
|
||||
void setRotateAmount(double value) { rotate_.amount = value; }
|
||||
void switchRotate() { rotate_.amount *= -1; } // Cambia el sentido de la rotación
|
||||
|
||||
// Cambia el sentido de la rotación
|
||||
void switchRotate() { rotate_.amount *= -1; }
|
||||
|
||||
// Establece el valor de la variable
|
||||
// --- 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; }
|
||||
|
||||
// Obtiene el valor de la variable
|
||||
SDL_FlipMode getFlip() { return flip_; }
|
||||
|
||||
// Establece la posición y_ el tamaño del objeto
|
||||
void setPos(SDL_FRect rect);
|
||||
// --- Posición y tamaño ---
|
||||
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
|
||||
void setPos(float x, float y);
|
||||
protected:
|
||||
// --- Variables de posición y movimiento ---
|
||||
float x_ = 0.0f; // Posición en el eje X
|
||||
float y_ = 0.0f; // Posición en el eje Y
|
||||
|
||||
// Establece el valor de la variable
|
||||
void setPosX(float value);
|
||||
float vx_ = 0.0f; // Velocidad en el eje X. Cantidad de píxeles a desplazarse
|
||||
float vy_ = 0.0f; // Velocidad en el eje Y. Cantidad de píxeles a desplazarse
|
||||
|
||||
// Establece el valor de la variable
|
||||
void setPosY(float value);
|
||||
float ax_ = 0.0f; // Aceleración en el eje X. Variación de la velocidad
|
||||
float ay_ = 0.0f; // Aceleración en el eje Y. Variación de la velocidad
|
||||
|
||||
// --- Efectos visuales ---
|
||||
Rotate rotate_; // Variables usadas para controlar la rotación del sprite
|
||||
float zoom_w_; // Zoom aplicado a la anchura
|
||||
float zoom_h_; // Zoom aplicado a la altura
|
||||
SDL_FlipMode flip_; // Indica cómo se voltea el sprite
|
||||
|
||||
// --- 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_render.h> // Para SDL_Renderer
|
||||
#include <memory> // Para shared_ptr
|
||||
#include <string> // Para string, basic_string
|
||||
#include <string> // Para string
|
||||
#include <vector> // Para vector
|
||||
#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
|
||||
{
|
||||
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:
|
||||
// [SINGLETON] Objeto notifier
|
||||
static Notifier *notifier_;
|
||||
|
||||
// --- Tipos internos ---
|
||||
enum class NotificationStatus
|
||||
{
|
||||
RISING,
|
||||
@@ -30,18 +61,19 @@ private:
|
||||
SQUARED,
|
||||
};
|
||||
|
||||
// --- Estructura Notification ---
|
||||
struct Notification
|
||||
{
|
||||
std::shared_ptr<Texture> texture;
|
||||
std::shared_ptr<Sprite> sprite;
|
||||
std::vector<std::string> texts;
|
||||
int counter;
|
||||
NotificationStatus state;
|
||||
NotificationShape shape;
|
||||
SDL_FRect rect;
|
||||
int y;
|
||||
int travel_dist;
|
||||
std::string code; // Permite asignar un código a la notificación
|
||||
std::shared_ptr<Texture> texture; // Textura de la notificación
|
||||
std::shared_ptr<Sprite> sprite; // Sprite asociado
|
||||
std::vector<std::string> texts; // Textos a mostrar
|
||||
int counter; // Contador de tiempo
|
||||
NotificationStatus state; // Estado de la notificación
|
||||
NotificationShape shape; // Forma de la notificación
|
||||
SDL_FRect rect; // Rectángulo de la notificación
|
||||
int y; // Posición vertical
|
||||
int travel_dist; // Distancia a recorrer
|
||||
std::string code; // Código identificador de la notificación
|
||||
|
||||
// Constructor
|
||||
explicit Notification()
|
||||
@@ -49,58 +81,23 @@ private:
|
||||
shape(NotificationShape::SQUARED), rect{0, 0, 0, 0}, y(0), travel_dist(0), code("") {}
|
||||
};
|
||||
|
||||
// Objetos y punteros
|
||||
SDL_Renderer *renderer_; // El renderizador de la ventana
|
||||
|
||||
// --- Objetos y punteros ---
|
||||
SDL_Renderer *renderer_; // El renderizador de la ventana
|
||||
std::shared_ptr<Texture> icon_texture_; // Textura para los iconos de las notificaciones
|
||||
std::shared_ptr<Text> text_; // Objeto para dibujar texto
|
||||
|
||||
// Variables
|
||||
// --- Variables de estado ---
|
||||
Color bg_color_; // Color de fondo de las notificaciones
|
||||
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 has_icons_; // Indica si el notificador tiene textura para iconos
|
||||
|
||||
// Elimina las notificaciones finalizadas
|
||||
void clearFinishedNotifications();
|
||||
// --- Métodos internos ---
|
||||
void clearFinishedNotifications(); // Elimina las notificaciones finalizadas
|
||||
void clearAllNotifications(); // Finaliza y elimina todas las notificaciones activas
|
||||
|
||||
// Finaliza y elimnina todas las notificaciones activas
|
||||
void clearAllNotifications();
|
||||
|
||||
// [SINGLETON] Ahora el constructor y el destructor son privados, para no poder crear objetos notifier desde fuera
|
||||
|
||||
// Constructor
|
||||
// [SINGLETON] Constructor y destructor privados
|
||||
Notifier(std::string icon_file, std::shared_ptr<Text> text);
|
||||
|
||||
// Destructor
|
||||
~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_surface.h> // Para SDL_ScaleMode
|
||||
#include <string> // Para string
|
||||
#include <vector> // Para vector
|
||||
#include <string> // Para std::string
|
||||
#include <vector> // Para std::vector
|
||||
#include "input.h" // Para InputAction, InputDeviceToUse
|
||||
#include "manage_hiscore_table.h" // Para HiScoreEntry
|
||||
|
||||
namespace lang
|
||||
{
|
||||
enum class Code : int;
|
||||
} // lines 11-11
|
||||
}
|
||||
|
||||
// Dificultad del juego
|
||||
// --- Dificultad del juego ---
|
||||
enum class GameDifficulty
|
||||
{
|
||||
EASY = 0,
|
||||
@@ -19,58 +20,58 @@ enum class GameDifficulty
|
||||
HARD = 2,
|
||||
};
|
||||
|
||||
// Estructura para las opciones de la ventana
|
||||
// --- Opciones de la ventana ---
|
||||
struct WindowOptions
|
||||
{
|
||||
std::string caption; // Texto que aparece en la barra de titulo de la ventana
|
||||
int zoom = 1; // Contiene el 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
|
||||
std::string caption; // Texto que aparece en la barra de título 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 la ventana no sea mayor que la pantalla
|
||||
};
|
||||
|
||||
// Estructura con opciones para el video
|
||||
// --- Opciones de vídeo ---
|
||||
struct VideoOptions
|
||||
{
|
||||
SDL_ScaleMode scale_mode; // Filtro usado para el escalado de la imagen
|
||||
bool fullscreen; // Contiene el valor del modo de pantalla completa
|
||||
bool v_sync; // Indica si se quiere usar vsync o no
|
||||
bool integer_scale; // Indica si se va a usar el escalado entero
|
||||
bool shaders; // Indica si se van a usar shaders para los filtros de video
|
||||
std::string info; // Información sobre el modo de video
|
||||
bool fullscreen; // Indica si se usa pantalla completa
|
||||
bool v_sync; // Indica si se usa vsync
|
||||
bool integer_scale; // Indica si se usa escalado entero
|
||||
bool shaders; // Indica si se usan shaders para los filtros de vídeo
|
||||
std::string info; // Información sobre el modo de vídeo
|
||||
};
|
||||
|
||||
// Estructura para las opciones de musica
|
||||
// --- Opciones de música ---
|
||||
struct MusicOptions
|
||||
{
|
||||
bool enabled; // Indica si la musica suena o no
|
||||
int volume; // Volumen al que suena la música
|
||||
bool enabled; // Indica si la música suena o no
|
||||
int volume; // Volumen de la música
|
||||
};
|
||||
|
||||
// Estructura para las opciones de sonido
|
||||
// --- Opciones de sonido ---
|
||||
struct SoundOptions
|
||||
{
|
||||
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
|
||||
{
|
||||
MusicOptions music; // Opciones para la música
|
||||
SoundOptions sound; // Opciones para los efectos de sonido
|
||||
bool enabled; // Indica si el audio está activo o no
|
||||
int volume; // Volumen al que suenan el audio
|
||||
int volume; // Volumen general del audio
|
||||
};
|
||||
|
||||
// Estructura para las opciones del juego
|
||||
// --- Opciones del juego ---
|
||||
struct GameOptions
|
||||
{
|
||||
GameDifficulty difficulty; // Dificultad del juego
|
||||
lang::Code language; // Idioma usado en el juego
|
||||
bool autofire; // Indicador de autofire
|
||||
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()
|
||||
{
|
||||
last_hi_score_entry[0] = -1;
|
||||
@@ -78,16 +79,16 @@ struct GameOptions
|
||||
}
|
||||
};
|
||||
|
||||
// Estructura para los controles del juego
|
||||
// --- Opciones de mando ---
|
||||
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
|
||||
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
|
||||
bool plugged; // Indica si el mando se encuentra conectado
|
||||
std::vector<InputAction> inputs; // Listado de inputs
|
||||
std::vector<SDL_GamepadButton> buttons; // Listado de botones asignados a cada input
|
||||
bool plugged; // Indica si el mando está conectado
|
||||
std::vector<InputAction> inputs; // Listado de acciones asignadas
|
||||
std::vector<SDL_GamepadButton> buttons; // Listado de botones asignados a cada acción
|
||||
|
||||
// Constructor por defecto
|
||||
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} {}
|
||||
};
|
||||
|
||||
// Estructura con todas las opciones de configuración del programa
|
||||
// --- Opciones generales del programa ---
|
||||
struct Options
|
||||
{
|
||||
WindowOptions window; // Opciones para la ventana del programa
|
||||
GameOptions game; // Opciones para el propio juego
|
||||
VideoOptions video; // Opciones relativas a la clase screen
|
||||
AudioOptions audio; // Opciones para el audio
|
||||
std::vector<GamepadOptions> controllers; // Opciones con las asignaciones del mando para cada jugador
|
||||
WindowOptions window; // Opciones de la ventana
|
||||
GameOptions game; // Opciones del juego
|
||||
VideoOptions video; // Opciones de vídeo
|
||||
AudioOptions audio; // Opciones de audio
|
||||
std::vector<GamepadOptions> controllers; // Opciones de mando para cada jugador
|
||||
};
|
||||
|
||||
// Variables
|
||||
// --- Variables globales ---
|
||||
extern Options options;
|
||||
|
||||
// Inicializa las opciones del programa
|
||||
void initOptions();
|
||||
|
||||
// Carga el fichero de configuración
|
||||
bool loadOptionsFile(std::string file_path);
|
||||
|
||||
// Guarda el fichero de configuración
|
||||
bool saveOptionsFile(std::string file_path);
|
||||
|
||||
// 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();
|
||||
// --- Funciones de configuración ---
|
||||
void initOptions(); // Inicializa las opciones del programa
|
||||
bool loadOptionsFile(std::string file_path); // Carga el fichero de configuración
|
||||
bool saveOptionsFile(std::string file_path); // Guarda el fichero de configuración
|
||||
void setKeyboardToPlayer(int player_id); // Asigna el teclado al jugador
|
||||
void swapOptionsKeyboard(); // Intercambia el teclado de jugador
|
||||
void swapOptionsControllers(); // Intercambia los jugadores asignados a los dos primeros mandos
|
||||
int getPlayerWhoUsesKeyboard(); // Averigua quién está usando el teclado
|
||||
@@ -2,88 +2,91 @@
|
||||
|
||||
#include <SDL3/SDL_rect.h> // Para SDL_FRect
|
||||
#include <SDL3/SDL_stdinc.h> // Para Uint32
|
||||
#include <string> // Para string
|
||||
#include <vector> // Para vector
|
||||
#include "utils.h" // Para Color, Zone
|
||||
#include <string> // Para std::string
|
||||
#include <vector> // Para std::vector
|
||||
#include "utils.h" // Para Color, Zone, NotifyPosition
|
||||
|
||||
// param.game
|
||||
// --- Parámetros del juego ---
|
||||
struct ParamGame
|
||||
{
|
||||
float width; // Ancho de la resolucion nativa del juego
|
||||
float height; // Alto de la resolucion nativa del juego
|
||||
float item_size; // Tamaño de los items del juego
|
||||
float coffee_machine_w; // Ancho 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 game_area; // Rectangulo con las dimensiones del juego
|
||||
float width; // Ancho de la resolución nativa del juego
|
||||
float height; // Alto de la resolución nativa del juego
|
||||
float item_size; // Tamaño de los ítems del juego
|
||||
float coffee_machine_w; // Ancho de la máquina de café
|
||||
float coffee_machine_h; // Alto de la máquina de café
|
||||
Zone play_area; // Rectángulo con la posición de la zona de juego
|
||||
Zone game_area; // Rectángulo con las dimensiones del juego
|
||||
int enter_name_seconds; // Duración en segundos para introducir el nombre al finalizar la partida
|
||||
Uint32 speed; // Velocidad a la que transcurre el juego
|
||||
};
|
||||
|
||||
// param.fade
|
||||
// --- Parámetros del fade ---
|
||||
struct ParamFade
|
||||
{
|
||||
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_width; // Cantidad total de cuadraditos en horizontal para el FadeType::RANDOM_SQUARE
|
||||
float num_squares_height; // Cantidad total de cuadraditos en vertical para el FadeType::RANDOM_SQUARE
|
||||
int random_squares_delay; // Duración entre cada pintado de cuadrados
|
||||
int random_squares_mult; // Cantidad de cuadrados que se pintaran cada vez
|
||||
int random_squares_mult; // Cantidad de cuadrados que se pintarán cada vez
|
||||
int post_duration; // Duración final del fade
|
||||
float venetian_size; // Altura de los 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
|
||||
{
|
||||
int press_start_position; // Posición del texto para empezar a jugar
|
||||
int title_duration; // Tiempo de inactividad del titulo
|
||||
int arcade_edition_position; // Posición del bitmap
|
||||
int title_c_c_position; // Posición del bitmap
|
||||
int title_duration; // Tiempo de inactividad del título
|
||||
int arcade_edition_position; // Posición del bitmap "Arcade Edition"
|
||||
int title_c_c_position; // Posición del bitmap "Coffee Crisis"
|
||||
};
|
||||
|
||||
// param.background
|
||||
// --- Parámetros del fondo ---
|
||||
struct ParamBackground
|
||||
{
|
||||
Color attenuate_color;
|
||||
int attenuate_alpha;
|
||||
Color attenuate_color; // Color para atenuar el fondo
|
||||
int attenuate_alpha; // Alpha para la atenuación
|
||||
};
|
||||
|
||||
// --- Parámetros de los globos (balloons) ---
|
||||
struct ParamBalloon
|
||||
{
|
||||
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
|
||||
explicit ParamBalloon(float grav_val = 0.0f, float vel_val = 0.0f)
|
||||
: grav(grav_val), vel(vel_val) {}
|
||||
};
|
||||
|
||||
// Estructura para las opciones de las notificaciones
|
||||
// --- Parámetros de las notificaciones ---
|
||||
struct ParamNotification
|
||||
{
|
||||
NotifyPosition pos_h; // Ubicación de las notificaciones en pantalla
|
||||
NotifyPosition pos_v; // Ubicación de las notificaciones en pantalla
|
||||
NotifyPosition pos_h; // Ubicación horizontal de las notificaciones en pantalla
|
||||
NotifyPosition pos_v; // Ubicación vertical de las notificaciones en pantalla
|
||||
bool sound; // Indica si las notificaciones suenan
|
||||
Color color; // Color de las notificaciones
|
||||
};
|
||||
|
||||
// Estructura para almacenar todos los parámetros del juego
|
||||
// --- Estructura principal para almacenar todos los parámetros del juego ---
|
||||
struct Param
|
||||
{
|
||||
ParamGame game;
|
||||
ParamFade fade;
|
||||
SDL_FRect scoreboard;
|
||||
ParamTitle title;
|
||||
ParamBackground background;
|
||||
std::vector<ParamBalloon> balloon;
|
||||
ParamNotification notification;
|
||||
ParamGame game; // Parámetros del juego
|
||||
ParamFade fade; // Parámetros del fade
|
||||
SDL_FRect scoreboard; // Rectángulo del marcador
|
||||
ParamTitle title; // Parámetros de la pantalla de título
|
||||
ParamBackground background; // Parámetros del fondo
|
||||
std::vector<ParamBalloon> balloon; // Parámetros de los globos
|
||||
ParamNotification notification; // Parámetros de las notificaciones
|
||||
|
||||
// Constructor
|
||||
Param() : game(), fade(), scoreboard(), title(), background(), notification()
|
||||
{
|
||||
balloon.reserve(4);
|
||||
}
|
||||
};
|
||||
|
||||
// --- Variable global con los parámetros del juego ---
|
||||
extern Param param;
|
||||
|
||||
// Establece valores para los parametros a partir de un fichero de texto
|
||||
void loadParamsFromFile(const std::string &file_path);
|
||||
// --- Funciones globales ---
|
||||
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
|
||||
|
||||
#include <SDL3/SDL_rect.h> // Para SDL_FPoint
|
||||
#include <functional> // Para function
|
||||
#include <functional> // Para std::function
|
||||
#include <memory> // Para shared_ptr
|
||||
#include <vector> // Para vector
|
||||
#include "sprite.h" // Para Sprite
|
||||
class Texture; // lines 8-8
|
||||
|
||||
class Texture;
|
||||
|
||||
// --- Tipos de recorrido ---
|
||||
enum class PathType
|
||||
{
|
||||
VERTICAL,
|
||||
HORIZONTAL,
|
||||
};
|
||||
|
||||
// --- Centrado del recorrido ---
|
||||
enum class PathCentered
|
||||
{
|
||||
ON_X,
|
||||
@@ -20,7 +23,7 @@ enum class PathCentered
|
||||
NONE,
|
||||
};
|
||||
|
||||
// Estructuras
|
||||
// --- Estructura Path: define un recorrido para el sprite ---
|
||||
struct Path
|
||||
{
|
||||
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
|
||||
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
|
||||
{
|
||||
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:
|
||||
// Constructor
|
||||
// --- Constructor y destructor ---
|
||||
explicit PathSprite(std::shared_ptr<Texture> texture)
|
||||
: Sprite(texture) {}
|
||||
|
||||
// Destructor
|
||||
~PathSprite() override = default;
|
||||
|
||||
// Actualiza la posición del sprite
|
||||
void update();
|
||||
// --- Métodos principales ---
|
||||
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
|
||||
void render() override;
|
||||
// --- Gestión de recorridos ---
|
||||
void addPath(Path path, bool centered = false); // Añade un recorrido (Path)
|
||||
void addPath(std::vector<SDL_FPoint> spots, int waiting_counter = 0); // Añade un recorrido a partir de puntos
|
||||
void addPath(int start, int end, PathType type, int fixed_pos, int steps, const std::function<double(double)> &easingFunction, int waiting_counter = 0); // Añade un recorrido generado
|
||||
|
||||
// Añade un recorrido
|
||||
void addPath(Path path, bool centered = false);
|
||||
void addPath(std::vector<SDL_FPoint> spots, int waiting_counter = 0);
|
||||
void addPath(int start, int end, PathType type, int fixed_pos, int steps, const std::function<double(double)> &easingFunction, int waiting_counter = 0);
|
||||
// --- Estado y control ---
|
||||
void enable(); // Habilita el objeto
|
||||
bool hasFinished(); // Indica si ha terminado todos los recorridos
|
||||
|
||||
// Habilita el objeto
|
||||
void enable();
|
||||
// --- Getters ---
|
||||
int getCurrentPath() const { return current_path_; } // Devuelve el índice del recorrido actual
|
||||
|
||||
// Indica si ha terminado todos los recorridos
|
||||
bool hasFinished();
|
||||
private:
|
||||
// --- Variables internas ---
|
||||
bool enabled_ = false; // Indica si el objeto está habilitado
|
||||
bool has_finished_ = false; // Indica si el objeto ha finalizado el recorrido
|
||||
int current_path_ = 0; // Recorrido que se está recorriendo actualmente
|
||||
std::vector<Path> paths_; // Caminos a recorrer por el sprite
|
||||
|
||||
// Getters
|
||||
int getCurrentPath() const { return current_path_; }
|
||||
// --- Métodos internos ---
|
||||
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
|
||||
|
||||
#include <SDL3/SDL_rect.h> // Para SDL_FRect
|
||||
#include <SDL3/SDL_stdinc.h> // Para Uint32
|
||||
#include <memory> // Para unique_ptr, shared_ptr
|
||||
#include <string> // Para string
|
||||
#include <vector> // Para vector
|
||||
#include "animated_sprite.h" // Para AnimatedSprite
|
||||
#include "enter_name.h" // Para EnterName
|
||||
#include <SDL3/SDL_rect.h> // Para SDL_FRect
|
||||
#include <SDL3/SDL_stdinc.h> // Para Uint32
|
||||
#include <memory> // Para unique_ptr, shared_ptr
|
||||
#include <string> // Para string
|
||||
#include <vector> // Para vector
|
||||
#include "animated_sprite.h" // Para AnimatedSprite
|
||||
#include "enter_name.h" // Para EnterName
|
||||
#include "manage_hiscore_table.h" // Para HiScoreEntry
|
||||
#include "options.h" // Para Options, OptionsGame, options
|
||||
#include "utils.h" // Para Circle
|
||||
class Texture; // lines 13-13
|
||||
enum class InputAction : int; // lines 14-14
|
||||
enum class ScoreboardMode; // lines 15-15
|
||||
#include "options.h" // Para Options, OptionsGame, options
|
||||
#include "utils.h" // Para Circle
|
||||
|
||||
// Estados del jugador
|
||||
class Texture;
|
||||
enum class InputAction : int;
|
||||
enum class ScoreboardMode;
|
||||
|
||||
// --- Estados del jugador ---
|
||||
enum class PlayerState
|
||||
{
|
||||
WALKING_LEFT,
|
||||
WALKING_RIGHT,
|
||||
WALKING_STOP,
|
||||
WALKING_LEFT,
|
||||
WALKING_RIGHT,
|
||||
WALKING_STOP,
|
||||
|
||||
FIRING_UP,
|
||||
FIRING_LEFT,
|
||||
FIRING_RIGHT,
|
||||
FIRING_NONE,
|
||||
FIRING_UP,
|
||||
FIRING_LEFT,
|
||||
FIRING_RIGHT,
|
||||
FIRING_NONE,
|
||||
|
||||
COOLING_UP,
|
||||
COOLING_LEFT,
|
||||
COOLING_RIGHT,
|
||||
COOLING_UP,
|
||||
COOLING_LEFT,
|
||||
COOLING_RIGHT,
|
||||
|
||||
PLAYING, // Está jugando
|
||||
CONTINUE, // Está con la cuenta atras para continuar
|
||||
WAITING, // No está jugando pero puede entrar a jugar
|
||||
ENTERING_NAME, // Introduciendo nombre
|
||||
SHOWING_NAME, // Mostrando el nombre introducido
|
||||
DYING, // El cadaver está volando por ahi
|
||||
DIED, // El cadaver ha desaparecido por el fondo
|
||||
GAME_OVER, // No está jugando y no puede entrar a jugar
|
||||
CELEBRATING, // Poniendo pose de victoria
|
||||
ENTERING_NAME_GAME_COMPLETED, // Poniendo nombre en el tramo final del juego
|
||||
LEAVING_SCREEN, // Moviendose fuera de la pantalla
|
||||
ENTERING_SCREEN, // Entando a la pantalla
|
||||
CREDITS, // Estado para los creditos del juego
|
||||
PLAYING, // Está jugando
|
||||
CONTINUE, // Cuenta atrás para continuar
|
||||
WAITING, // No está jugando pero puede entrar a jugar
|
||||
ENTERING_NAME, // Introduciendo nombre
|
||||
SHOWING_NAME, // Mostrando el nombre introducido
|
||||
DYING, // El cadáver está volando por ahí
|
||||
DIED, // El cadáver ha desaparecido por el fondo
|
||||
GAME_OVER, // No está jugando y no puede entrar a jugar
|
||||
CELEBRATING, // Poniendo pose de victoria
|
||||
ENTERING_NAME_GAME_COMPLETED, // Poniendo nombre en el tramo final del juego
|
||||
LEAVING_SCREEN, // Moviéndose fuera de la pantalla
|
||||
ENTERING_SCREEN, // Entrando a la pantalla
|
||||
CREDITS, // Estado para los créditos del juego
|
||||
};
|
||||
|
||||
// Clase Player
|
||||
// --- Clase 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:
|
||||
// Constructor
|
||||
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);
|
||||
// --- 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() = default;
|
||||
|
||||
// Destructor
|
||||
~Player() = default;
|
||||
// --- Inicialización y ciclo de vida ---
|
||||
void init(); // Inicializa el jugador
|
||||
void update(); // Actualiza estado, animación y contadores
|
||||
void render(); // Dibuja el jugador en pantalla
|
||||
|
||||
// Iniciador
|
||||
void init();
|
||||
// --- Entrada y control ---
|
||||
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
|
||||
void update();
|
||||
// --- Movimiento y animación ---
|
||||
void move(); // Mueve el jugador
|
||||
void setAnimation(); // Establece la animación según el estado
|
||||
|
||||
// Pinta el jugador en pantalla
|
||||
void render();
|
||||
// --- Texturas y animaciones ---
|
||||
void setPlayerTextures(const std::vector<std::shared_ptr<Texture>> &texture); // Cambia las texturas del jugador
|
||||
|
||||
// Pone las texturas del jugador
|
||||
void setPlayerTextures(const std::vector<std::shared_ptr<Texture>> &texture);
|
||||
// --- Estados y contadores ---
|
||||
void updateCooldown(); // Actualiza el cooldown de disparo
|
||||
|
||||
// Actua en consecuencia de la entrada recibida
|
||||
void setInput(InputAction input);
|
||||
// --- Puntuación y marcador ---
|
||||
void addScore(int score); // Añade puntos
|
||||
void incScoreMultiplier(); // Incrementa el multiplicador
|
||||
void decScoreMultiplier(); // Decrementa el multiplicador
|
||||
|
||||
// Procesa inputs para cuando está jugando
|
||||
void setInputPlaying(InputAction input);
|
||||
// --- Estados de juego ---
|
||||
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
|
||||
void setInputEnteringName(InputAction input);
|
||||
// --- Getters y comprobaciones de estado ---
|
||||
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
|
||||
void move();
|
||||
// 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; }
|
||||
|
||||
// Establece la animación correspondiente al estado
|
||||
void setAnimation();
|
||||
// Getters
|
||||
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
|
||||
void updateCooldown();
|
||||
// Setters inline
|
||||
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
|
||||
void addScore(int score);
|
||||
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
|
||||
|
||||
// Establece el estado del jugador en el juego
|
||||
void setPlayingState(PlayerState state);
|
||||
// --- 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
|
||||
|
||||
// Aumenta el valor de la variable hasta un máximo
|
||||
void incScoreMultiplier();
|
||||
// --- Variables de estado ---
|
||||
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
|
||||
void decScoreMultiplier();
|
||||
|
||||
// Establece el valor del estado
|
||||
void setInvulnerable(bool value);
|
||||
|
||||
// Establece el valor de la variable a verdadero
|
||||
void setPowerUp();
|
||||
|
||||
// Actualiza el valor de la variable
|
||||
void updatePowerUp();
|
||||
|
||||
// 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_; }
|
||||
};
|
||||
// --- Métodos internos ---
|
||||
void shiftColliders(); // Actualiza el círculo de colisión a la posición del jugador
|
||||
void shiftSprite(); // Recoloca el sprite
|
||||
void updateInvulnerable(); // Monitoriza el estado de invulnerabilidad
|
||||
void updateContinueCounter(); // Actualiza el contador de continue
|
||||
void updateEnterNameCounter();// Actualiza el contador de entrar nombre
|
||||
void updateShowingName(); // Actualiza el estado SHOWING_NAME
|
||||
void decEnterNameCounter(); // Decrementa el contador de entrar nombre
|
||||
void updateScoreboard(); // Actualiza el panel del marcador
|
||||
void setScoreboardMode(ScoreboardMode mode); // Cambia el modo del marcador
|
||||
void playRandomBubbleSound(); // Hace sonar un sonido aleatorio
|
||||
bool isRenderable() const { return !isWaiting() && !isGameOver(); }
|
||||
};
|
||||
@@ -4,173 +4,126 @@
|
||||
#include <string> // Para string
|
||||
#include <vector> // Para vector
|
||||
#include "animated_sprite.h" // Para AnimationsFileBuffer
|
||||
#include "text.h" // Para TextFile
|
||||
#include "text.h" // Para TextFile, Text
|
||||
#include "texture.h" // Para Texture
|
||||
#include "utils.h" // Para DemoData
|
||||
|
||||
struct JA_Music_t;
|
||||
struct JA_Sound_t;
|
||||
|
||||
// Estructura para almacenar ficheros de sonido y su nombre
|
||||
// --- Estructuras para recursos individuales ---
|
||||
|
||||
// Sonido
|
||||
struct ResourceSound
|
||||
{
|
||||
std::string name; // Nombre del sonido
|
||||
JA_Sound_t *sound; // Objeto con el sonido
|
||||
|
||||
// Constructor
|
||||
ResourceSound(const std::string &name, JA_Sound_t *sound)
|
||||
: name(name), sound(sound) {}
|
||||
};
|
||||
|
||||
// Estructura para almacenar ficheros musicales y su nombre
|
||||
// Música
|
||||
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
|
||||
|
||||
// Constructor
|
||||
ResourceMusic(const std::string &name, JA_Music_t *music)
|
||||
: name(name), music(music) {}
|
||||
};
|
||||
|
||||
// Estructura para almacenar objetos Texture y su nombre
|
||||
// Textura
|
||||
struct ResourceTexture
|
||||
{
|
||||
std::string name; // Nombre de la textura
|
||||
std::shared_ptr<Texture> texture; // Objeto con la textura
|
||||
|
||||
// Constructor
|
||||
ResourceTexture(const std::string &name, std::shared_ptr<Texture> texture)
|
||||
: name(name), texture(texture) {}
|
||||
};
|
||||
|
||||
// Estructura para almacenar ficheros TextFile y su nombre
|
||||
// Fichero de texto (fuente)
|
||||
struct ResourceTextFile
|
||||
{
|
||||
std::string name; // Nombre del fichero
|
||||
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)
|
||||
: name(name), text_file(text_file) {}
|
||||
};
|
||||
|
||||
// Estructura para almacenar objetos Text y su nombre
|
||||
// Objeto de texto
|
||||
struct ResourceText
|
||||
{
|
||||
std::string name; // Nombre del objeto
|
||||
std::shared_ptr<Text> text; // Objeto
|
||||
|
||||
// Constructor
|
||||
ResourceText(const std::string &name, std::shared_ptr<Text> text)
|
||||
: name(name), text(text) {}
|
||||
};
|
||||
|
||||
// Estructura para almacenar ficheros animaciones y su nombre
|
||||
// Animación
|
||||
struct ResourceAnimation
|
||||
{
|
||||
std::string name; // Nombre del fichero
|
||||
AnimationsFileBuffer animation; // Objeto con las animaciones
|
||||
|
||||
// Constructor
|
||||
ResourceAnimation(const std::string &name, const AnimationsFileBuffer &animation)
|
||||
: name(name), animation(animation) {}
|
||||
};
|
||||
|
||||
// --- Clase Resource: gestiona todos los recursos del juego (singleton) ---
|
||||
class Resource
|
||||
{
|
||||
public:
|
||||
// --- Métodos de singleton ---
|
||||
static void init(); // Inicializa el objeto Resource
|
||||
static void destroy(); // Libera el objeto Resource
|
||||
static 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:
|
||||
// [SINGLETON] Objeto resource privado
|
||||
// --- Singleton ---
|
||||
static Resource *resource_;
|
||||
|
||||
// --- Vectores de recursos ---
|
||||
std::vector<ResourceSound> sounds_; // Vector con los sonidos
|
||||
std::vector<ResourceMusic> musics_; // Vector con las musicas
|
||||
std::vector<ResourceTexture> textures_; // Vector con las musicas
|
||||
std::vector<ResourceMusic> musics_; // Vector con las músicas
|
||||
std::vector<ResourceTexture> textures_; // Vector con las texturas
|
||||
std::vector<ResourceTextFile> text_files_; // Vector con los ficheros de texto
|
||||
std::vector<ResourceText> texts_; // Vector con los objetos de texto
|
||||
std::vector<ResourceAnimation> animations_; // Vector con las animaciones
|
||||
std::vector<DemoData> demos_; // Vector con los ficheros de datos para el modo demostración
|
||||
|
||||
// Carga los sonidos
|
||||
void loadSounds();
|
||||
// --- Métodos internos de carga y gestión ---
|
||||
void loadSounds(); // Carga los sonidos
|
||||
void loadMusics(); // Carga las músicas
|
||||
void loadTextures(); // Carga las texturas
|
||||
void loadTextFiles(); // Carga los ficheros de texto
|
||||
void loadAnimations(); // Carga las animaciones
|
||||
void loadDemoData(); // Carga los datos para el modo demostración
|
||||
void addPalettes(); // Añade paletas a las texturas
|
||||
void createTextures(); // Crea las texturas a partir de los datos cargados
|
||||
void createText(); // Crea los objetos de texto
|
||||
void clear(); // Vacía todos los vectores de recursos
|
||||
void load(); // Carga todos los recursos
|
||||
void clearSounds(); // Vacía el vector de sonidos
|
||||
void clearMusics(); // Vacía el vector de músicas
|
||||
|
||||
// Carga las musicas
|
||||
void loadMusics();
|
||||
|
||||
// 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();
|
||||
// --- Constructores y destructor privados (singleton) ---
|
||||
Resource(); // Constructor privado
|
||||
~Resource() = default; // Destructor privado
|
||||
};
|
||||
@@ -9,17 +9,18 @@
|
||||
#include <string> // Para string
|
||||
#include <vector> // Para vector
|
||||
#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_CENTER_PANEL = 1;
|
||||
constexpr int SCOREBOARD_RIGHT_PANEL = 2;
|
||||
constexpr int SCOREBOARD_MAX_PANELS = 3;
|
||||
|
||||
// Enums
|
||||
// --- Enums ---
|
||||
enum class ScoreboardMode : int
|
||||
{
|
||||
SCORE,
|
||||
@@ -34,32 +35,55 @@ enum class ScoreboardMode : int
|
||||
NUM_MODES,
|
||||
};
|
||||
|
||||
// Structs
|
||||
// --- Structs ---
|
||||
struct Panel
|
||||
{
|
||||
ScoreboardMode mode; // Modo en el que se encuentra el panel
|
||||
SDL_FRect pos; // Posición donde dibujar el panel dentro del marcador
|
||||
};
|
||||
|
||||
// Clase Scoreboard
|
||||
// --- Clase 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:
|
||||
// [SINGLETON] Objeto scoreboard privado
|
||||
// --- Singleton ---
|
||||
static Scoreboard *scoreboard_;
|
||||
|
||||
// Objetos y punteros
|
||||
SDL_Renderer *renderer_; // El renderizador de la ventana
|
||||
|
||||
// --- Objetos y punteros ---
|
||||
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::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
|
||||
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
|
||||
std::vector<SDL_Texture *> panel_texture_; // Texturas para dibujar cada panel
|
||||
|
||||
// Variables
|
||||
std::string name_[SCOREBOARD_MAX_PANELS] = {}; // Nom de cada jugador
|
||||
// --- Variables de estado ---
|
||||
std::string name_[SCOREBOARD_MAX_PANELS] = {}; // Nombre de cada jugador
|
||||
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
|
||||
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
|
||||
Color color_ = Color(); // Color del marcador
|
||||
SDL_FRect rect_ = {0, 0, 320, 40}; // Posición y dimensiones del marcador
|
||||
Uint64 ticks_ = SDL_GetTicks(); // Variable donde almacenar el valor de SDL_GetTiks()
|
||||
Uint64 ticks_ = SDL_GetTicks(); // Variable donde almacenar el valor de SDL_GetTicks()
|
||||
int time_counter_ = 0; // Contador de segundos
|
||||
int loop_counter_ = 0; // Contador de bucle
|
||||
std::vector<Color> name_colors_; // Colores para destacar el nombre una vez introducido
|
||||
|
||||
// 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 enter_name_pos_;
|
||||
|
||||
// Recalcula las anclas de los elementos
|
||||
void recalculateAnchors();
|
||||
// --- Métodos internos ---
|
||||
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
|
||||
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
|
||||
// --- Constructor y destructor privados (singleton) ---
|
||||
Scoreboard();
|
||||
|
||||
// Destructor
|
||||
~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
|
||||
|
||||
#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_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 <memory> // Para shared_ptr
|
||||
#include "options.h" // Para Options, VideoOptions, options
|
||||
@@ -16,98 +16,116 @@
|
||||
#include "resource.h"
|
||||
#endif
|
||||
|
||||
// Clase Screen: gestiona la ventana, el renderizador y los efectos visuales globales
|
||||
class Screen
|
||||
{
|
||||
public:
|
||||
// --- Métodos de singleton ---
|
||||
static void init(); // Inicializa el objeto Screen
|
||||
static void destroy(); // Libera el objeto Screen
|
||||
static 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:
|
||||
// Constantes
|
||||
// --- Constantes ---
|
||||
static constexpr int WINDOWS_DECORATIONS_ = 35;
|
||||
|
||||
// Estructura para gestionar los fotogramas por segundo
|
||||
// --- Estructuras internas ---
|
||||
struct FPS
|
||||
{
|
||||
Uint32 ticks; // Tiempo en milisegundos desde que se comenzó a contar.
|
||||
int frameCount; // Número acumulado de frames en el intervalo.
|
||||
int lastValue; // Número de frames calculado en el último segundo.
|
||||
|
||||
// Constructor para inicializar la estructura.
|
||||
FPS() : ticks(0), frameCount(0), lastValue(0) {}
|
||||
|
||||
// Incrementador que se llama en cada frame.
|
||||
void increment()
|
||||
{
|
||||
frameCount++;
|
||||
}
|
||||
|
||||
// Método para calcular y devolver el valor de FPS.
|
||||
void increment() { frameCount++; }
|
||||
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.
|
||||
frameCount = 0; // Reiniciamos el contador de frames.
|
||||
ticks = currentTicks; // Actualizamos el tiempo base.
|
||||
lastValue = frameCount;
|
||||
frameCount = 0;
|
||||
ticks = currentTicks;
|
||||
}
|
||||
return lastValue;
|
||||
}
|
||||
};
|
||||
|
||||
// Estructura para gestionar el efecto de flash en la pantalla
|
||||
struct FlashEffect
|
||||
{
|
||||
bool enabled; // Indica si el efecto está activo
|
||||
int lenght; // Duración del efecto
|
||||
int delay; // Frames iniciales en los que no se aplica
|
||||
int counter; // Contador para el efecto
|
||||
Color color; // Color del efecto
|
||||
bool enabled;
|
||||
int lenght;
|
||||
int delay;
|
||||
int counter;
|
||||
Color color;
|
||||
|
||||
// Constructor
|
||||
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) {}
|
||||
|
||||
// Actualiza
|
||||
void update() { (enabled && counter > 0) ? counter-- : enabled = false; }
|
||||
|
||||
// Indica si se pude dibujar
|
||||
bool isRendarable() { return enabled && counter < lenght - delay; }
|
||||
};
|
||||
|
||||
// Estructura para agitar la pantalla
|
||||
struct ShakeEffect
|
||||
{
|
||||
int desp; // Pixels de desplazamiento para agitar la pantalla en el eje x
|
||||
int delay; // Retraso entre cada desplazamiento de la pantalla al agitarse
|
||||
int counter; // Contador para el retraso
|
||||
int lenght; // Cantidad de desplazamientos a realizar
|
||||
int remaining; // Cantidad de desplazamientos pendientes a realizar
|
||||
int original_pos; // Posición inicial de la pantalla para dejarla igual tras el desplazamiento
|
||||
int original_width; // Anchura inicial de la pantalla para dejarla igual tras el desplazamiento
|
||||
bool enabled; // Indica si el efecto está activo
|
||||
int desp;
|
||||
int delay;
|
||||
int counter;
|
||||
int lenght;
|
||||
int remaining;
|
||||
int original_pos;
|
||||
int original_width;
|
||||
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)
|
||||
: 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)
|
||||
{
|
||||
if (!enabled)
|
||||
{
|
||||
// Configurar el estado inicial si el efecto no está activo
|
||||
enabled = true;
|
||||
original_pos = src_rect.x;
|
||||
original_width = src_rect.w;
|
||||
|
||||
// Acortar los anchos iniciales durante el efecto
|
||||
src_rect.w -= desp;
|
||||
dst_rect.w = src_rect.w;
|
||||
}
|
||||
|
||||
// Renovar contadores y duración del efecto
|
||||
remaining = lenght;
|
||||
counter = delay;
|
||||
}
|
||||
|
||||
// Método para actualizar el efecto de movimiento/agitación
|
||||
void update(SDL_FRect &src_rect, SDL_FRect &dst_rect)
|
||||
{
|
||||
if (enabled)
|
||||
@@ -119,19 +137,13 @@ private:
|
||||
else
|
||||
{
|
||||
counter = delay;
|
||||
|
||||
// Calcular desplazamientos según el estado de la agitación
|
||||
const auto SRC_DESP = (remaining % 2 == 0) ? 0 : desp;
|
||||
const auto DST_DESP = (remaining % 2 == 1) ? 0 : desp;
|
||||
|
||||
src_rect.x = original_pos + SRC_DESP;
|
||||
dst_rect.x = original_pos + DST_DESP;
|
||||
|
||||
remaining--;
|
||||
|
||||
if (remaining == -1)
|
||||
{
|
||||
// Restaurar posición y dimensiones originales
|
||||
enabled = false;
|
||||
src_rect.x = original_pos;
|
||||
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
|
||||
// Estructura pra mostrar la información de debug
|
||||
struct Debug
|
||||
{
|
||||
std::shared_ptr<Text> text = nullptr; // Objeto de texto para escribir
|
||||
bool show = false; // Indica si se ha de mostrar la informacion por pantalla
|
||||
|
||||
std::shared_ptr<Text> text = nullptr;
|
||||
bool show = false;
|
||||
void init()
|
||||
{
|
||||
if (Resource::get())
|
||||
@@ -169,133 +176,42 @@ private:
|
||||
}
|
||||
};
|
||||
#endif
|
||||
// [SINGLETON] Objeto privado
|
||||
|
||||
// --- Singleton ---
|
||||
static Screen *screen_;
|
||||
|
||||
// Objetos y punteros
|
||||
// --- Objetos y punteros ---
|
||||
SDL_Window *window_; // Ventana de la aplicación
|
||||
SDL_Renderer *renderer_; // El renderizador de la ventana
|
||||
SDL_Texture *game_canvas_; // Textura donde se dibuja todo antes de volcarse al renderizador
|
||||
|
||||
// Variables
|
||||
SDL_FRect src_rect_; // Coordenadas de donde va a pillar la textura del juego para dibujarla
|
||||
SDL_FRect dst_rect_; // Coordenadas donde se va a dibujar la textura del juego sobre la pantalla o ventana
|
||||
FPS fps_; // Variable para gestionar los frames por segundo
|
||||
// --- Variables de estado ---
|
||||
SDL_FRect src_rect_; // Coordenadas de origen para dibujar la textura del juego
|
||||
SDL_FRect dst_rect_; // Coordenadas destino para dibujar la textura del juego
|
||||
FPS fps_; // Gestión de frames por segundo
|
||||
std::string shader_source_; // Almacena el contenido del archivo GLSL
|
||||
FlashEffect flash_effect_; // Variable para gestionar el efecto de flash
|
||||
ShakeEffect shake_effect_; // Variable para gestionar el efecto de agitar la pantalla
|
||||
FlashEffect flash_effect_; // Efecto de flash en pantalla
|
||||
ShakeEffect shake_effect_; // Efecto de agitar la pantalla
|
||||
bool attenuate_effect_ = false; // Indica si la pantalla ha de estar atenuada
|
||||
#ifdef DEBUG
|
||||
Debug debug_info_; // Variable para gestionar la informaciçón de debug
|
||||
Debug debug_info_; // Información de debug
|
||||
#endif
|
||||
// Arranca SDL VIDEO y crea la ventana
|
||||
bool initSDL();
|
||||
|
||||
// Dibuja el efecto de flash en la pantalla
|
||||
void renderFlash();
|
||||
|
||||
// Aplica el efecto de agitar la pantalla
|
||||
void renderShake();
|
||||
|
||||
// Muestra información por pantalla
|
||||
void renderInfo();
|
||||
|
||||
// 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
|
||||
// --- Métodos internos ---
|
||||
bool initSDL(); // Arranca SDL VIDEO y crea la ventana
|
||||
void renderFlash(); // Dibuja el efecto de flash en la pantalla
|
||||
void renderShake(); // Aplica el efecto de agitar la pantalla
|
||||
void renderInfo(); // Muestra información por pantalla
|
||||
void renderScreen(); // Selecciona y ejecuta el método de renderizado adecuado
|
||||
void loadShaders(); // Carga el contenido del archivo GLSL
|
||||
void initShaders(); // Inicializa los shaders
|
||||
void adjustWindowSize(); // Calcula el tamaño de la ventana
|
||||
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
|
||||
void getDisplayInfo();
|
||||
|
||||
// Renderiza todos los overlays y efectos
|
||||
void renderOverlays();
|
||||
|
||||
// Atenua la pantalla
|
||||
void renderAttenuate();
|
||||
|
||||
// Constructor
|
||||
// --- Constructores y destructor ---
|
||||
Screen();
|
||||
|
||||
// Destructor
|
||||
~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
|
||||
|
||||
/*
|
||||
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
|
||||
{
|
||||
// Secciones del programa
|
||||
// --- Enumeraciones de secciones del programa ---
|
||||
enum class Name
|
||||
{
|
||||
INIT,
|
||||
LOGO,
|
||||
INTRO,
|
||||
TITLE,
|
||||
GAME,
|
||||
HI_SCORE_TABLE,
|
||||
GAME_DEMO,
|
||||
INSTRUCTIONS,
|
||||
CREDITS,
|
||||
QUIT,
|
||||
INIT, // Inicialización
|
||||
LOGO, // Pantalla de logo
|
||||
INTRO, // Introducción
|
||||
TITLE, // Pantalla de título/menú principal
|
||||
GAME, // Juego principal
|
||||
HI_SCORE_TABLE, // Tabla de récords
|
||||
GAME_DEMO, // Modo demo
|
||||
INSTRUCTIONS, // Instrucciones
|
||||
CREDITS, // Créditos
|
||||
QUIT, // Salir del juego
|
||||
};
|
||||
|
||||
// Opciones para la sección
|
||||
// --- Opciones para la sección actual ---
|
||||
enum class Options
|
||||
{
|
||||
GAME_PLAY_1P,
|
||||
GAME_PLAY_2P,
|
||||
TITLE_TIME_OUT,
|
||||
TITLE_1,
|
||||
TITLE_2,
|
||||
QUIT_WITH_KEYBOARD,
|
||||
QUIT_WITH_CONTROLLER,
|
||||
QUIT_FROM_EVENT,
|
||||
RELOAD,
|
||||
HI_SCORE_AFTER_PLAYING,
|
||||
NONE,
|
||||
GAME_PLAY_1P, // Jugar 1 jugador
|
||||
GAME_PLAY_2P, // Jugar 2 jugadores
|
||||
TITLE_TIME_OUT, // Timeout en el título
|
||||
TITLE_1, // Opción 1 en el título
|
||||
TITLE_2, // Opción 2 en el título
|
||||
QUIT_WITH_KEYBOARD, // Salir con teclado
|
||||
QUIT_WITH_CONTROLLER, // Salir con mando
|
||||
QUIT_FROM_EVENT, // Salir por evento
|
||||
RELOAD, // Recargar sección
|
||||
HI_SCORE_AFTER_PLAYING, // Mostrar récord tras jugar
|
||||
NONE, // Sin opción
|
||||
};
|
||||
|
||||
// Variables para el Attract Mode
|
||||
// --- Modos para el Attract Mode ---
|
||||
enum class AttractMode
|
||||
{
|
||||
TITLE_TO_DEMO,
|
||||
TITLE_TO_LOGO,
|
||||
TITLE_TO_DEMO, // Pasar de título a demo
|
||||
TITLE_TO_LOGO, // Pasar de título a logo
|
||||
};
|
||||
|
||||
extern Name name;
|
||||
extern Options options;
|
||||
extern AttractMode attract_mode;
|
||||
// --- Variables globales de estado ---
|
||||
extern Name name; // Sección actual
|
||||
extern Options options; // Opción seleccionada en la sección
|
||||
extern AttractMode attract_mode; // Estado del Attract Mode
|
||||
}
|
||||
@@ -1,50 +1,45 @@
|
||||
#pragma once
|
||||
|
||||
#include <memory> // Para shared_ptr
|
||||
#include "animated_sprite.h" // Para SpriteAnimated
|
||||
#include "animated_sprite.h" // Para AnimatedSprite
|
||||
|
||||
class Texture;
|
||||
|
||||
// Clase SpriteSmart
|
||||
// Clase SmartSprite: Sprite animado que se mueve hacia un destino y puede deshabilitarse automáticamente
|
||||
class SmartSprite : public AnimatedSprite
|
||||
{
|
||||
public:
|
||||
// --- Constructor y destructor ---
|
||||
explicit SmartSprite(std::shared_ptr<Texture> texture)
|
||||
: AnimatedSprite(texture) {}
|
||||
~SmartSprite() override = default;
|
||||
|
||||
// --- 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:
|
||||
// Variables
|
||||
// --- Variables internas ---
|
||||
bool on_destination_ = false; // Indica si está en el destino
|
||||
int dest_x_ = 0; // Posicion de destino en el eje X
|
||||
int dest_y_ = 0; // Posicion de destino en el eje Y
|
||||
int dest_x_ = 0; // Posición de destino en el eje X
|
||||
int dest_y_ = 0; // Posición de destino en el eje Y
|
||||
int finished_counter_ = 0; // Contador para deshabilitarlo
|
||||
bool finished_ = false; // Indica si ya ha terminado
|
||||
bool enabled_ = false; // Indica si el objeto está habilitado
|
||||
|
||||
// Comprueba si ha terminado
|
||||
void checkFinished();
|
||||
|
||||
// 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; }
|
||||
// --- Métodos internos ---
|
||||
void checkFinished(); // Comprueba si ha terminado
|
||||
void checkMove(); // Comprueba el movimiento
|
||||
};
|
||||
@@ -2,71 +2,60 @@
|
||||
|
||||
#include <SDL3/SDL_rect.h> // Para SDL_FRect, SDL_FPoint
|
||||
#include <memory> // Para shared_ptr
|
||||
|
||||
class Texture;
|
||||
|
||||
// Clase sprite
|
||||
// Clase Sprite: representa un objeto gráfico básico con posición, tamaño y textura
|
||||
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:
|
||||
// Constructor
|
||||
Sprite(std::shared_ptr<Texture>, float x, float y, float w, float h);
|
||||
Sprite(std::shared_ptr<Texture>, SDL_FRect rect);
|
||||
explicit Sprite(std::shared_ptr<Texture>);
|
||||
|
||||
// Destructor
|
||||
// --- Constructores y destructor ---
|
||||
Sprite(std::shared_ptr<Texture> texture, float x, float y, float w, float h);
|
||||
Sprite(std::shared_ptr<Texture> texture, SDL_FRect rect);
|
||||
explicit Sprite(std::shared_ptr<Texture> texture);
|
||||
virtual ~Sprite() = default;
|
||||
|
||||
// Muestra el sprite por pantalla
|
||||
virtual void render();
|
||||
// --- Renderizado y control ---
|
||||
virtual void render(); // Muestra el sprite por pantalla
|
||||
virtual void clear(); // Reinicia las variables a cero
|
||||
|
||||
// Reinicia las variables a cero
|
||||
virtual void clear();
|
||||
|
||||
// Obtiene la posición y el tamaño
|
||||
// --- Getters de posición y tamaño ---
|
||||
float getX() const { return pos_.x; }
|
||||
float getY() const { return pos_.y; }
|
||||
float getWidth() const { return pos_.w; }
|
||||
float getHeight() const { return pos_.h; }
|
||||
|
||||
// Devuelve el rectangulo donde está el sprite
|
||||
SDL_FRect getPosition() const { 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 setY(float y) { pos_.y = y; }
|
||||
void setWidth(float w) { pos_.w = w; }
|
||||
void setHeight(float h) { pos_.h = h; }
|
||||
|
||||
// Establece la posición del objeto
|
||||
void setPosition(float x, float y);
|
||||
void setPosition(SDL_FPoint p);
|
||||
void setPosition(SDL_FRect r) { pos_ = r; }
|
||||
|
||||
// Establece el nivel de 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 incY(float value) { pos_.y += value; }
|
||||
|
||||
// Obtiene el rectangulo que se dibuja de la textura
|
||||
// --- 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(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_; }
|
||||
|
||||
// Establece la textura a utilizar
|
||||
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>
|
||||
|
||||
/*
|
||||
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
|
||||
{
|
||||
// --- Estructura con los datos de una fase ---
|
||||
struct Stage
|
||||
{
|
||||
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) {}
|
||||
};
|
||||
|
||||
extern std::vector<Stage> stages; // Variable con los datos de cada pantalla
|
||||
extern int power; // Poder acumulado en la fase
|
||||
// --- Variables globales del estado de las fases ---
|
||||
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 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
|
||||
|
||||
// Devuelve una fase
|
||||
Stage get(int index);
|
||||
|
||||
// Inicializa las variables del namespace Stage
|
||||
void init();
|
||||
|
||||
// Añade poder
|
||||
void addPower(int amount);
|
||||
// --- Funciones principales ---
|
||||
Stage get(int index); // Devuelve una fase por índice
|
||||
void init(); // Inicializa las variables del namespace Stage
|
||||
void addPower(int amount); // Añade poder a la fase actual
|
||||
}
|
||||
102
source/tabe.h
102
source/tabe.h
@@ -7,6 +7,7 @@
|
||||
#include <memory> // Para unique_ptr
|
||||
#include "animated_sprite.h" // Para AnimatedSprite
|
||||
|
||||
// --- Enumeraciones para dirección y estado ---
|
||||
enum class TabeDirection : int
|
||||
{
|
||||
TO_THE_LEFT = 0,
|
||||
@@ -19,6 +20,7 @@ enum class TabeState : int
|
||||
HIT = 1,
|
||||
};
|
||||
|
||||
// --- Estructura para el temporizador del Tabe ---
|
||||
struct TabeTimer
|
||||
{
|
||||
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
|
||||
{
|
||||
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:
|
||||
// Constantes
|
||||
// --- Constantes ---
|
||||
static constexpr int WIDTH_ = 32;
|
||||
static constexpr int HEIGHT_ = 32;
|
||||
|
||||
// Punteros
|
||||
std::unique_ptr<AnimatedSprite> sprite_; // Sprite con los graficos y animaciones
|
||||
// --- Objetos y punteros ---
|
||||
std::unique_ptr<AnimatedSprite> sprite_; // Sprite con los gráficos y animaciones
|
||||
|
||||
// Variables
|
||||
float x_ = 0; // Posición del objeto
|
||||
float y_ = 0; // Posición del objeto
|
||||
float speed_ = 0.0f; // Velocidad de movimiento del objeto
|
||||
float accel_ = 0.0f; // Aceleración del objeto
|
||||
// --- Variables de estado ---
|
||||
float x_ = 0; // Posición X
|
||||
float y_ = 0; // Posición Y
|
||||
float speed_ = 0.0f; // Velocidad de movimiento
|
||||
float accel_ = 0.0f; // Aceleración
|
||||
int fly_distance_ = 0; // Distancia de vuelo
|
||||
int waiting_counter_ = 0; // Tiempo que pasa quieto el objeto
|
||||
int waiting_counter_ = 0; // Tiempo que pasa quieto
|
||||
bool enabled_ = false; // Indica si el objeto está activo
|
||||
TabeDirection direction_ = TabeDirection::TO_THE_LEFT; // Dirección del objeto
|
||||
TabeDirection destiny_ = TabeDirection::TO_THE_LEFT; // Destino del objeto
|
||||
TabeState state_ = TabeState::FLY; // Estado
|
||||
TabeDirection direction_ = TabeDirection::TO_THE_LEFT; // Dirección actual
|
||||
TabeDirection destiny_ = TabeDirection::TO_THE_LEFT; // Destino
|
||||
TabeState state_ = TabeState::FLY; // Estado actual
|
||||
int hit_counter_ = 0; // Contador para el estado HIT
|
||||
int number_of_hits_ = 0; // Cantidad de disparos que ha recibido
|
||||
bool has_bonus_ = true; // Indica si el Tabe aun tiene el bonus para soltar
|
||||
TabeTimer timer_; // Temporizador para gestionar la aparición del Tabe
|
||||
int number_of_hits_ = 0; // Cantidad de disparos recibidos
|
||||
bool has_bonus_ = true; // Indica si aún tiene el bonus para soltar
|
||||
TabeTimer timer_; // Temporizador para gestionar la aparición
|
||||
|
||||
// Mueve el objeto
|
||||
void move();
|
||||
|
||||
// Actualiza la posición del sprite
|
||||
void shiftSprite() { sprite_->setPos(x_, y_); }
|
||||
|
||||
// Establece un vuelo aleatorio
|
||||
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_; }
|
||||
// --- Métodos internos ---
|
||||
void move(); // Mueve el objeto
|
||||
void shiftSprite() { sprite_->setPos(x_, y_); } // Actualiza la posición del sprite
|
||||
void setRandomFlyPath(TabeDirection direction, int lenght); // Establece un vuelo aleatorio
|
||||
void updateState(); // Actualiza el estado
|
||||
void updateTimer(); // Actualiza el temporizador
|
||||
void disable(); // Deshabilita el objeto
|
||||
};
|
||||
@@ -5,13 +5,16 @@
|
||||
#include <string> // Para string
|
||||
#include "sprite.h" // Para Sprite
|
||||
#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_SHADOW = 2;
|
||||
constexpr int TEXT_CENTER = 4;
|
||||
constexpr int TEXT_STROKE = 8;
|
||||
|
||||
// --- Estructuras auxiliares ---
|
||||
struct TextOffset
|
||||
{
|
||||
int x, y, w;
|
||||
@@ -24,61 +27,47 @@ struct TextFile
|
||||
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);
|
||||
|
||||
// Clase texto. Pinta texto en pantalla a partir de un bitmap
|
||||
// --- Clase Text: pinta texto en pantalla a partir de un bitmap ---
|
||||
class Text
|
||||
{
|
||||
private:
|
||||
// Objetos y punteros
|
||||
std::unique_ptr<Sprite> sprite_ = nullptr; // Objeto con los graficos para el texto
|
||||
public:
|
||||
// --- Constructores y destructor ---
|
||||
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_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
|
||||
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_pixels.h> // Para SDL_PixelFormat
|
||||
#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_surface.h> // Para SDL_FlipMode
|
||||
#include <memory> // Para shared_ptr
|
||||
#include <string> // Para string
|
||||
#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
|
||||
{
|
||||
std::shared_ptr<Uint8[]> data;
|
||||
@@ -22,86 +23,57 @@ struct Surface
|
||||
: data(pixels), w(width), h(height) {}
|
||||
};
|
||||
|
||||
// Clase Texture: gestiona texturas, paletas y renderizado
|
||||
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:
|
||||
// Objetos y punteros
|
||||
// --- Objetos y punteros ---
|
||||
SDL_Renderer *renderer_; // Renderizador donde dibujar la textura
|
||||
SDL_Texture *texture_ = nullptr; // La textura
|
||||
std::shared_ptr<Surface> surface_ = nullptr; // Surface para usar 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
|
||||
int width_ = 0; // Ancho de la imagen
|
||||
int height_ = 0; // Alto de la imagen
|
||||
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
|
||||
std::shared_ptr<Surface> loadSurface(const std::string &file_name);
|
||||
|
||||
// Vuelca la surface en la textura
|
||||
void flipSurface();
|
||||
|
||||
// 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();
|
||||
// --- Métodos internos ---
|
||||
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
|
||||
std::vector<Uint32> loadPaletteFromFile(const std::string &file_name); // Carga una paleta desde un fichero
|
||||
void unloadTexture(); // Libera la memoria de la textura
|
||||
void unloadSurface(); // Libera la surface actual
|
||||
};
|
||||
@@ -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.
|
||||
El rectangulo "window" recorre la textura de diferentes formas para generar el efecto de movimiento de la
|
||||
textura en pantalla
|
||||
El rectángulo "window" recorre la textura de diferentes formas para generar el efecto de movimiento de la
|
||||
textura en pantalla.
|
||||
*/
|
||||
|
||||
// Clase 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:
|
||||
// Constantes
|
||||
// --- Constantes ---
|
||||
static constexpr int TILE_WIDTH_ = 64; // Ancho 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_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 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
|
||||
double sin_[360]; // Vector con los valores del seno precalculados
|
||||
float desp_ = 0.0f; // Desplazamiento aplicado
|
||||
float speed_ = 1.0f; // Incremento que se añade al desplazamiento a cada bucle
|
||||
bool stopping_ = false; // Indica si se está deteniendo
|
||||
|
||||
// Rellena la textura con el contenido
|
||||
void fillTexture();
|
||||
|
||||
// Actualiza el desplazamiento
|
||||
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; }
|
||||
// --- Métodos internos ---
|
||||
void fillTexture(); // Rellena la textura con el contenido
|
||||
void updateDesp() { desp_ += speed_; } // Actualiza el desplazamiento
|
||||
void updateStop(); // Detiene el desplazamiento de forma ordenada
|
||||
};
|
||||
129
source/title.h
129
source/title.h
@@ -3,12 +3,13 @@
|
||||
#include <SDL3/SDL_stdinc.h> // Para Uint32
|
||||
#include <memory> // Para unique_ptr, shared_ptr
|
||||
#include "section.h" // Para Options
|
||||
class DefineButtons; // lines 5-5
|
||||
class Fade; // lines 6-6
|
||||
class GameLogo; // lines 7-7
|
||||
class Sprite; // lines 8-8
|
||||
class Text; // lines 9-9
|
||||
class TiledBG; // lines 11-11
|
||||
|
||||
class DefineButtons;
|
||||
class Fade;
|
||||
class GameLogo;
|
||||
class Sprite;
|
||||
class Text;
|
||||
class TiledBG;
|
||||
|
||||
// Textos
|
||||
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;
|
||||
|
||||
/*
|
||||
Esta clase gestiona un estado del programa. Se encarga de la parte del titulo o menu
|
||||
que sirve para empezar a jugar. Utiliza otras clases para:
|
||||
- Mostrar el logo del juego
|
||||
- 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 que gestiona el estado de título/menú principal del juego.
|
||||
Responsable de mostrar el logo, el fondo animado y gestionar la entrada para comenzar la partida.
|
||||
No permite saltar la animación del título salvo que se cambie el define.
|
||||
*/
|
||||
|
||||
// Clase 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:
|
||||
// Constructor
|
||||
// --- Constructores y destructor ---
|
||||
Title();
|
||||
|
||||
// Destructor
|
||||
~Title();
|
||||
|
||||
// Bucle para el titulo del juego
|
||||
void run();
|
||||
// --- Método principal ---
|
||||
void run(); // Bucle para el título del juego
|
||||
|
||||
private:
|
||||
// --- Enumeraciones ---
|
||||
enum class TitleState
|
||||
{
|
||||
LOGO_ANIMATING, // El logo está animándose
|
||||
LOGO_FINISHED, // El logo ha terminado de animarse
|
||||
START_HAS_BEEN_PRESSED, // Se ha pulsado el botón de start
|
||||
};
|
||||
|
||||
// --- 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 <vector> // Para vector
|
||||
|
||||
// Constantes
|
||||
// --- Constantes ---
|
||||
constexpr int BLOCK = 8;
|
||||
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
|
||||
{
|
||||
std::string param_file; // Fichero de parametros a utilizar
|
||||
bool clear_hi_score_table; // Reinicia la tabla de records
|
||||
bool set_v_sync; // Establece el vsync
|
||||
|
||||
// Constructor por defecto
|
||||
Overrides()
|
||||
: param_file(""), clear_hi_score_table(false), set_v_sync(false) {}
|
||||
};
|
||||
|
||||
extern Overrides overrides;
|
||||
|
||||
// Estructura para definir un circulo
|
||||
struct Circle
|
||||
{
|
||||
int x, y, r;
|
||||
|
||||
// Constructor por defecto
|
||||
Circle() : x(0), y(0), r(0) {}
|
||||
|
||||
// Constructor
|
||||
Circle(int xCoord, int yCoord, int radius)
|
||||
: x(xCoord), y(yCoord), r(radius) {}
|
||||
};
|
||||
@@ -46,13 +40,7 @@ struct Color
|
||||
constexpr Color() : r(0), g(0), b(0) {}
|
||||
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);
|
||||
}
|
||||
|
||||
// Método para aclarar el color
|
||||
constexpr Color getInverse() const { return Color(255 - r, 255 - g, 255 - b); }
|
||||
Color lighten(int amount = 50) const
|
||||
{
|
||||
return Color(
|
||||
@@ -60,8 +48,6 @@ struct Color
|
||||
std::min(255, g + amount),
|
||||
std::min(255, b + amount));
|
||||
}
|
||||
|
||||
// Método para oscurecer el color
|
||||
Color darken(int amount = 50) const
|
||||
{
|
||||
return Color(
|
||||
@@ -81,6 +67,7 @@ enum class NotifyPosition
|
||||
RIGHT,
|
||||
};
|
||||
|
||||
// Estructura para datos de la demo
|
||||
struct DemoKeys
|
||||
{
|
||||
Uint8 left;
|
||||
@@ -90,7 +77,6 @@ struct DemoKeys
|
||||
Uint8 fire_left;
|
||||
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)
|
||||
: 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
|
||||
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() {}
|
||||
|
||||
// Constructor con parámetros
|
||||
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) {}
|
||||
};
|
||||
@@ -122,83 +105,10 @@ struct Zone
|
||||
float third_quarter_x; // Anclaje al 75% del eje X
|
||||
float center_y; // Anclaje al 50% 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
|
||||
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);
|
||||
// --- Funciones utilitarias ---
|
||||
|
||||
// Colores
|
||||
extern const Color BG_COLOR;
|
||||
@@ -215,4 +125,56 @@ extern const Color ORANGE_SOFT_COLOR;
|
||||
extern const Color GREEN_COLOR;
|
||||
extern const Color BLUE_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
|
||||
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:
|
||||
// Constructor
|
||||
explicit Writer(std::shared_ptr<Text> text)
|
||||
@@ -39,33 +21,37 @@ public:
|
||||
// Dibuja el objeto en pantalla
|
||||
void render() const;
|
||||
|
||||
// Establece el valor de la variable
|
||||
void setPosX(int value);
|
||||
|
||||
// Establece el valor de la variable
|
||||
void setPosY(int value);
|
||||
|
||||
// Establece el valor de la variable
|
||||
void setKerning(int value);
|
||||
|
||||
// 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);
|
||||
// Setters
|
||||
void setPosX(int value); // Establece la posición X
|
||||
void setPosY(int value); // Establece la posición Y
|
||||
void setKerning(int value); // Establece el kerning (espaciado entre caracteres)
|
||||
void setCaption(const std::string &text); // Establece el texto a escribir
|
||||
void setSpeed(int value); // Establece la velocidad de escritura
|
||||
void setEnabled(bool value); // Habilita o deshabilita el objeto
|
||||
void setFinishedCounter(int time); // Establece el temporizador para deshabilitar el objeto
|
||||
|
||||
// Centra la cadena de texto a un punto X
|
||||
void center(int x);
|
||||
|
||||
// Obtiene el valor de la variable
|
||||
bool hasFinished() const;
|
||||
// Getters
|
||||
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