neteja tidy a source/game (fixes d'arrel: BulletKind enum class, signatures, branches)

This commit is contained in:
2026-05-14 21:52:45 +02:00
parent 0ee117135c
commit 9a2da460cc
19 changed files with 643 additions and 693 deletions
+69 -69
View File
@@ -1,6 +1,6 @@
#include "game/entities/balloon.h" #include "game/entities/balloon.h"
#include <math.h> // for abs #include <cmath> // for abs
#include "core/rendering/animatedsprite.h" // for AnimatedSprite #include "core/rendering/animatedsprite.h" // for AnimatedSprite
#include "core/rendering/movingsprite.h" // for MovingSprite #include "core/rendering/movingsprite.h" // for MovingSprite
@@ -26,9 +26,9 @@ Balloon::Balloon(float x, float y, Uint8 kind, float velx, float speed, Uint16 c
// Inicializa los valores de velocidad y gravedad // Inicializa los valores de velocidad y gravedad
this->velX = velx; this->velX = velx;
velY = 0; velY = 0;
maxVelY = 3.0f; maxVelY = 3.0F;
gravity = 0.09f; gravity = 0.09F;
defaultVelY = 2.6f; defaultVelY = 2.6F;
// Puntos que da el globo al ser destruido // Puntos que da el globo al ser destruido
score = BALLOON_SCORE_1; score = BALLOON_SCORE_1;
@@ -48,9 +48,9 @@ Balloon::Balloon(float x, float y, Uint8 kind, float velx, float speed, Uint16 c
// Inicializa los valores de velocidad y gravedad // Inicializa los valores de velocidad y gravedad
this->velX = velx; this->velX = velx;
velY = 0; velY = 0;
maxVelY = 3.0f; maxVelY = 3.0F;
gravity = 0.10f; gravity = 0.10F;
defaultVelY = 3.5f; defaultVelY = 3.5F;
// Puntos que da el globo al ser destruido // Puntos que da el globo al ser destruido
score = BALLOON_SCORE_2; score = BALLOON_SCORE_2;
@@ -70,9 +70,9 @@ Balloon::Balloon(float x, float y, Uint8 kind, float velx, float speed, Uint16 c
// Inicializa los valores de velocidad y gravedad // Inicializa los valores de velocidad y gravedad
this->velX = velx; this->velX = velx;
velY = 0; velY = 0;
maxVelY = 3.0f; maxVelY = 3.0F;
gravity = 0.10f; gravity = 0.10F;
defaultVelY = 4.50f; defaultVelY = 4.50F;
// Puntos que da el globo al ser destruido // Puntos que da el globo al ser destruido
score = BALLOON_SCORE_3; score = BALLOON_SCORE_3;
@@ -92,9 +92,9 @@ Balloon::Balloon(float x, float y, Uint8 kind, float velx, float speed, Uint16 c
// Inicializa los valores de velocidad y gravedad // Inicializa los valores de velocidad y gravedad
this->velX = velx; this->velX = velx;
velY = 0; velY = 0;
maxVelY = 3.0f; maxVelY = 3.0F;
gravity = 0.10f; gravity = 0.10F;
defaultVelY = 4.95f; defaultVelY = 4.95F;
// Puntos que da el globo al ser destruido // Puntos que da el globo al ser destruido
score = BALLOON_SCORE_4; score = BALLOON_SCORE_4;
@@ -115,7 +115,7 @@ Balloon::Balloon(float x, float y, Uint8 kind, float velx, float speed, Uint16 c
this->velX = velx; this->velX = velx;
velY = abs(velx) * 2; velY = abs(velx) * 2;
maxVelY = abs(velx) * 2; maxVelY = abs(velx) * 2;
gravity = 0.00f; gravity = 0.00F;
defaultVelY = abs(velx) * 2; defaultVelY = abs(velx) * 2;
// Puntos que da el globo al ser destruido // Puntos que da el globo al ser destruido
@@ -137,7 +137,7 @@ Balloon::Balloon(float x, float y, Uint8 kind, float velx, float speed, Uint16 c
this->velX = velx; this->velX = velx;
velY = abs(velx) * 2; velY = abs(velx) * 2;
maxVelY = abs(velx) * 2; maxVelY = abs(velx) * 2;
gravity = 0.00f; gravity = 0.00F;
defaultVelY = abs(velx) * 2; defaultVelY = abs(velx) * 2;
// Puntos que da el globo al ser destruido // Puntos que da el globo al ser destruido
@@ -159,7 +159,7 @@ Balloon::Balloon(float x, float y, Uint8 kind, float velx, float speed, Uint16 c
this->velX = velx; this->velX = velx;
velY = abs(velx) * 2; velY = abs(velx) * 2;
maxVelY = abs(velx) * 2; maxVelY = abs(velx) * 2;
gravity = 0.00f; gravity = 0.00F;
defaultVelY = abs(velx) * 2; defaultVelY = abs(velx) * 2;
// Puntos que da el globo al ser destruido // Puntos que da el globo al ser destruido
@@ -181,7 +181,7 @@ Balloon::Balloon(float x, float y, Uint8 kind, float velx, float speed, Uint16 c
this->velX = velx; this->velX = velx;
velY = abs(velx) * 2; velY = abs(velx) * 2;
maxVelY = abs(velx) * 2; maxVelY = abs(velx) * 2;
gravity = 0.00f; gravity = 0.00F;
defaultVelY = abs(velx) * 2; defaultVelY = abs(velx) * 2;
// Puntos que da el globo al ser destruido // Puntos que da el globo al ser destruido
@@ -202,9 +202,9 @@ Balloon::Balloon(float x, float y, Uint8 kind, float velx, float speed, Uint16 c
// Inicializa los valores de velocidad y gravedad // Inicializa los valores de velocidad y gravedad
this->velX = velx; this->velX = velx;
velY = 0; velY = 0;
maxVelY = 3.0f; maxVelY = 3.0F;
gravity = 0.10f; gravity = 0.10F;
defaultVelY = 4.95f; defaultVelY = 4.95F;
// Puntos que da el globo al ser destruido // Puntos que da el globo al ser destruido
score = 0; score = 0;
@@ -215,7 +215,7 @@ Balloon::Balloon(float x, float y, Uint8 kind, float velx, float speed, Uint16 c
// Añade rotación al sprite // Añade rotación al sprite
sprite->setRotate(false); sprite->setRotate(false);
sprite->setRotateSpeed(0); sprite->setRotateSpeed(0);
if (velX > 0.0f) { if (velX > 0.0F) {
sprite->setRotateAmount(2.0); sprite->setRotateAmount(2.0);
} else { } else {
sprite->setRotateAmount(-2.0); sprite->setRotateAmount(-2.0);
@@ -235,12 +235,12 @@ Balloon::Balloon(float x, float y, Uint8 kind, float velx, float speed, Uint16 c
bouncing.enabled = false; bouncing.enabled = false;
bouncing.counter = 0; bouncing.counter = 0;
bouncing.speed = 2; bouncing.speed = 2;
bouncing.zoomW = 1.0f; bouncing.zoomW = 1.0F;
bouncing.zoomH = 1.0f; bouncing.zoomH = 1.0F;
bouncing.despX = 0.0f; bouncing.despX = 0.0F;
bouncing.despY = 0.0f; bouncing.despY = 0.0F;
bouncing.w = {1.10f, 1.05f, 1.00f, 0.95f, 0.90f, 0.95f, 1.00f, 1.02f, 1.05f, 1.02f}; bouncing.w = {1.10F, 1.05F, 1.00F, 0.95F, 0.90F, 0.95F, 1.00F, 1.02F, 1.05F, 1.02F};
bouncing.h = {0.90f, 0.95f, 1.00f, 1.05f, 1.10f, 1.05f, 1.00f, 0.98f, 0.95f, 0.98f}; bouncing.h = {0.90F, 0.95F, 1.00F, 1.05F, 1.10F, 1.05F, 1.00F, 0.98F, 0.95F, 0.98F};
// Alto y ancho del sprite // Alto y ancho del sprite
sprite->setWidth(width); sprite->setWidth(width);
@@ -270,7 +270,7 @@ Balloon::Balloon(float x, float y, Uint8 kind, float velx, float speed, Uint16 c
invulnerable = beingCreated; invulnerable = beingCreated;
counter = 0; counter = 0;
travelY = 1.0f; travelY = 1.0F;
this->speed = speed; this->speed = speed;
// Tipo // Tipo
@@ -286,10 +286,11 @@ Balloon::~Balloon() {
void Balloon::allignTo(int x) { void Balloon::allignTo(int x) {
posX = float(x - (width / 2)); posX = float(x - (width / 2));
if (posX < PLAY_AREA_LEFT) if (posX < PLAY_AREA_LEFT) {
posX = PLAY_AREA_LEFT + 1; posX = PLAY_AREA_LEFT + 1;
else if ((posX + width) > PLAY_AREA_RIGHT) } else if ((posX + width) > PLAY_AREA_RIGHT) {
posX = float(PLAY_AREA_RIGHT - width - 1); posX = float(PLAY_AREA_RIGHT - width - 1);
}
// Posición X,Y del sprite // Posición X,Y del sprite
sprite->setPosX(getPosX()); sprite->setPosX(getPosX());
@@ -313,10 +314,10 @@ void Balloon::render() {
} }
} else if (isBeingCreated()) { } else if (isBeingCreated()) {
// Aplica alpha blending // Aplica alpha blending
sprite->getTexture()->setAlpha(255 - (int)((float)creationCounter * (255.0f / (float)creationCounterIni))); sprite->getTexture()->setAlpha(255 - (int)((float)creationCounter * (255.0F / (float)creationCounterIni)));
sprite->render(); sprite->render();
if (kind == POWER_BALL) { if (kind == POWER_BALL) {
Sprite *sp = new Sprite(sprite->getRect(), sprite->getTexture(), sprite->getRenderer()); auto *sp = new Sprite(sprite->getRect(), sprite->getTexture(), sprite->getRenderer());
sp->setSpriteClip(407, 0, 37, 37); sp->setSpriteClip(407, 0, 37, 37);
sp->render(); sp->render();
delete sp; delete sp;
@@ -326,7 +327,7 @@ void Balloon::render() {
sprite->render(); sprite->render();
if (kind == POWER_BALL and !popping) { if (kind == POWER_BALL and !popping) {
Sprite *sp = new Sprite(sprite->getRect(), sprite->getTexture(), sprite->getRenderer()); auto *sp = new Sprite(sprite->getRect(), sprite->getTexture(), sprite->getRenderer());
sp->setSpriteClip(407, 0, 37, 37); sp->setSpriteClip(407, 0, 37, 37);
sp->render(); sp->render();
delete sp; delete sp;
@@ -403,9 +404,9 @@ void Balloon::move() {
travelY += speed; travelY += speed;
// Si la distancia acumulada en Y es igual a la velocidad, se aplica la gravedad // Si la distancia acumulada en Y es igual a la velocidad, se aplica la gravedad
if (travelY >= 1.0f) { if (travelY >= 1.0F) {
// Quita el excedente // Quita el excedente
travelY -= 1.0f; travelY -= 1.0F;
// Aplica la gravedad al objeto sin pasarse de una velocidad máxima // Aplica la gravedad al objeto sin pasarse de una velocidad máxima
velY += gravity; velY += gravity;
@@ -431,17 +432,17 @@ void Balloon::disable() {
counter = 0; counter = 0;
creationCounter = 0; creationCounter = 0;
creationCounterIni = 0; creationCounterIni = 0;
defaultVelY = 0.0f; defaultVelY = 0.0F;
enabled = false; enabled = false;
gravity = 0.0f; gravity = 0.0F;
height = 0; height = 0;
invulnerable = false; invulnerable = false;
kind = 0; kind = 0;
maxVelY = 0.0f; maxVelY = 0.0F;
menace = 0; menace = 0;
popping = false; popping = false;
posX = 0.0f; posX = 0.0F;
posY = 0.0f; posY = 0.0F;
power = 0; power = 0;
score = 0; score = 0;
size = 0; size = 0;
@@ -449,8 +450,8 @@ void Balloon::disable() {
stopped = false; stopped = false;
stoppedCounter = 0; stoppedCounter = 0;
travelY = 0; travelY = 0;
velX = 0.0f; velX = 0.0F;
velY = 0.0f; velY = 0.0F;
visible = false; visible = false;
width = 0; width = 0;
sprite->clear(); sprite->clear();
@@ -580,32 +581,32 @@ void Balloon::updateAnimation() {
} }
// Comprueba si el globo está habilitado // Comprueba si el globo está habilitado
bool Balloon::isEnabled() { auto Balloon::isEnabled() const -> bool {
return enabled; return enabled;
} }
// Obtiene del valor de la variable // Obtiene del valor de la variable
float Balloon::getPosX() { auto Balloon::getPosX() const -> float {
return posX; return posX;
} }
// Obtiene del valor de la variable // Obtiene del valor de la variable
float Balloon::getPosY() { auto Balloon::getPosY() const -> float {
return posY; return posY;
} }
// Obtiene del valor de la variable // Obtiene del valor de la variable
float Balloon::getVelY() { auto Balloon::getVelY() const -> float {
return velY; return velY;
} }
// Obtiene del valor de la variable // Obtiene del valor de la variable
int Balloon::getWidth() { auto Balloon::getWidth() const -> int {
return width; return width;
} }
// Obtiene del valor de la variable // Obtiene del valor de la variable
int Balloon::getHeight() { auto Balloon::getHeight() const -> int {
return height; return height;
} }
@@ -620,22 +621,22 @@ void Balloon::setSpeed(float speed) {
} }
// Obtiene del valor de la variable // Obtiene del valor de la variable
int Balloon::getKind() { auto Balloon::getKind() const -> int {
return kind; return kind;
} }
// Obtiene del valor de la variable // Obtiene del valor de la variable
Uint8 Balloon::getSize() { auto Balloon::getSize() const -> Uint8 {
return size; return size;
} }
// Obtiene la clase a la que pertenece el globo // Obtiene la clase a la que pertenece el globo
Uint8 Balloon::getClass() { auto Balloon::getClass() const -> Uint8 {
if ((kind >= BALLOON_1) && (kind <= BALLOON_4)) { if ((kind >= BALLOON_1) && (kind <= BALLOON_4)) {
return BALLOON_CLASS; return BALLOON_CLASS;
} }
else if ((kind >= HEXAGON_1) && (kind <= HEXAGON_4)) { if ((kind >= HEXAGON_1) && (kind <= HEXAGON_4)) {
return HEXAGON_CLASS; return HEXAGON_CLASS;
} }
@@ -648,7 +649,7 @@ void Balloon::setStop(bool state) {
} }
// Obtiene del valor de la variable // Obtiene del valor de la variable
bool Balloon::isStopped() { auto Balloon::isStopped() const -> bool {
return stopped; return stopped;
} }
@@ -658,7 +659,7 @@ void Balloon::setBlink(bool value) {
} }
// Obtiene del valor de la variable // Obtiene del valor de la variable
bool Balloon::isBlinking() { auto Balloon::isBlinking() const -> bool {
return blinking; return blinking;
} }
@@ -668,7 +669,7 @@ void Balloon::setVisible(bool value) {
} }
// Obtiene del valor de la variable // Obtiene del valor de la variable
bool Balloon::isVisible() { auto Balloon::isVisible() const -> bool {
return visible; return visible;
} }
@@ -678,7 +679,7 @@ void Balloon::setInvulnerable(bool value) {
} }
// Obtiene del valor de la variable // Obtiene del valor de la variable
bool Balloon::isInvulnerable() { auto Balloon::isInvulnerable() const -> bool {
return invulnerable; return invulnerable;
} }
@@ -688,7 +689,7 @@ void Balloon::setBeingCreated(bool value) {
} }
// Obtiene del valor de la variable // Obtiene del valor de la variable
bool Balloon::isBeingCreated() { auto Balloon::isBeingCreated() const -> bool {
return beingCreated; return beingCreated;
} }
@@ -698,7 +699,7 @@ void Balloon::setPopping(bool value) {
} }
// Obtiene del valor de la variable // Obtiene del valor de la variable
bool Balloon::isPopping() { auto Balloon::isPopping() const -> bool {
return popping; return popping;
} }
@@ -708,17 +709,17 @@ void Balloon::setStoppedTimer(Uint16 time) {
} }
// Obtiene del valor de la variable // Obtiene del valor de la variable
Uint16 Balloon::getStoppedTimer() { auto Balloon::getStoppedTimer() const -> Uint16 {
return stoppedCounter; return stoppedCounter;
} }
// Obtiene del valor de la variable // Obtiene del valor de la variable
Uint16 Balloon::getScore() { auto Balloon::getScore() const -> Uint16 {
return score; return score;
} }
// Obtiene el circulo de colisión // Obtiene el circulo de colisión
circle_t &Balloon::getCollider() { auto Balloon::getCollider() -> circle_t & {
return collider; return collider;
} }
@@ -729,16 +730,15 @@ void Balloon::updateColliders() {
} }
// Obtiene le valor de la variable // Obtiene le valor de la variable
Uint8 Balloon::getMenace() { auto Balloon::getMenace() const -> Uint8 {
if (isEnabled()) { if (isEnabled()) {
return menace; return menace;
} else {
return 0;
} }
return 0;
} }
// Obtiene le valor de la variable // Obtiene le valor de la variable
Uint8 Balloon::getPower() { auto Balloon::getPower() const -> Uint8 {
return power; return power;
} }
@@ -755,12 +755,12 @@ void Balloon::bounceStart() {
void Balloon::bounceStop() { void Balloon::bounceStop() {
bouncing.enabled = false; bouncing.enabled = false;
bouncing.counter = 0; bouncing.counter = 0;
bouncing.zoomW = 1.0f; bouncing.zoomW = 1.0F;
bouncing.zoomH = 1.0f; bouncing.zoomH = 1.0F;
sprite->setZoomW(bouncing.zoomW); sprite->setZoomW(bouncing.zoomW);
sprite->setZoomH(bouncing.zoomH); sprite->setZoomH(bouncing.zoomH);
bouncing.despX = 0.0f; bouncing.despX = 0.0F;
bouncing.despY = 0.0f; bouncing.despY = 0.0F;
} }
void Balloon::updateBounce() { void Balloon::updateBounce() {
+29 -29
View File
@@ -40,8 +40,8 @@ constexpr int BALLOON_CLASS = 0;
constexpr int HEXAGON_CLASS = 1; constexpr int HEXAGON_CLASS = 1;
// Velocidad del globo // Velocidad del globo
constexpr float BALLOON_VELX_POSITIVE = 0.7f; constexpr float BALLOON_VELX_POSITIVE = 0.7F;
constexpr float BALLOON_VELX_NEGATIVE = -0.7f; constexpr float BALLOON_VELX_NEGATIVE = -0.7F;
// Índice para las animaciones de los globos // Índice para las animaciones de los globos
constexpr int BALLOON_MOVING_ANIMATION = 0; constexpr int BALLOON_MOVING_ANIMATION = 0;
@@ -52,11 +52,11 @@ constexpr int BALLOON_BORN_ANIMATION = 2;
constexpr int MAX_BALLOONS = 100; constexpr int MAX_BALLOONS = 100;
// Velocidades a las que se mueven los globos // Velocidades a las que se mueven los globos
constexpr float BALLOON_SPEED_1 = 0.60f; constexpr float BALLOON_SPEED_1 = 0.60F;
constexpr float BALLOON_SPEED_2 = 0.70f; constexpr float BALLOON_SPEED_2 = 0.70F;
constexpr float BALLOON_SPEED_3 = 0.80f; constexpr float BALLOON_SPEED_3 = 0.80F;
constexpr float BALLOON_SPEED_4 = 0.90f; constexpr float BALLOON_SPEED_4 = 0.90F;
constexpr float BALLOON_SPEED_5 = 1.00f; constexpr float BALLOON_SPEED_5 = 1.00F;
// Tamaño de los globos // Tamaño de los globos
constexpr int BALLOON_WIDTH_1 = 8; constexpr int BALLOON_WIDTH_1 = 8;
@@ -147,7 +147,7 @@ class Balloon {
~Balloon(); ~Balloon();
Balloon(const Balloon &) = delete; Balloon(const Balloon &) = delete;
Balloon &operator=(const Balloon &) = delete; auto operator=(const Balloon &) -> Balloon & = delete;
// Centra el globo en la posición X // Centra el globo en la posición X
void allignTo(int x); void allignTo(int x);
@@ -168,22 +168,22 @@ class Balloon {
void update(); void update();
// Comprueba si el globo está habilitado // Comprueba si el globo está habilitado
bool isEnabled(); [[nodiscard]] auto isEnabled() const -> bool;
// Obtiene del valor de la variable // Obtiene del valor de la variable
float getPosX(); [[nodiscard]] auto getPosX() const -> float;
// Obtiene del valor de la variable // Obtiene del valor de la variable
float getPosY(); [[nodiscard]] auto getPosY() const -> float;
// Obtiene del valor de la variable // Obtiene del valor de la variable
float getVelY(); [[nodiscard]] auto getVelY() const -> float;
// Obtiene del valor de la variable // Obtiene del valor de la variable
int getWidth(); [[nodiscard]] auto getWidth() const -> int;
// Obtiene del valor de la variable // Obtiene del valor de la variable
int getHeight(); [[nodiscard]] auto getHeight() const -> int;
// Establece el valor de la variable // Establece el valor de la variable
void setVelY(float velY); void setVelY(float velY);
@@ -192,62 +192,62 @@ class Balloon {
void setSpeed(float speed); void setSpeed(float speed);
// Obtiene del valor de la variable // Obtiene del valor de la variable
int getKind(); [[nodiscard]] auto getKind() const -> int;
// Obtiene del valor de la variable // Obtiene del valor de la variable
Uint8 getSize(); [[nodiscard]] auto getSize() const -> Uint8;
// Obtiene la clase a la que pertenece el globo // Obtiene la clase a la que pertenece el globo
Uint8 getClass(); [[nodiscard]] auto getClass() const -> Uint8;
// Establece el valor de la variable // Establece el valor de la variable
void setStop(bool value); void setStop(bool state);
// Obtiene del valor de la variable // Obtiene del valor de la variable
bool isStopped(); [[nodiscard]] auto isStopped() const -> bool;
// Establece el valor de la variable // Establece el valor de la variable
void setBlink(bool value); void setBlink(bool value);
// Obtiene del valor de la variable // Obtiene del valor de la variable
bool isBlinking(); [[nodiscard]] auto isBlinking() const -> bool;
// Establece el valor de la variable // Establece el valor de la variable
void setVisible(bool value); void setVisible(bool value);
// Obtiene del valor de la variable // Obtiene del valor de la variable
bool isVisible(); [[nodiscard]] auto isVisible() const -> bool;
// Establece el valor de la variable // Establece el valor de la variable
void setInvulnerable(bool value); void setInvulnerable(bool value);
// Obtiene del valor de la variable // Obtiene del valor de la variable
bool isInvulnerable(); [[nodiscard]] auto isInvulnerable() const -> bool;
// Obtiene del valor de la variable // Obtiene del valor de la variable
bool isBeingCreated(); [[nodiscard]] auto isBeingCreated() const -> bool;
// Establece el valor de la variable // Establece el valor de la variable
void setPopping(bool value); void setPopping(bool value);
// Obtiene del valor de la variable // Obtiene del valor de la variable
bool isPopping(); [[nodiscard]] auto isPopping() const -> bool;
// Establece el valor de la variable // Establece el valor de la variable
void setStoppedTimer(Uint16 time); void setStoppedTimer(Uint16 time);
// Obtiene del valor de la variable // Obtiene del valor de la variable
Uint16 getStoppedTimer(); [[nodiscard]] auto getStoppedTimer() const -> Uint16;
// Obtiene del valor de la variable // Obtiene del valor de la variable
Uint16 getScore(); [[nodiscard]] auto getScore() const -> Uint16;
// Obtiene el circulo de colisión // Obtiene el circulo de colisión
circle_t &getCollider(); auto getCollider() -> circle_t &;
// Obtiene le valor de la variable // Obtiene le valor de la variable
Uint8 getMenace(); [[nodiscard]] auto getMenace() const -> Uint8;
// Obtiene le valor de la variable // Obtiene le valor de la variable
Uint8 getPower(); [[nodiscard]] auto getPower() const -> Uint8;
}; };
+18 -22
View File
@@ -1,11 +1,11 @@
#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 NO_KIND, PLAY_AREA_LEFT, PLAY_AREA_RIGHT, PLAY_A... #include "game/defaults.hpp" // for BulletKind::NONE, PLAY_AREA_LEFT, PLAY_AREA_RIGHT, PLAY_A...
class Texture; class Texture;
// Constructor // Constructor
Bullet::Bullet(int x, int y, int kind, bool poweredUp, int owner, Texture *texture, SDL_Renderer *renderer) { Bullet::Bullet(int x, int y, BulletKind kind, bool poweredUp, 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
@@ -27,7 +27,7 @@ Bullet::Bullet(int x, int y, int kind, bool poweredUp, int owner, Texture *textu
// Valores especificos según el tipo // Valores especificos según el tipo
switch (kind) { switch (kind) {
case BULLET_UP: case BulletKind::UP:
// Establece la velocidad inicial // Establece la velocidad inicial
velX = 0; velX = 0;
@@ -39,7 +39,7 @@ Bullet::Bullet(int x, int y, int kind, bool poweredUp, int owner, Texture *textu
} }
break; break;
case BULLET_LEFT: case BulletKind::LEFT:
// Establece la velocidad inicial // Establece la velocidad inicial
velX = -2; velX = -2;
@@ -51,7 +51,7 @@ Bullet::Bullet(int x, int y, int kind, bool poweredUp, int owner, Texture *textu
} }
break; break;
case BULLET_RIGHT: case BulletKind::RIGHT:
// Establece la velocidad inicial // Establece la velocidad inicial
velX = 2; velX = 2;
@@ -85,7 +85,7 @@ void Bullet::render() {
} }
// Actualiza la posición y estado del objeto en horizontal // Actualiza la posición y estado del objeto en horizontal
Uint8 Bullet::move() { auto Bullet::move() -> Uint8 {
// Variable con el valor de retorno // Variable con el valor de retorno
Uint8 msg = BULLET_MOVE_OK; Uint8 msg = BULLET_MOVE_OK;
@@ -95,19 +95,19 @@ Uint8 Bullet::move() {
// 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 ((posX < PLAY_AREA_LEFT - width) || (posX > PLAY_AREA_RIGHT)) {
// Se deshabilita // Se deshabilita
kind = NO_KIND; kind = BulletKind::NONE;
// Mensaje de salida // Mensaje de salida
msg = BULLET_MOVE_OUT; msg = BULLET_MOVE_OUT;
} }
// Mueve el objeto a su nueva posición en vertical // Mueve el objeto a su nueva posición en vertical
posY += int(velY); posY += velY;
// 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 (posY < PLAY_AREA_TOP - height) {
// Se deshabilita // Se deshabilita
kind = NO_KIND; kind = BulletKind::NONE;
// Mensaje de salida // Mensaje de salida
msg = BULLET_MOVE_OUT; msg = BULLET_MOVE_OUT;
@@ -124,26 +124,22 @@ Uint8 Bullet::move() {
} }
// Comprueba si el objeto está habilitado // Comprueba si el objeto está habilitado
bool Bullet::isEnabled() { auto Bullet::isEnabled() const -> bool {
if (kind == NO_KIND) { return kind != BulletKind::NONE;
return false;
} else {
return true;
}
} }
// Deshabilita el objeto // Deshabilita el objeto
void Bullet::disable() { void Bullet::disable() {
kind = NO_KIND; kind = BulletKind::NONE;
} }
// Obtiene el valor de la variable // Obtiene el valor de la variable
int Bullet::getPosX() { auto Bullet::getPosX() const -> int {
return posX; return posX;
} }
// Obtiene el valor de la variable // Obtiene el valor de la variable
int Bullet::getPosY() { auto Bullet::getPosY() const -> int {
return posY; return posY;
} }
@@ -158,22 +154,22 @@ void Bullet::setPosY(int y) {
} }
// Obtiene el valor de la variable // Obtiene el valor de la variable
int Bullet::getVelY() { auto Bullet::getVelY() const -> int {
return velY; return velY;
} }
// Obtiene el valor de la variable // Obtiene el valor de la variable
int Bullet::getKind() { auto Bullet::getKind() const -> BulletKind {
return kind; return kind;
} }
// Obtiene el valor de la variable // Obtiene el valor de la variable
int Bullet::getOwner() { auto Bullet::getOwner() const -> int {
return owner; return owner;
} }
// Obtiene el circulo de colisión // Obtiene el circulo de colisión
circle_t &Bullet::getCollider() { auto Bullet::getCollider() -> circle_t & {
return collider; return collider;
} }
+20 -15
View File
@@ -2,14 +2,19 @@
#include <SDL3/SDL.h> #include <SDL3/SDL.h>
#include <cstdint> // for uint8_t
#include "utils/utils.h" // for circle_t #include "utils/utils.h" // for circle_t
class Sprite; class Sprite;
class Texture; class Texture;
// Tipos de bala // Tipus de bala. Enum class fortament tipat per evitar confusió accidental
constexpr int BULLET_UP = 1; // amb altres `int`/`Uint8` (p.ex. el `owner` a `createBullet`).
constexpr int BULLET_LEFT = 2; enum class BulletKind : std::uint8_t {
constexpr int BULLET_RIGHT = 3; NONE = 0, // bala desactivada / fora de pantalla
UP = 1,
LEFT = 2,
RIGHT = 3,
};
// Tipos de retorno de la función move de la bala // Tipos de retorno de la función move de la bala
constexpr int BULLET_MOVE_OK = 0; constexpr int BULLET_MOVE_OK = 0;
@@ -28,7 +33,7 @@ class Bullet {
Uint8 height; // Alto del objeto Uint8 height; // Alto del objeto
int velX; // Velocidad en el eje X int velX; // Velocidad en el eje X
int velY; // Velocidad en el eje Y int velY; // Velocidad en el eje Y
int kind; // Tipo de objeto BulletKind kind; // Tipo de objeto
int owner; // Identificador del dueño del objeto int owner; // Identificador del dueño del objeto
circle_t collider; // Circulo de colisión del objeto circle_t collider; // Circulo de colisión del objeto
@@ -37,31 +42,31 @@ class Bullet {
public: public:
// Constructor // Constructor
Bullet(int x, int y, int kind, bool poweredUp, int owner, Texture *texture, SDL_Renderer *renderer); Bullet(int x, int y, BulletKind kind, bool poweredUp, int owner, Texture *texture, SDL_Renderer *renderer);
// Destructor // Destructor
~Bullet(); ~Bullet();
Bullet(const Bullet &) = delete; Bullet(const Bullet &) = delete;
Bullet &operator=(const Bullet &) = delete; auto operator=(const Bullet &) -> Bullet & = delete;
// Pinta el objeto en pantalla // Pinta el objeto en pantalla
void render(); void render();
// Actualiza la posición y estado del objeto // Actualiza la posición y estado del objeto
Uint8 move(); auto move() -> Uint8;
// Comprueba si el objeto está habilitado // Comprueba si el objeto está habilitado
bool isEnabled(); [[nodiscard]] auto isEnabled() const -> bool;
// Deshabilita el objeto // Deshabilita el objeto
void disable(); void disable();
// Obtiene el valor de la variable // Obtiene el valor de la variable
int getPosX(); [[nodiscard]] auto getPosX() const -> int;
// Obtiene el valor de la variable // Obtiene el valor de la variable
int getPosY(); [[nodiscard]] auto getPosY() const -> int;
// Establece el valor de la variable // Establece el valor de la variable
void setPosX(int x); void setPosX(int x);
@@ -70,14 +75,14 @@ class Bullet {
void setPosY(int y); void setPosY(int y);
// Obtiene el valor de la variable // Obtiene el valor de la variable
int getVelY(); [[nodiscard]] auto getVelY() const -> int;
// Obtiene el valor de la variable // Obtiene el valor de la variable
int getKind(); [[nodiscard]] auto getKind() const -> BulletKind;
// Obtiene el valor de la variable // Obtiene el valor de la variable
int getOwner(); [[nodiscard]] auto getOwner() const -> int;
// Obtiene el circulo de colisión // Obtiene el circulo de colisión
circle_t &getCollider(); auto getCollider() -> circle_t &;
}; };
+22 -23
View File
@@ -1,6 +1,6 @@
#include "game/entities/item.h" #include "game/entities/item.h"
#include <stdlib.h> // for rand #include <cstdlib> // for rand
#include "core/rendering/animatedsprite.h" // for AnimatedSprite #include "core/rendering/animatedsprite.h" // for AnimatedSprite
#include "game/defaults.hpp" // for PLAY_AREA_LEFT, PLAY_AREA_RIGHT, PLAY_AR... #include "game/defaults.hpp" // for PLAY_AREA_LEFT, PLAY_AREA_RIGHT, PLAY_AR...
@@ -13,7 +13,7 @@ Item::Item(Uint8 kind, float x, float y, Texture *texture, std::vector<std::stri
this->kind = kind; this->kind = kind;
enabled = true; enabled = true;
timeToLive = 600; timeToLive = 600;
accelX = 0.0f; accelX = 0.0F;
floorCollision = false; floorCollision = false;
if (kind == ITEM_COFFEE_MACHINE) { if (kind == ITEM_COFFEE_MACHINE) {
@@ -21,18 +21,18 @@ Item::Item(Uint8 kind, float x, float y, Texture *texture, std::vector<std::stri
height = 29; height = 29;
posX = (((int)x + (PLAY_AREA_WIDTH / 2)) % (PLAY_AREA_WIDTH - width - 5)) + 2; posX = (((int)x + (PLAY_AREA_WIDTH / 2)) % (PLAY_AREA_WIDTH - width - 5)) + 2;
posY = PLAY_AREA_TOP - height; posY = PLAY_AREA_TOP - height;
velX = 0.0f; velX = 0.0F;
velY = -0.1f; velY = -0.1F;
accelY = 0.1f; accelY = 0.1F;
collider.r = 10; collider.r = 10;
} else { } else {
width = 16; width = 16;
height = 16; height = 16;
posX = x; posX = x;
posY = y; posY = y;
velX = -1.0f + ((rand() % 5) * 0.5f); velX = -1.0F + ((rand() % 5) * 0.5F);
velY = -4.0f; velY = -4.0F;
accelY = 0.2f; accelY = 0.2F;
collider.r = width / 2; collider.r = width / 2;
} }
@@ -66,12 +66,10 @@ void Item::allignTo(int x) {
// Pinta el objeto en la pantalla // Pinta el objeto en la pantalla
void Item::render() { void Item::render() {
if (enabled) { // Mentre quede temps de sobra (>200) es renderitza sempre; quan està a
if (timeToLive > 200) { // punt d'expirar, parpalleja alternant 10 frames visibles i 10 invisibles.
sprite->render(); if (enabled && (timeToLive > 200 || timeToLive % 20 > 10)) {
} else if (timeToLive % 20 > 10) { sprite->render();
sprite->render();
}
} }
} }
@@ -146,42 +144,43 @@ void Item::updateTimeToLive() {
// Comprueba si el objeto sigue vivo // Comprueba si el objeto sigue vivo
void Item::checkTimeToLive() { void Item::checkTimeToLive() {
if (timeToLive == 0) if (timeToLive == 0) {
disable(); disable();
}
} }
// Obtiene del valor de la variable // Obtiene del valor de la variable
float Item::getPosX() { auto Item::getPosX() const -> float {
return posX; return posX;
} }
// Obtiene del valor de la variable // Obtiene del valor de la variable
float Item::getPosY() { auto Item::getPosY() const -> float {
return posY; return posY;
} }
// Obtiene del valor de la variable // Obtiene del valor de la variable
int Item::getWidth() { auto Item::getWidth() const -> int {
return width; return width;
} }
// Obtiene del valor de la variable // Obtiene del valor de la variable
int Item::getHeight() { auto Item::getHeight() const -> int {
return height; return height;
} }
// Obtiene del valor de la variable // Obtiene del valor de la variable
int Item::getClass() { auto Item::getClass() const -> int {
return kind; return kind;
} }
// Obtiene el valor de la variable // Obtiene el valor de la variable
bool Item::isEnabled() { auto Item::isEnabled() const -> bool {
return enabled; return enabled;
} }
// Obtiene el circulo de colisión // Obtiene el circulo de colisión
circle_t &Item::getCollider() { auto Item::getCollider() -> circle_t & {
return collider; return collider;
} }
@@ -192,6 +191,6 @@ void Item::shiftColliders() {
} }
// Informa si el objeto ha colisionado con el suelo // Informa si el objeto ha colisionado con el suelo
bool Item::isOnFloor() { auto Item::isOnFloor() const -> bool {
return floorCollision; return floorCollision;
} }
+9 -9
View File
@@ -53,7 +53,7 @@ class Item {
~Item(); ~Item();
Item(const Item &) = delete; Item(const Item &) = delete;
Item &operator=(const Item &) = delete; auto operator=(const Item &) -> Item & = delete;
// Centra el objeto en la posición X // Centra el objeto en la posición X
void allignTo(int x); void allignTo(int x);
@@ -74,26 +74,26 @@ class Item {
void checkTimeToLive(); void checkTimeToLive();
// Obtiene del valor de la variable // Obtiene del valor de la variable
float getPosX(); [[nodiscard]] auto getPosX() const -> float;
// Obtiene del valor de la variable // Obtiene del valor de la variable
float getPosY(); [[nodiscard]] auto getPosY() const -> float;
// Obtiene del valor de la variable // Obtiene del valor de la variable
int getWidth(); [[nodiscard]] auto getWidth() const -> int;
// Obtiene del valor de la variable // Obtiene del valor de la variable
int getHeight(); [[nodiscard]] auto getHeight() const -> int;
// Obtiene del valor de la variable // Obtiene del valor de la variable
int getClass(); [[nodiscard]] auto getClass() const -> int;
// Obtiene el valor de la variable // Obtiene el valor de la variable
bool isEnabled(); [[nodiscard]] auto isEnabled() const -> bool;
// Obtiene el circulo de colisión // Obtiene el circulo de colisión
circle_t &getCollider(); auto getCollider() -> circle_t &;
// Informa si el objeto ha colisionado con el suelo // Informa si el objeto ha colisionado con el suelo
bool isOnFloor(); [[nodiscard]] auto isOnFloor() const -> bool;
}; };
+35 -40
View File
@@ -1,6 +1,7 @@
#include "game/entities/player.h" #include "game/entities/player.h"
#include <stdlib.h> // for rand #include <algorithm>
#include <cstdlib> // for rand
#include "core/input/input.h" // for inputs_e #include "core/input/input.h" // for inputs_e
#include "core/rendering/animatedsprite.h" // for AnimatedSprite #include "core/rendering/animatedsprite.h" // for AnimatedSprite
@@ -72,7 +73,7 @@ void Player::init() {
score = 0; score = 0;
// Establece el multiplicador de puntos inicial // Establece el multiplicador de puntos inicial
scoreMultiplier = 1.0f; scoreMultiplier = 1.0F;
// Inicia el contador para la cadencia de disparo // Inicia el contador para la cadencia de disparo
cooldown = 10; cooldown = 10;
@@ -200,8 +201,8 @@ void Player::setFiringStatus(Uint8 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 aBodyCoffees;
std::string aHeadCoffees = ""; std::string aHeadCoffees;
if (coffees > 0) { if (coffees > 0) {
aBodyCoffees = coffees == 1 ? "_1C" : "_2C"; aBodyCoffees = coffees == 1 ? "_1C" : "_2C";
aHeadCoffees = "_1C"; aHeadCoffees = "_1C";
@@ -239,33 +240,29 @@ void Player::setAnimation() {
} }
// Obtiene el valor de la variable // Obtiene el valor de la variable
int Player::getPosX() { auto Player::getPosX() const -> int {
return int(posX); return int(posX);
} }
// Obtiene el valor de la variable // Obtiene el valor de la variable
int Player::getPosY() { auto Player::getPosY() const -> int {
return posY; return posY;
} }
// Obtiene el valor de la variable // Obtiene el valor de la variable
int Player::getWidth() { auto Player::getWidth() const -> int {
return width; return width;
} }
// Obtiene el valor de la variable // Obtiene el valor de la variable
int Player::getHeight() { auto Player::getHeight() const -> int {
return height; return height;
} }
// Indica si el jugador puede disparar // Indica si el jugador puede disparar
bool Player::canFire() { 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
if (cooldown > 0) { return cooldown <= 0;
return false;
} else {
return true;
}
} }
// Establece el valor de la variable // Establece el valor de la variable
@@ -298,7 +295,7 @@ void Player::update() {
} }
// Obtiene la puntuación del jugador // Obtiene la puntuación del jugador
Uint32 Player::getScore() { auto Player::getScore() const -> Uint32 {
return score; return score;
} }
@@ -313,7 +310,7 @@ void Player::addScore(Uint32 score) {
} }
// Obtiene el valor de la variable // Obtiene el valor de la variable
bool Player::isAlive() { auto Player::isAlive() const -> bool {
return alive; return alive;
} }
@@ -324,17 +321,17 @@ void Player::setAlive(bool value) {
if (!value) { if (!value) {
deathSprite->setPosX(headSprite->getRect().x); deathSprite->setPosX(headSprite->getRect().x);
deathSprite->setPosY(headSprite->getRect().y); deathSprite->setPosY(headSprite->getRect().y);
deathSprite->setAccelY(0.2f); deathSprite->setAccelY(0.2F);
deathSprite->setVelY(-6.6f); deathSprite->setVelY(-6.6F);
deathSprite->setVelX(3.3f); deathSprite->setVelX(3.3F);
if (rand() % 2 == 0) { if (rand() % 2 == 0) {
deathSprite->setVelX(-3.3f); deathSprite->setVelX(-3.3F);
} }
} }
} }
// Obtiene el valor de la variable // Obtiene el valor de la variable
float Player::getScoreMultiplier() { auto Player::getScoreMultiplier() const -> float {
return scoreMultiplier; return scoreMultiplier;
} }
@@ -345,24 +342,24 @@ void Player::setScoreMultiplier(float 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 (scoreMultiplier < 5.0F) {
scoreMultiplier += 0.1f; scoreMultiplier += 0.1F;
} else { } else {
scoreMultiplier = 5.0f; scoreMultiplier = 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 (scoreMultiplier > 1.0F) {
scoreMultiplier -= 0.1f; scoreMultiplier -= 0.1F;
} else { } else {
scoreMultiplier = 1.0f; scoreMultiplier = 1.0F;
} }
} }
// Obtiene el valor de la variable // Obtiene el valor de la variable
bool Player::isInvulnerable() { auto Player::isInvulnerable() const -> bool {
return invulnerable; return invulnerable;
} }
@@ -372,7 +369,7 @@ void Player::setInvulnerable(bool value) {
} }
// Obtiene el valor de la variable // Obtiene el valor de la variable
Uint16 Player::getInvulnerableCounter() { auto Player::getInvulnerableCounter() const -> Uint16 {
return invulnerableCounter; return invulnerableCounter;
} }
@@ -403,7 +400,7 @@ void Player::updateDeathCounter() {
} }
// Obtiene el valor de la variable // Obtiene el valor de la variable
bool Player::isPowerUp() { auto Player::isPowerUp() const -> bool {
return powerUp; return powerUp;
} }
@@ -413,7 +410,7 @@ void Player::setPowerUp(bool value) {
} }
// Obtiene el valor de la variable // Obtiene el valor de la variable
Uint16 Player::getPowerUpCounter() { auto Player::getPowerUpCounter() const -> Uint16 {
return powerUpCounter; return powerUpCounter;
} }
@@ -433,7 +430,7 @@ void Player::updatePowerUpCounter() {
} }
// Obtiene el valor de la variable // Obtiene el valor de la variable
bool Player::hasExtraHit() { auto Player::hasExtraHit() const -> bool {
return extraHit; return extraHit;
} }
@@ -441,9 +438,7 @@ bool Player::hasExtraHit() {
void Player::giveExtraHit() { void Player::giveExtraHit() {
extraHit = true; extraHit = true;
coffees++; coffees++;
if (coffees > 2) { coffees = std::min<int>(coffees, 2);
coffees = 2;
}
} }
// Quita el toque extra al jugador // Quita el toque extra al jugador
@@ -469,29 +464,29 @@ void Player::disableInput() {
} }
// Devuelve el numero de cafes actuales // Devuelve el numero de cafes actuales
Uint8 Player::getCoffees() { auto Player::getCoffees() const -> Uint8 {
return coffees; return coffees;
} }
// Obtiene el circulo de colisión // Obtiene el circulo de colisión
circle_t &Player::getCollider() { auto Player::getCollider() -> circle_t & {
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(posX + (width / 2));
collider.y = int(posY + (height / 2)); collider.y = (posY + (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
Texture *Player::getDeadTexture() { auto Player::getDeadTexture() -> Texture * {
return deathSprite->getTexture(); return deathSprite->getTexture();
; ;
} }
// Obtiene el valor de la variable // Obtiene el valor de la variable
Uint16 Player::getDeathCounter() { auto Player::getDeathCounter() const -> Uint16 {
return deathCounter; return deathCounter;
} }
+18 -18
View File
@@ -87,7 +87,7 @@ class Player {
~Player(); ~Player();
Player(const Player &) = delete; Player(const Player &) = delete;
Player &operator=(const Player &) = delete; auto operator=(const Player &) -> Player & = delete;
// Iniciador // Iniciador
void init(); void init();
@@ -117,19 +117,19 @@ class Player {
void setAnimation(); void setAnimation();
// Obtiene el valor de la variable // Obtiene el valor de la variable
int getPosX(); [[nodiscard]] auto getPosX() const -> int;
// Obtiene el valor de la variable // Obtiene el valor de la variable
int getPosY(); [[nodiscard]] auto getPosY() const -> int;
// Obtiene el valor de la variable // Obtiene el valor de la variable
int getWidth(); [[nodiscard]] auto getWidth() const -> int;
// Obtiene el valor de la variable // Obtiene el valor de la variable
int getHeight(); [[nodiscard]] auto getHeight() const -> int;
// Indica si el jugador puede disparar // Indica si el jugador puede disparar
bool canFire(); [[nodiscard]] auto canFire() const -> bool;
// Establece el valor de la variable // Establece el valor de la variable
void setFireCooldown(int time); void setFireCooldown(int time);
@@ -138,7 +138,7 @@ class Player {
void updateCooldown(); void updateCooldown();
// Obtiene la puntuación del jugador // Obtiene la puntuación del jugador
Uint32 getScore(); [[nodiscard]] auto getScore() const -> Uint32;
// Asigna un valor a la puntuación del jugador // Asigna un valor a la puntuación del jugador
void setScore(Uint32 score); void setScore(Uint32 score);
@@ -147,13 +147,13 @@ class Player {
void addScore(Uint32 score); void addScore(Uint32 score);
// Obtiene el valor de la variable // Obtiene el valor de la variable
bool isAlive(); [[nodiscard]] auto isAlive() const -> bool;
// Establece el valor de la variable // Establece el valor de la variable
void setAlive(bool value); void setAlive(bool value);
// Obtiene el valor de la variable // Obtiene el valor de la variable
float getScoreMultiplier(); [[nodiscard]] auto getScoreMultiplier() const -> float;
// Establece el valor de la variable // Establece el valor de la variable
void setScoreMultiplier(float value); void setScoreMultiplier(float value);
@@ -165,25 +165,25 @@ class Player {
void decScoreMultiplier(); void decScoreMultiplier();
// Obtiene el valor de la variable // Obtiene el valor de la variable
bool isInvulnerable(); [[nodiscard]] auto isInvulnerable() const -> bool;
// Establece el valor de la variable // Establece el valor de la variable
void setInvulnerable(bool value); void setInvulnerable(bool value);
// Obtiene el valor de la variable // Obtiene el valor de la variable
Uint16 getInvulnerableCounter(); [[nodiscard]] auto getInvulnerableCounter() const -> Uint16;
// Establece el valor de la variable // Establece el valor de la variable
void setInvulnerableCounter(Uint16 value); void setInvulnerableCounter(Uint16 value);
// Obtiene el valor de la variable // Obtiene el valor de la variable
bool isPowerUp(); [[nodiscard]] auto isPowerUp() const -> bool;
// Establece el valor de la variable // Establece el valor de la variable
void setPowerUp(bool value); void setPowerUp(bool value);
// Obtiene el valor de la variable // Obtiene el valor de la variable
Uint16 getPowerUpCounter(); [[nodiscard]] auto getPowerUpCounter() const -> Uint16;
// Establece el valor de la variable // Establece el valor de la variable
void setPowerUpCounter(Uint16 value); void setPowerUpCounter(Uint16 value);
@@ -192,7 +192,7 @@ class Player {
void updatePowerUpCounter(); void updatePowerUpCounter();
// Obtiene el valor de la variable // Obtiene el valor de la variable
bool hasExtraHit(); [[nodiscard]] auto hasExtraHit() const -> bool;
// Concede un toque extra al jugador // Concede un toque extra al jugador
void giveExtraHit(); void giveExtraHit();
@@ -207,14 +207,14 @@ class Player {
void disableInput(); void disableInput();
// Devuelve el numero de cafes actuales // Devuelve el numero de cafes actuales
Uint8 getCoffees(); [[nodiscard]] auto getCoffees() const -> Uint8;
// Obtiene el circulo de colisión // Obtiene el circulo de colisión
circle_t &getCollider(); auto getCollider() -> circle_t &;
// 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
Texture *getDeadTexture(); auto getDeadTexture() -> Texture *;
// Obtiene el valor de la variable // Obtiene el valor de la variable
Uint16 getDeathCounter(); [[nodiscard]] auto getDeathCounter() const -> Uint16;
}; };
+168 -183
View File
File diff suppressed because it is too large Load Diff
+12 -10
View File
@@ -2,10 +2,12 @@
#include <SDL3/SDL.h> #include <SDL3/SDL.h>
#include <string> // for string, basic_string #include <cstdint> // for uint8_t
#include <vector> // for vector #include <string> // for string, basic_string
#include <vector> // for vector
#include "utils/utils.h" // for demoKeys_t, color_t #include "game/entities/bullet.h" // for BulletKind (signatura de createBullet)
#include "utils/utils.h" // for demoKeys_t, color_t
class Balloon; class Balloon;
class Bullet; class Bullet;
class Fade; class Fade;
@@ -92,7 +94,7 @@ class Game {
}; };
// Fases de la secuencia de muerte del jugador // Fases de la secuencia de muerte del jugador
enum class DeathPhase { None, enum class DeathPhase : std::uint8_t { None,
Shaking, Shaking,
Waiting, Waiting,
Done }; Done };
@@ -299,7 +301,7 @@ class Game {
void updateHiScore(); void updateHiScore();
// Transforma un valor numérico en una cadena de 6 cifras // Transforma un valor numérico en una cadena de 6 cifras
auto updateScoreText(Uint32 num) -> std::string; static auto updateScoreText(Uint32 num) -> std::string;
// Pinta el marcador en pantalla usando un objeto texto // Pinta el marcador en pantalla usando un objeto texto
void renderScoreBoard(); void renderScoreBoard();
@@ -326,7 +328,7 @@ class Game {
void renderBalloons(); void renderBalloons();
// Crea un globo nuevo en el vector de globos // Crea un globo nuevo en el vector de globos
auto createBalloon(float x, int y, Uint8 kind, float velx, float speed, Uint16 stoppedcounter) -> Uint8; auto createBalloon(float x, float y, Uint8 kind, float velx, float speed, Uint16 creationtimer) -> Uint8;
// Crea una PowerBall // Crea una PowerBall
void createPowerBall(); void createPowerBall();
@@ -374,7 +376,7 @@ class Game {
void renderBullets(); void renderBullets();
// Crea un objeto bala // Crea un objeto bala
void createBullet(int x, int y, Uint8 kind, bool poweredUp, int owner); void createBullet(int x, int y, BulletKind kind, bool poweredUp, int owner);
// Vacia el vector de balas // Vacia el vector de balas
void freeBullets(); void freeBullets();
@@ -422,13 +424,13 @@ class Game {
void evaluateAndSetMenace(); void evaluateAndSetMenace();
// Obtiene el valor de la variable // Obtiene el valor de la variable
auto getMenace() -> Uint8; [[nodiscard]] auto getMenace() const -> Uint8;
// Establece el valor de la variable // Establece el valor de la variable
void setTimeStopped(bool value); void setTimeStopped(bool value);
// Obtiene el valor de la variable // Obtiene el valor de la variable
auto isTimeStopped() -> bool; [[nodiscard]] auto isTimeStopped() const -> bool;
// Establece el valor de la variable // Establece el valor de la variable
void setTimeStoppedCounter(Uint16 value); void setTimeStoppedCounter(Uint16 value);
@@ -470,7 +472,7 @@ class Game {
void updateDeathShake(); void updateDeathShake();
// Indica si el efecto de agitación intensa está activo // Indica si el efecto de agitación intensa está activo
auto isDeathShaking() -> bool; [[nodiscard]] auto isDeathShaking() const -> bool;
// Actualiza la secuencia de muerte del jugador // Actualiza la secuencia de muerte del jugador
void updateDeathSequence(); void updateDeathSequence();
+60 -102
View File
@@ -30,30 +30,38 @@ namespace Options {
std::string crtpi_file_path; std::string crtpi_file_path;
int current_crtpi_preset = 0; int current_crtpi_preset = 0;
// Lectura tolerant d'un camp YAML: assigna a `target` el valor del camp
// si existeix i el tipus encaixa. Si la clau no hi és o el tipus YAML
// no és compatible amb T, conserva el valor previ de `target` (default).
// Retorna true si s'ha llegit, false si s'ha conservat el default.
template <typename T>
auto tryGet(const fkyaml::node &node, const std::string &key, T &target) -> bool {
if (!node.contains(key)) {
return false;
}
try {
target = node[key].get_value<T>();
return true;
} catch (...) {
// @INTENTIONAL: valor YAML amb tipus incompatible per a T. La
// política del loader és conservar el default existent en
// `target` enlloc d'avortar la càrrega de la resta del fitxer.
return false;
}
}
// --- Helpers locals --- // --- Helpers locals ---
namespace { namespace {
void parseBoolField(const fkyaml::node &node, const std::string &key, bool &target) { void parseBoolField(const fkyaml::node &node, const std::string &key, bool &target) {
if (node.contains(key)) { tryGet<bool>(node, key, target);
try {
target = node[key].get_value<bool>();
} catch (...) {}
}
} }
void parseIntField(const fkyaml::node &node, const std::string &key, int &target) { void parseIntField(const fkyaml::node &node, const std::string &key, int &target) {
if (node.contains(key)) { tryGet<int>(node, key, target);
try {
target = node[key].get_value<int>();
} catch (...) {}
}
} }
void parseStringField(const fkyaml::node &node, const std::string &key, std::string &target) { void parseStringField(const fkyaml::node &node, const std::string &key, std::string &target) {
if (node.contains(key)) { tryGet<std::string>(node, key, target);
try {
target = node[key].get_value<std::string>();
} catch (...) {}
}
} }
void loadWindowFromYaml(const fkyaml::node &yaml) { void loadWindowFromYaml(const fkyaml::node &yaml) {
@@ -72,10 +80,9 @@ namespace Options {
parseBoolField(vid, "fullscreen", video.fullscreen); parseBoolField(vid, "fullscreen", video.fullscreen);
parseBoolField(vid, "vsync", video.vsync); parseBoolField(vid, "vsync", video.vsync);
parseBoolField(vid, "integer_scale", video.integer_scale); parseBoolField(vid, "integer_scale", video.integer_scale);
if (vid.contains("scale_mode")) { int scale_mode_int = static_cast<int>(video.scale_mode);
try { if (tryGet<int>(vid, "scale_mode", scale_mode_int)) {
video.scale_mode = static_cast<SDL_ScaleMode>(vid["scale_mode"].get_value<int>()); video.scale_mode = static_cast<SDL_ScaleMode>(scale_mode_int);
} catch (...) {}
} }
if (vid.contains("gpu")) { if (vid.contains("gpu")) {
@@ -94,13 +101,11 @@ namespace Options {
if (vid.contains("shader")) { if (vid.contains("shader")) {
const auto &sh = vid["shader"]; const auto &sh = vid["shader"];
parseBoolField(sh, "enabled", video.shader.enabled); parseBoolField(sh, "enabled", video.shader.enabled);
if (sh.contains("current_shader")) { std::string shader_kind;
try { if (tryGet<std::string>(sh, "current_shader", shader_kind)) {
auto s = sh["current_shader"].get_value<std::string>(); video.shader.current_shader = (shader_kind == "crtpi" || shader_kind == "CRTPI")
video.shader.current_shader = (s == "crtpi" || s == "CRTPI") ? Rendering::ShaderType::CRTPI
? Rendering::ShaderType::CRTPI : Rendering::ShaderType::POSTFX;
: Rendering::ShaderType::POSTFX;
} catch (...) {}
} }
parseStringField(sh, "current_postfx_preset", video.shader.current_postfx_preset_name); parseStringField(sh, "current_postfx_preset", video.shader.current_postfx_preset_name);
parseStringField(sh, "current_crtpi_preset", video.shader.current_crtpi_preset_name); parseStringField(sh, "current_crtpi_preset", video.shader.current_crtpi_preset_name);
@@ -112,27 +117,21 @@ namespace Options {
const auto &aud = yaml["audio"]; const auto &aud = yaml["audio"];
parseBoolField(aud, "enabled", audio.enabled); parseBoolField(aud, "enabled", audio.enabled);
if (aud.contains("volume")) { if (tryGet<float>(aud, "volume", audio.volume)) {
try { audio.volume = std::clamp(audio.volume, 0.0F, 1.0F);
audio.volume = std::clamp(aud["volume"].get_value<float>(), 0.0F, 1.0F);
} catch (...) {}
} }
if (aud.contains("music")) { if (aud.contains("music")) {
const auto &mus = aud["music"]; const auto &mus = aud["music"];
parseBoolField(mus, "enabled", audio.music.enabled); parseBoolField(mus, "enabled", audio.music.enabled);
if (mus.contains("volume")) { if (tryGet<float>(mus, "volume", audio.music.volume)) {
try { audio.music.volume = std::clamp(audio.music.volume, 0.0F, 1.0F);
audio.music.volume = std::clamp(mus["volume"].get_value<float>(), 0.0F, 1.0F);
} catch (...) {}
} }
} }
if (aud.contains("sound")) { if (aud.contains("sound")) {
const auto &snd = aud["sound"]; const auto &snd = aud["sound"];
parseBoolField(snd, "enabled", audio.sound.enabled); parseBoolField(snd, "enabled", audio.sound.enabled);
if (snd.contains("volume")) { if (tryGet<float>(snd, "volume", audio.sound.volume)) {
try { audio.sound.volume = std::clamp(audio.sound.volume, 0.0F, 1.0F);
audio.sound.volume = std::clamp(snd["volume"].get_value<float>(), 0.0F, 1.0F);
} catch (...) {}
} }
} }
} }
@@ -162,10 +161,9 @@ namespace Options {
size_t i = 0; size_t i = 0;
for (const auto &entry : ins) { for (const auto &entry : ins) {
if (i >= inputs.size()) { break; } if (i >= inputs.size()) { break; }
if (entry.contains("device_type")) { int device_type_int = inputs[i].deviceType;
try { if (tryGet<int>(entry, "device_type", device_type_int)) {
inputs[i].deviceType = static_cast<Uint8>(entry["device_type"].get_value<int>()); inputs[i].deviceType = static_cast<Uint8>(device_type_int);
} catch (...) {}
} }
++i; ++i;
} }
@@ -229,11 +227,7 @@ namespace Options {
auto yaml = fkyaml::node::deserialize(CONTENT); auto yaml = fkyaml::node::deserialize(CONTENT);
int file_version = 0; int file_version = 0;
if (yaml.contains("config_version")) { tryGet<int>(yaml, "config_version", file_version);
try {
file_version = yaml["config_version"].get_value<int>();
} catch (...) {}
}
if (file_version != Settings::CURRENT_CONFIG_VERSION) { if (file_version != Settings::CURRENT_CONFIG_VERSION) {
std::cout << "Config version " << file_version std::cout << "Config version " << file_version
<< " != expected " << Settings::CURRENT_CONFIG_VERSION << " != expected " << Settings::CURRENT_CONFIG_VERSION
@@ -352,31 +346,27 @@ namespace Options {
namespace { namespace {
void parseFloatField(const fkyaml::node &node, const std::string &key, float &target) { void parseFloatField(const fkyaml::node &node, const std::string &key, float &target) {
if (node.contains(key)) { tryGet<float>(node, key, target);
try {
target = node[key].get_value<float>();
} catch (...) {}
}
} }
auto defaultPostFXPresets() -> const std::vector<PostFXPreset> & { auto defaultPostFXPresets() -> const std::vector<PostFXPreset> & {
static const std::vector<PostFXPreset> DEFAULTS = { static const std::vector<PostFXPreset> DEFAULTS = {
{"CRT", 0.6F, 0.7F, 0.15F, 0.6F, 0.8F}, {.name = "CRT", .vignette = 0.6F, .scanlines = 0.7F, .chroma = 0.15F, .mask = 0.6F, .gamma = 0.8F},
{"NTSC", 0.4F, 0.5F, 0.2F, 0.4F, 0.5F, 0.0F, 0.6F}, {.name = "NTSC", .vignette = 0.4F, .scanlines = 0.5F, .chroma = 0.2F, .mask = 0.4F, .gamma = 0.5F, .curvature = 0.0F, .bleeding = 0.6F},
{"CURVED", 0.5F, 0.6F, 0.1F, 0.5F, 0.7F, 0.8F}, {.name = "CURVED", .vignette = 0.5F, .scanlines = 0.6F, .chroma = 0.1F, .mask = 0.5F, .gamma = 0.7F, .curvature = 0.8F},
{"SCANLINES", 0.0F, 0.8F}, {.name = "SCANLINES", .vignette = 0.0F, .scanlines = 0.8F},
{"SUBTLE", 0.3F, 0.4F, 0.05F, 0.0F, 0.3F}, {.name = "SUBTLE", .vignette = 0.3F, .scanlines = 0.4F, .chroma = 0.05F, .mask = 0.0F, .gamma = 0.3F},
{"CRT LIVE", 0.5F, 0.6F, 0.3F, 0.3F, 0.4F, 0.3F, 0.4F, 0.8F}, {.name = "CRT LIVE", .vignette = 0.5F, .scanlines = 0.6F, .chroma = 0.3F, .mask = 0.3F, .gamma = 0.4F, .curvature = 0.3F, .bleeding = 0.4F, .flicker = 0.8F},
}; };
return DEFAULTS; return DEFAULTS;
} }
auto defaultCrtPiPresets() -> const std::vector<CrtPiPreset> & { auto defaultCrtPiPresets() -> const std::vector<CrtPiPreset> & {
static const std::vector<CrtPiPreset> DEFAULTS = { static const std::vector<CrtPiPreset> DEFAULTS = {
{"Default", 6.0F, 0.12F, 3.5F, 2.4F, 2.2F, 0.80F, 0.05F, 0.10F, 2, true, true, true, false, false}, {.name = "Default", .scanline_weight = 6.0F, .scanline_gap_brightness = 0.12F, .bloom_factor = 3.5F, .input_gamma = 2.4F, .output_gamma = 2.2F, .mask_brightness = 0.80F, .curvature_x = 0.05F, .curvature_y = 0.10F, .mask_type = 2, .enable_scanlines = true, .enable_multisample = true, .enable_gamma = true, .enable_curvature = false, .enable_sharper = false},
{"Curved", 6.0F, 0.12F, 3.5F, 2.4F, 2.2F, 0.80F, 0.05F, 0.10F, 2, true, true, true, true, false}, {.name = "Curved", .scanline_weight = 6.0F, .scanline_gap_brightness = 0.12F, .bloom_factor = 3.5F, .input_gamma = 2.4F, .output_gamma = 2.2F, .mask_brightness = 0.80F, .curvature_x = 0.05F, .curvature_y = 0.10F, .mask_type = 2, .enable_scanlines = true, .enable_multisample = true, .enable_gamma = true, .enable_curvature = true, .enable_sharper = false},
{"Sharp", 6.0F, 0.12F, 3.5F, 2.4F, 2.2F, 0.80F, 0.05F, 0.10F, 2, true, false, true, false, true}, {.name = "Sharp", .scanline_weight = 6.0F, .scanline_gap_brightness = 0.12F, .bloom_factor = 3.5F, .input_gamma = 2.4F, .output_gamma = 2.2F, .mask_brightness = 0.80F, .curvature_x = 0.05F, .curvature_y = 0.10F, .mask_type = 2, .enable_scanlines = true, .enable_multisample = false, .enable_gamma = true, .enable_curvature = false, .enable_sharper = true},
{"Minimal", 8.0F, 0.05F, 2.0F, 2.4F, 2.2F, 1.00F, 0.0F, 0.0F, 0, true, false, false, false, false}, {.name = "Minimal", .scanline_weight = 8.0F, .scanline_gap_brightness = 0.05F, .bloom_factor = 2.0F, .input_gamma = 2.4F, .output_gamma = 2.2F, .mask_brightness = 1.00F, .curvature_x = 0.0F, .curvature_y = 0.0F, .mask_type = 0, .enable_scanlines = true, .enable_multisample = false, .enable_gamma = false, .enable_curvature = false, .enable_sharper = false},
}; };
return DEFAULTS; return DEFAULTS;
} }
@@ -449,11 +439,7 @@ namespace Options {
if (yaml.contains("presets")) { if (yaml.contains("presets")) {
for (const auto &p : yaml["presets"]) { for (const auto &p : yaml["presets"]) {
PostFXPreset preset; PostFXPreset preset;
if (p.contains("name")) { tryGet<std::string>(p, "name", preset.name);
try {
preset.name = p["name"].get_value<std::string>();
} catch (...) {}
}
parseFloatField(p, "vignette", preset.vignette); parseFloatField(p, "vignette", preset.vignette);
parseFloatField(p, "scanlines", preset.scanlines); parseFloatField(p, "scanlines", preset.scanlines);
parseFloatField(p, "chroma", preset.chroma); parseFloatField(p, "chroma", preset.chroma);
@@ -506,11 +492,7 @@ namespace Options {
if (yaml.contains("presets")) { if (yaml.contains("presets")) {
for (const auto &p : yaml["presets"]) { for (const auto &p : yaml["presets"]) {
CrtPiPreset preset; CrtPiPreset preset;
if (p.contains("name")) { tryGet<std::string>(p, "name", preset.name);
try {
preset.name = p["name"].get_value<std::string>();
} catch (...) {}
}
parseFloatField(p, "scanline_weight", preset.scanline_weight); parseFloatField(p, "scanline_weight", preset.scanline_weight);
parseFloatField(p, "scanline_gap_brightness", preset.scanline_gap_brightness); parseFloatField(p, "scanline_gap_brightness", preset.scanline_gap_brightness);
parseFloatField(p, "bloom_factor", preset.bloom_factor); parseFloatField(p, "bloom_factor", preset.bloom_factor);
@@ -519,36 +501,12 @@ namespace Options {
parseFloatField(p, "mask_brightness", preset.mask_brightness); parseFloatField(p, "mask_brightness", preset.mask_brightness);
parseFloatField(p, "curvature_x", preset.curvature_x); parseFloatField(p, "curvature_x", preset.curvature_x);
parseFloatField(p, "curvature_y", preset.curvature_y); parseFloatField(p, "curvature_y", preset.curvature_y);
if (p.contains("mask_type")) { tryGet<int>(p, "mask_type", preset.mask_type);
try { tryGet<bool>(p, "enable_scanlines", preset.enable_scanlines);
preset.mask_type = p["mask_type"].get_value<int>(); tryGet<bool>(p, "enable_multisample", preset.enable_multisample);
} catch (...) {} tryGet<bool>(p, "enable_gamma", preset.enable_gamma);
} tryGet<bool>(p, "enable_curvature", preset.enable_curvature);
if (p.contains("enable_scanlines")) { tryGet<bool>(p, "enable_sharper", preset.enable_sharper);
try {
preset.enable_scanlines = p["enable_scanlines"].get_value<bool>();
} catch (...) {}
}
if (p.contains("enable_multisample")) {
try {
preset.enable_multisample = p["enable_multisample"].get_value<bool>();
} catch (...) {}
}
if (p.contains("enable_gamma")) {
try {
preset.enable_gamma = p["enable_gamma"].get_value<bool>();
} catch (...) {}
}
if (p.contains("enable_curvature")) {
try {
preset.enable_curvature = p["enable_curvature"].get_value<bool>();
} catch (...) {}
}
if (p.contains("enable_sharper")) {
try {
preset.enable_sharper = p["enable_sharper"].get_value<bool>();
} catch (...) {}
}
crtpi_presets.push_back(preset); crtpi_presets.push_back(preset);
} }
} }
+4 -4
View File
@@ -43,7 +43,7 @@ Instructions::Instructions(SDL_Renderer *renderer, section_t *section) {
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() << std::endl; std::cout << "Error: textTexture could not be created!\nSDL Error: " << SDL_GetError() << '\n';
} }
// Inicializa variables // Inicializa variables
@@ -197,7 +197,7 @@ 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 (SDL_PollEvent(eventHandler) != 0) { while (static_cast<int>(SDL_PollEvent(eventHandler)) != 0) {
// Evento de salida de la aplicación // Evento de salida de la aplicación
if (eventHandler->type == SDL_EVENT_QUIT) { if (eventHandler->type == SDL_EVENT_QUIT) {
quitRequested = true; quitRequested = true;
@@ -260,11 +260,11 @@ void Instructions::start(mode_e mode) {
} }
// Indica si las instrucciones han terminado // Indica si las instrucciones han terminado
bool Instructions::hasFinished() const { 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
bool Instructions::isQuitRequested() const { auto Instructions::isQuitRequested() const -> bool {
return quitRequested; return quitRequested;
} }
+3 -2
View File
@@ -2,13 +2,14 @@
#include <SDL3/SDL.h> #include <SDL3/SDL.h>
#include <vector> // for vector #include <cstdint> // for uint8_t
#include <vector> // for vector
class Sprite; class Sprite;
class Text; class Text;
class Texture; class Texture;
struct section_t; struct section_t;
enum mode_e { enum mode_e : std::uint8_t {
m_manual, m_manual,
m_auto m_auto
}; };
+30 -30
View File
@@ -39,7 +39,7 @@ Intro::Intro(SDL_Renderer *renderer, section_t *section) {
// Inicializa los bitmaps de la intro // Inicializa los bitmaps de la intro
const int totalBitmaps = 6; const int totalBitmaps = 6;
for (int i = 0; i < totalBitmaps; ++i) { for (int i = 0; i < totalBitmaps; ++i) {
SmartSprite *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);
@@ -50,57 +50,57 @@ Intro::Intro(SDL_Renderer *renderer, section_t *section) {
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 totalTexts = 9;
for (int i = 0; i < totalTexts; ++i) { for (int i = 0; i < totalTexts; ++i) {
Writer *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);
@@ -157,11 +157,11 @@ Intro::~Intro() {
delete eventHandler; delete eventHandler;
// 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;
} }
} }
@@ -329,7 +329,7 @@ void Intro::update() {
ticks = SDL_GetTicks(); ticks = SDL_GetTicks();
// Actualiza los objetos // Actualiza los objetos
for (auto bitmap : bitmaps) { for (auto *bitmap : bitmaps) {
bitmap->update(); bitmap->update();
} }
@@ -351,7 +351,7 @@ 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();
} }
+77 -73
View File
@@ -1,8 +1,8 @@
#include "game/scenes/title.h" #include "game/scenes/title.h"
#include <SDL3/SDL.h> #include <SDL3/SDL.h>
#include <stdlib.h> // for rand
#include <cstdlib> // for rand
#include <iostream> // for basic_ostream, operator<<, basic_ostrea... #include <iostream> // for basic_ostream, operator<<, basic_ostrea...
#include <string> // for basic_string, operator+, char_traits #include <string> // for basic_string, operator+, char_traits
@@ -147,10 +147,10 @@ void Title::init() {
coffeeBitmap->setPosY(11 - 200); coffeeBitmap->setPosY(11 - 200);
coffeeBitmap->setWidth(167); coffeeBitmap->setWidth(167);
coffeeBitmap->setHeight(46); coffeeBitmap->setHeight(46);
coffeeBitmap->setVelX(0.0f); coffeeBitmap->setVelX(0.0F);
coffeeBitmap->setVelY(2.5f); coffeeBitmap->setVelY(2.5F);
coffeeBitmap->setAccelX(0.0f); coffeeBitmap->setAccelX(0.0F);
coffeeBitmap->setAccelY(0.1f); coffeeBitmap->setAccelY(0.1F);
coffeeBitmap->setSpriteClip(0, 0, 167, 46); coffeeBitmap->setSpriteClip(0, 0, 167, 46);
coffeeBitmap->setEnabled(true); coffeeBitmap->setEnabled(true);
coffeeBitmap->setEnabledCounter(0); coffeeBitmap->setEnabledCounter(0);
@@ -163,10 +163,10 @@ void Title::init() {
crisisBitmap->setPosY(57 + 200); crisisBitmap->setPosY(57 + 200);
crisisBitmap->setWidth(137); crisisBitmap->setWidth(137);
crisisBitmap->setHeight(46); crisisBitmap->setHeight(46);
crisisBitmap->setVelX(0.0f); crisisBitmap->setVelX(0.0F);
crisisBitmap->setVelY(-2.5f); crisisBitmap->setVelY(-2.5F);
crisisBitmap->setAccelX(0.0f); crisisBitmap->setAccelX(0.0F);
crisisBitmap->setAccelY(-0.1f); crisisBitmap->setAccelY(-0.1F);
crisisBitmap->setSpriteClip(0, 0, 137, 46); crisisBitmap->setSpriteClip(0, 0, 137, 46);
crisisBitmap->setEnabled(true); crisisBitmap->setEnabled(true);
crisisBitmap->setEnabledCounter(0); crisisBitmap->setEnabledCounter(0);
@@ -202,7 +202,7 @@ void Title::init() {
// Inicializa los valores del vector con los valores del seno // Inicializa los valores del vector con los valores del seno
for (int i = 0; i < 360; ++i) { for (int i = 0; i < 360; ++i) {
sin[i] = SDL_sinf((float)i * 3.14f / 180.0f); sin[i] = SDL_sinf((float)i * 3.14F / 180.0F);
} }
// Actualiza los textos de los menus // Actualiza los textos de los menus
@@ -313,8 +313,9 @@ void Title::update() {
if (demo) { if (demo) {
demoThenInstructions = true; demoThenInstructions = true;
runDemoGame(); runDemoGame();
} else } else {
section->name = SECTION_PROG_LOGO; section->name = SECTION_PROG_LOGO;
}
break; break;
default: default:
@@ -326,7 +327,7 @@ void Title::update() {
updateBG(); updateBG();
// Comprueba las entradas para el menu // Comprueba las entradas para el menu
if (menuVisible == true && !fade->isEnabled()) { if (menuVisible && !fade->isEnabled()) {
menu.active->update(); menu.active->update();
} }
@@ -393,12 +394,13 @@ void Title::update() {
if (menu.active->getName() == "OPTIONS") { if (menu.active->getName() == "OPTIONS") {
switch (menu.active->getItemSelected()) { switch (menu.active->getItemSelected()) {
case 0: // Difficulty case 0: // Difficulty
if (Options::settings.difficulty == DIFFICULTY_EASY) if (Options::settings.difficulty == DIFFICULTY_EASY) {
Options::settings.difficulty = DIFFICULTY_NORMAL; Options::settings.difficulty = DIFFICULTY_NORMAL;
else if (Options::settings.difficulty == DIFFICULTY_NORMAL) } else if (Options::settings.difficulty == DIFFICULTY_NORMAL) {
Options::settings.difficulty = DIFFICULTY_HARD; Options::settings.difficulty = DIFFICULTY_HARD;
else } else {
Options::settings.difficulty = DIFFICULTY_EASY; Options::settings.difficulty = DIFFICULTY_EASY;
}
updateMenuLabels(); updateMenuLabels();
break; break;
@@ -414,8 +416,9 @@ void Title::update() {
case 5: // Language case 5: // Language
Options::settings.language++; Options::settings.language++;
if (Options::settings.language == 3) if (Options::settings.language == 3) {
Options::settings.language = 0; Options::settings.language = 0;
}
updateMenuLabels(); updateMenuLabels();
break; break;
@@ -433,8 +436,9 @@ void Title::update() {
case 8: // Windows size case 8: // Windows size
Options::window.zoom++; Options::window.zoom++;
if (Options::window.zoom > Options::window.max_zoom) if (Options::window.zoom > Options::window.max_zoom) {
Options::window.zoom = 1; Options::window.zoom = 1;
}
updateMenuLabels(); updateMenuLabels();
break; break;
@@ -585,7 +589,7 @@ void Title::render() {
text2->writeDX(TXT_CENTER | TXT_SHADOW, GAMECANVAS_CENTER_X, GAMECANVAS_HEIGHT - (BLOCK * 2), TEXT_COPYRIGHT, 1, noColor, 1, shdwTxtColor); text2->writeDX(TXT_CENTER | TXT_SHADOW, GAMECANVAS_CENTER_X, GAMECANVAS_HEIGHT - (BLOCK * 2), TEXT_COPYRIGHT, 1, noColor, 1, shdwTxtColor);
} }
if (menuVisible == true) { if (menuVisible) {
menu.active->render(); menu.active->render();
} }
@@ -593,7 +597,7 @@ void Title::render() {
dustBitmapL->render(); dustBitmapL->render();
// PRESS ANY KEY! // PRESS ANY KEY!
if ((counter % 50 > 14) && (menuVisible == false)) { if ((counter % 50 > 14) && (!menuVisible)) {
text1->writeDX(TXT_CENTER | TXT_SHADOW, GAMECANVAS_CENTER_X, PLAY_AREA_THIRD_QUARTER_Y + BLOCK, Lang::get()->getText(23), 1, noColor, 1, shdwTxtColor); text1->writeDX(TXT_CENTER | TXT_SHADOW, GAMECANVAS_CENTER_X, PLAY_AREA_THIRD_QUARTER_Y + BLOCK, Lang::get()->getText(23), 1, noColor, 1, shdwTxtColor);
} }
@@ -638,7 +642,7 @@ void Title::switchFullScreenModeVar() {
} }
// Actualiza los elementos de los menus // Actualiza los elementos de los menus
void Title::updateMenuLabels() { void Title::updateMenuLabels() const {
int i = 0; int i = 0;
// DIFFICULTY // DIFFICULTY
switch (Options::settings.difficulty) { switch (Options::settings.difficulty) {
@@ -673,9 +677,9 @@ void Title::updateMenuLabels() {
case INPUT_USE_GAMECONTROLLER: case INPUT_USE_GAMECONTROLLER:
menu.options->setItemCaption(i, Lang::get()->getText(70)); // GAME CONTROLLER menu.options->setItemCaption(i, Lang::get()->getText(70)); // GAME CONTROLLER
if (!Input::get()->gameControllerFound()) if (!Input::get()->gameControllerFound()) {
menu.options->setGreyed(i, true); menu.options->setGreyed(i, true);
else { } else {
menu.options->setGreyed(i, false); menu.options->setGreyed(i, false);
menu.options->setItemCaption(i, Options::inputs[0].name); menu.options->setItemCaption(i, Options::inputs[0].name);
} }
@@ -700,9 +704,9 @@ void Title::updateMenuLabels() {
case INPUT_USE_GAMECONTROLLER: case INPUT_USE_GAMECONTROLLER:
menu.options->setItemCaption(i, Lang::get()->getText(70)); // GAME CONTROLLER menu.options->setItemCaption(i, Lang::get()->getText(70)); // GAME CONTROLLER
if (!Input::get()->gameControllerFound()) if (!Input::get()->gameControllerFound()) {
menu.options->setGreyed(i, true); menu.options->setGreyed(i, true);
else { } else {
menu.options->setGreyed(i, false); menu.options->setGreyed(i, false);
menu.options->setItemCaption(i, Options::inputs[1].name); menu.options->setItemCaption(i, Options::inputs[1].name);
} }
@@ -725,11 +729,9 @@ void Title::updateMenuLabels() {
break; break;
case en_UK: case en_UK:
menu.options->setItemCaption(i, Lang::get()->getText(8) + ": " + Lang::get()->getText(26)); // ENGLISH
break;
default: default:
menu.options->setItemCaption(i, Lang::get()->getText(8) + ": " + Lang::get()->getText(26)); // ENGLISH // ENGLISH (i fallback per a llengües no reconegudes)
menu.options->setItemCaption(i, Lang::get()->getText(8) + ": " + Lang::get()->getText(26));
break; break;
} }
@@ -747,17 +749,19 @@ void Title::updateMenuLabels() {
i++; i++;
// SCALE MODE // SCALE MODE
if (Options::video.scale_mode == SDL_SCALEMODE_LINEAR) if (Options::video.scale_mode == SDL_SCALEMODE_LINEAR) {
menu.options->setItemCaption(i, Lang::get()->getText(60) + ": " + Lang::get()->getText(71)); // BILINEAL menu.options->setItemCaption(i, Lang::get()->getText(60) + ": " + Lang::get()->getText(71)); // BILINEAL
else } else {
menu.options->setItemCaption(i, Lang::get()->getText(60) + ": " + Lang::get()->getText(72)); // LINEAL menu.options->setItemCaption(i, Lang::get()->getText(60) + ": " + Lang::get()->getText(72)); // LINEAL
}
i++; i++;
// VSYNC // VSYNC
if (Options::video.vsync) if (Options::video.vsync) {
menu.options->setItemCaption(i, Lang::get()->getText(61) + ": " + Lang::get()->getText(73)); // ON menu.options->setItemCaption(i, Lang::get()->getText(61) + ": " + Lang::get()->getText(73)); // ON
else } else {
menu.options->setItemCaption(i, Lang::get()->getText(61) + ": " + Lang::get()->getText(74)); // OFF menu.options->setItemCaption(i, Lang::get()->getText(61) + ": " + Lang::get()->getText(74)); // OFF
}
i++; i++;
// HOW TO PLAY // HOW TO PLAY
@@ -893,12 +897,12 @@ void Title::iterate() {
// Procesa un evento individual // Procesa un evento individual
void Title::handleEvent(const SDL_Event *event) { void Title::handleEvent(const SDL_Event *event) {
// Si hay un sub-estado activo, delega el evento // Si hay un sub-estado activo, delega el evento
if (instructionsActive && instructions) { if (instructionsActive && (instructions != nullptr)) {
// SDL_EVENT_QUIT ya lo maneja Director // SDL_EVENT_QUIT ya lo maneja Director
return; return;
} }
if (demoGameActive && demoGame) { if (demoGameActive && (demoGame != nullptr)) {
demoGame->handleEvent(event); demoGame->handleEvent(event);
return; return;
} }
@@ -944,7 +948,7 @@ void Title::runDemoGame() {
} }
// Modifica las opciones para los controles de los jugadores // Modifica las opciones para los controles de los jugadores
bool Title::updatePlayerInputs(int numPlayer) { auto Title::updatePlayerInputs(int numPlayer) -> bool {
const int numDevices = availableInputDevices.size(); const int numDevices = availableInputDevices.size();
if (!Input::get()->gameControllerFound()) { // Si no hay mandos se deja todo de manera prefijada if (!Input::get()->gameControllerFound()) { // Si no hay mandos se deja todo de manera prefijada
@@ -960,37 +964,36 @@ bool Title::updatePlayerInputs(int numPlayer) {
Options::inputs[1].deviceType = INPUT_USE_GAMECONTROLLER; Options::inputs[1].deviceType = INPUT_USE_GAMECONTROLLER;
return true; return true;
} else { // Si hay mas de un dispositivo, se recorre el vector } // Si hay mas de un dispositivo, se recorre el vector
if (Options::settings.console) { if (Options::settings.console) {
std::cout << "numplayer:" << numPlayer << std::endl; std::cout << "numplayer:" << numPlayer << '\n';
std::cout << "deviceindex:" << deviceIndex[numPlayer] << std::endl; std::cout << "deviceindex:" << deviceIndex[numPlayer] << '\n';
}
// Incrementa el indice
if (deviceIndex[numPlayer] < numDevices - 1) {
deviceIndex[numPlayer]++;
} else {
deviceIndex[numPlayer] = 0;
}
if (Options::settings.console) {
std::cout << "deviceindex:" << deviceIndex[numPlayer] << std::endl;
}
// Si coincide con el del otro jugador, se lo intercambian
if (deviceIndex[0] == deviceIndex[1]) {
const int theOtherPlayer = (numPlayer + 1) % 2;
deviceIndex[theOtherPlayer]--;
if (deviceIndex[theOtherPlayer] < 0) {
deviceIndex[theOtherPlayer] = numDevices - 1;
}
}
// Copia el dispositivo marcado por el indice a la variable de opciones de cada jugador
Options::inputs[0] = availableInputDevices[deviceIndex[0]];
Options::inputs[1] = availableInputDevices[deviceIndex[1]];
return true;
} }
// Incrementa el indice
if (deviceIndex[numPlayer] < numDevices - 1) {
deviceIndex[numPlayer]++;
} else {
deviceIndex[numPlayer] = 0;
}
if (Options::settings.console) {
std::cout << "deviceindex:" << deviceIndex[numPlayer] << '\n';
}
// Si coincide con el del otro jugador, se lo intercambian
if (deviceIndex[0] == deviceIndex[1]) {
const int theOtherPlayer = (numPlayer + 1) % 2;
deviceIndex[theOtherPlayer]--;
if (deviceIndex[theOtherPlayer] < 0) {
deviceIndex[theOtherPlayer] = numDevices - 1;
}
}
// Copia el dispositivo marcado por el indice a la variable de opciones de cada jugador
Options::inputs[0] = availableInputDevices[deviceIndex[0]];
Options::inputs[1] = availableInputDevices[deviceIndex[1]];
return true;
} }
// Crea el mosaico de fondo del titulo // Crea el mosaico de fondo del titulo
@@ -1002,13 +1005,13 @@ void Title::createTiledBackground() {
} }
if (background == nullptr) { if (background == nullptr) {
if (Options::settings.console) { if (Options::settings.console) {
std::cout << "TitleSurface could not be created!\nSDL Error: " << SDL_GetError() << std::endl; std::cout << "TitleSurface could not be created!\nSDL Error: " << SDL_GetError() << '\n';
} }
} }
// Crea los objetos para pintar en la textura de fondo // Crea los objetos para pintar en la textura de fondo
Texture *bgTileTexture = new Texture(renderer, Asset::get()->get("title_bg_tile.png")); auto *bgTileTexture = new Texture(renderer, Asset::get()->get("title_bg_tile.png"));
Sprite *tile = new Sprite({0, 0, 64, 64}, bgTileTexture, renderer); auto *tile = new Sprite({0, 0, 64, 64}, bgTileTexture, renderer);
// Prepara para dibujar sobre la textura // Prepara para dibujar sobre la textura
SDL_SetRenderTarget(renderer, background); SDL_SetRenderTarget(renderer, background);
@@ -1039,23 +1042,24 @@ void Title::createTiledBackground() {
// así que aquí solo leemos la lista actual sin reescanear. // así que aquí solo leemos la lista actual sin reescanear.
void Title::checkInputDevices() { void Title::checkInputDevices() {
if (Options::settings.console) { if (Options::settings.console) {
std::cout << "Filling devices for options menu..." << std::endl; std::cout << "Filling devices for options menu..." << '\n';
} }
const int numControllers = Input::get()->getNumControllers(); const int numControllers = Input::get()->getNumControllers();
availableInputDevices.clear(); availableInputDevices.clear();
input_t temp; input_t temp;
// Añade todos los mandos // Añade todos los mandos
if (numControllers > 0) if (numControllers > 0) {
for (int i = 0; i < numControllers; ++i) { for (int i = 0; i < numControllers; ++i) {
temp.id = i; temp.id = i;
temp.name = Input::get()->getControllerName(i); temp.name = Input::get()->getControllerName(i);
temp.deviceType = INPUT_USE_GAMECONTROLLER; temp.deviceType = INPUT_USE_GAMECONTROLLER;
availableInputDevices.push_back(temp); availableInputDevices.push_back(temp);
if (Options::settings.console) { if (Options::settings.console) {
std::cout << "Device " << (int)availableInputDevices.size() << " - " << temp.name.c_str() << std::endl; std::cout << "Device " << (int)availableInputDevices.size() << " - " << temp.name.c_str() << '\n';
} }
} }
}
// Añade el teclado al final // Añade el teclado al final
temp.id = -1; temp.id = -1;
@@ -1063,8 +1067,8 @@ void Title::checkInputDevices() {
temp.deviceType = INPUT_USE_KEYBOARD; temp.deviceType = INPUT_USE_KEYBOARD;
availableInputDevices.push_back(temp); availableInputDevices.push_back(temp);
if (Options::settings.console) { if (Options::settings.console) {
std::cout << "Device " << (int)availableInputDevices.size() << " - " << temp.name.c_str() << std::endl; std::cout << "Device " << (int)availableInputDevices.size() << " - " << temp.name.c_str() << '\n';
std::cout << std::endl; std::cout << '\n';
} }
} }
+2 -2
View File
@@ -114,10 +114,10 @@ class Title {
void updateBG(); void updateBG();
// Cambia el valor de la variable de modo de pantalla completa // Cambia el valor de la variable de modo de pantalla completa
void switchFullScreenModeVar(); static void switchFullScreenModeVar();
// Actualiza los elementos de los menus // Actualiza los elementos de los menus
void updateMenuLabels(); void updateMenuLabels() const;
// Aplica las opciones de menu seleccionadas // Aplica las opciones de menu seleccionadas
void applyOptions(); void applyOptions();
+62 -57
View File
@@ -14,9 +14,7 @@
// Constructor // Constructor
Menu::Menu(SDL_Renderer *renderer, const std::string &file) Menu::Menu(SDL_Renderer *renderer, const std::string &file)
: colorGreyed{128, 128, 128}, : colorGreyed{128, 128, 128} {
font_png(""),
font_txt("") {
// Copia punteros // Copia punteros
this->renderer = renderer; this->renderer = renderer;
@@ -32,7 +30,7 @@ Menu::Menu(SDL_Renderer *renderer, const std::string &file)
x = 0; x = 0;
y = 0; y = 0;
w = 0; w = 0;
rectBG.rect = {0, 0, 0, 0}; rectBG.rect = {.x = 0, .y = 0, .w = 0, .h = 0};
rectBG.color = {0, 0, 0}; rectBG.color = {0, 0, 0};
rectBG.a = 0; rectBG.a = 0;
backgroundType = MENU_BACKGROUND_SOLID; backgroundType = MENU_BACKGROUND_SOLID;
@@ -51,12 +49,12 @@ Menu::Menu(SDL_Renderer *renderer, const std::string &file)
selector.originH = 0; selector.originH = 0;
selector.targetH = 0; selector.targetH = 0;
selector.incH = 0; selector.incH = 0;
selector.y = 0.0f; selector.y = 0.0F;
selector.h = 0.0f; selector.h = 0.0F;
selector.numJumps = 8; selector.numJumps = 8;
selector.moving = false; selector.moving = false;
selector.resizing = false; selector.resizing = false;
selector.rect = {0, 0, 0, 0}; selector.rect = {.x = 0, .y = 0, .w = 0, .h = 0};
selector.color = {0, 0, 0}; selector.color = {0, 0, 0};
selector.itemColor = {0, 0, 0}; selector.itemColor = {0, 0, 0};
selector.a = 255; selector.a = 255;
@@ -74,25 +72,23 @@ Menu::Menu(SDL_Renderer *renderer, const std::string &file)
Menu::~Menu() { Menu::~Menu() {
renderer = nullptr; renderer = nullptr;
if (soundMove) { if (soundMove != nullptr) {
JA_DeleteSound(soundMove); JA_DeleteSound(soundMove);
} }
if (soundAccept) { if (soundAccept != nullptr) {
JA_DeleteSound(soundAccept); JA_DeleteSound(soundAccept);
} }
if (soundCancel) { if (soundCancel != nullptr) {
JA_DeleteSound(soundCancel); JA_DeleteSound(soundCancel);
} }
if (text != nullptr) {
delete text; delete text;
}
} }
// Parser compartido (recibe cualquier istream) // Parser compartido (recibe cualquier istream)
bool Menu::parseFromStream(std::istream &file, const std::string &filename) { auto Menu::parseFromStream(std::istream &file, const std::string &filename) -> bool {
bool success = true; bool success = true;
bool textAllocated = false; bool textAllocated = false;
std::string line; std::string line;
@@ -103,7 +99,9 @@ bool Menu::parseFromStream(std::istream &file, const std::string &filename) {
// deixant un \r residual. Sense això, "[item]" no fa match i el vector // deixant un \r residual. Sense això, "[item]" no fa match i el vector
// d'items queda buit → reset() accedeix a item[0] i crasheja. // d'items queda buit → reset() accedeix a item[0] i crasheja.
auto strip_cr = [](std::string &s) { auto strip_cr = [](std::string &s) {
if (!s.empty() && s.back() == '\r') s.pop_back(); if (!s.empty() && s.back() == '\r') {
s.pop_back();
}
}; };
while (std::getline(file, line)) { while (std::getline(file, line)) {
@@ -119,9 +117,11 @@ bool Menu::parseFromStream(std::istream &file, const std::string &filename) {
newItem.line = false; newItem.line = false;
do { do {
if (!std::getline(file, line)) break; if (!std::getline(file, line)) {
break;
}
strip_cr(line); strip_cr(line);
int pos = line.find("="); int pos = line.find('=');
if (!setItem(&newItem, line.substr(0, pos), line.substr(pos + 1, line.length()))) { if (!setItem(&newItem, line.substr(0, pos), line.substr(pos + 1, line.length()))) {
success = false; success = false;
} }
@@ -129,14 +129,14 @@ bool Menu::parseFromStream(std::istream &file, const std::string &filename) {
addItem(newItem); addItem(newItem);
} else { } else {
int pos = line.find("="); int pos = line.find('=');
if (!setVars(line.substr(0, pos), line.substr(pos + 1, line.length()))) { if (!setVars(line.substr(0, pos), line.substr(pos + 1, line.length()))) {
success = false; success = false;
} }
// Crea el objeto text tan pronto como se pueda. Necesario para añadir items. // Crea el objeto text tan pronto como se pueda. Necesario para añadir items.
// Carga via ResourceHelper para que funcione tanto con pack como con filesystem. // Carga via ResourceHelper para que funcione tanto con pack como con filesystem.
if (font_png != "" && font_txt != "" && !textAllocated) { if (!font_png.empty() && !font_txt.empty() && !textAllocated) {
auto pngBytes = ResourceHelper::loadFile(Asset::get()->get(font_png)); auto pngBytes = ResourceHelper::loadFile(Asset::get()->get(font_png));
auto txtBytes = ResourceHelper::loadFile(Asset::get()->get(font_txt)); auto txtBytes = ResourceHelper::loadFile(Asset::get()->get(font_txt));
text = new Text(pngBytes, txtBytes, renderer); text = new Text(pngBytes, txtBytes, renderer);
@@ -148,7 +148,7 @@ bool Menu::parseFromStream(std::istream &file, const std::string &filename) {
} }
// Carga la configuración del menu (vía ResourceHelper: pack si està inicialitzat, filesystem si no) // Carga la configuración del menu (vía ResourceHelper: pack si està inicialitzat, filesystem si no)
bool Menu::load(const std::string &file_path) { auto Menu::load(const std::string &file_path) -> bool {
const std::string filename = file_path.substr(file_path.find_last_of("\\/") + 1); const std::string filename = file_path.substr(file_path.find_last_of("\\/") + 1);
auto bytes = ResourceHelper::loadFile(file_path); auto bytes = ResourceHelper::loadFile(file_path);
if (bytes.empty()) { if (bytes.empty()) {
@@ -158,8 +158,10 @@ bool Menu::load(const std::string &file_path) {
} }
// Carga el menu desde bytes en memoria // Carga el menu desde bytes en memoria
bool Menu::loadFromBytes(const std::vector<uint8_t> &bytes, const std::string &nameForLogs) { auto Menu::loadFromBytes(const std::vector<uint8_t> &bytes, const std::string &nameForLogs) -> bool {
if (bytes.empty()) return false; if (bytes.empty()) {
return false;
}
std::string content(reinterpret_cast<const char *>(bytes.data()), bytes.size()); std::string content(reinterpret_cast<const char *>(bytes.data()), bytes.size());
std::stringstream ss(content); std::stringstream ss(content);
bool ok = parseFromStream(ss, nameForLogs); bool ok = parseFromStream(ss, nameForLogs);
@@ -169,7 +171,7 @@ bool Menu::loadFromBytes(const std::vector<uint8_t> &bytes, const std::string &n
} }
// Asigna variables a partir de dos cadenas // Asigna variables a partir de dos cadenas
bool Menu::setItem(item_t *item, const std::string &var, const std::string &value) { auto Menu::setItem(item_t *item, const std::string &var, const std::string &value) -> bool {
// Indicador de éxito en la asignación // Indicador de éxito en la asignación
bool success = true; bool success = true;
@@ -182,26 +184,26 @@ bool Menu::setItem(item_t *item, const std::string &var, const std::string &valu
} }
else if (var == "selectable") { else if (var == "selectable") {
item->selectable = value == "true" ? true : false; item->selectable = value == "true";
} }
else if (var == "greyed") { else if (var == "greyed") {
item->greyed = value == "true" ? true : false; item->greyed = value == "true";
} }
else if (var == "linkedDown") { else if (var == "linkedDown") {
item->linkedDown = value == "true" ? true : false; item->linkedDown = value == "true";
} }
else if (var == "visible") { else if (var == "visible") {
item->visible = value == "true" ? true : false; item->visible = value == "true";
} }
else if (var == "line") { else if (var == "line") {
item->line = value == "true" ? true : false; item->line = value == "true";
} }
else if ((var == "") || (var == "[/item]")) { else if ((var.empty()) || (var == "[/item]")) {
} }
else { else {
@@ -212,7 +214,7 @@ bool Menu::setItem(item_t *item, const std::string &var, const std::string &valu
} }
// Asigna variables a partir de dos cadenas // Asigna variables a partir de dos cadenas
bool Menu::setVars(const std::string &var, const std::string &value) { auto Menu::setVars(const std::string &var, const std::string &value) -> bool {
// Indicador de éxito en la asignación // Indicador de éxito en la asignación
bool success = true; bool success = true;
@@ -226,17 +228,23 @@ bool Menu::setVars(const std::string &var, const std::string &value) {
else if (var == "sound_cancel") { else if (var == "sound_cancel") {
auto bytes = ResourceHelper::loadFile(Asset::get()->get(value)); auto bytes = ResourceHelper::loadFile(Asset::get()->get(value));
if (!bytes.empty()) soundCancel = JA_LoadSound(bytes.data(), (uint32_t)bytes.size()); if (!bytes.empty()) {
soundCancel = JA_LoadSound(bytes.data(), (uint32_t)bytes.size());
}
} }
else if (var == "sound_accept") { else if (var == "sound_accept") {
auto bytes = ResourceHelper::loadFile(Asset::get()->get(value)); auto bytes = ResourceHelper::loadFile(Asset::get()->get(value));
if (!bytes.empty()) soundAccept = JA_LoadSound(bytes.data(), (uint32_t)bytes.size()); if (!bytes.empty()) {
soundAccept = JA_LoadSound(bytes.data(), (uint32_t)bytes.size());
}
} }
else if (var == "sound_move") { else if (var == "sound_move") {
auto bytes = ResourceHelper::loadFile(Asset::get()->get(value)); auto bytes = ResourceHelper::loadFile(Asset::get()->get(value));
if (!bytes.empty()) soundMove = JA_LoadSound(bytes.data(), (uint32_t)bytes.size()); if (!bytes.empty()) {
soundMove = JA_LoadSound(bytes.data(), (uint32_t)bytes.size());
}
} }
else if (var == "name") { else if (var == "name") {
@@ -304,22 +312,22 @@ bool Menu::setVars(const std::string &var, const std::string &value) {
} }
else if (var == "areElementsCenteredOnX") { else if (var == "areElementsCenteredOnX") {
areElementsCenteredOnX = value == "true" ? true : false; areElementsCenteredOnX = value == "true";
} }
else if (var == "isCenteredOnX") { else if (var == "isCenteredOnX") {
isCenteredOnX = value == "true" ? true : false; isCenteredOnX = value == "true";
} }
else if (var == "isCenteredOnY") { else if (var == "isCenteredOnY") {
isCenteredOnY = value == "true" ? true : false; isCenteredOnY = value == "true";
} }
else if (var == "defaultActionWhenCancel") { else if (var == "defaultActionWhenCancel") {
defaultActionWhenCancel = std::stoi(value); defaultActionWhenCancel = std::stoi(value);
} }
else if (var == "") { else if (var.empty()) {
} }
else { else {
@@ -350,12 +358,12 @@ void Menu::loadAudioFile(const std::string &file, int sound) {
} }
// Obtiene el nombre del menu // Obtiene el nombre del menu
const std::string &Menu::getName() const { auto Menu::getName() const -> const std::string & {
return name; return name;
} }
// Obtiene el valor de la variable // Obtiene el valor de la variable
int Menu::getItemSelected() { auto Menu::getItemSelected() -> int {
// Al llamar a esta funcion, se obtiene el valor y se borra // Al llamar a esta funcion, se obtiene el valor y se borra
const int temp = itemSelected; const int temp = itemSelected;
itemSelected = MENU_NO_OPTION; itemSelected = MENU_NO_OPTION;
@@ -440,7 +448,7 @@ void Menu::setSelectorPos(int index) {
} }
// Obtiene la anchura del elemento más ancho del menu // Obtiene la anchura del elemento más ancho del menu
int Menu::getWidestItem() { auto Menu::getWidestItem() -> int {
return std::accumulate(item.begin(), item.end(), 0, [](int acc, const item_t &i) { return std::max(acc, i.rect.w); }); return std::accumulate(item.begin(), item.end(), 0, [](int acc, const item_t &i) { return std::max(acc, i.rect.w); });
} }
@@ -729,20 +737,18 @@ void Menu::centerMenuElementsOnX() {
} }
// Añade un item al menu // Añade un item al menu
void Menu::addItem(item_t temp) { void Menu::addItem(item_t new_item) {
// item_t temp;
if (item.empty()) { // Si es el primer item coge la posición en el eje Y del propio menu if (item.empty()) { // Si es el primer item coge la posición en el eje Y del propio menu
temp.rect.y = y; new_item.rect.y = y;
} else { // En caso contrario, coge la posición en el eje Y a partir del último elemento } else { // En caso contrario, coge la posición en el eje Y a partir del último elemento
temp.rect.y = item.back().rect.y + item.back().rect.h + item.back().hPaddingDown; new_item.rect.y = item.back().rect.y + item.back().rect.h + item.back().hPaddingDown;
} }
temp.rect.x = x; new_item.rect.x = x;
item.push_back(temp); item.push_back(new_item);
setItemCaption(item.size() - 1, temp.label); setItemCaption(item.size() - 1, new_item.label);
if (item.size() > 1) { if (item.size() > 1) {
if (item[item.size() - 2].linkedDown) { if (item[item.size() - 2].linkedDown) {
@@ -771,40 +777,40 @@ void Menu::setDefaultActionWhenCancel(int item) {
void Menu::checkInput() { void Menu::checkInput() {
if (Input::get()->checkInput(input_up, REPEAT_FALSE)) { if (Input::get()->checkInput(input_up, REPEAT_FALSE)) {
decreaseSelectorIndex(); decreaseSelectorIndex();
if (soundMove) { if (soundMove != nullptr) {
Audio::get()->playSound(soundMove); Audio::get()->playSound(soundMove);
} }
} }
if (Input::get()->checkInput(input_down, REPEAT_FALSE)) { if (Input::get()->checkInput(input_down, REPEAT_FALSE)) {
increaseSelectorIndex(); increaseSelectorIndex();
if (soundMove) { if (soundMove != nullptr) {
Audio::get()->playSound(soundMove); Audio::get()->playSound(soundMove);
} }
} }
if (Input::get()->checkInput(input_accept, REPEAT_FALSE)) { if (Input::get()->checkInput(input_accept, REPEAT_FALSE)) {
itemSelected = selector.index; itemSelected = selector.index;
if (soundAccept) { if (soundAccept != nullptr) {
Audio::get()->playSound(soundAccept); Audio::get()->playSound(soundAccept);
} }
} }
if (Input::get()->checkInput(input_cancel, REPEAT_FALSE)) { if (Input::get()->checkInput(input_cancel, REPEAT_FALSE)) {
itemSelected = defaultActionWhenCancel; itemSelected = defaultActionWhenCancel;
if (soundCancel) { if (soundCancel != nullptr) {
Audio::get()->playSound(soundCancel); Audio::get()->playSound(soundCancel);
} }
} }
} }
// Calcula el ancho del menu // Calcula el ancho del menu
int Menu::findWidth() { auto Menu::findWidth() -> int {
return getWidestItem(); return getWidestItem();
} }
// Calcula el alto del menu // Calcula el alto del menu
int Menu::findHeight() { auto Menu::findHeight() -> int {
const int height = std::accumulate(item.begin(), item.end(), 0, [](int acc, const item_t &i) { return acc + i.rect.h + i.hPaddingDown; }); const int height = std::accumulate(item.begin(), item.end(), 0, [](int acc, const item_t &i) { return acc + i.rect.h + i.hPaddingDown; });
return height - item.back().hPaddingDown; return height - item.back().hPaddingDown;
@@ -840,12 +846,11 @@ void Menu::setVisible(int index, bool value) {
} }
// Calcula la altura del selector // Calcula la altura del selector
int Menu::getSelectorHeight(int value) { auto Menu::getSelectorHeight(int value) -> int {
if (item[value].linkedDown) { if (item[value].linkedDown) {
return item[value].rect.h + item[value].hPaddingDown + item[value + 1].rect.h; return item[value].rect.h + item[value].hPaddingDown + item[value + 1].rect.h;
} else {
return item[value].rect.h;
} }
return item[value].rect.h;
} }
// Establece el nombre del menu // Establece el nombre del menu
@@ -866,7 +871,7 @@ void Menu::setBackgroundType(int value) {
// Establece la fuente de texto que se utilizará // Establece la fuente de texto que se utilizará
void Menu::setText(const std::string &font_png, const std::string &font_txt) { void Menu::setText(const std::string &font_png, const std::string &font_txt) {
if (!text) { if (text == nullptr) {
text = new Text(Asset::get()->get(font_png), Asset::get()->get(font_txt), renderer); text = new Text(Asset::get()->get(font_png), Asset::get()->get(font_txt), renderer);
} }
} }
+2 -2
View File
@@ -105,7 +105,7 @@ class Menu {
auto setVars(const std::string &var, const std::string &value) -> bool; auto setVars(const std::string &var, const std::string &value) -> bool;
// Asigna variables a partir de dos cadenas // Asigna variables a partir de dos cadenas
auto setItem(item_t *item, const std::string &var, const std::string &value) -> bool; static auto setItem(item_t *item, const std::string &var, const std::string &value) -> bool;
// Actualiza el menu para recolocarlo correctamente y establecer el tamaño // Actualiza el menu para recolocarlo correctamente y establecer el tamaño
void reorganize(); void reorganize();
@@ -190,7 +190,7 @@ class Menu {
void centerMenuElementsOnX(); void centerMenuElementsOnX();
// Añade un item al menu // Añade un item al menu
void addItem(item_t item); void addItem(item_t new_item);
// Cambia el texto de un item // Cambia el texto de un item
void setItemCaption(int index, const std::string &text); void setItemCaption(int index, const std::string &text);
+3 -3
View File
@@ -44,17 +44,17 @@ Reescribiendo el código el 27/09/2022
#include "core/system/director.h" #include "core/system/director.h"
SDL_AppResult SDL_AppInit(void **appstate, int argc, char *argv[]) { auto SDL_AppInit(void **appstate, int argc, char *argv[]) -> SDL_AppResult {
auto *director = new Director(argc, const_cast<const char **>(argv)); auto *director = new Director(argc, const_cast<const char **>(argv));
*appstate = director; *appstate = director;
return SDL_APP_CONTINUE; return SDL_APP_CONTINUE;
} }
SDL_AppResult SDL_AppIterate(void *appstate) { auto SDL_AppIterate(void *appstate) -> SDL_AppResult {
return static_cast<Director *>(appstate)->iterate(); return static_cast<Director *>(appstate)->iterate();
} }
SDL_AppResult SDL_AppEvent(void *appstate, SDL_Event *event) { auto SDL_AppEvent(void *appstate, SDL_Event *event) -> SDL_AppResult {
return static_cast<Director *>(appstate)->handleEvent(event); return static_cast<Director *>(appstate)->handleEvent(event);
} }