treball en curs: correccions de tidy

This commit is contained in:
2026-05-16 14:04:59 +02:00
parent 48af959814
commit be18f51735
31 changed files with 1741 additions and 1966 deletions
+2
View File
@@ -1,5 +1,6 @@
.vscode .vscode
build/ build/
compile_commands.json
dist/ dist/
*.DS_Store *.DS_Store
thumbs.db thumbs.db
@@ -15,3 +16,4 @@ coffee_crisis_debug
release/windows/coffee.res release/windows/coffee.res
resources.pack resources.pack
tools/pack_resources/pack_resources tools/pack_resources/pack_resources
.cache/
+6 -6
View File
@@ -69,12 +69,12 @@ class Input {
// Variables // Variables
std::vector<KeyBindings> keyBindings; // Vector con las teclas asociadas a los inputs predefinidos std::vector<KeyBindings> keyBindings; // Vector con las teclas asociadas a los inputs predefinidos
std::vector<GameControllerBindings> gameControllerBindings; // Vector con las teclas asociadas a los inputs predefinidos std::vector<GameControllerBindings> gameControllerBindings; // Vector con las teclas asociadas a los inputs predefinidos
std::vector<std::string> controllerNames; // Vector con los nombres de los mandos std::vector<std::string> controllerNames; // Vector con los nombres de los mandos
int numGamepads{0}; // Numero de mandos conectados int numGamepads{0}; // Numero de mandos conectados
std::string dbPath; // Ruta al archivo gamecontrollerdb.txt std::string dbPath; // Ruta al archivo gamecontrollerdb.txt
bool verbose{true}; // Indica si ha de mostrar mensajes bool verbose{true}; // Indica si ha de mostrar mensajes
InputDisable disabledUntil{d_notDisabled}; // Tiempo que esta deshabilitado InputDisable disabledUntil{d_notDisabled}; // Tiempo que esta deshabilitado
bool enabled{true}; // Indica si está habilitado bool enabled{true}; // Indica si está habilitado
// Construye el nombre visible de un mando (name truncado + sufijo #N) // Construye el nombre visible de un mando (name truncado + sufijo #N)
static auto buildControllerName(SDL_Gamepad *pad, int padIndex) -> std::string; static auto buildControllerName(SDL_Gamepad *pad, int padIndex) -> std::string;
+2 -2
View File
@@ -21,7 +21,7 @@ struct Animation {
struct AnimatedSpriteData { struct AnimatedSpriteData {
std::vector<Animation> animations; // Vector con las diferentes animaciones std::vector<Animation> animations; // Vector con las diferentes animaciones
Texture *texture; // Textura con los graficos para el sprite Texture *texture; // Textura con los graficos para el sprite
}; };
// Carga la animación desde un fichero // Carga la animación desde un fichero
@@ -34,7 +34,7 @@ class AnimatedSprite : public MovingSprite {
private: private:
// Variables // Variables
std::vector<Animation> animation; // Vector con las diferentes animaciones std::vector<Animation> animation; // Vector con las diferentes animaciones
int currentAnimation; // Animacion activa int currentAnimation; // Animacion activa
public: public:
// Constructor // Constructor
+25 -25
View File
@@ -39,36 +39,36 @@ class Screen {
// Render loop // Render loop
void clean(Color color = {0x00, 0x00, 0x00}); // Limpia la pantalla void clean(Color color = {0x00, 0x00, 0x00}); // Limpia la pantalla
void start(); // Prepara para empezar a dibujar en la textura de juego void start(); // Prepara para empezar a dibujar en la textura de juego
void blit(); // Vuelca el contenido del renderizador en pantalla void blit(); // Vuelca el contenido del renderizador en pantalla
// Video y ventana // Video y ventana
void setVideoMode(bool fullscreen); // Establece el modo de video void setVideoMode(bool fullscreen); // Establece el modo de video
void toggleVideoMode(); // Cambia entre pantalla completa y ventana void toggleVideoMode(); // Cambia entre pantalla completa y ventana
void handleCanvasResized(); // En Emscripten, reaplica setVideoMode tras un cambio del navegador (salida de fullscreen con Esc, rotación). No-op fuera de Emscripten void handleCanvasResized(); // En Emscripten, reaplica setVideoMode tras un cambio del navegador (salida de fullscreen con Esc, rotación). No-op fuera de Emscripten
static void syncFullscreenFlagFromBrowser(bool isFullscreen); // Sincroniza el flag interno de fullscreen con el estado real del navegador. Debe llamarse antes de diferir handleCanvasResized. No-op fuera de Emscripten static void syncFullscreenFlagFromBrowser(bool isFullscreen); // Sincroniza el flag interno de fullscreen con el estado real del navegador. Debe llamarse antes de diferir handleCanvasResized. No-op fuera de Emscripten
void toggleIntegerScale(); // Alterna el escalado entero void toggleIntegerScale(); // Alterna el escalado entero
void setIntegerScale(bool enabled); // Establece el escalado entero void setIntegerScale(bool enabled); // Establece el escalado entero
void toggleVSync(); // Alterna el V-Sync void toggleVSync(); // Alterna el V-Sync
void setVSync(bool enabled); // Establece el V-Sync void setVSync(bool enabled); // Establece el V-Sync
auto decWindowZoom() -> bool; // Reduce el zoom de la ventana (devuelve true si cambió) auto decWindowZoom() -> bool; // Reduce el zoom de la ventana (devuelve true si cambió)
auto incWindowZoom() -> bool; // Aumenta el zoom de la ventana (devuelve true si cambió) auto incWindowZoom() -> bool; // Aumenta el zoom de la ventana (devuelve true si cambió)
auto setWindowZoom(int zoom) -> bool; // Establece el zoom de la ventana (devuelve true si cambió) auto setWindowZoom(int zoom) -> bool; // Establece el zoom de la ventana (devuelve true si cambió)
// Borde // Borde
void setBorderColor(Color color); // Cambia el color del borde void setBorderColor(Color color); // Cambia el color del borde
// Notificaciones // Notificaciones
void initNotifications(); // Enllaça el Text de notificacions amb `Resource`. A cridar després de `Resource::init(...)`. void initNotifications(); // Enllaça el Text de notificacions amb `Resource`. A cridar després de `Resource::init(...)`.
void notify(const std::string &text, Color textColor, Color outlineColor, Uint32 durationMs); // Muestra una notificación en la línea superior del canvas durante durationMs. Sobrescribe cualquier notificación activa (sin apilación). void notify(const std::string &text, Color textColor, Color outlineColor, Uint32 durationMs); // Muestra una notificación en la línea superior del canvas durante durationMs. Sobrescribe cualquier notificación activa (sin apilación).
void clearNotification(); // Limpia la notificación actual void clearNotification(); // Limpia la notificación actual
// GPU / shaders (post-procesado). En builds con NO_SHADERS (Emscripten) son no-op. // GPU / shaders (post-procesado). En builds con NO_SHADERS (Emscripten) son no-op.
void initShaders(); // Crea el backend GPU si no existe y lo inicializa void initShaders(); // Crea el backend GPU si no existe y lo inicializa
void shutdownShaders(); // Libera el backend GPU void shutdownShaders(); // Libera el backend GPU
[[nodiscard]] auto isGpuAccelerated() const -> bool; // true si el backend existe y reporta hardware OK [[nodiscard]] auto isGpuAccelerated() const -> bool; // true si el backend existe y reporta hardware OK
void setShaderEnabled(bool enabled); // Activa o desactiva el post-procesado (persiste) void setShaderEnabled(bool enabled); // Activa o desactiva el post-procesado (persiste)
void toggleShaderEnabled(); // Alterna post-procesado void toggleShaderEnabled(); // Alterna post-procesado
[[nodiscard]] static auto isShaderEnabled() -> bool; // Estado actual (lee options) [[nodiscard]] static auto isShaderEnabled() -> bool; // Estado actual (lee options)
#ifndef NO_SHADERS #ifndef NO_SHADERS
void setActiveShader(Rendering::ShaderType type); // POSTFX o CRTPI void setActiveShader(Rendering::ShaderType type); // POSTFX o CRTPI
@@ -121,15 +121,15 @@ class Screen {
int gameCanvasWidth; // Resolución interna del juego. Es el ancho de la textura donde se dibuja el juego int gameCanvasWidth; // Resolución interna del juego. Es el ancho de la textura donde se dibuja el juego
int gameCanvasHeight; // Resolución interna del juego. Es el alto de la textura donde se dibuja el juego int gameCanvasHeight; // Resolución interna del juego. Es el alto de la textura donde se dibuja el juego
SDL_Rect dest; // Coordenadas donde se va a dibujar la textura del juego sobre la pantalla o ventana SDL_Rect dest; // Coordenadas donde se va a dibujar la textura del juego sobre la pantalla o ventana
Color borderColor; // Color del borde añadido a la textura de juego para rellenar la pantalla Color borderColor; // Color del borde añadido a la textura de juego para rellenar la pantalla
// Notificaciones - una sola activa, sin apilación ni animaciones // Notificaciones - una sola activa, sin apilación ni animaciones
Text *notificationText; // Fuente 8bithud dedicada a las notificaciones Text *notificationText; // Fuente 8bithud dedicada a las notificaciones
std::string notificationMessage; // Texto a mostrar std::string notificationMessage; // Texto a mostrar
Color notificationTextColor; // Color del texto Color notificationTextColor; // Color del texto
Color notificationOutlineColor; // Color del outline Color notificationOutlineColor; // Color del outline
Uint32 notificationEndTime; // SDL_GetTicks() hasta el cual se muestra Uint32 notificationEndTime; // SDL_GetTicks() hasta el cual se muestra
int notificationY; // Fila vertical en el canvas virtual int notificationY; // Fila vertical en el canvas virtual
#ifndef NO_SHADERS #ifndef NO_SHADERS
// GPU / shaders // GPU / shaders
+1 -1
View File
@@ -171,7 +171,7 @@ Text::Text(const std::vector<uint8_t> &pngBytes, const std::vector<uint8_t> &txt
Text::~Text() { Text::~Text() {
delete sprite; delete sprite;
delete texture; delete texture;
} }
// Escribe texto en pantalla // Escribe texto en pantalla
+5 -5
View File
@@ -22,8 +22,8 @@ struct Offset {
}; };
struct TextFile { struct TextFile {
int boxWidth; // Anchura de la caja de cada caracter en el png int boxWidth; // Anchura de la caja de cada caracter en el png
int boxHeight; // Altura de la caja de cada caracter en el png int boxHeight; // Altura de la caja de cada caracter en el png
Offset offset[128]; // Vector con las posiciones y ancho de cada letra Offset offset[128]; // Vector con las posiciones y ancho de cada letra
}; };
@@ -41,9 +41,9 @@ class Text {
Texture *texture; // Textura con los bitmaps del texto Texture *texture; // Textura con los bitmaps del texto
// Variables // Variables
int boxWidth; // Anchura de la caja de cada caracter en el png int boxWidth; // Anchura de la caja de cada caracter en el png
int boxHeight; // Altura de la caja de cada caracter en el png int boxHeight; // Altura de la caja de cada caracter en el png
bool fixedWidth; // Indica si el texto se ha de escribir con longitud fija en todas las letras bool fixedWidth; // Indica si el texto se ha de escribir con longitud fija en todas las letras
Offset offset[128]; // Vector con las posiciones y ancho de cada letra Offset offset[128]; // Vector con las posiciones y ancho de cada letra
public: public:
+1 -1
View File
@@ -7,7 +7,7 @@
#include <iostream> // for basic_ostream, operator<<, cout, endl #include <iostream> // for basic_ostream, operator<<, cout, endl
#define STB_IMAGE_IMPLEMENTATION #define STB_IMAGE_IMPLEMENTATION
#include "core/resources/resource_helper.h" // for loadFile (pack + filesystem fallback) #include "core/resources/resource_helper.h" // for loadFile (pack + filesystem fallback)
#include "external/stb_image.h" // for stbi_failure_reason, stbi_image_free #include "external/stb_image.h" // for stbi_failure_reason, stbi_image_free
SDL_ScaleMode Texture::currentScaleMode = SDL_SCALEMODE_NEAREST; SDL_ScaleMode Texture::currentScaleMode = SDL_SCALEMODE_NEAREST;
+5 -5
View File
@@ -10,11 +10,11 @@ class Writer {
Text *text; // Objeto encargado de escribir el texto Text *text; // Objeto encargado de escribir el texto
// Variables // Variables
int posX{0}; // Posicion en el eje X donde empezar a escribir el texto int posX{0}; // Posicion en el eje X donde empezar a escribir el texto
int posY{0}; // Posicion en el eje Y donde empezar a escribir el texto int posY{0}; // Posicion en el eje Y donde empezar a escribir el texto
int kerning{0}; // Kerning del texto, es decir, espaciado entre caracteres int kerning{0}; // Kerning del texto, es decir, espaciado entre caracteres
std::string caption; // El texto para escribir std::string caption; // El texto para escribir
int speed{0}; // Velocidad de escritura int speed{0}; // Velocidad de escritura
int writingCounter{0}; // Temporizador de escritura para cada caracter int writingCounter{0}; // Temporizador de escritura para cada caracter
int index{0}; // Posición del texto que se está escribiendo int index{0}; // Posición del texto que se está escribiendo
int lenght{0}; // Longitud de la cadena a escribir int lenght{0}; // Longitud de la cadena a escribir
+3 -3
View File
@@ -29,10 +29,10 @@ class Asset {
private: private:
// Variables // Variables
int longestName{0}; // Contiene la longitud del nombre de fichero mas largo int longestName{0}; // Contiene la longitud del nombre de fichero mas largo
std::vector<Item> fileList; // Listado con todas las rutas a los ficheros std::vector<Item> fileList; // Listado con todas las rutas a los ficheros
std::string executablePath; // Ruta al ejecutable std::string executablePath; // Ruta al ejecutable
bool verbose{true}; // Indica si ha de mostrar información por pantalla bool verbose{true}; // Indica si ha de mostrar información por pantalla
// Comprueba que existe un fichero // Comprueba que existe un fichero
[[nodiscard]] auto checkFile(const std::string &executablePath) const -> bool; [[nodiscard]] auto checkFile(const std::string &executablePath) const -> bool;
+2 -2
View File
@@ -134,8 +134,8 @@ void Resource::preloadAll() {
} }
break; break;
} }
case t_font: // Fonts: se emparejan en pass 2 case t_font: // Fonts: se emparejan en pass 2
case t_lang: // Lenguaje: lo sigue leyendo la clase Lang via ResourceHelper case t_lang: // Lenguaje: lo sigue leyendo la clase Lang via ResourceHelper
default: default:
break; break;
} }
+1 -1
View File
@@ -23,7 +23,7 @@ class Director {
// Objetos y punteros // Objetos y punteros
SDL_Window *window; // La ventana donde dibujamos SDL_Window *window; // La ventana donde dibujamos
SDL_Renderer *renderer; // El renderizador de la ventana SDL_Renderer *renderer; // El renderizador de la ventana
Section *section; // Sección y subsección actual del programa; Section *section; // Sección y subsección actual del programa;
// Secciones del juego // Secciones del juego
ActiveSection activeSection; ActiveSection activeSection;
File diff suppressed because it is too large Load Diff
+172 -253
View File
@@ -1,253 +1,172 @@
#pragma once #pragma once
#include <SDL3/SDL.h> #include <SDL3/SDL.h>
#include <string> // for string #include <string> // for string
#include <vector> // for vector #include <vector> // for vector
#include "utils/utils.h" // for Circle #include "utils/utils.h" // for Circle
class AnimatedSprite; class AnimatedSprite;
class Texture; class Texture;
// Cantidad de elementos del vector con los valores de la deformación del globo al rebotar // Tipos de globo
constexpr int MAX_BOUNCE = 10; constexpr int BALLOON_1 = 1;
constexpr int BALLOON_2 = 2;
// Tipos de globo constexpr int BALLOON_3 = 3;
constexpr int BALLOON_1 = 1; constexpr int BALLOON_4 = 4;
constexpr int BALLOON_2 = 2; constexpr int HEXAGON_1 = 5;
constexpr int BALLOON_3 = 3; constexpr int HEXAGON_2 = 6;
constexpr int BALLOON_4 = 4; constexpr int HEXAGON_3 = 7;
constexpr int HEXAGON_1 = 5; constexpr int HEXAGON_4 = 8;
constexpr int HEXAGON_2 = 6; constexpr int POWER_BALL = 9;
constexpr int HEXAGON_3 = 7;
constexpr int HEXAGON_4 = 8; // Puntos de globo
constexpr int POWER_BALL = 9; constexpr int BALLOON_SCORE_1 = 50;
constexpr int BALLOON_SCORE_2 = 100;
// Puntos de globo constexpr int BALLOON_SCORE_3 = 200;
constexpr int BALLOON_SCORE_1 = 50; constexpr int BALLOON_SCORE_4 = 400;
constexpr int BALLOON_SCORE_2 = 100;
constexpr int BALLOON_SCORE_3 = 200; // Tamaños de globo
constexpr int BALLOON_SCORE_4 = 400; constexpr int BALLOON_SIZE_1 = 1;
constexpr int BALLOON_SIZE_2 = 2;
// Tamaños de globo constexpr int BALLOON_SIZE_3 = 3;
constexpr int BALLOON_SIZE_1 = 1; constexpr int BALLOON_SIZE_4 = 4;
constexpr int BALLOON_SIZE_2 = 2;
constexpr int BALLOON_SIZE_3 = 3; // Clases de globo
constexpr int BALLOON_SIZE_4 = 4; constexpr int BALLOON_CLASS = 0;
constexpr int HEXAGON_CLASS = 1;
// Clases de globo
constexpr int BALLOON_CLASS = 0; // Velocidad del globo
constexpr int HEXAGON_CLASS = 1; constexpr float BALLOON_VELX_POSITIVE = 0.7F;
constexpr float BALLOON_VELX_NEGATIVE = -0.7F;
// Velocidad del globo
constexpr float BALLOON_VELX_POSITIVE = 0.7F; // Velocidades a las que se mueven los globos
constexpr float BALLOON_VELX_NEGATIVE = -0.7F; constexpr float BALLOON_SPEED_1 = 0.60F;
constexpr float BALLOON_SPEED_2 = 0.70F;
// Índice para las animaciones de los globos constexpr float BALLOON_SPEED_3 = 0.80F;
constexpr int BALLOON_MOVING_ANIMATION = 0; constexpr float BALLOON_SPEED_4 = 0.90F;
constexpr int BALLOON_POP_ANIMATION = 1; constexpr float BALLOON_SPEED_5 = 1.00F;
constexpr int BALLOON_BORN_ANIMATION = 2;
// Tamaño de los globos
// Cantidad posible de globos constexpr int BALLOON_WIDTH_1 = 8;
constexpr int MAX_BALLOONS = 100; constexpr int BALLOON_WIDTH_2 = 13;
constexpr int BALLOON_WIDTH_3 = 21;
// Velocidades a las que se mueven los globos constexpr int BALLOON_WIDTH_4 = 37;
constexpr float BALLOON_SPEED_1 = 0.60F;
constexpr float BALLOON_SPEED_2 = 0.70F; // PowerBall
constexpr float BALLOON_SPEED_3 = 0.80F; constexpr int POWERBALL_SCREENPOWER_MINIMUM = 10;
constexpr float BALLOON_SPEED_4 = 0.90F; constexpr int POWERBALL_COUNTER = 8;
constexpr float BALLOON_SPEED_5 = 1.00F;
// Clase Balloon
// Tamaño de los globos class Balloon {
constexpr int BALLOON_WIDTH_1 = 8; public:
constexpr int BALLOON_WIDTH_2 = 13; Balloon(float x, float y, Uint8 kind, float velx, float speed, Uint16 creationtimer, Texture *texture, std::vector<std::string> *animation, SDL_Renderer *renderer); // Constructor
constexpr int BALLOON_WIDTH_3 = 21; ~Balloon(); // Destructor
constexpr int BALLOON_WIDTH_4 = 37;
Balloon(const Balloon &) = delete;
// PowerBall auto operator=(const Balloon &) -> Balloon & = delete;
constexpr int POWERBALL_SCREENPOWER_MINIMUM = 10;
constexpr int POWERBALL_COUNTER = 8; void allignTo(int x); // Centra el globo en la posición X
void render(); // Pinta el globo en la pantalla
// Clase Balloon void move(); // Actualiza la posición y estados del globo
class Balloon { void disable(); // Deshabilita el globo y pone a cero todos los valores
private: void pop(); // Explosiona el globo
// Estructura para las variables para el efecto de los rebotes void update(); // Actualiza al globo a su posicion, animación y controla los contadores
struct Bouncing {
bool enabled; // Si el efecto está activo [[nodiscard]] auto isEnabled() const -> bool; // Comprueba si el globo está habilitado
Uint8 counter; // Countador para el efecto [[nodiscard]] auto isStopped() const -> bool; // Obtiene del valor de la variable
Uint8 speed; // Velocidad a la que transcurre el efecto [[nodiscard]] auto isBlinking() const -> bool; // Obtiene del valor de la variable
float zoomW; // Zoom aplicado a la anchura [[nodiscard]] auto isVisible() const -> bool; // Obtiene del valor de la variable
float zoomH; // Zoom aplicado a la altura [[nodiscard]] auto isInvulnerable() const -> bool; // Obtiene del valor de la variable
float despX; // Desplazamiento de pixeles en el eje X antes de pintar el objeto con zoom [[nodiscard]] auto isBeingCreated() const -> bool; // Obtiene del valor de la variable
float despY; // Desplazamiento de pixeles en el eje Y antes de pintar el objeto con zoom [[nodiscard]] auto isPopping() const -> bool; // Obtiene del valor de la variable
std::vector<float> w; // Vector con los valores de zoom para el ancho del globo
std::vector<float> h; // Vector con los valores de zoom para el alto del globo [[nodiscard]] auto getPosX() const -> float; // Obtiene del valor de la variable
}; [[nodiscard]] auto getPosY() const -> float; // Obtiene del valor de la variable
[[nodiscard]] auto getVelY() const -> float; // Obtiene del valor de la variable
// Objetos y punteros [[nodiscard]] auto getWidth() const -> int; // Obtiene del valor de la variable
AnimatedSprite *sprite; // Sprite del objeto globo [[nodiscard]] auto getHeight() const -> int; // Obtiene del valor de la variable
[[nodiscard]] auto getKind() const -> int; // Obtiene del valor de la variable
// Variables [[nodiscard]] auto getSize() const -> Uint8; // Obtiene del valor de la variable
float posX; // Posición en el eje X [[nodiscard]] auto getClass() const -> Uint8; // Obtiene la clase a la que pertenece el globo
float posY; // Posición en el eje Y [[nodiscard]] auto getStoppedTimer() const -> Uint16; // Obtiene del valor de la variable
Uint8 width; // Ancho [[nodiscard]] auto getScore() const -> Uint16; // Obtiene del valor de la variable
Uint8 height; // Alto [[nodiscard]] auto getMenace() const -> Uint8; // Obtiene le valor de la variable
float velX; // Velocidad en el eje X. Cantidad de pixeles a desplazarse [[nodiscard]] auto getPower() const -> Uint8; // Obtiene le valor de la variable
float velY; // Velocidad en el eje Y. Cantidad de pixeles a desplazarse
float gravity; // Aceleración en el eje Y. Modifica la velocidad void setVelY(float vel_y); // Establece el valor de la variable
float defaultVelY; // Velocidad inicial que tienen al rebotar contra el suelo void setSpeed(float speed); // Establece el valor de la variable
float maxVelY; // Máxima velocidad que puede alcanzar el objeto en el eje Y void setStop(bool state); // Establece el valor de la variable
bool beingCreated; // Indica si el globo se está creando void setBlink(bool value); // Establece el valor de la variable
bool blinking; // Indica si el globo está intermitente void setVisible(bool value); // Establece el valor de la variable
bool enabled; // Indica si el globo esta activo void setInvulnerable(bool value); // Establece el valor de la variable
bool invulnerable; // Indica si el globo es invulnerable void setPopping(bool value); // Establece el valor de la variable
bool popping; // Indica si el globo está explotando void setStoppedTimer(Uint16 time); // Establece el valor de la variable
bool stopped; // Indica si el globo está parado
bool visible; // Indica si el globo es visible auto getCollider() -> Circle &; // Obtiene el circulo de colisión
Circle collider; // Circulo de colisión del objeto
Uint16 creationCounter; // Temporizador para controlar el estado "creandose" private:
Uint16 creationCounterIni; // Valor inicial para el temporizador para controlar el estado "creandose" // Cantidad de elementos del vector con los valores de la deformación del globo al rebotar
Uint16 score; // Puntos que da el globo al ser destruido static constexpr int MAX_BOUNCE = 10;
Uint16 stoppedCounter; // Contador para controlar el estado "parado"
Uint8 kind; // Tipo de globo // Estructura para las variables para el efecto de los rebotes
Uint8 menace; // Cantidad de amenaza que genera el globo struct Bouncing {
Uint32 counter; // Contador interno bool enabled; // Si el efecto está activo
float travelY; // Distancia que ha de recorrer el globo en el eje Y antes de que se le aplique la gravedad Uint8 counter; // Countador para el efecto
float speed; // Velocidad a la que se mueven los globos Uint8 speed; // Velocidad a la que transcurre el efecto
Uint8 size; // Tamaño del globo float zoom_width; // Zoom aplicado a la anchura
Uint8 power; // Cantidad de poder que alberga el globo float zoom_height; // Zoom aplicado a la altura
Bouncing bouncing; // Contiene las variables para el efecto de rebote float desp_x; // Desplazamiento de pixeles en el eje X antes de pintar el objeto con zoom
float desp_y; // Desplazamiento de pixeles en el eje Y antes de pintar el objeto con zoom
// Alinea el circulo de colisión con la posición del objeto globo std::vector<float> w; // Vector con los valores de zoom para el ancho del globo
void updateColliders(); std::vector<float> h; // Vector con los valores de zoom para el alto del globo
};
// Activa el efecto
void bounceStart(); // Objetos y punteros
AnimatedSprite *sprite_; // Sprite del objeto globo
// Detiene el efecto
void bounceStop(); // Variables
float pos_x_; // Posición en el eje X
// Aplica el efecto float pos_y_; // Posición en el eje Y
void updateBounce(); Uint8 width_; // Ancho
Uint8 height_; // Alto
// Actualiza los estados del globo float vel_x_; // Velocidad en el eje X. Cantidad de pixeles a desplazarse
void updateState(); float vel_y_; // Velocidad en el eje Y. Cantidad de pixeles a desplazarse
float gravity_; // Aceleración en el eje Y. Modifica la velocidad
// Establece la animación correspondiente float default_vel_y_; // Velocidad inicial que tienen al rebotar contra el suelo
void updateAnimation(); float max_vel_y_; // Máxima velocidad que puede alcanzar el objeto en el eje Y
bool being_created_; // Indica si el globo se está creando
// Establece el valor de la variable bool blinking_; // Indica si el globo está intermitente
void setBeingCreated(bool value); bool enabled_; // Indica si el globo esta activo
bool invulnerable_; // Indica si el globo es invulnerable
public: bool popping_; // Indica si el globo está explotando
// Constructor bool stopped_; // Indica si el globo está parado
Balloon(float x, float y, Uint8 kind, float velx, float speed, Uint16 creationtimer, Texture *texture, std::vector<std::string> *animation, SDL_Renderer *renderer); bool visible_; // Indica si el globo es visible
Circle collider_; // Circulo de colisión del objeto
// Destructor Uint16 creation_counter_; // Temporizador para controlar el estado "creandose"
~Balloon(); Uint16 creation_counter_ini_; // Valor inicial para el temporizador para controlar el estado "creandose"
Uint16 score_; // Puntos que da el globo al ser destruido
Balloon(const Balloon &) = delete; Uint16 stopped_counter_; // Contador para controlar el estado "parado"
auto operator=(const Balloon &) -> Balloon & = delete; Uint8 kind_; // Tipo de globo
Uint8 menace_; // Cantidad de amenaza que genera el globo
// Centra el globo en la posición X Uint32 counter_; // Contador interno
void allignTo(int x); float travel_y_; // 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
// Pinta el globo en la pantalla Uint8 size_; // Tamaño del globo
void render(); Uint8 power_; // Cantidad de poder que alberga el globo
Bouncing bouncing_; // Contiene las variables para el efecto de rebote
// Actualiza la posición y estados del globo
void move(); void updateColliders(); // Alinea el circulo de colisión con la posición del objeto globo
void bounceStart(); // Activa el efecto
// Deshabilita el globo y pone a cero todos los valores void bounceStop(); // Detiene el efecto
void disable(); void updateBounce(); // Aplica el efecto
void updateAnimation(); // Establece la animación correspondiente
// Explosiona el globo void setBeingCreated(bool value); // Establece el valor de la variable
void pop();
void updateState(); // Actualiza los estados del globo
// Actualiza al globo a su posicion, animación y controla los contadores
void update(); // Helpers de updateState, uno por cada rama de estado
void updateStatePopping();
// Comprueba si el globo está habilitado void updateStateBeingCreated();
[[nodiscard]] auto isEnabled() const -> bool; void updateStateStopped();
};
// Obtiene del valor de la variable
[[nodiscard]] auto getPosX() const -> float;
// Obtiene del valor de la variable
[[nodiscard]] auto getPosY() const -> float;
// Obtiene del valor de la variable
[[nodiscard]] auto getVelY() const -> float;
// Obtiene del valor de la variable
[[nodiscard]] auto getWidth() const -> int;
// Obtiene del valor de la variable
[[nodiscard]] auto getHeight() const -> int;
// Establece el valor de la variable
void setVelY(float velY);
// Establece el valor de la variable
void setSpeed(float speed);
// Obtiene del valor de la variable
[[nodiscard]] auto getKind() const -> int;
// Obtiene del valor de la variable
[[nodiscard]] auto getSize() const -> Uint8;
// Obtiene la clase a la que pertenece el globo
[[nodiscard]] auto getClass() const -> Uint8;
// Establece el valor de la variable
void setStop(bool state);
// Obtiene del valor de la variable
[[nodiscard]] auto isStopped() const -> bool;
// Establece el valor de la variable
void setBlink(bool value);
// Obtiene del valor de la variable
[[nodiscard]] auto isBlinking() const -> bool;
// Establece el valor de la variable
void setVisible(bool value);
// Obtiene del valor de la variable
[[nodiscard]] auto isVisible() const -> bool;
// Establece el valor de la variable
void setInvulnerable(bool value);
// Obtiene del valor de la variable
[[nodiscard]] auto isInvulnerable() const -> bool;
// Obtiene del valor de la variable
[[nodiscard]] auto isBeingCreated() const -> bool;
// Establece el valor de la variable
void setPopping(bool value);
// Obtiene del valor de la variable
[[nodiscard]] auto isPopping() const -> bool;
// Establece el valor de la variable
void setStoppedTimer(Uint16 time);
// Obtiene del valor de la variable
[[nodiscard]] auto getStoppedTimer() const -> Uint16;
// Obtiene del valor de la variable
[[nodiscard]] auto getScore() const -> Uint16;
// Obtiene el circulo de colisión
auto getCollider() -> Circle &;
// Obtiene le valor de la variable
[[nodiscard]] auto getMenace() const -> Uint8;
// Obtiene le valor de la variable
[[nodiscard]] auto getPower() const -> Uint8;
};
+53 -53
View File
@@ -1,65 +1,65 @@
#include "game/entities/bullet.h" #include "game/entities/bullet.h"
#include "core/rendering/sprite.h" // for Sprite #include "core/rendering/sprite.h" // for Sprite
#include "game/defaults.hpp" // for BulletKind::NONE, PLAY_AREA_LEFT, PLAY_AREA_RIGHT, PLAY_A... #include "game/defaults.hpp" // for PLAY_AREA_LEFT, PLAY_AREA_RIGHT, PLAY_A...
class Texture; class Texture;
// Constructor // Constructor
Bullet::Bullet(int x, int y, BulletKind kind, bool poweredUp, int owner, Texture *texture, SDL_Renderer *renderer) { Bullet::Bullet(int x, int y, Bullet::Kind kind, bool powered_up, int owner, Texture *texture, SDL_Renderer *renderer) {
sprite = new Sprite({x, y, 10, 10}, texture, renderer); sprite_ = new Sprite({x, y, 10, 10}, texture, renderer);
// Posición inicial del objeto // Posición inicial del objeto
posX = x; pos_x_ = x;
posY = y; pos_y_ = y;
// Alto y ancho del objeto // Alto y ancho del objeto
width = 10; width_ = 10;
height = 10; height_ = 10;
// Velocidad inicial en el eje Y // Velocidad inicial en el eje Y
velY = -3; vel_y_ = -3;
// Tipo de bala // Tipo de bala
this->kind = kind; this->kind_ = kind;
// Identificador del dueño del objeto // Identificador del dueño del objeto
this->owner = owner; this->owner_ = owner;
// Valores especificos según el tipo // Valores especificos según el tipo
switch (kind) { switch (kind) {
case BulletKind::UP: case Bullet::Kind::UP:
// Establece la velocidad inicial // Establece la velocidad inicial
velX = 0; vel_x_ = 0;
// Rectangulo con los gráficos del objeto // Rectangulo con los gráficos del objeto
if (!poweredUp) { if (!powered_up) {
sprite->setSpriteClip(0 * width, 0, sprite->getWidth(), sprite->getHeight()); sprite_->setSpriteClip(0 * width_, 0, sprite_->getWidth(), sprite_->getHeight());
} else { } else {
sprite->setSpriteClip((0 + 3) * width, 0, sprite->getWidth(), sprite->getHeight()); sprite_->setSpriteClip((0 + 3) * width_, 0, sprite_->getWidth(), sprite_->getHeight());
} }
break; break;
case BulletKind::LEFT: case Bullet::Kind::LEFT:
// Establece la velocidad inicial // Establece la velocidad inicial
velX = -2; vel_x_ = -2;
// Rectangulo con los gráficos del objeto // Rectangulo con los gráficos del objeto
if (!poweredUp) { if (!powered_up) {
sprite->setSpriteClip(1 * width, 0, sprite->getWidth(), sprite->getHeight()); sprite_->setSpriteClip(1 * width_, 0, sprite_->getWidth(), sprite_->getHeight());
} else { } else {
sprite->setSpriteClip((1 + 3) * width, 0, sprite->getWidth(), sprite->getHeight()); sprite_->setSpriteClip((1 + 3) * width_, 0, sprite_->getWidth(), sprite_->getHeight());
} }
break; break;
case BulletKind::RIGHT: case Bullet::Kind::RIGHT:
// Establece la velocidad inicial // Establece la velocidad inicial
velX = 2; vel_x_ = 2;
// Rectangulo con los gráficos del objeto // Rectangulo con los gráficos del objeto
if (!poweredUp) { if (!powered_up) {
sprite->setSpriteClip(2 * width, 0, sprite->getWidth(), sprite->getHeight()); sprite_->setSpriteClip(2 * width_, 0, sprite_->getWidth(), sprite_->getHeight());
} else { } else {
sprite->setSpriteClip((2 + 3) * width, 0, sprite->getWidth(), sprite->getHeight()); sprite_->setSpriteClip((2 + 3) * width_, 0, sprite_->getWidth(), sprite_->getHeight());
} }
break; break;
@@ -68,7 +68,7 @@ Bullet::Bullet(int x, int y, BulletKind kind, bool poweredUp, int owner, Texture
} }
// Establece el tamaño del circulo de colisión // Establece el tamaño del circulo de colisión
collider.r = width / 2; collider_.r = width_ / 2;
// Alinea el circulo de colisión con el objeto // Alinea el circulo de colisión con el objeto
shiftColliders(); shiftColliders();
@@ -76,46 +76,46 @@ Bullet::Bullet(int x, int y, BulletKind kind, bool poweredUp, int owner, Texture
// Destructor // Destructor
Bullet::~Bullet() { Bullet::~Bullet() {
delete sprite; delete sprite_;
} }
// Pinta el objeto en pantalla // Pinta el objeto en pantalla
void Bullet::render() { void Bullet::render() {
sprite->render(); sprite_->render();
} }
// Actualiza la posición y estado del objeto en horizontal // Actualiza la posición y estado del objeto en horizontal
auto Bullet::move() -> Uint8 { auto Bullet::move() -> MoveResult {
// Variable con el valor de retorno // Variable con el valor de retorno
Uint8 msg = BULLET_MOVE_OK; MoveResult msg = MoveResult::OK;
// Mueve el objeto a su nueva posición // Mueve el objeto a su nueva posición
posX += velX; pos_x_ += vel_x_;
// Si el objeto se sale del area de juego por los laterales // Si el objeto se sale del area de juego por los laterales
if ((posX < PLAY_AREA_LEFT - width) || (posX > PLAY_AREA_RIGHT)) { if ((pos_x_ < PLAY_AREA_LEFT - width_) || (pos_x_ > PLAY_AREA_RIGHT)) {
// Se deshabilita // Se deshabilita
kind = BulletKind::NONE; kind_ = Bullet::Kind::NONE;
// Mensaje de salida // Mensaje de salida
msg = BULLET_MOVE_OUT; msg = MoveResult::OUT;
} }
// Mueve el objeto a su nueva posición en vertical // Mueve el objeto a su nueva posición en vertical
posY += velY; pos_y_ += vel_y_;
// Si el objeto se sale del area de juego por la parte superior // Si el objeto se sale del area de juego por la parte superior
if (posY < PLAY_AREA_TOP - height) { if (pos_y_ < PLAY_AREA_TOP - height_) {
// Se deshabilita // Se deshabilita
kind = BulletKind::NONE; kind_ = Bullet::Kind::NONE;
// Mensaje de salida // Mensaje de salida
msg = BULLET_MOVE_OUT; msg = MoveResult::OUT;
} }
// Actualiza la posición del sprite // Actualiza la posición del sprite
sprite->setPosX(posX); sprite_->setPosX(pos_x_);
sprite->setPosY(posY); sprite_->setPosY(pos_y_);
// Alinea el circulo de colisión con el objeto // Alinea el circulo de colisión con el objeto
shiftColliders(); shiftColliders();
@@ -125,56 +125,56 @@ auto Bullet::move() -> Uint8 {
// Comprueba si el objeto está habilitado // Comprueba si el objeto está habilitado
auto Bullet::isEnabled() const -> bool { auto Bullet::isEnabled() const -> bool {
return kind != BulletKind::NONE; return kind_ != Bullet::Kind::NONE;
} }
// Deshabilita el objeto // Deshabilita el objeto
void Bullet::disable() { void Bullet::disable() {
kind = BulletKind::NONE; kind_ = Bullet::Kind::NONE;
} }
// Obtiene el valor de la variable // Obtiene el valor de la variable
auto Bullet::getPosX() const -> int { auto Bullet::getPosX() const -> int {
return posX; return pos_x_;
} }
// Obtiene el valor de la variable // Obtiene el valor de la variable
auto Bullet::getPosY() const -> int { auto Bullet::getPosY() const -> int {
return posY; return pos_y_;
} }
// Establece el valor de la variable // Establece el valor de la variable
void Bullet::setPosX(int x) { void Bullet::setPosX(int x) {
posX = x; pos_x_ = x;
} }
// Establece el valor de la variable // Establece el valor de la variable
void Bullet::setPosY(int y) { void Bullet::setPosY(int y) {
posY = y; pos_y_ = y;
} }
// Obtiene el valor de la variable // Obtiene el valor de la variable
auto Bullet::getVelY() const -> int { auto Bullet::getVelY() const -> int {
return velY; return vel_y_;
} }
// Obtiene el valor de la variable // Obtiene el valor de la variable
auto Bullet::getKind() const -> BulletKind { auto Bullet::getKind() const -> Bullet::Kind {
return kind; return kind_;
} }
// Obtiene el valor de la variable // Obtiene el valor de la variable
auto Bullet::getOwner() const -> int { auto Bullet::getOwner() const -> int {
return owner; return owner_;
} }
// Obtiene el circulo de colisión // Obtiene el circulo de colisión
auto Bullet::getCollider() -> Circle & { auto Bullet::getCollider() -> Circle & {
return collider; return collider_;
} }
// Alinea el circulo de colisión con el objeto // Alinea el circulo de colisión con el objeto
void Bullet::shiftColliders() { void Bullet::shiftColliders() {
collider.x = posX + collider.r; collider_.x = pos_x_ + collider_.r;
collider.y = posY + collider.r; collider_.y = pos_y_ + collider_.r;
} }
+67 -88
View File
@@ -1,88 +1,67 @@
#pragma once #pragma once
#include <SDL3/SDL.h> #include <SDL3/SDL.h>
#include <cstdint> // for uint8_t #include <cstdint> // for uint8_t
#include "utils/utils.h" // for Circle
class Sprite; #include "utils/utils.h" // for Circle
class Texture; class Sprite;
class Texture;
// Tipus de bala. Enum class fortament tipat per evitar confusió accidental
// amb altres `int`/`Uint8` (p.ex. el `owner` a `createBullet`). // Clase Bullet
enum class BulletKind : std::uint8_t { class Bullet {
NONE = 0, // bala desactivada / fora de pantalla public:
UP = 1, // Tipus de bala. Enum class fortament tipat per evitar confusió accidental
LEFT = 2, // amb altres `int`/`Uint8` (p.ex. el `owner` a `createBullet`).
RIGHT = 3, enum class Kind : std::uint8_t {
}; NONE = 0, // bala desactivada / fora de pantalla
UP = 1,
// Tipos de retorno de la función move de la bala LEFT = 2,
constexpr int BULLET_MOVE_OK = 0; RIGHT = 3,
constexpr int BULLET_MOVE_OUT = 1; };
// Clase Bullet // Resultado de Bullet::move()
class Bullet { enum class MoveResult : std::uint8_t {
private: OK = 0,
// Objetos y punteros OUT = 1,
Sprite *sprite; // Sprite con los graficos y métodos de pintado };
// Variables Bullet(int x, int y, Kind kind, bool powered_up, int owner, Texture *texture, SDL_Renderer *renderer); // Constructor
int posX; // Posición en el eje X ~Bullet(); // Destructor
int posY; // Posición en el eje Y
Uint8 width; // Ancho del objeto Bullet(const Bullet &) = delete;
Uint8 height; // Alto del objeto auto operator=(const Bullet &) -> Bullet & = delete;
int velX; // Velocidad en el eje X
int velY; // Velocidad en el eje Y void render(); // Pinta el objeto en pantalla
BulletKind kind; // Tipo de objeto auto move() -> MoveResult; // Actualiza la posición y estado del objeto
int owner; // Identificador del dueño del objeto void disable(); // Deshabilita el objeto
Circle collider; // Circulo de colisión del objeto
[[nodiscard]] auto isEnabled() const -> bool; // Comprueba si el objeto está habilitado
// Alinea el circulo de colisión con el objeto [[nodiscard]] auto getPosX() const -> int; // Obtiene el valor de la variable
void shiftColliders(); [[nodiscard]] auto getPosY() const -> int; // Obtiene el valor de la variable
[[nodiscard]] auto getVelY() const -> int; // Obtiene el valor de la variable
public: [[nodiscard]] auto getKind() const -> Kind; // Obtiene el valor de la variable
// Constructor [[nodiscard]] auto getOwner() const -> int; // Obtiene el valor de la variable
Bullet(int x, int y, BulletKind kind, bool poweredUp, int owner, Texture *texture, SDL_Renderer *renderer);
void setPosX(int x); // Establece el valor de la variable
// Destructor void setPosY(int y); // Establece el valor de la variable
~Bullet();
auto getCollider() -> Circle &; // Obtiene el circulo de colisión
Bullet(const Bullet &) = delete;
auto operator=(const Bullet &) -> Bullet & = delete; private:
// Objetos y punteros
// Pinta el objeto en pantalla Sprite *sprite_; // Sprite con los graficos y métodos de pintado
void render();
// Variables
// Actualiza la posición y estado del objeto int pos_x_; // Posición en el eje X
auto move() -> Uint8; int pos_y_; // Posición en el eje Y
Uint8 width_; // Ancho del objeto
// Comprueba si el objeto está habilitado Uint8 height_; // Alto del objeto
[[nodiscard]] auto isEnabled() const -> bool; int vel_x_; // Velocidad en el eje X
int vel_y_; // Velocidad en el eje Y
// Deshabilita el objeto Kind kind_; // Tipo de objeto
void disable(); int owner_; // Identificador del dueño del objeto
Circle collider_; // Circulo de colisión del objeto
// Obtiene el valor de la variable
[[nodiscard]] auto getPosX() const -> int; void shiftColliders(); // Alinea el circulo de colisión con el objeto
};
// Obtiene el valor de la variable
[[nodiscard]] auto getPosY() const -> int;
// Establece el valor de la variable
void setPosX(int x);
// Establece el valor de la variable
void setPosY(int y);
// Obtiene el valor de la variable
[[nodiscard]] auto getVelY() const -> int;
// Obtiene el valor de la variable
[[nodiscard]] auto getKind() const -> BulletKind;
// Obtiene el valor de la variable
[[nodiscard]] auto getOwner() const -> int;
// Obtiene el circulo de colisión
auto getCollider() -> Circle &;
};
+73 -73
View File
@@ -7,58 +7,58 @@
class Texture; class Texture;
// Constructor // Constructor
Item::Item(Uint8 kind, float x, float y, Texture *texture, std::vector<std::string> *animation, SDL_Renderer *renderer) { Item::Item(Id id, float x, float y, Texture *texture, std::vector<std::string> *animation, SDL_Renderer *renderer) {
sprite = new AnimatedSprite(texture, renderer, "", animation); sprite_ = new AnimatedSprite(texture, renderer, "", animation);
this->kind = kind; this->id_ = id;
enabled = true; enabled_ = true;
timeToLive = 600; time_to_live_ = 600;
accelX = 0.0F; accel_x_ = 0.0F;
floorCollision = false; floor_collision_ = false;
if (kind == ITEM_COFFEE_MACHINE) { if (id == Item::Id::COFFEE_MACHINE) {
width = 23; width_ = 23;
height = 29; height_ = 29;
posX = (((int)x + (PLAY_AREA_WIDTH / 2)) % (PLAY_AREA_WIDTH - width - 5)) + 2; pos_x_ = (((int)x + (PLAY_AREA_WIDTH / 2)) % (PLAY_AREA_WIDTH - width_ - 5)) + 2;
posY = PLAY_AREA_TOP - height; pos_y_ = PLAY_AREA_TOP - height_;
velX = 0.0F; vel_x_ = 0.0F;
velY = -0.1F; vel_y_ = -0.1F;
accelY = 0.1F; accel_y_ = 0.1F;
collider.r = 10; collider_.r = 10;
} else { } else {
width = 16; width_ = 16;
height = 16; height_ = 16;
posX = x; pos_x_ = x;
posY = y; pos_y_ = y;
velX = -1.0F + ((rand() % 5) * 0.5F); vel_x_ = -1.0F + ((rand() % 5) * 0.5F);
velY = -4.0F; vel_y_ = -4.0F;
accelY = 0.2F; accel_y_ = 0.2F;
collider.r = width / 2; collider_.r = width_ / 2;
} }
sprite->setPosX(posX); sprite_->setPosX(pos_x_);
sprite->setPosY(posY); sprite_->setPosY(pos_y_);
shiftColliders(); shiftColliders();
} }
// Destructor // Destructor
Item::~Item() { Item::~Item() {
delete sprite; delete sprite_;
} }
// Centra el objeto en la posición X // Centra el objeto en la posición X
void Item::allignTo(int x) { void Item::allignTo(int x) {
posX = float(x - (width / 2)); pos_x_ = float(x - (width_ / 2));
if (posX < PLAY_AREA_LEFT) { if (pos_x_ < PLAY_AREA_LEFT) {
posX = PLAY_AREA_LEFT + 1; pos_x_ = PLAY_AREA_LEFT + 1;
} else if ((posX + width) > PLAY_AREA_RIGHT) { } else if ((pos_x_ + width_) > PLAY_AREA_RIGHT) {
posX = float(PLAY_AREA_RIGHT - width - 1); pos_x_ = float(PLAY_AREA_RIGHT - width_ - 1);
} }
// Posición X,Y del sprite // Posición X,Y del sprite
sprite->setPosX(int(posX)); sprite_->setPosX(int(pos_x_));
sprite->setPosY(int(posY)); sprite_->setPosY(int(pos_y_));
// Alinea el circulo de colisión con el objeto // Alinea el circulo de colisión con el objeto
shiftColliders(); shiftColliders();
@@ -68,129 +68,129 @@ void Item::allignTo(int x) {
void Item::render() { void Item::render() {
// Mentre quede temps de sobra (>200) es renderitza sempre; quan està a // Mentre quede temps de sobra (>200) es renderitza sempre; quan està a
// punt d'expirar, parpalleja alternant 10 frames visibles i 10 invisibles. // punt d'expirar, parpalleja alternant 10 frames visibles i 10 invisibles.
if (enabled && (timeToLive > 200 || timeToLive % 20 > 10)) { if (enabled_ && (time_to_live_ > 200 || time_to_live_ % 20 > 10)) {
sprite->render(); sprite_->render();
} }
} }
// Actualiza la posición y estados del objeto // Actualiza la posición y estados del objeto
void Item::move() { void Item::move() {
floorCollision = false; floor_collision_ = false;
// Calcula la nueva posición // Calcula la nueva posición
posX += velX; pos_x_ += vel_x_;
posY += velY; pos_y_ += vel_y_;
// Aplica las aceleraciones a la velocidad // Aplica las aceleraciones a la velocidad
velX += accelX; vel_x_ += accel_x_;
velY += accelY; vel_y_ += accel_y_;
// Si queda fuera de pantalla, corregimos su posición y cambiamos su sentido // Si queda fuera de pantalla, corregimos su posición y cambiamos su sentido
if ((posX < PLAY_AREA_LEFT) || (posX + width > PLAY_AREA_RIGHT)) { if ((pos_x_ < PLAY_AREA_LEFT) || (pos_x_ + width_ > PLAY_AREA_RIGHT)) {
// Corregir posición // Corregir posición
posX -= velX; pos_x_ -= vel_x_;
// Invertir sentido // Invertir sentido
velX = -velX; vel_x_ = -vel_x_;
} }
// Si se sale por arriba rebota (excepto la maquina de café) // Si se sale por arriba rebota (excepto la maquina de café)
if ((posY < PLAY_AREA_TOP) && !(kind == ITEM_COFFEE_MACHINE)) { if ((pos_y_ < PLAY_AREA_TOP) && !(id_ == Item::Id::COFFEE_MACHINE)) {
// Corrige // Corrige
posY -= velY; pos_y_ -= vel_y_;
// Invierte el sentido // Invierte el sentido
velY = -velY; vel_y_ = -vel_y_;
} }
// Si el objeto se sale por la parte inferior // Si el objeto se sale por la parte inferior
if (posY + height > PLAY_AREA_BOTTOM) { if (pos_y_ + height_ > PLAY_AREA_BOTTOM) {
// Detiene el objeto // Detiene el objeto
velY = 0; vel_y_ = 0;
velX = 0; vel_x_ = 0;
accelX = 0; accel_x_ = 0;
accelY = 0; accel_y_ = 0;
posY = PLAY_AREA_BOTTOM - height; pos_y_ = PLAY_AREA_BOTTOM - height_;
if (kind == ITEM_COFFEE_MACHINE) { if (id_ == Item::Id::COFFEE_MACHINE) {
floorCollision = true; floor_collision_ = true;
} }
} }
// Actualiza la posición del sprite // Actualiza la posición del sprite
sprite->setPosX(int(posX)); sprite_->setPosX(int(pos_x_));
sprite->setPosY(int(posY)); sprite_->setPosY(int(pos_y_));
shiftColliders(); shiftColliders();
} }
// Pone a cero todos los valores del objeto // Pone a cero todos los valores del objeto
void Item::disable() { void Item::disable() {
enabled = false; enabled_ = false;
} }
// Actualiza el objeto a su posicion, animación y controla los contadores // Actualiza el objeto a su posicion, animación y controla los contadores
void Item::update() { void Item::update() {
move(); move();
sprite->animate(); sprite_->animate();
updateTimeToLive(); updateTimeToLive();
checkTimeToLive(); checkTimeToLive();
} }
// Actualiza el contador // Actualiza el contador
void Item::updateTimeToLive() { void Item::updateTimeToLive() {
if (timeToLive > 0) { if (time_to_live_ > 0) {
timeToLive--; time_to_live_--;
} }
} }
// Comprueba si el objeto sigue vivo // Comprueba si el objeto sigue vivo
void Item::checkTimeToLive() { void Item::checkTimeToLive() {
if (timeToLive == 0) { if (time_to_live_ == 0) {
disable(); disable();
} }
} }
// Obtiene del valor de la variable // Obtiene del valor de la variable
auto Item::getPosX() const -> float { auto Item::getPosX() const -> float {
return posX; return pos_x_;
} }
// Obtiene del valor de la variable // Obtiene del valor de la variable
auto Item::getPosY() const -> float { auto Item::getPosY() const -> float {
return posY; return pos_y_;
} }
// Obtiene del valor de la variable // Obtiene del valor de la variable
auto Item::getWidth() const -> int { auto Item::getWidth() const -> int {
return width; return width_;
} }
// Obtiene del valor de la variable // Obtiene del valor de la variable
auto Item::getHeight() const -> int { auto Item::getHeight() const -> int {
return height; return height_;
} }
// Obtiene del valor de la variable // Obtiene del valor de la variable
auto Item::getClass() const -> int { auto Item::getId() const -> Id {
return kind; return id_;
} }
// Obtiene el valor de la variable // Obtiene el valor de la variable
auto Item::isEnabled() const -> bool { auto Item::isEnabled() const -> bool {
return enabled; return enabled_;
} }
// Obtiene el circulo de colisión // Obtiene el circulo de colisión
auto Item::getCollider() -> Circle & { auto Item::getCollider() -> Circle & {
return collider; return collider_;
} }
// Alinea el circulo de colisión con la posición del objeto // Alinea el circulo de colisión con la posición del objeto
void Item::shiftColliders() { void Item::shiftColliders() {
collider.x = int(posX + (width / 2)); collider_.x = int(pos_x_ + (width_ / 2));
collider.y = int(posY + (height / 2)); collider_.y = int(pos_y_ + (height_ / 2));
} }
// Informa si el objeto ha colisionado con el suelo // Informa si el objeto ha colisionado con el suelo
auto Item::isOnFloor() const -> bool { auto Item::isOnFloor() const -> bool {
return floorCollision; return floor_collision_;
} }
+70 -99
View File
@@ -1,99 +1,70 @@
#pragma once #pragma once
#include <SDL3/SDL.h> #include <SDL3/SDL.h>
#include <string> // for string #include <string> // for string
#include <vector> // for vector #include <vector> // for vector
#include "utils/utils.h" // for Circle #include "utils/utils.h" // for Circle
class AnimatedSprite; class AnimatedSprite;
class Texture; class Texture;
// Tipos de objetos // Clase Item
constexpr int ITEM_POINTS_1_DISK = 1; class Item {
constexpr int ITEM_POINTS_2_GAVINA = 2; public:
constexpr int ITEM_POINTS_3_PACMAR = 3; // Tipos de objetos
constexpr int ITEM_CLOCK = 4; enum class Id : Uint8 {
constexpr int ITEM_COFFEE = 5; NONE = 0,
constexpr int ITEM_COFFEE_MACHINE = 6; DISK = 1,
GAVINA = 2,
// Clase Item PACMAR = 3,
class Item { CLOCK = 4,
private: COFFEE = 5,
// Objetos y punteros COFFEE_MACHINE = 6,
AnimatedSprite *sprite; // Sprite con los graficos del objeto };
// Variables Item(Id id, float x, float y, Texture *texture, std::vector<std::string> *animation, SDL_Renderer *renderer); // Constructor
float posX; // Posición X del objeto ~Item(); // Destructor
float posY; // Posición Y del objeto
Uint8 width; // Ancho del objeto Item(const Item &) = delete;
Uint8 height; // Alto del objeto auto operator=(const Item &) -> Item & = delete;
float velX; // Velocidad en el eje X
float velY; // Velocidad en el eje Y void allignTo(int x); // Centra el objeto en la posición X
float accelX; // Aceleración en el eje X void render(); // Pinta el objeto en la pantalla
float accelY; // Aceleración en el eje Y void disable(); // Pone a cero todos los valores del objeto
bool floorCollision; // Indica si el objeto colisiona con el suelo void update(); // Actualiza al objeto a su posicion, animación y controla los contadores
Uint8 kind; // Especifica el tipo de objeto que es void updateTimeToLive(); // Actualiza el contador
bool enabled; // Especifica si el objeto está habilitado void checkTimeToLive(); // Comprueba si el objeto sigue vivo
Circle collider; // Circulo de colisión del objeto
[[nodiscard]] auto getPosX() const -> float; // Obtiene del valor de la variable
// Alinea el circulo de colisión con la posición del objeto [[nodiscard]] auto getPosY() const -> float; // Obtiene del valor de la variable
void shiftColliders(); [[nodiscard]] auto getWidth() const -> int; // Obtiene del valor de la variable
[[nodiscard]] auto getHeight() const -> int; // Obtiene del valor de la variable
// Actualiza la posición y estados del objeto [[nodiscard]] auto getId() const -> Id; // Obtiene del valor de la variable
void move(); [[nodiscard]] auto isEnabled() const -> bool; // Obtiene el valor de la variable
[[nodiscard]] auto isOnFloor() const -> bool; // Informa si el objeto ha colisionado con el suelo
public:
Uint16 timeToLive; // Temporizador con el tiempo que el objeto está presente auto getCollider() -> Circle &; // Obtiene el circulo de colisión
// Constructor private:
Item(Uint8 kind, float x, float y, Texture *texture, std::vector<std::string> *animation, SDL_Renderer *renderer); // Objetos y punteros
AnimatedSprite *sprite_; // Sprite con los graficos del objeto
// Destructor
~Item(); // Variables
float pos_x_; // Posición X del objeto
Item(const Item &) = delete; float pos_y_; // Posición Y del objeto
auto operator=(const Item &) -> Item & = delete; Uint8 width_; // Ancho del objeto
Uint8 height_; // Alto del objeto
// Centra el objeto en la posición X float vel_x_; // Velocidad en el eje X
void allignTo(int x); float vel_y_; // Velocidad en el eje Y
float accel_x_; // Aceleración en el eje X
// Pinta el objeto en la pantalla float accel_y_; // Aceleración en el eje Y
void render(); bool floor_collision_; // Indica si el objeto colisiona con el suelo
Id id_; // Especifica el tipo de objeto que es
// Pone a cero todos los valores del objeto bool enabled_; // Especifica si el objeto está habilitado
void disable(); Uint16 time_to_live_; // Temporizador con el tiempo que el objeto está presente
Circle collider_; // Circulo de colisión del objeto
// Actualiza al objeto a su posicion, animación y controla los contadores
void update(); void shiftColliders(); // Alinea el circulo de colisión con la posición del objeto
void move(); // Actualiza la posición y estados del objeto
// Actualiza el contador };
void updateTimeToLive();
// Comprueba si el objeto sigue vivo
void checkTimeToLive();
// Obtiene del valor de la variable
[[nodiscard]] auto getPosX() const -> float;
// Obtiene del valor de la variable
[[nodiscard]] auto getPosY() const -> float;
// Obtiene del valor de la variable
[[nodiscard]] auto getWidth() const -> int;
// Obtiene del valor de la variable
[[nodiscard]] auto getHeight() const -> int;
// Obtiene del valor de la variable
[[nodiscard]] auto getClass() const -> int;
// Obtiene el valor de la variable
[[nodiscard]] auto isEnabled() const -> bool;
// Obtiene el circulo de colisión
auto getCollider() -> Circle &;
// Informa si el objeto ha colisionado con el suelo
[[nodiscard]] auto isOnFloor() const -> bool;
};
+187 -187
View File
@@ -11,117 +11,117 @@
// Constructor // Constructor
Player::Player(float x, int y, SDL_Renderer *renderer, const std::vector<Texture *> &texture, const std::vector<std::vector<std::string> *> &animations) { Player::Player(float x, int y, SDL_Renderer *renderer, const std::vector<Texture *> &texture, const std::vector<std::vector<std::string> *> &animations) {
// Copia los punteros // Copia los punteros
this->renderer = renderer; this->renderer_ = renderer;
// Reserva memoria para los objetos // Reserva memoria para los objetos
headSprite = new AnimatedSprite(texture[0], renderer, "", animations[0]); head_sprite_ = new AnimatedSprite(texture[0], renderer, "", animations[0]);
bodySprite = new AnimatedSprite(texture[1], renderer, "", animations[1]); body_sprite_ = new AnimatedSprite(texture[1], renderer, "", animations[1]);
legsSprite = new AnimatedSprite(texture[2], renderer, "", animations[2]); legs_sprite_ = new AnimatedSprite(texture[2], renderer, "", animations[2]);
deathSprite = new AnimatedSprite(texture[3], renderer, "", animations[3]); death_sprite_ = new AnimatedSprite(texture[3], renderer, "", animations[3]);
fireSprite = new AnimatedSprite(texture[4], renderer, "", animations[4]); fire_sprite_ = new AnimatedSprite(texture[4], renderer, "", animations[4]);
fireSprite->getTexture()->setAlpha(224); fire_sprite_->getTexture()->setAlpha(224);
// Establece la posición inicial del jugador // Establece la posición inicial del jugador
posX = x; pos_x_ = x;
posY = y; pos_y_ = y;
init(); init();
} }
// Destructor // Destructor
Player::~Player() { Player::~Player() {
delete headSprite; delete head_sprite_;
delete bodySprite; delete body_sprite_;
delete legsSprite; delete legs_sprite_;
delete deathSprite; delete death_sprite_;
delete fireSprite; delete fire_sprite_;
} }
// Iniciador // Iniciador
void Player::init() { void Player::init() {
// Inicializa variables de estado // Inicializa variables de estado
alive = true; alive_ = true;
deathCounter = DEATH_COUNTER; death_counter_ = DEATH_COUNTER;
statusWalking = PLAYER_STATUS_WALKING_STOP; status_walking_ = STATUS_WALKING_STOP;
statusFiring = PLAYER_STATUS_FIRING_NO; status_firing_ = STATUS_FIRING_NO;
invulnerable = false; invulnerable_ = false;
invulnerableCounter = PLAYER_INVULNERABLE_COUNTER; invulnerable_counter_ = INVULNERABLE_COUNTER;
powerUp = false; power_up_ = false;
powerUpCounter = PLAYER_POWERUP_COUNTER; power_up_counter_ = POWERUP_COUNTER;
extraHit = false; extra_hit_ = false;
coffees = 0; coffees_ = 0;
input = true; input_ = true;
// Establece la altura y el ancho del jugador // Establece la altura y el ancho del jugador
width = 24; width_ = 24;
height = 24; height_ = 24;
// Establece el tamaño del circulo de colisión // Establece el tamaño del circulo de colisión
collider.r = 7; collider_.r = 7;
// Actualiza la posición del circulo de colisión // Actualiza la posición del circulo de colisión
shiftColliders(); shiftColliders();
// Establece la velocidad inicial // Establece la velocidad inicial
velX = 0; vel_x_ = 0;
velY = 0; vel_y_ = 0;
// Establece la velocidad base // Establece la velocidad base
baseSpeed = 1.5; base_speed_ = 1.5;
// Establece la puntuación inicial // Establece la puntuación inicial
score = 0; score_ = 0;
// Establece el multiplicador de puntos inicial // Establece el multiplicador de puntos inicial
scoreMultiplier = 1.0F; score_multiplier_ = 1.0F;
// Inicia el contador para la cadencia de disparo // Inicia el contador para la cadencia de disparo
cooldown = 10; cooldown_ = 10;
// Establece la posición del sprite // Establece la posición del sprite
legsSprite->setPosX(posX); legs_sprite_->setPosX(pos_x_);
legsSprite->setPosY(posY); legs_sprite_->setPosY(pos_y_);
bodySprite->setPosX(posX); body_sprite_->setPosX(pos_x_);
bodySprite->setPosY(posY); body_sprite_->setPosY(pos_y_);
headSprite->setPosX(posX); head_sprite_->setPosX(pos_x_);
headSprite->setPosY(posY); head_sprite_->setPosY(pos_y_);
// Selecciona un frame para pintar // Selecciona un frame para pintar
legsSprite->setCurrentAnimation("stand"); legs_sprite_->setCurrentAnimation("stand");
bodySprite->setCurrentAnimation("stand"); body_sprite_->setCurrentAnimation("stand");
headSprite->setCurrentAnimation("stand"); head_sprite_->setCurrentAnimation("stand");
} }
// Actua en consecuencia de la entrada recibida // Actua en consecuencia de la entrada recibida
void Player::setInput(Uint8 input) { void Player::setInput(Uint8 input) {
switch (input) { switch (input) {
case input_left: case input_left:
velX = -baseSpeed; vel_x_ = -base_speed_;
setWalkingStatus(PLAYER_STATUS_WALKING_LEFT); setWalkingStatus(STATUS_WALKING_LEFT);
break; break;
case input_right: case input_right:
velX = baseSpeed; vel_x_ = base_speed_;
setWalkingStatus(PLAYER_STATUS_WALKING_RIGHT); setWalkingStatus(STATUS_WALKING_RIGHT);
break; break;
case input_fire_center: case input_fire_center:
setFiringStatus(PLAYER_STATUS_FIRING_UP); setFiringStatus(STATUS_FIRING_UP);
break; break;
case input_fire_left: case input_fire_left:
setFiringStatus(PLAYER_STATUS_FIRING_LEFT); setFiringStatus(STATUS_FIRING_LEFT);
break; break;
case input_fire_right: case input_fire_right:
setFiringStatus(PLAYER_STATUS_FIRING_RIGHT); setFiringStatus(STATUS_FIRING_RIGHT);
break; break;
default: default:
velX = 0; vel_x_ = 0;
setWalkingStatus(PLAYER_STATUS_WALKING_STOP); setWalkingStatus(STATUS_WALKING_STOP);
break; break;
} }
} }
@@ -130,35 +130,35 @@ void Player::setInput(Uint8 input) {
void Player::move() { void Player::move() {
if (isAlive()) { if (isAlive()) {
// Mueve el jugador a derecha o izquierda // Mueve el jugador a derecha o izquierda
posX += velX; pos_x_ += vel_x_;
// Si el jugador abandona el area de juego por los laterales // Si el jugador abandona el area de juego por los laterales
if ((posX < PLAY_AREA_LEFT - 5) || (posX + width > PLAY_AREA_RIGHT + 5)) { // Restaura su posición if ((pos_x_ < PLAY_AREA_LEFT - 5) || (pos_x_ + width_ > PLAY_AREA_RIGHT + 5)) { // Restaura su posición
posX -= velX; pos_x_ -= vel_x_;
} }
// Actualiza la posición del sprite // Actualiza la posición del sprite
legsSprite->setPosX(getPosX()); legs_sprite_->setPosX(getPosX());
legsSprite->setPosY(posY); legs_sprite_->setPosY(pos_y_);
bodySprite->setPosX(getPosX()); body_sprite_->setPosX(getPosX());
bodySprite->setPosY(posY); body_sprite_->setPosY(pos_y_);
headSprite->setPosX(getPosX()); head_sprite_->setPosX(getPosX());
headSprite->setPosY(posY); head_sprite_->setPosY(pos_y_);
fireSprite->setPosX(getPosX() - 2); fire_sprite_->setPosX(getPosX() - 2);
fireSprite->setPosY(posY - 8); fire_sprite_->setPosY(pos_y_ - 8);
} else { } else {
deathSprite->update(); death_sprite_->update();
// Si el cadaver abandona el area de juego por los laterales // Si el cadaver abandona el area de juego por los laterales
if ((deathSprite->getPosX() < PLAY_AREA_LEFT) || (deathSprite->getPosX() + width > PLAY_AREA_RIGHT)) { // Restaura su posición if ((death_sprite_->getPosX() < PLAY_AREA_LEFT) || (death_sprite_->getPosX() + width_ > PLAY_AREA_RIGHT)) { // Restaura su posición
const float vx = deathSprite->getVelX(); const float VX = death_sprite_->getVelX();
deathSprite->setPosX(deathSprite->getPosX() - vx); death_sprite_->setPosX(death_sprite_->getPosX() - VX);
// Rebota // Rebota
deathSprite->setVelX(-vx); death_sprite_->setVelX(-VX);
} }
} }
} }
@@ -166,119 +166,119 @@ void Player::move() {
// Pinta el jugador en pantalla // Pinta el jugador en pantalla
void Player::render() { void Player::render() {
if (isAlive()) { if (isAlive()) {
if (invulnerable) { if (invulnerable_) {
if ((invulnerableCounter % 10) > 4) { if ((invulnerable_counter_ % 10) > 4) {
if (powerUp) { if (power_up_) {
fireSprite->render(); fire_sprite_->render();
} }
legsSprite->render(); legs_sprite_->render();
bodySprite->render(); body_sprite_->render();
headSprite->render(); head_sprite_->render();
} }
} else { } else {
if (powerUp) { if (power_up_) {
fireSprite->render(); fire_sprite_->render();
} }
legsSprite->render(); legs_sprite_->render();
bodySprite->render(); body_sprite_->render();
headSprite->render(); head_sprite_->render();
} }
} else { } else {
deathSprite->render(); death_sprite_->render();
} }
} }
// Establece el estado del jugador cuando camina // Establece el estado del jugador cuando camina
void Player::setWalkingStatus(Uint8 status) { void Player::setWalkingStatus(Uint8 status) {
statusWalking = status; status_walking_ = status;
} }
// Establece el estado del jugador cuando dispara // Establece el estado del jugador cuando dispara
void Player::setFiringStatus(Uint8 status) { void Player::setFiringStatus(Uint8 status) {
statusFiring = status; status_firing_ = status;
} }
// Establece la animación correspondiente al estado // Establece la animación correspondiente al estado
void Player::setAnimation() { void Player::setAnimation() {
// Crea cadenas de texto para componer el nombre de la animación // Crea cadenas de texto para componer el nombre de la animación
std::string aBodyCoffees; std::string body_coffees;
std::string aHeadCoffees; std::string head_coffees;
if (coffees > 0) { if (coffees_ > 0) {
aBodyCoffees = coffees == 1 ? "_1C" : "_2C"; body_coffees = coffees_ == 1 ? "_1C" : "_2C";
aHeadCoffees = "_1C"; head_coffees = "_1C";
} }
const std::string aPowerUp = powerUp ? "_pwr" : ""; const std::string POWER_UP = power_up_ ? "_pwr" : "";
const std::string aWalking = statusWalking == PLAYER_STATUS_WALKING_STOP ? "stand" : "walk"; const std::string WALKING = status_walking_ == STATUS_WALKING_STOP ? "stand" : "walk";
const std::string aFiring = statusFiring == PLAYER_STATUS_FIRING_UP ? "centershoot" : "sideshoot"; const std::string FIRING = status_firing_ == STATUS_FIRING_UP ? "centershoot" : "sideshoot";
const SDL_FlipMode flipWalk = statusWalking == PLAYER_STATUS_WALKING_RIGHT ? SDL_FLIP_HORIZONTAL : SDL_FLIP_NONE; const SDL_FlipMode FLIP_WALK = status_walking_ == STATUS_WALKING_RIGHT ? SDL_FLIP_HORIZONTAL : SDL_FLIP_NONE;
const SDL_FlipMode flipFire = statusFiring == PLAYER_STATUS_FIRING_RIGHT ? SDL_FLIP_HORIZONTAL : SDL_FLIP_NONE; const SDL_FlipMode FLIP_FIRE = status_firing_ == STATUS_FIRING_RIGHT ? SDL_FLIP_HORIZONTAL : SDL_FLIP_NONE;
// Establece la animación a partir de las cadenas // Establece la animación a partir de las cadenas
legsSprite->setCurrentAnimation(aWalking); legs_sprite_->setCurrentAnimation(WALKING);
legsSprite->setFlip(flipWalk); legs_sprite_->setFlip(FLIP_WALK);
if (statusFiring == PLAYER_STATUS_FIRING_NO) { // No esta disparando if (status_firing_ == STATUS_FIRING_NO) { // No esta disparando
bodySprite->setCurrentAnimation(aWalking + aBodyCoffees + aPowerUp); body_sprite_->setCurrentAnimation(WALKING + body_coffees + POWER_UP);
bodySprite->setFlip(flipWalk); body_sprite_->setFlip(FLIP_WALK);
headSprite->setCurrentAnimation(aWalking + aHeadCoffees + aPowerUp); head_sprite_->setCurrentAnimation(WALKING + head_coffees + POWER_UP);
headSprite->setFlip(flipWalk); head_sprite_->setFlip(FLIP_WALK);
} else { // Está disparando } else { // Está disparando
bodySprite->setCurrentAnimation(aFiring + aBodyCoffees + aPowerUp); body_sprite_->setCurrentAnimation(FIRING + body_coffees + POWER_UP);
bodySprite->setFlip(flipFire); body_sprite_->setFlip(FLIP_FIRE);
headSprite->setCurrentAnimation(aFiring + aHeadCoffees + aPowerUp); head_sprite_->setCurrentAnimation(FIRING + head_coffees + POWER_UP);
headSprite->setFlip(flipFire); head_sprite_->setFlip(FLIP_FIRE);
} }
// Actualiza las animaciones de los sprites // Actualiza las animaciones de los sprites
legsSprite->animate(); legs_sprite_->animate();
bodySprite->animate(); body_sprite_->animate();
headSprite->animate(); head_sprite_->animate();
fireSprite->animate(); fire_sprite_->animate();
fireSprite->setFlip(flipWalk); fire_sprite_->setFlip(FLIP_WALK);
} }
// Obtiene el valor de la variable // Obtiene el valor de la variable
auto Player::getPosX() const -> int { auto Player::getPosX() const -> int {
return int(posX); return int(pos_x_);
} }
// Obtiene el valor de la variable // Obtiene el valor de la variable
auto Player::getPosY() const -> int { auto Player::getPosY() const -> int {
return posY; return pos_y_;
} }
// Obtiene el valor de la variable // Obtiene el valor de la variable
auto Player::getWidth() const -> int { auto Player::getWidth() const -> int {
return width; return width_;
} }
// Obtiene el valor de la variable // Obtiene el valor de la variable
auto Player::getHeight() const -> int { auto Player::getHeight() const -> int {
return height; return height_;
} }
// Indica si el jugador puede disparar // Indica si el jugador puede disparar
auto Player::canFire() const -> bool { auto Player::canFire() const -> bool {
// Si el contador a llegado a cero, podemos disparar. En caso contrario decrementamos el contador // Si el contador a llegado a cero, podemos disparar. En caso contrario decrementamos el contador
return cooldown <= 0; return cooldown_ <= 0;
} }
// Establece el valor de la variable // Establece el valor de la variable
void Player::setFireCooldown(int time) { void Player::setFireCooldown(int time) {
cooldown = time; cooldown_ = time;
} }
// Actualiza el valor de la variable // Actualiza el valor de la variable
void Player::updateCooldown() { void Player::updateCooldown() {
if (cooldown > 0) { if (cooldown_ > 0) {
cooldown--; cooldown_--;
if (powerUp) { if (power_up_) {
cooldown--; cooldown_--;
} }
} else { } else {
setFiringStatus(PLAYER_STATUS_FIRING_NO); setFiringStatus(STATUS_FIRING_NO);
} }
} }
@@ -296,213 +296,213 @@ void Player::update() {
// Obtiene la puntuación del jugador // Obtiene la puntuación del jugador
auto Player::getScore() const -> Uint32 { auto Player::getScore() const -> Uint32 {
return score; return score_;
} }
// Asigna un valor a la puntuación del jugador // Asigna un valor a la puntuación del jugador
void Player::setScore(Uint32 score) { void Player::setScore(Uint32 score) {
this->score = score; this->score_ = score;
} }
// Incrementa la puntuación del jugador // Incrementa la puntuación del jugador
void Player::addScore(Uint32 score) { void Player::addScore(Uint32 score) {
this->score += score; this->score_ += score;
} }
// Obtiene el valor de la variable // Obtiene el valor de la variable
auto Player::isAlive() const -> bool { auto Player::isAlive() const -> bool {
return alive; return alive_;
} }
// Establece el valor de la variable // Establece el valor de la variable
void Player::setAlive(bool value) { void Player::setAlive(bool value) {
alive = value; alive_ = value;
if (!value) { if (!value) {
deathSprite->setPosX(headSprite->getRect().x); death_sprite_->setPosX(head_sprite_->getRect().x);
deathSprite->setPosY(headSprite->getRect().y); death_sprite_->setPosY(head_sprite_->getRect().y);
deathSprite->setAccelY(0.2F); death_sprite_->setAccelY(0.2F);
deathSprite->setVelY(-6.6F); death_sprite_->setVelY(-6.6F);
deathSprite->setVelX(3.3F); death_sprite_->setVelX(3.3F);
if (rand() % 2 == 0) { if (rand() % 2 == 0) {
deathSprite->setVelX(-3.3F); death_sprite_->setVelX(-3.3F);
} }
} }
} }
// Obtiene el valor de la variable // Obtiene el valor de la variable
auto Player::getScoreMultiplier() const -> float { auto Player::getScoreMultiplier() const -> float {
return scoreMultiplier; return score_multiplier_;
} }
// Establece el valor de la variable // Establece el valor de la variable
void Player::setScoreMultiplier(float value) { void Player::setScoreMultiplier(float value) {
scoreMultiplier = value; score_multiplier_ = value;
} }
// Aumenta el valor de la variable hasta un máximo // Aumenta el valor de la variable hasta un máximo
void Player::incScoreMultiplier() { void Player::incScoreMultiplier() {
if (scoreMultiplier < 5.0F) { if (score_multiplier_ < 5.0F) {
scoreMultiplier += 0.1F; score_multiplier_ += 0.1F;
} else { } else {
scoreMultiplier = 5.0F; score_multiplier_ = 5.0F;
} }
} }
// Decrementa el valor de la variable hasta un mínimo // Decrementa el valor de la variable hasta un mínimo
void Player::decScoreMultiplier() { void Player::decScoreMultiplier() {
if (scoreMultiplier > 1.0F) { if (score_multiplier_ > 1.0F) {
scoreMultiplier -= 0.1F; score_multiplier_ -= 0.1F;
} else { } else {
scoreMultiplier = 1.0F; score_multiplier_ = 1.0F;
} }
} }
// Obtiene el valor de la variable // Obtiene el valor de la variable
auto Player::isInvulnerable() const -> bool { auto Player::isInvulnerable() const -> bool {
return invulnerable; return invulnerable_;
} }
// Establece el valor de la variable // Establece el valor de la variable
void Player::setInvulnerable(bool value) { void Player::setInvulnerable(bool value) {
invulnerable = value; invulnerable_ = value;
} }
// Obtiene el valor de la variable // Obtiene el valor de la variable
auto Player::getInvulnerableCounter() const -> Uint16 { auto Player::getInvulnerableCounter() const -> Uint16 {
return invulnerableCounter; return invulnerable_counter_;
} }
// Establece el valor de la variable // Establece el valor de la variable
void Player::setInvulnerableCounter(Uint16 value) { void Player::setInvulnerableCounter(Uint16 value) {
invulnerableCounter = value; invulnerable_counter_ = value;
} }
// Actualiza el valor de la variable // Actualiza el valor de la variable
void Player::updateInvulnerableCounter() { void Player::updateInvulnerableCounter() {
if (invulnerable) { if (invulnerable_) {
if (invulnerableCounter > 0) { if (invulnerable_counter_ > 0) {
invulnerableCounter--; invulnerable_counter_--;
} else { } else {
invulnerable = false; invulnerable_ = false;
invulnerableCounter = PLAYER_INVULNERABLE_COUNTER; invulnerable_counter_ = INVULNERABLE_COUNTER;
} }
} }
} }
// Actualiza el valor de la variable // Actualiza el valor de la variable
void Player::updateDeathCounter() { void Player::updateDeathCounter() {
if (!alive) { if (!alive_) {
if (deathCounter > 0) { if (death_counter_ > 0) {
deathCounter--; death_counter_--;
} }
} }
} }
// Obtiene el valor de la variable // Obtiene el valor de la variable
auto Player::isPowerUp() const -> bool { auto Player::isPowerUp() const -> bool {
return powerUp; return power_up_;
} }
// Establece el valor de la variable // Establece el valor de la variable
void Player::setPowerUp(bool value) { void Player::setPowerUp(bool value) {
powerUp = value; power_up_ = value;
} }
// Obtiene el valor de la variable // Obtiene el valor de la variable
auto Player::getPowerUpCounter() const -> Uint16 { auto Player::getPowerUpCounter() const -> Uint16 {
return powerUpCounter; return power_up_counter_;
} }
// Establece el valor de la variable // Establece el valor de la variable
void Player::setPowerUpCounter(Uint16 value) { void Player::setPowerUpCounter(Uint16 value) {
powerUpCounter = value; power_up_counter_ = value;
} }
// Actualiza el valor de la variable // Actualiza el valor de la variable
void Player::updatePowerUpCounter() { void Player::updatePowerUpCounter() {
if ((powerUpCounter > 0) && (powerUp)) { if ((power_up_counter_ > 0) && (power_up_)) {
powerUpCounter--; power_up_counter_--;
} else { } else {
powerUp = false; power_up_ = false;
powerUpCounter = PLAYER_POWERUP_COUNTER; power_up_counter_ = POWERUP_COUNTER;
} }
} }
// Obtiene el valor de la variable // Obtiene el valor de la variable
auto Player::hasExtraHit() const -> bool { auto Player::hasExtraHit() const -> bool {
return extraHit; return extra_hit_;
} }
// Concede un toque extra al jugador // Concede un toque extra al jugador
void Player::giveExtraHit() { void Player::giveExtraHit() {
extraHit = true; extra_hit_ = true;
coffees++; coffees_++;
coffees = std::min<int>(coffees, 2); coffees_ = std::min<int>(coffees_, 2);
} }
// Quita el toque extra al jugador // Quita el toque extra al jugador
void Player::removeExtraHit() { void Player::removeExtraHit() {
if (coffees > 0) { if (coffees_ > 0) {
coffees--; coffees_--;
} }
if (coffees == 0) { if (coffees_ == 0) {
extraHit = false; extra_hit_ = false;
} }
invulnerable = true; invulnerable_ = true;
invulnerableCounter = PLAYER_INVULNERABLE_COUNTER; invulnerable_counter_ = INVULNERABLE_COUNTER;
} }
// Habilita la entrada de ordenes // Habilita la entrada de ordenes
void Player::enableInput() { void Player::enableInput() {
input = true; input_ = true;
} }
// Deshabilita la entrada de ordenes // Deshabilita la entrada de ordenes
void Player::disableInput() { void Player::disableInput() {
input = false; input_ = false;
} }
// Devuelve el numero de cafes actuales // Devuelve el numero de cafes actuales
auto Player::getCoffees() const -> Uint8 { auto Player::getCoffees() const -> Uint8 {
return coffees; return coffees_;
} }
// Obtiene el circulo de colisión // Obtiene el circulo de colisión
auto Player::getCollider() -> Circle & { auto Player::getCollider() -> Circle & {
return collider; return collider_;
} }
// Actualiza el circulo de colisión a la posición del jugador // Actualiza el circulo de colisión a la posición del jugador
void Player::shiftColliders() { void Player::shiftColliders() {
collider.x = int(posX + (width / 2)); collider_.x = int(pos_x_ + (width_ / 2));
collider.y = (posY + (height / 2)); collider_.y = (pos_y_ + (height_ / 2));
} }
// Obtiene el puntero a la textura con los gráficos de la animación de morir // Obtiene el puntero a la textura con los gráficos de la animación de morir
auto Player::getDeadTexture() -> Texture * { auto Player::getDeadTexture() -> Texture * {
return deathSprite->getTexture(); return death_sprite_->getTexture();
; ;
} }
// Obtiene el valor de la variable // Obtiene el valor de la variable
auto Player::getDeathCounter() const -> Uint16 { auto Player::getDeathCounter() const -> Uint16 {
return deathCounter; return death_counter_;
} }
// Actualiza el valor de la variable // Actualiza el valor de la variable
void Player::updatePowerUpHeadOffset() { void Player::updatePowerUpHeadOffset() {
if (!powerUp) { if (!power_up_) {
// powerUpHeadOffset = 0; // powerUpHeadOffset = 0;
} else { } else {
// powerUpHeadOffset = 96; // powerUpHeadOffset = 96;
if (powerUpCounter < 300) { if (power_up_counter_ < 300) {
if (powerUpCounter % 10 > 4) { if (power_up_counter_ % 10 > 4) {
// powerUpHeadOffset = 96; // powerUpHeadOffset = 96;
fireSprite->setEnabled(false); fire_sprite_->setEnabled(false);
} else { } else {
// powerUpHeadOffset = 0; // powerUpHeadOffset = 0;
fireSprite->setEnabled(true); fire_sprite_->setEnabled(true);
} }
} }
} }
@@ -510,9 +510,9 @@ void Player::updatePowerUpHeadOffset() {
// Pone las texturas del jugador // Pone las texturas del jugador
void Player::setPlayerTextures(const std::vector<Texture *> &texture) { void Player::setPlayerTextures(const std::vector<Texture *> &texture) {
headSprite->setTexture(texture[0]); head_sprite_->setTexture(texture[0]);
bodySprite->setTexture(texture[1]); body_sprite_->setTexture(texture[1]);
legsSprite->setTexture(texture[2]); legs_sprite_->setTexture(texture[2]);
deathSprite->setTexture(texture[3]); death_sprite_->setTexture(texture[3]);
fireSprite->setTexture(texture[4]); fire_sprite_->setTexture(texture[4]);
} }
+136 -220
View File
@@ -1,220 +1,136 @@
#pragma once #pragma once
#include <SDL3/SDL.h> #include <SDL3/SDL.h>
#include <string> // for string #include <string> // for string
#include <vector> // for vector #include <vector> // for vector
#include "utils/utils.h" // for Circle #include "utils/utils.h" // for Circle
class AnimatedSprite; class AnimatedSprite;
class Texture; class Texture;
// Contadores // Clase Player
constexpr int DEATH_COUNTER = 350; class Player {
public:
// Estados del jugador static constexpr int DEATH_COUNTER = 350; // Frames de la animación de muerte
constexpr int PLAYER_STATUS_WALKING_LEFT = 0;
constexpr int PLAYER_STATUS_WALKING_RIGHT = 1; Player(float x, int y, SDL_Renderer *renderer, const std::vector<Texture *> &texture, const std::vector<std::vector<std::string> *> &animations); // Constructor
constexpr int PLAYER_STATUS_WALKING_STOP = 2; ~Player(); // Destructor
constexpr int PLAYER_STATUS_FIRING_UP = 0; Player(const Player &) = delete;
constexpr int PLAYER_STATUS_FIRING_LEFT = 1; auto operator=(const Player &) -> Player & = delete;
constexpr int PLAYER_STATUS_FIRING_RIGHT = 2;
constexpr int PLAYER_STATUS_FIRING_NO = 3; void init(); // Iniciador
void update(); // Actualiza al jugador a su posicion, animación y controla los contadores
// Variables del jugador void render(); // Pinta el jugador en pantalla
constexpr int PLAYER_INVULNERABLE_COUNTER = 200; void move(); // Mueve el jugador a la posición y animación que le corresponde
constexpr int PLAYER_POWERUP_COUNTER = 1500;
void setPlayerTextures(const std::vector<Texture *> &texture); // Pone las texturas del jugador
// Clase Player void setInput(Uint8 input); // Actua en consecuencia de la entrada recibida
class Player { void setAnimation(); // Establece la animación correspondiente al estado
private:
// Objetos y punteros [[nodiscard]] auto getPosX() const -> int; // Obtiene el valor de la variable
SDL_Renderer *renderer; // El renderizador de la ventana [[nodiscard]] auto getPosY() const -> int; // Obtiene el valor de la variable
AnimatedSprite *headSprite; // Sprite para dibujar la cabeza [[nodiscard]] auto getWidth() const -> int; // Obtiene el valor de la variable
AnimatedSprite *bodySprite; // Sprite para dibujar el cuerpo [[nodiscard]] auto getHeight() const -> int; // Obtiene el valor de la variable
AnimatedSprite *legsSprite; // Sprite para dibujar las piernas
AnimatedSprite *deathSprite; // Sprite para dibujar el jugador derrotado [[nodiscard]] auto canFire() const -> bool; // Indica si el jugador puede disparar
AnimatedSprite *fireSprite; // Sprite para dibujar el aura del jugador con el poder a tope void setFireCooldown(int time); // Establece el valor de la variable
void updateCooldown(); // Actualiza el valor de la variable
// Variables
float posX; // Posicion en el eje X [[nodiscard]] auto getScore() const -> Uint32; // Obtiene la puntuación del jugador
int posY; // Posicion en el eje Y void setScore(Uint32 score); // Asigna un valor a la puntuación del jugador
void addScore(Uint32 score); // Incrementa la puntuación del jugador
Uint8 width; // Anchura
Uint8 height; // Altura [[nodiscard]] auto isAlive() const -> bool; // Obtiene el valor de la variable
void setAlive(bool value); // Establece el valor de la variable
float velX; // Cantidad de pixeles a desplazarse en el eje X
int velY; // Cantidad de pixeles a desplazarse en el eje Y [[nodiscard]] auto getScoreMultiplier() const -> float; // Obtiene el valor de la variable
void setScoreMultiplier(float value); // Establece el valor de la variable
float baseSpeed; // Velocidad base del jugador void incScoreMultiplier(); // Aumenta el valor de la variable hasta un máximo
int cooldown; // Contador durante el cual no puede disparar void decScoreMultiplier(); // Decrementa el valor de la variable hasta un mínimo
Uint32 score; // Puntos del jugador [[nodiscard]] auto isInvulnerable() const -> bool; // Obtiene el valor de la variable
float scoreMultiplier; // Multiplicador de puntos void setInvulnerable(bool value); // Establece el valor de la variable
[[nodiscard]] auto getInvulnerableCounter() const -> Uint16; // Obtiene el valor de la variable
Uint8 statusWalking; // Estado del jugador void setInvulnerableCounter(Uint16 value); // Establece el valor de la variable
Uint8 statusFiring; // Estado del jugador
[[nodiscard]] auto isPowerUp() const -> bool; // Obtiene el valor de la variable
bool alive; // Indica si el jugador está vivo void setPowerUp(bool value); // Establece el valor de la variable
Uint16 deathCounter; // Contador para la animación de morirse [[nodiscard]] auto getPowerUpCounter() const -> Uint16; // Obtiene el valor de la variable
bool invulnerable; // Indica si el jugador es invulnerable void setPowerUpCounter(Uint16 value); // Establece el valor de la variable
Uint16 invulnerableCounter; // Contador para la invulnerabilidad void updatePowerUpCounter(); // Actualiza el valor de la variable
bool extraHit; // Indica si el jugador tiene un toque extra
Uint8 coffees; // Indica cuantos cafes lleva acumulados [[nodiscard]] auto hasExtraHit() const -> bool; // Obtiene el valor de la variable
bool powerUp; // Indica si el jugador tiene activo el modo PowerUp void giveExtraHit(); // Concede un toque extra al jugador
Uint16 powerUpCounter; // Temporizador para el modo PowerUp void removeExtraHit(); // Quita el toque extra al jugador
bool input; // Indica si puede recibir ordenes de entrada
Circle collider; // Circulo de colisión del jugador void enableInput(); // Habilita la entrada de ordenes
void disableInput(); // Deshabilita la entrada de ordenes
// Actualiza el circulo de colisión a la posición del jugador
void shiftColliders(); [[nodiscard]] auto getCoffees() const -> Uint8; // Devuelve el numero de cafes actuales
auto getCollider() -> Circle &; // Obtiene el circulo de colisión
// Actualiza el valor de la variable auto getDeadTexture() -> Texture *; // Obtiene el puntero a la textura con los gráficos de la animación de morir
void updateInvulnerableCounter(); [[nodiscard]] auto getDeathCounter() const -> Uint16; // Obtiene el valor de la variable
// Actualiza el valor de la variable private:
void updateDeathCounter(); // Estados del jugador
static constexpr int STATUS_WALKING_LEFT = 0;
// Actualiza el valor de la variable static constexpr int STATUS_WALKING_RIGHT = 1;
void updatePowerUpHeadOffset(); static constexpr int STATUS_WALKING_STOP = 2;
public: static constexpr int STATUS_FIRING_UP = 0;
// Constructor static constexpr int STATUS_FIRING_LEFT = 1;
Player(float x, int y, SDL_Renderer *renderer, const std::vector<Texture *> &texture, const std::vector<std::vector<std::string> *> &animations); static constexpr int STATUS_FIRING_RIGHT = 2;
static constexpr int STATUS_FIRING_NO = 3;
// Destructor
~Player(); // Variables del jugador
static constexpr int INVULNERABLE_COUNTER = 200;
Player(const Player &) = delete; static constexpr int POWERUP_COUNTER = 1500;
auto operator=(const Player &) -> Player & = delete;
// Objetos y punteros
// Iniciador SDL_Renderer *renderer_; // El renderizador de la ventana
void init(); AnimatedSprite *head_sprite_; // Sprite para dibujar la cabeza
AnimatedSprite *body_sprite_; // Sprite para dibujar el cuerpo
// Actualiza al jugador a su posicion, animación y controla los contadores AnimatedSprite *legs_sprite_; // Sprite para dibujar las piernas
void update(); AnimatedSprite *death_sprite_; // Sprite para dibujar el jugador derrotado
AnimatedSprite *fire_sprite_; // Sprite para dibujar el aura del jugador con el poder a tope
// Pinta el jugador en pantalla
void render(); // Variables
float pos_x_; // Posicion en el eje X
// Pone las texturas del jugador int pos_y_; // Posicion en el eje Y
void setPlayerTextures(const std::vector<Texture *> &texture);
Uint8 width_; // Anchura
// Actua en consecuencia de la entrada recibida Uint8 height_; // Altura
void setInput(Uint8 input);
float vel_x_; // Cantidad de pixeles a desplazarse en el eje X
// Mueve el jugador a la posición y animación que le corresponde int vel_y_; // Cantidad de pixeles a desplazarse en el eje Y
void move();
float base_speed_; // Velocidad base del jugador
// Establece el estado del jugador int cooldown_; // Contador durante el cual no puede disparar
void setWalkingStatus(Uint8 status);
Uint32 score_; // Puntos del jugador
// Establece el estado del jugador float score_multiplier_; // Multiplicador de puntos
void setFiringStatus(Uint8 status);
Uint8 status_walking_; // Estado del jugador
// Establece la animación correspondiente al estado Uint8 status_firing_; // Estado del jugador
void setAnimation();
bool alive_; // Indica si el jugador está vivo
// Obtiene el valor de la variable Uint16 death_counter_; // Contador para la animación de morirse
[[nodiscard]] auto getPosX() const -> int; bool invulnerable_; // Indica si el jugador es invulnerable
Uint16 invulnerable_counter_; // Contador para la invulnerabilidad
// Obtiene el valor de la variable bool extra_hit_; // Indica si el jugador tiene un toque extra
[[nodiscard]] auto getPosY() const -> int; Uint8 coffees_; // Indica cuantos cafes lleva acumulados
bool power_up_; // Indica si el jugador tiene activo el modo PowerUp
// Obtiene el valor de la variable Uint16 power_up_counter_; // Temporizador para el modo PowerUp
[[nodiscard]] auto getWidth() const -> int; bool input_; // Indica si puede recibir ordenes de entrada
Circle collider_; // Circulo de colisión del jugador
// Obtiene el valor de la variable
[[nodiscard]] auto getHeight() const -> int; void setWalkingStatus(Uint8 status); // Establece el estado del jugador
void setFiringStatus(Uint8 status); // Establece el estado del jugador
// Indica si el jugador puede disparar
[[nodiscard]] auto canFire() const -> bool; void shiftColliders(); // Actualiza el circulo de colisión a la posición del jugador
void updateInvulnerableCounter(); // Actualiza el valor de la variable
// Establece el valor de la variable void updateDeathCounter(); // Actualiza el valor de la variable
void setFireCooldown(int time); void updatePowerUpHeadOffset(); // Actualiza el valor de la variable
};
// Actualiza el valor de la variable
void updateCooldown();
// Obtiene la puntuación del jugador
[[nodiscard]] auto getScore() const -> Uint32;
// Asigna un valor a la puntuación del jugador
void setScore(Uint32 score);
// Incrementa la puntuación del jugador
void addScore(Uint32 score);
// Obtiene el valor de la variable
[[nodiscard]] auto isAlive() const -> bool;
// Establece el valor de la variable
void setAlive(bool value);
// Obtiene el valor de la variable
[[nodiscard]] auto getScoreMultiplier() const -> float;
// Establece el valor de la variable
void setScoreMultiplier(float value);
// Aumenta el valor de la variable hasta un máximo
void incScoreMultiplier();
// Decrementa el valor de la variable hasta un mínimo
void decScoreMultiplier();
// Obtiene el valor de la variable
[[nodiscard]] auto isInvulnerable() const -> bool;
// Establece el valor de la variable
void setInvulnerable(bool value);
// Obtiene el valor de la variable
[[nodiscard]] auto getInvulnerableCounter() const -> Uint16;
// Establece el valor de la variable
void setInvulnerableCounter(Uint16 value);
// Obtiene el valor de la variable
[[nodiscard]] auto isPowerUp() const -> bool;
// Establece el valor de la variable
void setPowerUp(bool value);
// Obtiene el valor de la variable
[[nodiscard]] auto getPowerUpCounter() const -> Uint16;
// Establece el valor de la variable
void setPowerUpCounter(Uint16 value);
// Actualiza el valor de la variable
void updatePowerUpCounter();
// Obtiene el valor de la variable
[[nodiscard]] auto hasExtraHit() const -> bool;
// Concede un toque extra al jugador
void giveExtraHit();
// Quita el toque extra al jugador
void removeExtraHit();
// Habilita la entrada de ordenes
void enableInput();
// Deshabilita la entrada de ordenes
void disableInput();
// Devuelve el numero de cafes actuales
[[nodiscard]] auto getCoffees() const -> Uint8;
// Obtiene el circulo de colisión
auto getCollider() -> Circle &;
// Obtiene el puntero a la textura con los gráficos de la animación de morir
auto getDeadTexture() -> Texture *;
// Obtiene el valor de la variable
[[nodiscard]] auto getDeathCounter() const -> Uint16;
};
+33 -32
View File
@@ -23,9 +23,9 @@
#include "core/resources/resource.h" #include "core/resources/resource.h"
#include "game/defaults.hpp" // for PLAY_AREA_CENTER_X, BLOCK, PLAY_AREA_CEN... #include "game/defaults.hpp" // for PLAY_AREA_CENTER_X, BLOCK, PLAY_AREA_CEN...
#include "game/entities/balloon.h" // for Balloon, BALLOON_VELX_NEGATIVE, BALLOON_... #include "game/entities/balloon.h" // for Balloon, BALLOON_VELX_NEGATIVE, BALLOON_...
#include "game/entities/bullet.h" // for Bullet, BulletKind::LEFT, BulletKind::RIGHT, BULLE... #include "game/entities/bullet.h" // for Bullet, Bullet::Kind::LEFT, Bullet::Kind::RIGHT, BULLE...
#include "game/entities/item.h" // for Item, ITEM_COFFEE_MACHINE, ITEM_CLOCK #include "game/entities/item.h" // for Item
#include "game/entities/player.h" // for Player, DEATH_COUNTER #include "game/entities/player.h" // for Player
#include "game/options.hpp" // for Options #include "game/options.hpp" // for Options
#include "game/ui/menu.h" // for Menu #include "game/ui/menu.h" // for Menu
struct JA_Sound_t; struct JA_Sound_t;
@@ -190,7 +190,7 @@ void Game::init() {
menaceThreshold = 0; menaceThreshold = 0;
hiScoreAchieved = false; hiScoreAchieved = false;
stageBitmapCounter = STAGE_COUNTER; stageBitmapCounter = STAGE_COUNTER;
deathCounter = DEATH_COUNTER; deathCounter = Player::DEATH_COUNTER;
timeStopped = false; timeStopped = false;
timeStoppedCounter = 0; timeStoppedCounter = 0;
counter = 0; counter = 0;
@@ -1801,34 +1801,34 @@ void Game::checkPlayerItemCollision(Player *player) {
for (auto *item : items) { for (auto *item : items) {
if (item->isEnabled()) { if (item->isEnabled()) {
if (checkCollision(player->getCollider(), item->getCollider())) { if (checkCollision(player->getCollider(), item->getCollider())) {
switch (item->getClass()) { switch (item->getId()) {
case ITEM_POINTS_1_DISK: case Item::Id::DISK:
player->addScore(1000); player->addScore(1000);
updateHiScore(); updateHiScore();
createItemScoreSprite(item->getPosX() + (item->getWidth() / 2) - (n1000Sprite->getWidth() / 2), player->getPosY(), n1000Sprite); createItemScoreSprite(item->getPosX() + (item->getWidth() / 2) - (n1000Sprite->getWidth() / 2), player->getPosY(), n1000Sprite);
Audio::get()->playSound(itemPickUpSound); Audio::get()->playSound(itemPickUpSound);
break; break;
case ITEM_POINTS_2_GAVINA: case Item::Id::GAVINA:
player->addScore(2500); player->addScore(2500);
updateHiScore(); updateHiScore();
createItemScoreSprite(item->getPosX() + (item->getWidth() / 2) - (n2500Sprite->getWidth() / 2), player->getPosY(), n2500Sprite); createItemScoreSprite(item->getPosX() + (item->getWidth() / 2) - (n2500Sprite->getWidth() / 2), player->getPosY(), n2500Sprite);
Audio::get()->playSound(itemPickUpSound); Audio::get()->playSound(itemPickUpSound);
break; break;
case ITEM_POINTS_3_PACMAR: case Item::Id::PACMAR:
player->addScore(5000); player->addScore(5000);
updateHiScore(); updateHiScore();
createItemScoreSprite(item->getPosX() + (item->getWidth() / 2) - (n5000Sprite->getWidth() / 2), player->getPosY(), n5000Sprite); createItemScoreSprite(item->getPosX() + (item->getWidth() / 2) - (n5000Sprite->getWidth() / 2), player->getPosY(), n5000Sprite);
Audio::get()->playSound(itemPickUpSound); Audio::get()->playSound(itemPickUpSound);
break; break;
case ITEM_CLOCK: case Item::Id::CLOCK:
enableTimeStopItem(); enableTimeStopItem();
Audio::get()->playSound(itemPickUpSound); Audio::get()->playSound(itemPickUpSound);
break; break;
case ITEM_COFFEE: case Item::Id::COFFEE:
if (player->getCoffees() == 2) { if (player->getCoffees() == 2) {
player->addScore(5000); player->addScore(5000);
updateHiScore(); updateHiScore();
@@ -1838,7 +1838,7 @@ void Game::checkPlayerItemCollision(Player *player) {
Audio::get()->playSound(itemPickUpSound); Audio::get()->playSound(itemPickUpSound);
break; break;
case ITEM_COFFEE_MACHINE: case Item::Id::COFFEE_MACHINE:
player->setPowerUp(true); player->setPowerUp(true);
Audio::get()->playSound(itemPickUpSound); Audio::get()->playSound(itemPickUpSound);
coffeeMachineEnabled = false; coffeeMachineEnabled = false;
@@ -1878,9 +1878,9 @@ void Game::checkBulletBalloonCollision() {
bullet->disable(); bullet->disable();
// Suelta el item en caso de que salga uno // Suelta el item en caso de que salga uno
const Uint8 droppeditem = dropItem(); const Item::Id droppeditem = dropItem();
if ((droppeditem != NO_KIND) && !(demo.enabled) && !(demo.recording)) { if ((droppeditem != Item::Id::NONE) && !(demo.enabled) && !(demo.recording)) {
if (droppeditem != ITEM_COFFEE_MACHINE) { if (droppeditem != Item::Id::COFFEE_MACHINE) {
createItem(droppeditem, balloon->getPosX(), balloon->getPosY()); createItem(droppeditem, balloon->getPosX(), balloon->getPosY());
Audio::get()->playSound(itemDropSound); Audio::get()->playSound(itemDropSound);
} else { } else {
@@ -1900,7 +1900,7 @@ void Game::checkBulletBalloonCollision() {
void Game::moveBullets() { void Game::moveBullets() {
for (auto *bullet : bullets) { for (auto *bullet : bullets) {
if (bullet->isEnabled()) { if (bullet->isEnabled()) {
if (bullet->move() == BULLET_MOVE_OUT) { if (bullet->move() == Bullet::MoveResult::OUT) {
players[bullet->getOwner()]->decScoreMultiplier(); players[bullet->getOwner()]->decScoreMultiplier();
} }
} }
@@ -1917,7 +1917,7 @@ void Game::renderBullets() {
} }
// Crea un objeto bala // Crea un objeto bala
void Game::createBullet(int x, int y, BulletKind kind, bool poweredUp, int owner) { void Game::createBullet(int x, int y, Bullet::Kind kind, bool poweredUp, int owner) {
auto *b = new Bullet(x, y, kind, poweredUp, owner, bulletTexture, renderer); auto *b = new Bullet(x, y, kind, poweredUp, owner, bulletTexture, renderer);
bullets.push_back(b); bullets.push_back(b);
} }
@@ -1955,39 +1955,39 @@ void Game::renderItems() {
} }
// Devuelve un item en función del azar // Devuelve un item en función del azar
auto Game::dropItem() -> Uint8 { auto Game::dropItem() -> Item::Id {
const Uint8 luckyNumber = rand() % 100; const Uint8 luckyNumber = rand() % 100;
const Uint8 item = rand() % 6; const Uint8 item = rand() % 6;
switch (item) { switch (item) {
case 0: case 0:
if (luckyNumber < helper.itemPoints1Odds) { if (luckyNumber < helper.itemPoints1Odds) {
return ITEM_POINTS_1_DISK; return Item::Id::DISK;
} }
break; break;
case 1: case 1:
if (luckyNumber < helper.itemPoints2Odds) { if (luckyNumber < helper.itemPoints2Odds) {
return ITEM_POINTS_2_GAVINA; return Item::Id::GAVINA;
} }
break; break;
case 2: case 2:
if (luckyNumber < helper.itemPoints3Odds) { if (luckyNumber < helper.itemPoints3Odds) {
return ITEM_POINTS_3_PACMAR; return Item::Id::PACMAR;
} }
break; break;
case 3: case 3:
if (luckyNumber < helper.itemClockOdds) { if (luckyNumber < helper.itemClockOdds) {
return ITEM_CLOCK; return Item::Id::CLOCK;
} }
break; break;
case 4: case 4:
if (luckyNumber < helper.itemCoffeeOdds) { if (luckyNumber < helper.itemCoffeeOdds) {
helper.itemCoffeeOdds = ITEM_COFFEE_ODDS; helper.itemCoffeeOdds = ITEM_COFFEE_ODDS;
return ITEM_COFFEE; return Item::Id::COFFEE;
} else { } else {
if (helper.needCoffee) { if (helper.needCoffee) {
helper.itemCoffeeOdds++; helper.itemCoffeeOdds++;
@@ -1999,7 +1999,7 @@ auto Game::dropItem() -> Uint8 {
if (luckyNumber < helper.itemCoffeeMachineOdds) { if (luckyNumber < helper.itemCoffeeMachineOdds) {
helper.itemCoffeeMachineOdds = ITEM_COFFEE_MACHINE_ODDS; helper.itemCoffeeMachineOdds = ITEM_COFFEE_MACHINE_ODDS;
if ((!coffeeMachineEnabled) && (helper.needCoffeeMachine)) { if ((!coffeeMachineEnabled) && (helper.needCoffeeMachine)) {
return ITEM_COFFEE_MACHINE; return Item::Id::COFFEE_MACHINE;
} }
} else { } else {
if (helper.needCoffeeMachine) { if (helper.needCoffeeMachine) {
@@ -2012,12 +2012,13 @@ auto Game::dropItem() -> Uint8 {
break; break;
} }
return NO_KIND; return Item::Id::NONE;
} }
// Crea un objeto item // Crea un objeto item
void Game::createItem(Uint8 kind, float x, float y) { void Game::createItem(Item::Id kind, float x, float y) {
Item *item = new Item(kind, x, y, itemTextures[kind - 1], itemAnimations[kind - 1], renderer); const auto index = static_cast<std::size_t>(kind) - 1;
Item *item = new Item(kind, x, y, itemTextures[index], itemAnimations[index], renderer);
items.push_back(item); items.push_back(item);
} }
@@ -2474,7 +2475,7 @@ void Game::checkGameInput() {
if (demo.dataFile[demo.counter].fire == 1) { if (demo.dataFile[demo.counter].fire == 1) {
if (players[index]->canFire()) { if (players[index]->canFire()) {
players[index]->setInput(input_fire_center); players[index]->setInput(input_fire_center);
createBullet(players[index]->getPosX() + (players[index]->getWidth() / 2) - 4, players[index]->getPosY() + (players[index]->getHeight() / 2), BulletKind::UP, players[index]->isPowerUp(), index); createBullet(players[index]->getPosX() + (players[index]->getWidth() / 2) - 4, players[index]->getPosY() + (players[index]->getHeight() / 2), Bullet::Kind::UP, players[index]->isPowerUp(), index);
players[index]->setFireCooldown(10); players[index]->setFireCooldown(10);
} }
} }
@@ -2482,7 +2483,7 @@ void Game::checkGameInput() {
if (demo.dataFile[demo.counter].fireLeft == 1) { if (demo.dataFile[demo.counter].fireLeft == 1) {
if (players[index]->canFire()) { if (players[index]->canFire()) {
players[index]->setInput(input_fire_left); players[index]->setInput(input_fire_left);
createBullet(players[index]->getPosX() + (players[index]->getWidth() / 2) - 4, players[index]->getPosY() + (players[index]->getHeight() / 2), BulletKind::LEFT, players[index]->isPowerUp(), index); createBullet(players[index]->getPosX() + (players[index]->getWidth() / 2) - 4, players[index]->getPosY() + (players[index]->getHeight() / 2), Bullet::Kind::LEFT, players[index]->isPowerUp(), index);
players[index]->setFireCooldown(10); players[index]->setFireCooldown(10);
} }
} }
@@ -2490,7 +2491,7 @@ void Game::checkGameInput() {
if (demo.dataFile[demo.counter].fireRight == 1) { if (demo.dataFile[demo.counter].fireRight == 1) {
if (players[index]->canFire()) { if (players[index]->canFire()) {
players[index]->setInput(input_fire_right); players[index]->setInput(input_fire_right);
createBullet(players[index]->getPosX() + (players[index]->getWidth() / 2) - 4, players[index]->getPosY() + (players[index]->getHeight() / 2), BulletKind::RIGHT, players[index]->isPowerUp(), index); createBullet(players[index]->getPosX() + (players[index]->getWidth() / 2) - 4, players[index]->getPosY() + (players[index]->getHeight() / 2), Bullet::Kind::RIGHT, players[index]->isPowerUp(), index);
players[index]->setFireCooldown(10); players[index]->setFireCooldown(10);
} }
} }
@@ -2532,7 +2533,7 @@ void Game::checkGameInput() {
if (Input::get()->checkInput(input_fire_center, REPEAT_TRUE, Options::inputs[i].deviceType, Options::inputs[i].id)) { if (Input::get()->checkInput(input_fire_center, REPEAT_TRUE, Options::inputs[i].deviceType, Options::inputs[i].id)) {
if (player->canFire()) { if (player->canFire()) {
player->setInput(input_fire_center); player->setInput(input_fire_center);
createBullet(player->getPosX() + (player->getWidth() / 2) - 4, player->getPosY() + (player->getHeight() / 2), BulletKind::UP, player->isPowerUp(), i); createBullet(player->getPosX() + (player->getWidth() / 2) - 4, player->getPosY() + (player->getHeight() / 2), Bullet::Kind::UP, player->isPowerUp(), i);
player->setFireCooldown(10); player->setFireCooldown(10);
// Reproduce el sonido de disparo // Reproduce el sonido de disparo
@@ -2546,7 +2547,7 @@ void Game::checkGameInput() {
if (Input::get()->checkInput(input_fire_left, REPEAT_TRUE, Options::inputs[i].deviceType, Options::inputs[i].id)) { if (Input::get()->checkInput(input_fire_left, REPEAT_TRUE, Options::inputs[i].deviceType, Options::inputs[i].id)) {
if (player->canFire()) { if (player->canFire()) {
player->setInput(input_fire_left); player->setInput(input_fire_left);
createBullet(player->getPosX() + (player->getWidth() / 2) - 4, player->getPosY() + (player->getHeight() / 2), BulletKind::LEFT, player->isPowerUp(), i); createBullet(player->getPosX() + (player->getWidth() / 2) - 4, player->getPosY() + (player->getHeight() / 2), Bullet::Kind::LEFT, player->isPowerUp(), i);
player->setFireCooldown(10); player->setFireCooldown(10);
// Reproduce el sonido de disparo // Reproduce el sonido de disparo
@@ -2560,7 +2561,7 @@ void Game::checkGameInput() {
if (Input::get()->checkInput(input_fire_right, REPEAT_TRUE, Options::inputs[i].deviceType, Options::inputs[i].id)) { if (Input::get()->checkInput(input_fire_right, REPEAT_TRUE, Options::inputs[i].deviceType, Options::inputs[i].id)) {
if (player->canFire()) { if (player->canFire()) {
player->setInput(input_fire_right); player->setInput(input_fire_right);
createBullet(player->getPosX() + (player->getWidth() / 2) - 4, player->getPosY() + (player->getHeight() / 2), BulletKind::RIGHT, player->isPowerUp(), i); createBullet(player->getPosX() + (player->getWidth() / 2) - 4, player->getPosY() + (player->getHeight() / 2), Bullet::Kind::RIGHT, player->isPowerUp(), i);
player->setFireCooldown(10); player->setFireCooldown(10);
// Reproduce el sonido de disparo // Reproduce el sonido de disparo
+50 -51
View File
@@ -6,12 +6,11 @@
#include <string> // for string, basic_string #include <string> // for string, basic_string
#include <vector> // for vector #include <vector> // for vector
#include "game/entities/bullet.h" // for BulletKind (signatura de createBullet) #include "game/entities/bullet.h" // for Bullet::Kind (signatura de createBullet)
#include "game/entities/item.h" // for Item::Id (signatura de dropItem/createItem)
#include "utils/utils.h" // for DemoKeys, Color #include "utils/utils.h" // for DemoKeys, Color
class Balloon; class Balloon;
class Bullet;
class Fade; class Fade;
class Item;
class Menu; class Menu;
class MovingSprite; class MovingSprite;
class Player; class Player;
@@ -62,7 +61,7 @@ class Game {
struct EnemyFormation // Contiene la información de una formación enemiga struct EnemyFormation // Contiene la información de una formación enemiga
{ {
Uint8 numberOfEnemies; // Cantidad de enemigos que forman la formación Uint8 numberOfEnemies; // Cantidad de enemigos que forman la formación
EnemyInit init[MAX_NUMBER_OF_ENEMIES_IN_A_FORMATION]; // Vector con todas las inicializaciones de los enemigos de la formación EnemyInit init[MAX_NUMBER_OF_ENEMIES_IN_A_FORMATION]; // Vector con todas las inicializaciones de los enemigos de la formación
}; };
@@ -72,7 +71,7 @@ class Game {
struct Stage // Contiene todas las variables relacionadas con una fase struct Stage // Contiene todas las variables relacionadas con una fase
{ {
EnemyPool *enemyPool; // El conjunto de formaciones enemigas de la fase EnemyPool *enemyPool; // El conjunto de formaciones enemigas de la fase
Uint16 currentPower; // Cantidad actual de poder Uint16 currentPower; // Cantidad actual de poder
Uint16 powerToComplete; // Cantidad de poder que se necesita para completar la fase Uint16 powerToComplete; // Cantidad de poder que se necesita para completar la fase
Uint8 maxMenace; // Umbral máximo de amenaza de la fase Uint8 maxMenace; // Umbral máximo de amenaza de la fase
@@ -120,16 +119,16 @@ class Game {
}; };
struct Demo { struct Demo {
bool enabled; // Indica si está activo el modo demo bool enabled; // Indica si está activo el modo demo
bool recording; // Indica si está activado el modo para grabar la demo bool recording; // Indica si está activado el modo para grabar la demo
Uint16 counter; // Contador para el modo demo Uint16 counter; // Contador para el modo demo
DemoKeys keys; // Variable con las pulsaciones de teclas del modo demo DemoKeys keys; // Variable con las pulsaciones de teclas del modo demo
DemoKeys dataFile[TOTAL_DEMO_DATA]; // Datos del fichero con los movimientos para la demo DemoKeys dataFile[TOTAL_DEMO_DATA]; // Datos del fichero con los movimientos para la demo
}; };
// Objetos y punteros // Objetos y punteros
SDL_Renderer *renderer; // El renderizador de la ventana SDL_Renderer *renderer; // El renderizador de la ventana
Section *section; // Seccion actual dentro del juego Section *section; // Seccion actual dentro del juego
std::vector<Player *> players; // Vector con los jugadores std::vector<Player *> players; // Vector con los jugadores
std::vector<Balloon *> balloons; // Vector con los globos std::vector<Balloon *> balloons; // Vector con los globos
@@ -203,54 +202,54 @@ class Game {
JA_Music_t *gameMusic; // Musica de fondo JA_Music_t *gameMusic; // Musica de fondo
// Variables // Variables
int numPlayers; // Numero de jugadores int numPlayers; // Numero de jugadores
Uint32 ticks; // Contador de ticks para ajustar la velocidad del programa Uint32 ticks; // Contador de ticks para ajustar la velocidad del programa
Uint8 ticksSpeed; // Velocidad a la que se repiten los bucles del programa Uint8 ticksSpeed; // Velocidad a la que se repiten los bucles del programa
Uint32 hiScore; // Puntuación máxima Uint32 hiScore; // Puntuación máxima
bool hiScoreAchieved; // Indica si se ha superado la puntuación máxima bool hiScoreAchieved; // Indica si se ha superado la puntuación máxima
std::string hiScoreName; // Nombre del jugador que ostenta la máxima puntuación std::string hiScoreName; // Nombre del jugador que ostenta la máxima puntuación
Stage stage[10]; // Variable con los datos de cada pantalla Stage stage[10]; // Variable con los datos de cada pantalla
Uint8 currentStage; // Indica la fase actual Uint8 currentStage; // Indica la fase actual
Uint8 stageBitmapCounter; // Contador para el tiempo visible del texto de Stage Uint8 stageBitmapCounter; // Contador para el tiempo visible del texto de Stage
float stageBitmapPath[STAGE_COUNTER]; // Vector con los puntos Y por donde se desplaza el texto float stageBitmapPath[STAGE_COUNTER]; // Vector con los puntos Y por donde se desplaza el texto
float getReadyBitmapPath[STAGE_COUNTER]; // Vector con los puntos X por donde se desplaza el texto float getReadyBitmapPath[STAGE_COUNTER]; // Vector con los puntos X por donde se desplaza el texto
Uint16 deathCounter; // Contador para la animación de muerte del jugador Uint16 deathCounter; // Contador para la animación de muerte del jugador
Uint8 menaceCurrent; // Nivel de amenaza actual Uint8 menaceCurrent; // Nivel de amenaza actual
Uint8 menaceThreshold; // 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 numero de globos Uint8 menaceThreshold; // 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 numero de globos
bool timeStopped; // Indica si el tiempo está detenido bool timeStopped; // Indica si el tiempo está detenido
Uint16 timeStoppedCounter; // Temporizador para llevar la cuenta del tiempo detenido Uint16 timeStoppedCounter; // Temporizador para llevar la cuenta del tiempo detenido
Uint32 counter; // Contador para el juego Uint32 counter; // Contador para el juego
Uint32 scoreDataFile[TOTAL_SCORE_DATA]; // Datos del fichero de puntos Uint32 scoreDataFile[TOTAL_SCORE_DATA]; // Datos del fichero de puntos
SDL_Rect skyColorsRect[4]; // Vector con las coordenadas de los 4 colores de cielo SDL_Rect skyColorsRect[4]; // Vector con las coordenadas de los 4 colores de cielo
Uint16 balloonsPopped; // Lleva la cuenta de los globos explotados Uint16 balloonsPopped; // Lleva la cuenta de los globos explotados
Uint8 lastEnemyDeploy; // Guarda cual ha sido la última formación desplegada para no repetir; Uint8 lastEnemyDeploy; // Guarda cual ha sido la última formación desplegada para no repetir;
int enemyDeployCounter; // Cuando se lanza una formación, se le da un valor y no sale otra hasta que llegue a cero int enemyDeployCounter; // Cuando se lanza una formación, se le da un valor y no sale otra hasta que llegue a cero
float enemySpeed; // Velocidad a la que se mueven los enemigos float enemySpeed; // Velocidad a la que se mueven los enemigos
float defaultEnemySpeed; // Velocidad base de los enemigos, sin incrementar float defaultEnemySpeed; // Velocidad base de los enemigos, sin incrementar
Effect effect; // Variable para gestionar los efectos visuales Effect effect; // Variable para gestionar los efectos visuales
DeathShake deathShake; // Variable para gestionar el efecto de agitación intensa DeathShake deathShake; // Variable para gestionar el efecto de agitación intensa
DeathSequence deathSequence; // Variable para gestionar la secuencia de muerte DeathSequence deathSequence; // Variable para gestionar la secuencia de muerte
Helper helper; // Variable para gestionar las ayudas Helper helper; // Variable para gestionar las ayudas
bool powerBallEnabled; // Indica si hay una powerball ya activa bool powerBallEnabled; // Indica si hay una powerball ya activa
Uint8 powerBallCounter; // Contador de formaciones enemigas entre la aparicion de una PowerBall y otra Uint8 powerBallCounter; // Contador de formaciones enemigas entre la aparicion de una PowerBall y otra
bool coffeeMachineEnabled; // Indica si hay una máquina de café en el terreno de juego bool coffeeMachineEnabled; // Indica si hay una máquina de café en el terreno de juego
bool gameCompleted; // Indica si se ha completado la partida, llegando al final de la ultima pantalla bool gameCompleted; // Indica si se ha completado la partida, llegando al final de la ultima pantalla
int gameCompletedCounter; // Contador para el tramo final, cuando se ha completado la partida y ya no aparecen más enemigos int gameCompletedCounter; // Contador para el tramo final, cuando se ha completado la partida y ya no aparecen más enemigos
Uint8 difficulty; // Dificultad del juego Uint8 difficulty; // Dificultad del juego
float difficultyScoreMultiplier; // Multiplicador de puntos en función de la dificultad float difficultyScoreMultiplier; // Multiplicador de puntos en función de la dificultad
Color difficultyColor; // Color asociado a la dificultad Color difficultyColor; // Color asociado a la dificultad
Uint8 onePlayerControl; // Variable para almacenar el valor de las opciones Uint8 onePlayerControl; // Variable para almacenar el valor de las opciones
EnemyFormation enemyFormation[NUMBER_OF_ENEMY_FORMATIONS]; // Vector con todas las formaciones enemigas EnemyFormation enemyFormation[NUMBER_OF_ENEMY_FORMATIONS]; // Vector con todas las formaciones enemigas
EnemyPool enemyPool[10]; // Variable con los diferentes conjuntos de formaciones enemigas EnemyPool enemyPool[10]; // Variable con los diferentes conjuntos de formaciones enemigas
Uint8 lastStageReached; // Contiene el numero de la última pantalla que se ha alcanzado Uint8 lastStageReached; // Contiene el numero de la última pantalla que se ha alcanzado
Demo demo; // Variable con todas las variables relacionadas con el modo demo Demo demo; // Variable con todas las variables relacionadas con el modo demo
int totalPowerToCompleteGame; // La suma del poder necesario para completar todas las fases int totalPowerToCompleteGame; // La suma del poder necesario para completar todas las fases
int cloudsSpeed{0}; // Velocidad a la que se desplazan las nubes int cloudsSpeed{0}; // Velocidad a la que se desplazan las nubes
int pauseCounter; // Contador para salir del menu de pausa y volver al juego int pauseCounter; // Contador para salir del menu de pausa y volver al juego
bool leavingPauseMenu; // Indica si esta saliendo del menu de pausa para volver al juego bool leavingPauseMenu; // Indica si esta saliendo del menu de pausa para volver al juego
bool pauseInitialized; // Indica si la pausa ha sido inicializada bool pauseInitialized; // Indica si la pausa ha sido inicializada
bool gameOverInitialized; // Indica si el game over ha sido inicializado bool gameOverInitialized; // Indica si el game over ha sido inicializado
int gameOverPostFade; // Opción a realizar cuando termina el fundido del game over int gameOverPostFade; // Opción a realizar cuando termina el fundido del game over
#ifdef PAUSE #ifdef PAUSE
bool pause; bool pause;
#endif #endif
@@ -376,7 +375,7 @@ class Game {
void renderBullets(); void renderBullets();
// Crea un objeto bala // Crea un objeto bala
void createBullet(int x, int y, BulletKind kind, bool poweredUp, int owner); void createBullet(int x, int y, Bullet::Kind kind, bool poweredUp, int owner);
// Vacia el vector de balas // Vacia el vector de balas
void freeBullets(); void freeBullets();
@@ -388,10 +387,10 @@ class Game {
void renderItems(); void renderItems();
// Devuelve un item en función del azar // Devuelve un item en función del azar
auto dropItem() -> Uint8; auto dropItem() -> Item::Id;
// Crea un objeto item // Crea un objeto item
void createItem(Uint8 kind, float x, float y); void createItem(Item::Id kind, float x, float y);
// Vacia el vector de items // Vacia el vector de items
void freeItems(); void freeItems();
+113 -113
View File
@@ -21,50 +21,50 @@
// Constructor // Constructor
Instructions::Instructions(SDL_Renderer *renderer, Section *section) { Instructions::Instructions(SDL_Renderer *renderer, Section *section) {
// Copia los punteros // Copia los punteros
this->renderer = renderer; this->renderer_ = renderer;
this->section = section; this->section_ = section;
// Texturas (handles compartidos de Resource) // Texturas (handles compartidos de Resource)
Resource *R = Resource::get(); Resource *resource = Resource::get();
itemTextures.push_back(R->getTexture("item_points1_disk.png")); item_textures_.push_back(resource->getTexture("item_points1_disk.png"));
itemTextures.push_back(R->getTexture("item_points2_gavina.png")); item_textures_.push_back(resource->getTexture("item_points2_gavina.png"));
itemTextures.push_back(R->getTexture("item_points3_pacmar.png")); item_textures_.push_back(resource->getTexture("item_points3_pacmar.png"));
itemTextures.push_back(R->getTexture("item_clock.png")); item_textures_.push_back(resource->getTexture("item_clock.png"));
itemTextures.push_back(R->getTexture("item_coffee.png")); item_textures_.push_back(resource->getTexture("item_coffee.png"));
itemTextures.push_back(R->getTexture("item_coffee_machine.png")); item_textures_.push_back(resource->getTexture("item_coffee_machine.png"));
eventHandler = new SDL_Event(); event_handler_ = new SDL_Event();
sprite = new Sprite(0, 0, 16, 16, itemTextures[0], renderer); sprite_ = new Sprite(0, 0, 16, 16, item_textures_[0], renderer);
text = R->getText("smb2"); text_ = resource->getText("smb2");
// Crea un backbuffer para el renderizador // Crea un backbuffer para el renderizador
backbuffer = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, GAMECANVAS_WIDTH, GAMECANVAS_HEIGHT); backbuffer_ = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, GAMECANVAS_WIDTH, GAMECANVAS_HEIGHT);
if (backbuffer != nullptr) { if (backbuffer_ != nullptr) {
SDL_SetTextureScaleMode(backbuffer, Texture::currentScaleMode); SDL_SetTextureScaleMode(backbuffer_, Texture::currentScaleMode);
} else { } else {
std::cout << "Error: textTexture could not be created!\nSDL Error: " << SDL_GetError() << '\n'; std::cout << "Error: textTexture could not be created!\nSDL Error: " << SDL_GetError() << '\n';
} }
// Inicializa variables // Inicializa variables
ticks = 0; ticks_ = 0;
ticksSpeed = 15; ticks_speed_ = 15;
manualQuit = false; manual_quit_ = false;
counter = 0; counter_ = 0;
counterEnd = 600; counter_end_ = 600;
finished = false; finished_ = false;
quitRequested = false; quit_requested_ = false;
} }
// Destructor // Destructor
Instructions::~Instructions() { Instructions::~Instructions() {
// itemTextures y text son propiedad de Resource — no liberar. // itemTextures y text son propiedad de Resource — no liberar.
itemTextures.clear(); item_textures_.clear();
delete sprite; delete sprite_;
delete eventHandler; delete event_handler_;
SDL_DestroyTexture(backbuffer); SDL_DestroyTexture(backbuffer_);
} }
// Actualiza las variables // Actualiza las variables
@@ -77,21 +77,21 @@ void Instructions::update() {
checkInput(); checkInput();
// Actualiza las variables // Actualiza las variables
if (SDL_GetTicks() - ticks > ticksSpeed) { if (SDL_GetTicks() - ticks_ > ticks_speed_) {
// Actualiza el contador de ticks // Actualiza el contador de ticks
ticks = SDL_GetTicks(); ticks_ = SDL_GetTicks();
if (mode == m_auto) { // Modo automático if (mode_ == Mode::AUTO) { // Modo automático
counter++; counter_++;
if (counter == counterEnd) { if (counter_ == counter_end_) {
finished = true; finished_ = true;
} }
} else { // Modo manual } else { // Modo manual
++counter %= 60000; ++counter_ %= 60000;
if (manualQuit) { if (manual_quit_) {
finished = true; finished_ = true;
} }
} }
} }
@@ -101,76 +101,76 @@ void Instructions::update() {
void Instructions::render() { void Instructions::render() {
// Pinta en pantalla // Pinta en pantalla
SDL_Rect window = {0, 0, GAMECANVAS_WIDTH, GAMECANVAS_HEIGHT}; SDL_Rect window = {0, 0, GAMECANVAS_WIDTH, GAMECANVAS_HEIGHT};
SDL_Rect srcRect = {0, 0, 16, 16}; SDL_Rect src_rect = {0, 0, 16, 16};
const Color orangeColor = {0xFF, 0x7A, 0x00}; const Color ORANGE_COLOR = {0xFF, 0x7A, 0x00};
const SDL_Rect destRect1 = {60, 88 + (16 * 0), 16, 16}; // Disquito const SDL_Rect DEST_RECT1 = {60, 88 + (16 * 0), 16, 16}; // Disquito
const SDL_Rect destRect2 = {60, 88 + (16 * 1), 16, 16}; // Gavineixon const SDL_Rect DEST_RECT2 = {60, 88 + (16 * 1), 16, 16}; // Gavineixon
const SDL_Rect destRect3 = {60, 88 + (16 * 2), 16, 16}; // Pacmar const SDL_Rect DEST_RECT3 = {60, 88 + (16 * 2), 16, 16}; // Pacmar
const SDL_Rect destRect4 = {60, 88 + (16 * 3), 16, 16}; // Time Stopper const SDL_Rect DEST_RECT4 = {60, 88 + (16 * 3), 16, 16}; // Time Stopper
const SDL_Rect destRect5 = {60, 88 + (16 * 4), 16, 16}; // Coffee const SDL_Rect DEST_RECT5 = {60, 88 + (16 * 4), 16, 16}; // Coffee
// Pinta en el backbuffer el texto y los sprites // Pinta en el backbuffer el texto y los sprites
SDL_SetRenderTarget(renderer, backbuffer); SDL_SetRenderTarget(renderer_, backbuffer_);
SDL_SetRenderDrawColor(renderer, bgColor.r, bgColor.g, bgColor.b, 255); SDL_SetRenderDrawColor(renderer_, bgColor.r, bgColor.g, bgColor.b, 255);
SDL_RenderClear(renderer); SDL_RenderClear(renderer_);
// Escribe el texto // Escribe el texto
text->writeDX(TXT_CENTER | TXT_COLOR | TXT_SHADOW, GAMECANVAS_CENTER_X, 8, Lang::get()->getText(11), 1, orangeColor, 1, shdwTxtColor); text_->writeDX(TXT_CENTER | TXT_COLOR | TXT_SHADOW, GAMECANVAS_CENTER_X, 8, Lang::get()->getText(11), 1, ORANGE_COLOR, 1, shdwTxtColor);
text->writeDX(TXT_CENTER | TXT_COLOR | TXT_SHADOW, GAMECANVAS_CENTER_X, 24, Lang::get()->getText(12), 1, noColor, 1, shdwTxtColor); text_->writeDX(TXT_CENTER | TXT_COLOR | TXT_SHADOW, GAMECANVAS_CENTER_X, 24, Lang::get()->getText(12), 1, noColor, 1, shdwTxtColor);
text->writeDX(TXT_CENTER | TXT_COLOR | TXT_SHADOW, GAMECANVAS_CENTER_X, 34, Lang::get()->getText(13), 1, noColor, 1, shdwTxtColor); text_->writeDX(TXT_CENTER | TXT_COLOR | TXT_SHADOW, GAMECANVAS_CENTER_X, 34, Lang::get()->getText(13), 1, noColor, 1, shdwTxtColor);
text->writeDX(TXT_CENTER | TXT_COLOR | TXT_SHADOW, GAMECANVAS_CENTER_X, 48, Lang::get()->getText(14), 1, noColor, 1, shdwTxtColor); text_->writeDX(TXT_CENTER | TXT_COLOR | TXT_SHADOW, GAMECANVAS_CENTER_X, 48, Lang::get()->getText(14), 1, noColor, 1, shdwTxtColor);
text->writeDX(TXT_CENTER | TXT_COLOR | TXT_SHADOW, GAMECANVAS_CENTER_X, 58, Lang::get()->getText(15), 1, noColor, 1, shdwTxtColor); text_->writeDX(TXT_CENTER | TXT_COLOR | TXT_SHADOW, GAMECANVAS_CENTER_X, 58, Lang::get()->getText(15), 1, noColor, 1, shdwTxtColor);
text->writeDX(TXT_CENTER | TXT_COLOR | TXT_SHADOW, GAMECANVAS_CENTER_X, 75, Lang::get()->getText(16), 1, orangeColor, 1, shdwTxtColor); text_->writeDX(TXT_CENTER | TXT_COLOR | TXT_SHADOW, GAMECANVAS_CENTER_X, 75, Lang::get()->getText(16), 1, ORANGE_COLOR, 1, shdwTxtColor);
text->writeShadowed(84, 92, Lang::get()->getText(17), shdwTxtColor); text_->writeShadowed(84, 92, Lang::get()->getText(17), shdwTxtColor);
text->writeShadowed(84, 108, Lang::get()->getText(18), shdwTxtColor); text_->writeShadowed(84, 108, Lang::get()->getText(18), shdwTxtColor);
text->writeShadowed(84, 124, Lang::get()->getText(19), shdwTxtColor); text_->writeShadowed(84, 124, Lang::get()->getText(19), shdwTxtColor);
text->writeShadowed(84, 140, Lang::get()->getText(20), shdwTxtColor); text_->writeShadowed(84, 140, Lang::get()->getText(20), shdwTxtColor);
text->writeShadowed(84, 156, Lang::get()->getText(21), shdwTxtColor); text_->writeShadowed(84, 156, Lang::get()->getText(21), shdwTxtColor);
if ((mode == m_manual) && (counter % 50 > 14)) { if ((mode_ == Mode::MANUAL) && (counter_ % 50 > 14)) {
text->writeDX(TXT_CENTER | TXT_COLOR | TXT_SHADOW, GAMECANVAS_CENTER_X, GAMECANVAS_HEIGHT - 12, Lang::get()->getText(22), 1, orangeColor, 1, shdwTxtColor); text_->writeDX(TXT_CENTER | TXT_COLOR | TXT_SHADOW, GAMECANVAS_CENTER_X, GAMECANVAS_HEIGHT - 12, Lang::get()->getText(22), 1, ORANGE_COLOR, 1, shdwTxtColor);
} }
// Disquito // Disquito
sprite->setTexture(itemTextures[0]); sprite_->setTexture(item_textures_[0]);
sprite->setPos(destRect1); sprite_->setPos(DEST_RECT1);
srcRect.y = 16 * (((counter + 12) / 36) % 2); src_rect.y = 16 * (((counter_ + 12) / 36) % 2);
sprite->setSpriteClip(srcRect); sprite_->setSpriteClip(src_rect);
sprite->render(); sprite_->render();
// Gavineixon // Gavineixon
sprite->setTexture(itemTextures[1]); sprite_->setTexture(item_textures_[1]);
sprite->setPos(destRect2); sprite_->setPos(DEST_RECT2);
srcRect.y = 16 * (((counter + 9) / 36) % 2); src_rect.y = 16 * (((counter_ + 9) / 36) % 2);
sprite->setSpriteClip(srcRect); sprite_->setSpriteClip(src_rect);
sprite->render(); sprite_->render();
// Pacmar // Pacmar
sprite->setTexture(itemTextures[2]); sprite_->setTexture(item_textures_[2]);
sprite->setPos(destRect3); sprite_->setPos(DEST_RECT3);
srcRect.y = 16 * (((counter + 6) / 36) % 2); src_rect.y = 16 * (((counter_ + 6) / 36) % 2);
sprite->setSpriteClip(srcRect); sprite_->setSpriteClip(src_rect);
sprite->render(); sprite_->render();
// Time Stopper // Time Stopper
sprite->setTexture(itemTextures[3]); sprite_->setTexture(item_textures_[3]);
sprite->setPos(destRect4); sprite_->setPos(DEST_RECT4);
srcRect.y = 16 * (((counter + 3) / 36) % 2); src_rect.y = 16 * (((counter_ + 3) / 36) % 2);
sprite->setSpriteClip(srcRect); sprite_->setSpriteClip(src_rect);
sprite->render(); sprite_->render();
// Coffee // Coffee
sprite->setTexture(itemTextures[4]); sprite_->setTexture(item_textures_[4]);
sprite->setPos(destRect5); sprite_->setPos(DEST_RECT5);
srcRect.y = 16 * (((counter + 0) / 36) % 2); src_rect.y = 16 * (((counter_ + 0) / 36) % 2);
sprite->setSpriteClip(srcRect); sprite_->setSpriteClip(src_rect);
sprite->render(); sprite_->render();
// Cambia el destino de renderizado // Cambia el destino de renderizado
SDL_SetRenderTarget(renderer, nullptr); SDL_SetRenderTarget(renderer_, nullptr);
// Prepara para empezar a dibujar en la textura de juego // Prepara para empezar a dibujar en la textura de juego
Screen::get()->start(); Screen::get()->start();
@@ -179,15 +179,15 @@ void Instructions::render() {
Screen::get()->clean(bgColor); Screen::get()->clean(bgColor);
// Establece la ventana del backbuffer // Establece la ventana del backbuffer
if (mode == m_auto) { if (mode_ == Mode::AUTO) {
window.y = std::max(8, GAMECANVAS_HEIGHT - counter + 100); window.y = std::max(8, GAMECANVAS_HEIGHT - counter_ + 100);
} else { } else {
window.y = 0; window.y = 0;
} }
// Copia el backbuffer al renderizador // Copia el backbuffer al renderizador
SDL_FRect fWindow = {(float)window.x, (float)window.y, (float)window.w, (float)window.h}; SDL_FRect f_window = {(float)window.x, (float)window.y, (float)window.w, (float)window.h};
SDL_RenderTexture(renderer, backbuffer, nullptr, &fWindow); SDL_RenderTexture(renderer_, backbuffer_, nullptr, &f_window);
// Vuelca el contenido del renderizador en pantalla // Vuelca el contenido del renderizador en pantalla
Screen::get()->blit(); Screen::get()->blit();
@@ -197,11 +197,11 @@ void Instructions::render() {
void Instructions::checkEvents() { void Instructions::checkEvents() {
#ifndef __EMSCRIPTEN__ #ifndef __EMSCRIPTEN__
// Comprueba los eventos que hay en la cola // Comprueba los eventos que hay en la cola
while (static_cast<int>(SDL_PollEvent(eventHandler)) != 0) { while (static_cast<int>(SDL_PollEvent(event_handler_)) != 0) {
// Evento de salida de la aplicación // Evento de salida de la aplicación
if (eventHandler->type == SDL_EVENT_QUIT) { if (event_handler_->type == SDL_EVENT_QUIT) {
quitRequested = true; quit_requested_ = true;
finished = true; finished_ = true;
break; break;
} }
} }
@@ -212,59 +212,59 @@ void Instructions::checkEvents() {
void Instructions::checkInput() { void Instructions::checkInput() {
#ifndef __EMSCRIPTEN__ #ifndef __EMSCRIPTEN__
if (Input::get()->checkInput(input_exit, REPEAT_FALSE)) { if (Input::get()->checkInput(input_exit, REPEAT_FALSE)) {
quitRequested = true; quit_requested_ = true;
finished = true; finished_ = true;
return; return;
} }
#endif #endif
if (GlobalInputs::handle()) { return; } if (GlobalInputs::handle()) { return; }
if (Input::get()->checkInput(input_pause, REPEAT_FALSE) || Input::get()->checkInput(input_accept, REPEAT_FALSE) || Input::get()->checkInput(input_fire_left, REPEAT_FALSE) || Input::get()->checkInput(input_fire_center, REPEAT_FALSE) || Input::get()->checkInput(input_fire_right, REPEAT_FALSE)) { if (Input::get()->checkInput(input_pause, REPEAT_FALSE) || Input::get()->checkInput(input_accept, REPEAT_FALSE) || Input::get()->checkInput(input_fire_left, REPEAT_FALSE) || Input::get()->checkInput(input_fire_center, REPEAT_FALSE) || Input::get()->checkInput(input_fire_right, REPEAT_FALSE)) {
if (mode == m_auto) { if (mode_ == Mode::AUTO) {
finished = true; finished_ = true;
} else { } else {
if (counter > 30) { if (counter_ > 30) {
manualQuit = true; manual_quit_ = true;
} }
} }
} }
} }
// Bucle para la pantalla de instrucciones (compatibilidad) // Bucle para la pantalla de instrucciones (compatibilidad)
void Instructions::run(InstructionsMode mode) { void Instructions::run(Mode mode) {
start(mode); start(mode);
while (!finished) { while (!finished_) {
update(); update();
checkEvents(); checkEvents();
render(); render();
} }
// Aplica los cambios de sección según el resultado // Aplica los cambios de sección según el resultado
if (quitRequested) { if (quit_requested_) {
section->name = SECTION_PROG_QUIT; section_->name = SECTION_PROG_QUIT;
} else { } else {
section->name = SECTION_PROG_TITLE; section_->name = SECTION_PROG_TITLE;
section->subsection = (mode == m_auto) ? SUBSECTION_TITLE_1 : SUBSECTION_TITLE_3; section_->subsection = (mode == Mode::AUTO) ? SUBSECTION_TITLE_1 : SUBSECTION_TITLE_3;
} }
} }
// Inicia las instrucciones (sin bucle) // Inicia las instrucciones (sin bucle)
void Instructions::start(InstructionsMode mode) { void Instructions::start(Mode mode) {
this->mode = mode; mode_ = mode;
finished = false; finished_ = false;
quitRequested = false; quit_requested_ = false;
manualQuit = false; manual_quit_ = false;
counter = 0; counter_ = 0;
ticks = 0; ticks_ = 0;
} }
// Indica si las instrucciones han terminado // Indica si las instrucciones han terminado
auto Instructions::hasFinished() const -> bool { auto Instructions::hasFinished() const -> bool {
return finished; return finished_;
} }
// Indica si se ha solicitado salir de la aplicación // Indica si se ha solicitado salir de la aplicación
auto Instructions::isQuitRequested() const -> bool { auto Instructions::isQuitRequested() const -> bool {
return quitRequested; return quit_requested_;
} }
+33 -49
View File
@@ -9,64 +9,48 @@ class Text;
class Texture; class Texture;
struct Section; struct Section;
enum InstructionsMode : std::uint8_t {
m_manual,
m_auto
};
// Clase Instructions // Clase Instructions
class Instructions { class Instructions {
private:
// Objetos y punteros
SDL_Renderer *renderer; // El renderizador de la ventana
std::vector<Texture *> itemTextures; // Vector con las texturas de los items
SDL_Event *eventHandler; // Manejador de eventos
SDL_Texture *backbuffer; // Textura para usar como backbuffer
Sprite *sprite; // Sprite con la textura de las instrucciones
Text *text; // Objeto para escribir texto
Section *section; // Estado del bucle principal para saber si continua o se sale
// Variables
Uint16 counter; // Contador
Uint16 counterEnd; // Valor final para el contador
Uint32 ticks; // Contador de ticks para ajustar la velocidad del programa
Uint32 ticksSpeed; // Velocidad a la que se repiten los bucles del programa
bool manualQuit; // Indica si se quiere salir del modo manual
InstructionsMode mode{m_auto}; // Modo en el que se van a ejecutar las instrucciones
bool finished; // Indica si las instrucciones han terminado
bool quitRequested; // Indica si se ha solicitado salir de la aplicación
// Comprueba las entradas
void checkInput();
public: public:
// Constructor enum class Mode : std::uint8_t {
Instructions(SDL_Renderer *renderer, Section *section); MANUAL,
AUTO
};
// Destructor Instructions(SDL_Renderer *renderer, Section *section); // Constructor
~Instructions(); ~Instructions(); // Destructor
Instructions(const Instructions &) = delete; Instructions(const Instructions &) = delete;
auto operator=(const Instructions &) -> Instructions & = delete; auto operator=(const Instructions &) -> Instructions & = delete;
// Bucle principal void run(Mode mode); // Bucle principal
void run(InstructionsMode mode); void start(Mode mode); // Inicia las instrucciones (sin bucle)
void update(); // Actualiza las variables
void render(); // Pinta en pantalla
void checkEvents(); // Comprueba los eventos
// Inicia las instrucciones (sin bucle) [[nodiscard]] auto hasFinished() const -> bool; // Indica si las instrucciones han terminado
void start(InstructionsMode mode); [[nodiscard]] auto isQuitRequested() const -> bool; // Indica si se ha solicitado salir de la aplicación
// Actualiza las variables private:
void update(); // Objetos y punteros
SDL_Renderer *renderer_; // El renderizador de la ventana
std::vector<Texture *> item_textures_; // Vector con las texturas de los items
SDL_Event *event_handler_; // Manejador de eventos
SDL_Texture *backbuffer_; // Textura para usar como backbuffer
Sprite *sprite_; // Sprite con la textura de las instrucciones
Text *text_; // Objeto para escribir texto
Section *section_; // Estado del bucle principal para saber si continua o se sale
// Pinta en pantalla // Variables
void render(); Uint16 counter_; // Contador
Uint16 counter_end_; // Valor final para el contador
Uint32 ticks_; // Contador de ticks para ajustar la velocidad del programa
Uint32 ticks_speed_; // Velocidad a la que se repiten los bucles del programa
bool manual_quit_; // Indica si se quiere salir del modo manual
Mode mode_{Instructions::Mode::AUTO}; // Modo en el que se van a ejecutar las instrucciones
bool finished_; // Indica si las instrucciones han terminado
bool quit_requested_; // Indica si se ha solicitado salir de la aplicación
// Comprueba los eventos void checkInput(); // Comprueba las entradas
void checkEvents(); };
// Indica si las instrucciones han terminado
[[nodiscard]] auto hasFinished() const -> bool;
// Indica si se ha solicitado salir de la aplicación
[[nodiscard]] auto isQuitRequested() const -> bool;
};
+229 -213
View File
@@ -10,8 +10,6 @@
#include "core/locale/lang.h" // for Lang #include "core/locale/lang.h" // for Lang
#include "core/rendering/screen.h" // for Screen #include "core/rendering/screen.h" // for Screen
#include "core/rendering/smartsprite.h" // for SmartSprite #include "core/rendering/smartsprite.h" // for SmartSprite
#include "core/rendering/text.h" // for Text
#include "core/rendering/texture.h" // for Texture
#include "core/rendering/writer.h" // for Writer #include "core/rendering/writer.h" // for Writer
#include "core/resources/resource.h" #include "core/resources/resource.h"
#include "game/defaults.hpp" // for GAMECANVAS_CENTER_X, GAMECANVAS_FIRST_QU... #include "game/defaults.hpp" // for GAMECANVAS_CENTER_X, GAMECANVAS_FIRST_QU...
@@ -20,148 +18,148 @@
// Constructor // Constructor
Intro::Intro(SDL_Renderer *renderer, Section *section) { Intro::Intro(SDL_Renderer *renderer, Section *section) {
// Copia los punteros // Copia los punteros
this->renderer = renderer; this->renderer_ = renderer;
this->section = section; this->section_ = section;
// Reserva memoria para los objetos // Reserva memoria para los objetos
eventHandler = new SDL_Event(); event_handler_ = new SDL_Event();
texture = Resource::get()->getTexture("intro.png"); texture_ = Resource::get()->getTexture("intro.png");
text = Resource::get()->getText("nokia"); text_ = Resource::get()->getText("nokia");
music = Resource::get()->getMusic("intro.ogg"); music_ = Resource::get()->getMusic("intro.ogg");
// Inicializa variables // Inicializa variables
section->name = SECTION_PROG_INTRO; section->name = SECTION_PROG_INTRO;
section->subsection = 0; section->subsection = 0;
ticks = 0; ticks_ = 0;
ticksSpeed = 15; ticks_speed_ = 15;
scene = 1; scene_ = 1;
// Inicializa los bitmaps de la intro // Inicializa los bitmaps de la intro
const int totalBitmaps = 6; const int TOTAL_BITMAPS = 6;
for (int i = 0; i < totalBitmaps; ++i) { for (int i = 0; i < TOTAL_BITMAPS; ++i) {
auto *ss = new SmartSprite(texture, renderer); auto *ss = new SmartSprite(texture_, renderer);
ss->setWidth(128); ss->setWidth(128);
ss->setHeight(96); ss->setHeight(96);
ss->setEnabledCounter(20); ss->setEnabledCounter(20);
ss->setDestX(GAMECANVAS_CENTER_X - 64); ss->setDestX(GAMECANVAS_CENTER_X - 64);
ss->setDestY(GAMECANVAS_FIRST_QUARTER_Y - 24); ss->setDestY(GAMECANVAS_FIRST_QUARTER_Y - 24);
bitmaps.push_back(ss); bitmaps_.push_back(ss);
} }
bitmaps[0]->setPosX(-128); bitmaps_[0]->setPosX(-128);
bitmaps[0]->setPosY(GAMECANVAS_FIRST_QUARTER_Y - 24); bitmaps_[0]->setPosY(GAMECANVAS_FIRST_QUARTER_Y - 24);
bitmaps[0]->setVelX(0.0F); bitmaps_[0]->setVelX(0.0F);
bitmaps[0]->setVelY(0.0F); bitmaps_[0]->setVelY(0.0F);
bitmaps[0]->setAccelX(0.6F); bitmaps_[0]->setAccelX(0.6F);
bitmaps[0]->setAccelY(0.0F); bitmaps_[0]->setAccelY(0.0F);
bitmaps[0]->setSpriteClip(0, 0, 128, 96); bitmaps_[0]->setSpriteClip(0, 0, 128, 96);
bitmaps[1]->setPosX(GAMECANVAS_WIDTH); bitmaps_[1]->setPosX(GAMECANVAS_WIDTH);
bitmaps[1]->setPosY(GAMECANVAS_FIRST_QUARTER_Y - 24); bitmaps_[1]->setPosY(GAMECANVAS_FIRST_QUARTER_Y - 24);
bitmaps[1]->setVelX(-1.0F); bitmaps_[1]->setVelX(-1.0F);
bitmaps[1]->setVelY(0.0F); bitmaps_[1]->setVelY(0.0F);
bitmaps[1]->setAccelX(-0.3F); bitmaps_[1]->setAccelX(-0.3F);
bitmaps[1]->setAccelY(0.0F); bitmaps_[1]->setAccelY(0.0F);
bitmaps[1]->setSpriteClip(128, 0, 128, 96); bitmaps_[1]->setSpriteClip(128, 0, 128, 96);
bitmaps[2]->setPosX(GAMECANVAS_CENTER_X - 64); bitmaps_[2]->setPosX(GAMECANVAS_CENTER_X - 64);
bitmaps[2]->setPosY(-96); bitmaps_[2]->setPosY(-96);
bitmaps[2]->setVelX(0.0F); bitmaps_[2]->setVelX(0.0F);
bitmaps[2]->setVelY(3.0F); bitmaps_[2]->setVelY(3.0F);
bitmaps[2]->setAccelX(0.1F); bitmaps_[2]->setAccelX(0.1F);
bitmaps[2]->setAccelY(0.3F); bitmaps_[2]->setAccelY(0.3F);
bitmaps[2]->setSpriteClip(0, 96, 128, 96); bitmaps_[2]->setSpriteClip(0, 96, 128, 96);
bitmaps[2]->setEnabledCounter(250); bitmaps_[2]->setEnabledCounter(250);
bitmaps[3]->setPosX(GAMECANVAS_CENTER_X - 64); bitmaps_[3]->setPosX(GAMECANVAS_CENTER_X - 64);
bitmaps[3]->setPosY(GAMECANVAS_HEIGHT); bitmaps_[3]->setPosY(GAMECANVAS_HEIGHT);
bitmaps[3]->setVelX(0.0F); bitmaps_[3]->setVelX(0.0F);
bitmaps[3]->setVelY(-0.7F); bitmaps_[3]->setVelY(-0.7F);
bitmaps[3]->setAccelX(0.0F); bitmaps_[3]->setAccelX(0.0F);
bitmaps[3]->setAccelY(0.0F); bitmaps_[3]->setAccelY(0.0F);
bitmaps[3]->setSpriteClip(128, 96, 128, 96); bitmaps_[3]->setSpriteClip(128, 96, 128, 96);
bitmaps[4]->setPosX(GAMECANVAS_CENTER_X - 64); bitmaps_[4]->setPosX(GAMECANVAS_CENTER_X - 64);
bitmaps[4]->setPosY(-96); bitmaps_[4]->setPosY(-96);
bitmaps[4]->setVelX(0.0F); bitmaps_[4]->setVelX(0.0F);
bitmaps[4]->setVelY(3.0F); bitmaps_[4]->setVelY(3.0F);
bitmaps[4]->setAccelX(0.1F); bitmaps_[4]->setAccelX(0.1F);
bitmaps[4]->setAccelY(0.3F); bitmaps_[4]->setAccelY(0.3F);
bitmaps[4]->setSpriteClip(0, 192, 128, 96); bitmaps_[4]->setSpriteClip(0, 192, 128, 96);
bitmaps[5]->setPosX(GAMECANVAS_WIDTH); bitmaps_[5]->setPosX(GAMECANVAS_WIDTH);
bitmaps[5]->setPosY(GAMECANVAS_FIRST_QUARTER_Y - 24); bitmaps_[5]->setPosY(GAMECANVAS_FIRST_QUARTER_Y - 24);
bitmaps[5]->setVelX(-0.7F); bitmaps_[5]->setVelX(-0.7F);
bitmaps[5]->setVelY(0.0F); bitmaps_[5]->setVelY(0.0F);
bitmaps[5]->setAccelX(0.0F); bitmaps_[5]->setAccelX(0.0F);
bitmaps[5]->setAccelY(0.0F); bitmaps_[5]->setAccelY(0.0F);
bitmaps[5]->setSpriteClip(128, 192, 128, 96); bitmaps_[5]->setSpriteClip(128, 192, 128, 96);
// Inicializa los textos de la intro // Inicializa los textos de la intro
const int totalTexts = 9; const int TOTAL_TEXTS = 9;
for (int i = 0; i < totalTexts; ++i) { for (int i = 0; i < TOTAL_TEXTS; ++i) {
auto *w = new Writer(text); auto *w = new Writer(text_);
w->setPosX(BLOCK * 0); w->setPosX(BLOCK * 0);
w->setPosY(GAMECANVAS_HEIGHT - (BLOCK * 6)); w->setPosY(GAMECANVAS_HEIGHT - (BLOCK * 6));
w->setKerning(-1); w->setKerning(-1);
w->setEnabled(false); w->setEnabled(false);
w->setEnabledCounter(180); w->setEnabledCounter(180);
texts.push_back(w); texts_.push_back(w);
} }
// Un dia qualsevol de l'any 2000 // Un dia qualsevol de l'any 2000
texts[0]->setCaption(Lang::get()->getText(27)); texts_[0]->setCaption(Lang::get()->getText(27));
texts[0]->setSpeed(8); texts_[0]->setSpeed(8);
// Tot esta tranquil a la UPV // Tot esta tranquil a la UPV
texts[1]->setCaption(Lang::get()->getText(28)); texts_[1]->setCaption(Lang::get()->getText(28));
texts[1]->setSpeed(8); texts_[1]->setSpeed(8);
// Fins que un desaprensiu... // Fins que un desaprensiu...
texts[2]->setCaption(Lang::get()->getText(29)); texts_[2]->setCaption(Lang::get()->getText(29));
texts[2]->setSpeed(12); texts_[2]->setSpeed(12);
// HEY! ME ANE A FERME UN CORTAET... // HEY! ME ANE A FERME UN CORTAET...
texts[3]->setCaption(Lang::get()->getText(30)); texts_[3]->setCaption(Lang::get()->getText(30));
texts[3]->setSpeed(8); texts_[3]->setSpeed(8);
// UAAAAAAAAAAAAA!!! // UAAAAAAAAAAAAA!!!
texts[4]->setCaption(Lang::get()->getText(31)); texts_[4]->setCaption(Lang::get()->getText(31));
texts[4]->setSpeed(1); texts_[4]->setSpeed(1);
// Espera un moment... // Espera un moment...
texts[5]->setCaption(Lang::get()->getText(32)); texts_[5]->setCaption(Lang::get()->getText(32));
texts[5]->setSpeed(16); texts_[5]->setSpeed(16);
// Si resulta que no tinc solt! // Si resulta que no tinc solt!
texts[6]->setCaption(Lang::get()->getText(33)); texts_[6]->setCaption(Lang::get()->getText(33));
texts[6]->setSpeed(2); texts_[6]->setSpeed(2);
// MERDA DE MAQUINA! // MERDA DE MAQUINA!
texts[7]->setCaption(Lang::get()->getText(34)); texts_[7]->setCaption(Lang::get()->getText(34));
texts[7]->setSpeed(3); texts_[7]->setSpeed(3);
// Blop... blop... blop... // Blop... blop... blop...
texts[8]->setCaption(Lang::get()->getText(35)); texts_[8]->setCaption(Lang::get()->getText(35));
texts[8]->setSpeed(16); texts_[8]->setSpeed(16);
for (auto *t : texts) { for (auto *t : texts_) {
t->center(GAMECANVAS_CENTER_X); t->center(GAMECANVAS_CENTER_X);
} }
Audio::get()->playMusic(music, 0); Audio::get()->playMusic(music_, 0);
} }
// Destructor // Destructor
Intro::~Intro() { Intro::~Intro() {
delete eventHandler; delete event_handler_;
// texture, text, music son propiedad de Resource — no liberar aquí. // texture, text, music son propiedad de Resource — no liberar aquí.
for (auto *bitmap : bitmaps) { for (auto *bitmap : bitmaps_) {
delete bitmap; delete bitmap;
} }
for (auto *t : texts) { for (auto *t : texts_) {
delete t; delete t;
} }
} }
@@ -170,7 +168,7 @@ Intro::~Intro() {
void Intro::checkInput() { void Intro::checkInput() {
#ifndef __EMSCRIPTEN__ #ifndef __EMSCRIPTEN__
if (Input::get()->checkInput(input_exit, REPEAT_FALSE)) { if (Input::get()->checkInput(input_exit, REPEAT_FALSE)) {
section->name = SECTION_PROG_QUIT; section_->name = SECTION_PROG_QUIT;
return; return;
} }
#endif #endif
@@ -178,162 +176,180 @@ void Intro::checkInput() {
if (Input::get()->checkInput(input_pause, REPEAT_FALSE) || Input::get()->checkInput(input_accept, REPEAT_FALSE) || Input::get()->checkInput(input_fire_left, REPEAT_FALSE) || Input::get()->checkInput(input_fire_center, REPEAT_FALSE) || Input::get()->checkInput(input_fire_right, REPEAT_FALSE)) { if (Input::get()->checkInput(input_pause, REPEAT_FALSE) || Input::get()->checkInput(input_accept, REPEAT_FALSE) || Input::get()->checkInput(input_fire_left, REPEAT_FALSE) || Input::get()->checkInput(input_fire_center, REPEAT_FALSE) || Input::get()->checkInput(input_fire_right, REPEAT_FALSE)) {
Audio::get()->stopMusic(); Audio::get()->stopMusic();
section->name = SECTION_PROG_TITLE; section_->name = SECTION_PROG_TITLE;
section->subsection = SUBSECTION_TITLE_1; section_->subsection = SUBSECTION_TITLE_1;
} }
} }
// Actualiza las escenas de la intro // Actualiza las escenas de la intro
void Intro::updateScenes() { void Intro::updateScenes() {
switch (scene) { switch (scene_) {
case 1: case 1:
// Primera imagen - UPV updateScene1();
if (!bitmaps[0]->hasFinished()) {
bitmaps[0]->setEnabled(true);
}
// Primer texto de la primera imagen
if (bitmaps[0]->hasFinished() && !texts[0]->hasFinished()) {
texts[0]->setEnabled(true);
}
// Segundo texto de la primera imagen
if (texts[0]->hasFinished() && !texts[1]->hasFinished()) {
texts[0]->setEnabled(false);
texts[1]->setEnabled(true);
}
// Tercer texto de la primera imagen
if (texts[1]->hasFinished() && !texts[2]->hasFinished()) {
texts[1]->setEnabled(false);
texts[2]->setEnabled(true);
}
// Fin de la primera escena
if (texts[2]->hasFinished()) {
bitmaps[0]->setEnabled(false);
texts[2]->setEnabled(false);
scene++;
}
break; break;
case 2: case 2:
// Segunda imagen - Máquina updateScene2();
if (!bitmaps[1]->hasFinished()) {
bitmaps[1]->setEnabled(true);
}
// Primer texto de la segunda imagen
if (bitmaps[1]->hasFinished() && !texts[3]->hasFinished()) {
texts[3]->setEnabled(true);
}
// Fin de la segunda escena
if (texts[3]->hasFinished()) {
bitmaps[1]->setEnabled(false);
texts[3]->setEnabled(false);
scene++;
}
break; break;
case 3: case 3:
// Tercera imagen junto con primer texto - GRITO updateScene3();
if (!bitmaps[2]->hasFinished() && !texts[4]->hasFinished()) {
bitmaps[2]->setEnabled(true);
texts[4]->setEnabled(true);
}
// Fin de la tercera escena
if (bitmaps[2]->hasFinished() && texts[4]->hasFinished()) {
bitmaps[2]->setEnabled(false);
texts[4]->setEnabled(false);
scene++;
}
break; break;
case 4: case 4:
// Cuarta imagen junto con primer texto - Reflexión updateScene4();
if (!bitmaps[3]->hasFinished() && !texts[5]->hasFinished()) {
bitmaps[3]->setEnabled(true);
texts[5]->setEnabled(true);
}
// Segundo texto de la cuarta imagen
if (texts[5]->hasFinished() && !texts[6]->hasFinished()) {
texts[5]->setEnabled(false);
texts[6]->setEnabled(true);
}
// Fin de la cuarta escena
if (bitmaps[3]->hasFinished() && texts[6]->hasFinished()) {
bitmaps[3]->setEnabled(false);
texts[6]->setEnabled(false);
scene++;
}
break; break;
case 5: case 5:
// Quinta imagen - Patada updateScene5();
if (!bitmaps[4]->hasFinished()) {
bitmaps[4]->setEnabled(true);
}
// Primer texto de la quinta imagen
if (bitmaps[4]->hasFinished() && !texts[7]->hasFinished()) {
texts[7]->setEnabled(true);
}
// Fin de la quinta escena
if (bitmaps[4]->hasFinished() && texts[7]->hasFinished()) {
bitmaps[4]->setEnabled(false);
texts[7]->setEnabled(false);
scene++;
}
break; break;
case 6: case 6:
// Sexta imagen junto con texto - Globos de café updateScene6();
if (!bitmaps[5]->hasFinished() && !texts[8]->hasFinished()) {
bitmaps[5]->setEnabled(true);
texts[8]->setEnabled(true);
}
// Acaba el último texto
if (bitmaps[5]->hasFinished() && texts[8]->hasFinished()) {
bitmaps[5]->setEnabled(false);
texts[8]->setEnabled(false);
Audio::get()->stopMusic();
section->name = SECTION_PROG_TITLE;
section->subsection = SUBSECTION_TITLE_1;
}
break; break;
default: default:
break; break;
} }
} }
// Primera escena - UPV
void Intro::updateScene1() {
// Primera imagen - UPV
if (!bitmaps_[0]->hasFinished()) {
bitmaps_[0]->setEnabled(true);
}
// Primer texto de la primera imagen
if (bitmaps_[0]->hasFinished() && !texts_[0]->hasFinished()) {
texts_[0]->setEnabled(true);
}
// Segundo texto de la primera imagen
if (texts_[0]->hasFinished() && !texts_[1]->hasFinished()) {
texts_[0]->setEnabled(false);
texts_[1]->setEnabled(true);
}
// Tercer texto de la primera imagen
if (texts_[1]->hasFinished() && !texts_[2]->hasFinished()) {
texts_[1]->setEnabled(false);
texts_[2]->setEnabled(true);
}
// Fin de la primera escena
if (texts_[2]->hasFinished()) {
bitmaps_[0]->setEnabled(false);
texts_[2]->setEnabled(false);
scene_++;
}
}
// Segunda escena - Máquina
void Intro::updateScene2() {
// Segunda imagen - Máquina
if (!bitmaps_[1]->hasFinished()) {
bitmaps_[1]->setEnabled(true);
}
// Primer texto de la segunda imagen
if (bitmaps_[1]->hasFinished() && !texts_[3]->hasFinished()) {
texts_[3]->setEnabled(true);
}
// Fin de la segunda escena
if (texts_[3]->hasFinished()) {
bitmaps_[1]->setEnabled(false);
texts_[3]->setEnabled(false);
scene_++;
}
}
// Tercera escena - GRITO
void Intro::updateScene3() {
// Tercera imagen junto con primer texto - GRITO
if (!bitmaps_[2]->hasFinished() && !texts_[4]->hasFinished()) {
bitmaps_[2]->setEnabled(true);
texts_[4]->setEnabled(true);
}
// Fin de la tercera escena
if (bitmaps_[2]->hasFinished() && texts_[4]->hasFinished()) {
bitmaps_[2]->setEnabled(false);
texts_[4]->setEnabled(false);
scene_++;
}
}
// Cuarta escena - Reflexión
void Intro::updateScene4() {
// Cuarta imagen junto con primer texto - Reflexión
if (!bitmaps_[3]->hasFinished() && !texts_[5]->hasFinished()) {
bitmaps_[3]->setEnabled(true);
texts_[5]->setEnabled(true);
}
// Segundo texto de la cuarta imagen
if (texts_[5]->hasFinished() && !texts_[6]->hasFinished()) {
texts_[5]->setEnabled(false);
texts_[6]->setEnabled(true);
}
// Fin de la cuarta escena
if (bitmaps_[3]->hasFinished() && texts_[6]->hasFinished()) {
bitmaps_[3]->setEnabled(false);
texts_[6]->setEnabled(false);
scene_++;
}
}
// Quinta escena - Patada
void Intro::updateScene5() {
// Quinta imagen - Patada
if (!bitmaps_[4]->hasFinished()) {
bitmaps_[4]->setEnabled(true);
}
// Primer texto de la quinta imagen
if (bitmaps_[4]->hasFinished() && !texts_[7]->hasFinished()) {
texts_[7]->setEnabled(true);
}
// Fin de la quinta escena
if (bitmaps_[4]->hasFinished() && texts_[7]->hasFinished()) {
bitmaps_[4]->setEnabled(false);
texts_[7]->setEnabled(false);
scene_++;
}
}
// Sexta escena - Globos de café
void Intro::updateScene6() {
// Sexta imagen junto con texto - Globos de café
if (!bitmaps_[5]->hasFinished() && !texts_[8]->hasFinished()) {
bitmaps_[5]->setEnabled(true);
texts_[8]->setEnabled(true);
}
// Acaba el último texto
if (bitmaps_[5]->hasFinished() && texts_[8]->hasFinished()) {
bitmaps_[5]->setEnabled(false);
texts_[8]->setEnabled(false);
Audio::get()->stopMusic();
section_->name = SECTION_PROG_TITLE;
section_->subsection = SUBSECTION_TITLE_1;
}
}
// Actualiza las variables del objeto // Actualiza las variables del objeto
void Intro::update() { void Intro::update() {
Audio::update(); Audio::update();
checkInput(); checkInput();
if (SDL_GetTicks() - ticks > ticksSpeed) { if (SDL_GetTicks() - ticks_ > ticks_speed_) {
// Actualiza el contador de ticks // Actualiza el contador de ticks
ticks = SDL_GetTicks(); ticks_ = SDL_GetTicks();
// Actualiza los objetos // Actualiza los objetos
for (auto *bitmap : bitmaps) { for (auto *bitmap : bitmaps_) {
bitmap->update(); bitmap->update();
} }
for (auto *t : texts) { for (auto *t : texts_) {
t->update(); t->update();
} }
@@ -351,11 +367,11 @@ void Intro::render() {
Screen::get()->clean(bgColor); Screen::get()->clean(bgColor);
// Dibuja los objetos // Dibuja los objetos
for (auto *bitmap : bitmaps) { for (auto *bitmap : bitmaps_) {
bitmap->render(); bitmap->render();
} }
for (auto *t : texts) { for (auto *t : texts_) {
t->render(); t->render();
} }
@@ -365,9 +381,9 @@ void Intro::render() {
// Bucle principal // Bucle principal
void Intro::run() { void Intro::run() {
Audio::get()->playMusic(music, 0); Audio::get()->playMusic(music_, 0);
while (section->name == SECTION_PROG_INTRO) { while (section_->name == SECTION_PROG_INTRO) {
iterate(); iterate();
} }
} }
+32 -39
View File
@@ -12,50 +12,43 @@ struct Section;
// Clase Intro // Clase Intro
class Intro { class Intro {
private:
// Objetos y punteros
SDL_Renderer *renderer; // El renderizador de la ventana
Texture *texture; // Textura con los graficos
SDL_Event *eventHandler; // Manejador de eventos
std::vector<SmartSprite *> bitmaps; // Vector con los sprites inteligentes para los dibujos de la intro
std::vector<Writer *> texts; // Textos de la intro
Text *text; // Textos de la intro
Section *section; // Estado del bucle principal para saber si continua o se sale
// Variables
Uint32 ticks; // Contador de ticks para ajustar la velocidad del programa
Uint8 ticksSpeed; // Velocidad a la que se repiten los bucles del programa
JA_Music_t *music; // Musica para la intro
int scene; // Indica que escena está activa
// Actualiza las variables del objeto
void update();
// Dibuja el objeto en pantalla
void render();
// Comprueba las entradas
void checkInput();
// Actualiza las escenas de la intro
void updateScenes();
public: public:
// Constructor Intro(SDL_Renderer *renderer, Section *section); // Constructor
Intro(SDL_Renderer *renderer, Section *section); ~Intro(); // Destructor
// Destructor
~Intro();
Intro(const Intro &) = delete; Intro(const Intro &) = delete;
auto operator=(const Intro &) -> Intro & = delete; auto operator=(const Intro &) -> Intro & = delete;
// Bucle principal void run(); // Bucle principal
void run(); void iterate(); // Ejecuta un frame
void handleEvent(const SDL_Event *event); // Procesa un evento
// Ejecuta un frame private:
void iterate(); // Objetos y punteros
SDL_Renderer *renderer_; // El renderizador de la ventana
Texture *texture_; // Textura con los graficos
SDL_Event *event_handler_; // Manejador de eventos
std::vector<SmartSprite *> bitmaps_; // Vector con los sprites inteligentes para los dibujos de la intro
std::vector<Writer *> texts_; // Textos de la intro
Text *text_; // Textos de la intro
Section *section_; // Estado del bucle principal para saber si continua o se sale
// Procesa un evento // Variables
void handleEvent(const SDL_Event *event); Uint32 ticks_; // Contador de ticks para ajustar la velocidad del programa
Uint8 ticks_speed_; // Velocidad a la que se repiten los bucles del programa
JA_Music_t *music_; // Musica para la intro
int scene_; // Indica que escena está activa
void update(); // Actualiza las variables del objeto
void render(); // Dibuja el objeto en pantalla
void checkInput(); // Comprueba las entradas
void updateScenes(); // Actualiza las escenas de la intro
// Helpers de updateScenes, uno por cada escena
void updateScene1();
void updateScene2();
void updateScene3();
void updateScene4();
void updateScene5();
void updateScene6();
}; };
+25 -25
View File
@@ -23,20 +23,20 @@ constexpr int END_LOGO = 200;
// Constructor // Constructor
Logo::Logo(SDL_Renderer *renderer, Section *section) { Logo::Logo(SDL_Renderer *renderer, Section *section) {
// Copia la dirección de los objetos // Copia la dirección de los objetos
this->renderer = renderer; this->renderer_ = renderer;
this->section = section; this->section_ = section;
// Reserva memoria para los punteros // Reserva memoria para los punteros
eventHandler = new SDL_Event(); event_handler_ = new SDL_Event();
texture = Resource::get()->getTexture("logo.png"); texture_ = Resource::get()->getTexture("logo.png");
sprite = new Sprite(14, 75, 226, 44, texture, renderer); sprite_ = new Sprite(14, 75, 226, 44, texture_, renderer);
// Inicializa variables // Inicializa variables
counter = 0; counter_ = 0;
section->name = SECTION_PROG_LOGO; section->name = SECTION_PROG_LOGO;
section->subsection = 0; section->subsection = 0;
ticks = 0; ticks_ = 0;
ticksSpeed = 15; ticks_speed_ = 15;
Audio::get()->stopMusic(); Audio::get()->stopMusic();
} }
@@ -44,15 +44,15 @@ Logo::Logo(SDL_Renderer *renderer, Section *section) {
// Destructor // Destructor
Logo::~Logo() { Logo::~Logo() {
// texture es propiedad de Resource — no liberar aquí. // texture es propiedad de Resource — no liberar aquí.
delete sprite; delete sprite_;
delete eventHandler; delete event_handler_;
} }
// Comprueba si ha terminado el logo // Comprueba si ha terminado el logo
void Logo::checkLogoEnd() { void Logo::checkLogoEnd() {
if (counter >= END_LOGO + 20) { if (counter_ >= END_LOGO + 20) {
section->name = SECTION_PROG_INTRO; section_->name = SECTION_PROG_INTRO;
section->subsection = 0; section_->subsection = 0;
} }
} }
@@ -60,26 +60,26 @@ void Logo::checkLogoEnd() {
void Logo::checkInput() { void Logo::checkInput() {
#ifndef __EMSCRIPTEN__ #ifndef __EMSCRIPTEN__
if (Input::get()->checkInput(input_exit, REPEAT_FALSE)) { if (Input::get()->checkInput(input_exit, REPEAT_FALSE)) {
section->name = SECTION_PROG_QUIT; section_->name = SECTION_PROG_QUIT;
return; return;
} }
#endif #endif
if (GlobalInputs::handle()) { return; } if (GlobalInputs::handle()) { return; }
if (Input::get()->checkInput(input_pause, REPEAT_FALSE) || Input::get()->checkInput(input_accept, REPEAT_FALSE) || Input::get()->checkInput(input_fire_left, REPEAT_FALSE) || Input::get()->checkInput(input_fire_center, REPEAT_FALSE) || Input::get()->checkInput(input_fire_right, REPEAT_FALSE)) { if (Input::get()->checkInput(input_pause, REPEAT_FALSE) || Input::get()->checkInput(input_accept, REPEAT_FALSE) || Input::get()->checkInput(input_fire_left, REPEAT_FALSE) || Input::get()->checkInput(input_fire_center, REPEAT_FALSE) || Input::get()->checkInput(input_fire_right, REPEAT_FALSE)) {
section->name = SECTION_PROG_TITLE; section_->name = SECTION_PROG_TITLE;
section->subsection = SUBSECTION_TITLE_1; section_->subsection = SUBSECTION_TITLE_1;
} }
} }
// Dibuja el fade // Dibuja el fade
void Logo::renderFade() { void Logo::renderFade() {
// Dibuja el fade // Dibuja el fade
if (counter >= INIT_FADE) { if (counter_ >= INIT_FADE) {
const float step = (float)(counter - INIT_FADE) / (float)(END_LOGO - INIT_FADE); const float step = (float)(counter_ - INIT_FADE) / (float)(END_LOGO - INIT_FADE);
const int alpha = std::min((int)(255 * step), 255); const int alpha = std::min((int)(255 * step), 255);
SDL_SetRenderDrawColor(renderer, bgColor.r, bgColor.g, bgColor.b, alpha); SDL_SetRenderDrawColor(renderer_, bgColor.r, bgColor.g, bgColor.b, alpha);
SDL_RenderFillRect(renderer, nullptr); SDL_RenderFillRect(renderer_, nullptr);
} }
} }
@@ -88,12 +88,12 @@ void Logo::update() {
Audio::update(); Audio::update();
checkInput(); checkInput();
if (SDL_GetTicks() - ticks > ticksSpeed) { if (SDL_GetTicks() - ticks_ > ticks_speed_) {
// Actualiza el contador de ticks // Actualiza el contador de ticks
ticks = SDL_GetTicks(); ticks_ = SDL_GetTicks();
// Actualiza el contador // Actualiza el contador
counter++; counter_++;
// Comprueba si ha terminado el logo // Comprueba si ha terminado el logo
checkLogoEnd(); checkLogoEnd();
@@ -109,7 +109,7 @@ void Logo::render() {
Screen::get()->clean({238, 238, 238}); Screen::get()->clean({238, 238, 238});
// Dibuja los objetos // Dibuja los objetos
sprite->render(); sprite_->render();
// Dibuja el fade // Dibuja el fade
renderFade(); renderFade();
@@ -122,7 +122,7 @@ void Logo::render() {
void Logo::run() { void Logo::run() {
Audio::get()->stopMusic(); Audio::get()->stopMusic();
while (section->name == SECTION_PROG_LOGO) { while (section_->name == SECTION_PROG_LOGO) {
iterate(); iterate();
} }
} }
+22 -39
View File
@@ -7,50 +7,33 @@ struct Section;
// Clase Logo // Clase Logo
class Logo { class Logo {
private:
// Objetos y punteros
SDL_Renderer *renderer; // El renderizador de la ventana
Texture *texture; // Textura con los graficos
SDL_Event *eventHandler; // Manejador de eventos
Sprite *sprite; // Sprite con la textura del logo
Section *section; // Estado del bucle principal para saber si continua o se sale
// Variables
Uint32 ticks; // Contador de ticks para ajustar la velocidad del programa
Uint32 ticksSpeed; // Velocidad a la que se repiten los bucles del programa
int counter; // Contador
// Actualiza las variables del objeto
void update();
// Dibuja el objeto en pantalla
void render();
// Comprueba si ha terminado el logo
void checkLogoEnd();
// Comprueba las entradas
void checkInput();
// Dibuja el fade
void renderFade();
public: public:
// Constructor Logo(SDL_Renderer *renderer, Section *section); // Constructor
Logo(SDL_Renderer *renderer, Section *section); ~Logo(); // Destructor
// Destructor
~Logo();
Logo(const Logo &) = delete; Logo(const Logo &) = delete;
auto operator=(const Logo &) -> Logo & = delete; auto operator=(const Logo &) -> Logo & = delete;
// Bucle principal void run(); // Bucle principal
void run(); void iterate(); // Ejecuta un frame
void handleEvent(const SDL_Event *event); // Procesa un evento
// Ejecuta un frame private:
void iterate(); // Objetos y punteros
SDL_Renderer *renderer_; // El renderizador de la ventana
Texture *texture_; // Textura con los graficos
SDL_Event *event_handler_; // Manejador de eventos
Sprite *sprite_; // Sprite con la textura del logo
Section *section_; // Estado del bucle principal para saber si continua o se sale
// Procesa un evento // Variables
void handleEvent(const SDL_Event *event); Uint32 ticks_; // Contador de ticks para ajustar la velocidad del programa
Uint32 ticks_speed_; // Velocidad a la que se repiten los bucles del programa
int counter_; // Contador
void update(); // Actualiza las variables del objeto
void render(); // Dibuja el objeto en pantalla
void checkLogoEnd(); // Comprueba si ha terminado el logo
void checkInput(); // Comprueba las entradas
void renderFade(); // Dibuja el fade
}; };
+5 -5
View File
@@ -457,7 +457,7 @@ void Title::update() {
break; break;
case 11: // HOW TO PLAY case 11: // HOW TO PLAY
runInstructions(m_manual); runInstructions(Instructions::Mode::MANUAL);
break; break;
case 12: // ACCEPT case 12: // ACCEPT
@@ -495,7 +495,7 @@ void Title::update() {
// Sección Instrucciones // Sección Instrucciones
if (section->subsection == SUBSECTION_TITLE_INSTRUCTIONS) { if (section->subsection == SUBSECTION_TITLE_INSTRUCTIONS) {
runInstructions(m_auto); runInstructions(Instructions::Mode::AUTO);
} }
} }
@@ -845,7 +845,7 @@ void Title::iterate() {
if (wasQuit) { if (wasQuit) {
section->name = SECTION_PROG_QUIT; section->name = SECTION_PROG_QUIT;
} else if (instructionsMode == m_auto) { } else if (instructionsMode == Instructions::Mode::AUTO) {
section->name = SECTION_PROG_TITLE; section->name = SECTION_PROG_TITLE;
init(); init();
demo = true; demo = true;
@@ -877,7 +877,7 @@ void Title::iterate() {
section->name = SECTION_PROG_TITLE; section->name = SECTION_PROG_TITLE;
section->subsection = SUBSECTION_TITLE_3; section->subsection = SUBSECTION_TITLE_3;
demoThenInstructions = false; demoThenInstructions = false;
runInstructions(m_auto); runInstructions(Instructions::Mode::AUTO);
} else { } else {
section->name = SECTION_PROG_TITLE; section->name = SECTION_PROG_TITLE;
section->subsection = SUBSECTION_TITLE_1; section->subsection = SUBSECTION_TITLE_1;
@@ -929,7 +929,7 @@ void Title::run() {
} }
// Inicia la parte donde se muestran las instrucciones // Inicia la parte donde se muestran las instrucciones
void Title::runInstructions(InstructionsMode mode) { void Title::runInstructions(Instructions::Mode mode) {
instructions = new Instructions(renderer, section); instructions = new Instructions(renderer, section);
instructions->start(mode); instructions->start(mode);
instructionsActive = true; instructionsActive = true;
+10 -10
View File
@@ -5,7 +5,7 @@
#include <vector> // for vector #include <vector> // for vector
#include "game/options.hpp" // for Options::Video, Options::Window (per snapshot cancel) #include "game/options.hpp" // for Options::Video, Options::Window (per snapshot cancel)
#include "game/scenes/instructions.h" // for InstructionsMode #include "game/scenes/instructions.h" // for Instructions::Mode
#include "utils/utils.h" // for InputDevice, Section #include "utils/utils.h" // for InputDevice, Section
class AnimatedSprite; class AnimatedSprite;
class Fade; class Fade;
@@ -42,7 +42,7 @@ class Title {
Instructions *instructions{nullptr}; // Objeto para la sección de las instrucciones Instructions *instructions{nullptr}; // Objeto para la sección de las instrucciones
Game *demoGame{nullptr}; // Objeto para lanzar la demo del juego Game *demoGame{nullptr}; // Objeto para lanzar la demo del juego
SDL_Event *eventHandler; // Manejador de eventos SDL_Event *eventHandler; // Manejador de eventos
Section *section; // Indicador para el bucle del titulo Section *section; // Indicador para el bucle del titulo
Texture *dustTexture; // Textura con los graficos del polvo Texture *dustTexture; // Textura con los graficos del polvo
Texture *coffeeTexture; // Textura con los graficos de la palabra coffee Texture *coffeeTexture; // Textura con los graficos de la palabra coffee
@@ -74,17 +74,17 @@ class Title {
float sin[360]; // Vector con los valores del seno precalculados float sin[360]; // Vector con los valores del seno precalculados
bool menuVisible; // Indicador para saber si se muestra el menu del titulo o la frase intermitente bool menuVisible; // Indicador para saber si se muestra el menu del titulo o la frase intermitente
bool demo; // Indica si el modo demo estará activo bool demo; // Indica si el modo demo estará activo
Section nextSection; // Indica cual es la siguiente sección a cargar cuando termine el contador del titulo Section nextSection; // Indica cual es la siguiente sección a cargar cuando termine el contador del titulo
Uint32 ticksSpeed; // Velocidad a la que se repiten los bucles del programa Uint32 ticksSpeed; // Velocidad a la que se repiten los bucles del programa
Uint8 postFade; // Opción a realizar cuando termina el fundido Uint8 postFade; // Opción a realizar cuando termina el fundido
MenuData menu; // Variable con todos los objetos menus y sus variables MenuData menu; // Variable con todos los objetos menus y sus variables
// Snapshot per a permetre CANCEL al menú d'opcions. // Snapshot per a permetre CANCEL al menú d'opcions.
Options::Video prevVideo; Options::Video prevVideo;
Options::Window prevWindow; Options::Window prevWindow;
Options::Settings prevSettings; Options::Settings prevSettings;
std::vector<InputDevice> prevInputs; std::vector<InputDevice> prevInputs;
std::vector<InputDevice> availableInputDevices; // Vector con todos los metodos de control disponibles std::vector<InputDevice> availableInputDevices; // Vector con todos los metodos de control disponibles
std::vector<int> deviceIndex; // Indice para el jugador [i] del vector de dispositivos de entrada disponibles std::vector<int> deviceIndex; // Indice para el jugador [i] del vector de dispositivos de entrada disponibles
// Variables para la vibración del título (SUBSECTION_TITLE_2) // Variables para la vibración del título (SUBSECTION_TITLE_2)
int vibrationStep; // Paso actual de la vibración int vibrationStep; // Paso actual de la vibración
@@ -93,10 +93,10 @@ class Title {
bool vibrationInitialized; // Indica si se han capturado las posiciones base bool vibrationInitialized; // Indica si se han capturado las posiciones base
// Variables para sub-estados delegados (instrucciones y demo) // Variables para sub-estados delegados (instrucciones y demo)
bool instructionsActive; // Indica si las instrucciones están activas bool instructionsActive; // Indica si las instrucciones están activas
bool demoGameActive; // Indica si el juego demo está activo bool demoGameActive; // Indica si el juego demo está activo
InstructionsMode instructionsMode{m_auto}; // Modo de las instrucciones activas Instructions::Mode instructionsMode{Instructions::Mode::AUTO}; // Modo de las instrucciones activas
bool demoThenInstructions; // Indica si tras la demo hay que mostrar instrucciones bool demoThenInstructions; // Indica si tras la demo hay que mostrar instrucciones
// Inicializa los valores // Inicializa los valores
void init(); void init();
@@ -123,7 +123,7 @@ class Title {
void applyOptions(); void applyOptions();
// Ejecuta la parte donde se muestran las instrucciones // Ejecuta la parte donde se muestran las instrucciones
void runInstructions(InstructionsMode mode); void runInstructions(Instructions::Mode mode);
// Ejecuta el juego en modo demo // Ejecuta el juego en modo demo
void runDemoGame(); void runDemoGame();
+1 -1
View File
@@ -84,7 +84,7 @@ Menu::~Menu() {
JA_DeleteSound(soundCancel); JA_DeleteSound(soundCancel);
} }
delete text; delete text;
} }
// Parser compartido (recibe cualquier istream) // Parser compartido (recibe cualquier istream)
+21 -21
View File
@@ -27,7 +27,7 @@ class Menu {
private: private:
struct Rectangle { struct Rectangle {
SDL_Rect rect; // Rectangulo SDL_Rect rect; // Rectangulo
Color color; // Color Color color; // Color
int a; // Transparencia int a; // Transparencia
}; };
@@ -44,26 +44,26 @@ class Menu {
}; };
struct Selector { struct Selector {
float originY; // Coordenada de origen float originY; // Coordenada de origen
float targetY; // Coordenada de destino float targetY; // Coordenada de destino
float despY; // Cantidad de pixeles que se desplaza el selector en cada salto: (target - origin) / numJumps float despY; // Cantidad de pixeles que se desplaza el selector en cada salto: (target - origin) / numJumps
bool moving; // Indica si el selector está avanzando hacia el destino bool moving; // Indica si el selector está avanzando hacia el destino
float originH; // Altura de origen float originH; // Altura de origen
float targetH; // Altura de destino float targetH; // Altura de destino
float incH; // Cantidad de pixels que debe incrementar o decrementar el selector en cada salto float incH; // Cantidad de pixels que debe incrementar o decrementar el selector en cada salto
bool resizing; // Indica si el selector está cambiando de tamaño bool resizing; // Indica si el selector está cambiando de tamaño
float y; // Coordenada actual, usado para el desplazamiento float y; // Coordenada actual, usado para el desplazamiento
float h; // Altura actual, usado para el cambio de tamaño float h; // Altura actual, usado para el cambio de tamaño
int numJumps; // Numero de pasos preestablecido para llegar al destino int numJumps; // Numero de pasos preestablecido para llegar al destino
int index; // Elemento del menu que tiene el foco int index; // Elemento del menu que tiene el foco
int previousIndex; // Elemento que tenia el foco previamente int previousIndex; // Elemento que tenia el foco previamente
Color previousItemColor; // Color del item nque tenia el foco previamente Color previousItemColor; // Color del item nque tenia el foco previamente
SDL_Rect rect; // Rectangulo del selector SDL_Rect rect; // Rectangulo del selector
Color color; // Color del selector Color color; // Color del selector
Color itemColor; // Color del item Color itemColor; // Color del item
Color jumpItemColors[8]; // Transición de colores para el item seleccionado Color jumpItemColors[8]; // Transición de colores para el item seleccionado
int itemColorIndex; // Indice del color de transición para el item seleccionado int itemColorIndex; // Indice del color de transición para el item seleccionado
int a; // Cantidad de transparencia para el rectangulo del selector int a; // Cantidad de transparencia para el rectangulo del selector
}; };
// Objetos y punteros // Objetos y punteros
@@ -88,10 +88,10 @@ class Menu {
JA_Sound_t *soundAccept; // Sonido al aceptar o elegir una opción del menu JA_Sound_t *soundAccept; // Sonido al aceptar o elegir una opción del menu
JA_Sound_t *soundCancel; // Sonido al cancelar el menu JA_Sound_t *soundCancel; // Sonido al cancelar el menu
JA_Sound_t *soundMove; // Sonido al mover el selector JA_Sound_t *soundMove; // Sonido al mover el selector
Color colorGreyed; // Color para los elementos agrisados Color colorGreyed; // Color para los elementos agrisados
Rectangle rectBG; // Rectangulo de fondo del menu Rectangle rectBG; // Rectangulo de fondo del menu
std::vector<Item> item; // Estructura para cada elemento del menu std::vector<Item> item; // Estructura para cada elemento del menu
Selector selector; // Variables para pintar el selector del menu Selector selector; // Variables para pintar el selector del menu
std::string font_png; std::string font_png;
std::string font_txt; std::string font_txt;