diff --git a/source/game/entities/balloon.cpp b/source/game/entities/balloon.cpp index 9dd1d83..96cff4e 100644 --- a/source/game/entities/balloon.cpp +++ b/source/game/entities/balloon.cpp @@ -1,6 +1,6 @@ #include "game/entities/balloon.h" -#include // for abs +#include // for abs #include "core/rendering/animatedsprite.h" // for AnimatedSprite #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 this->velX = velx; velY = 0; - maxVelY = 3.0f; - gravity = 0.09f; - defaultVelY = 2.6f; + maxVelY = 3.0F; + gravity = 0.09F; + defaultVelY = 2.6F; // Puntos que da el globo al ser destruido 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 this->velX = velx; velY = 0; - maxVelY = 3.0f; - gravity = 0.10f; - defaultVelY = 3.5f; + maxVelY = 3.0F; + gravity = 0.10F; + defaultVelY = 3.5F; // Puntos que da el globo al ser destruido 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 this->velX = velx; velY = 0; - maxVelY = 3.0f; - gravity = 0.10f; - defaultVelY = 4.50f; + maxVelY = 3.0F; + gravity = 0.10F; + defaultVelY = 4.50F; // Puntos que da el globo al ser destruido 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 this->velX = velx; velY = 0; - maxVelY = 3.0f; - gravity = 0.10f; - defaultVelY = 4.95f; + maxVelY = 3.0F; + gravity = 0.10F; + defaultVelY = 4.95F; // Puntos que da el globo al ser destruido 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; velY = abs(velx) * 2; maxVelY = abs(velx) * 2; - gravity = 0.00f; + gravity = 0.00F; defaultVelY = abs(velx) * 2; // 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; velY = abs(velx) * 2; maxVelY = abs(velx) * 2; - gravity = 0.00f; + gravity = 0.00F; defaultVelY = abs(velx) * 2; // 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; velY = abs(velx) * 2; maxVelY = abs(velx) * 2; - gravity = 0.00f; + gravity = 0.00F; defaultVelY = abs(velx) * 2; // 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; velY = abs(velx) * 2; maxVelY = abs(velx) * 2; - gravity = 0.00f; + gravity = 0.00F; defaultVelY = abs(velx) * 2; // 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 this->velX = velx; velY = 0; - maxVelY = 3.0f; - gravity = 0.10f; - defaultVelY = 4.95f; + maxVelY = 3.0F; + gravity = 0.10F; + defaultVelY = 4.95F; // Puntos que da el globo al ser destruido 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 sprite->setRotate(false); sprite->setRotateSpeed(0); - if (velX > 0.0f) { + if (velX > 0.0F) { sprite->setRotateAmount(2.0); } else { 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.counter = 0; bouncing.speed = 2; - bouncing.zoomW = 1.0f; - bouncing.zoomH = 1.0f; - bouncing.despX = 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.h = {0.90f, 0.95f, 1.00f, 1.05f, 1.10f, 1.05f, 1.00f, 0.98f, 0.95f, 0.98f}; + bouncing.zoomW = 1.0F; + bouncing.zoomH = 1.0F; + bouncing.despX = 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.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 sprite->setWidth(width); @@ -270,7 +270,7 @@ Balloon::Balloon(float x, float y, Uint8 kind, float velx, float speed, Uint16 c invulnerable = beingCreated; counter = 0; - travelY = 1.0f; + travelY = 1.0F; this->speed = speed; // Tipo @@ -286,10 +286,11 @@ Balloon::~Balloon() { void Balloon::allignTo(int x) { posX = float(x - (width / 2)); - if (posX < PLAY_AREA_LEFT) + if (posX < PLAY_AREA_LEFT) { 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); + } // Posición X,Y del sprite sprite->setPosX(getPosX()); @@ -313,10 +314,10 @@ void Balloon::render() { } } else if (isBeingCreated()) { // 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(); 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->render(); delete sp; @@ -326,7 +327,7 @@ void Balloon::render() { sprite->render(); 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->render(); delete sp; @@ -403,9 +404,9 @@ void Balloon::move() { travelY += speed; // 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 - travelY -= 1.0f; + travelY -= 1.0F; // Aplica la gravedad al objeto sin pasarse de una velocidad máxima velY += gravity; @@ -431,17 +432,17 @@ void Balloon::disable() { counter = 0; creationCounter = 0; creationCounterIni = 0; - defaultVelY = 0.0f; + defaultVelY = 0.0F; enabled = false; - gravity = 0.0f; + gravity = 0.0F; height = 0; invulnerable = false; kind = 0; - maxVelY = 0.0f; + maxVelY = 0.0F; menace = 0; popping = false; - posX = 0.0f; - posY = 0.0f; + posX = 0.0F; + posY = 0.0F; power = 0; score = 0; size = 0; @@ -449,8 +450,8 @@ void Balloon::disable() { stopped = false; stoppedCounter = 0; travelY = 0; - velX = 0.0f; - velY = 0.0f; + velX = 0.0F; + velY = 0.0F; visible = false; width = 0; sprite->clear(); @@ -580,32 +581,32 @@ void Balloon::updateAnimation() { } // Comprueba si el globo está habilitado -bool Balloon::isEnabled() { +auto Balloon::isEnabled() const -> bool { return enabled; } // Obtiene del valor de la variable -float Balloon::getPosX() { +auto Balloon::getPosX() const -> float { return posX; } // Obtiene del valor de la variable -float Balloon::getPosY() { +auto Balloon::getPosY() const -> float { return posY; } // Obtiene del valor de la variable -float Balloon::getVelY() { +auto Balloon::getVelY() const -> float { return velY; } // Obtiene del valor de la variable -int Balloon::getWidth() { +auto Balloon::getWidth() const -> int { return width; } // Obtiene del valor de la variable -int Balloon::getHeight() { +auto Balloon::getHeight() const -> int { return height; } @@ -620,22 +621,22 @@ void Balloon::setSpeed(float speed) { } // Obtiene del valor de la variable -int Balloon::getKind() { +auto Balloon::getKind() const -> int { return kind; } // Obtiene del valor de la variable -Uint8 Balloon::getSize() { +auto Balloon::getSize() const -> Uint8 { return size; } // Obtiene la clase a la que pertenece el globo -Uint8 Balloon::getClass() { +auto Balloon::getClass() const -> Uint8 { if ((kind >= BALLOON_1) && (kind <= BALLOON_4)) { return BALLOON_CLASS; } - else if ((kind >= HEXAGON_1) && (kind <= HEXAGON_4)) { + if ((kind >= HEXAGON_1) && (kind <= HEXAGON_4)) { return HEXAGON_CLASS; } @@ -648,7 +649,7 @@ void Balloon::setStop(bool state) { } // Obtiene del valor de la variable -bool Balloon::isStopped() { +auto Balloon::isStopped() const -> bool { return stopped; } @@ -658,7 +659,7 @@ void Balloon::setBlink(bool value) { } // Obtiene del valor de la variable -bool Balloon::isBlinking() { +auto Balloon::isBlinking() const -> bool { return blinking; } @@ -668,7 +669,7 @@ void Balloon::setVisible(bool value) { } // Obtiene del valor de la variable -bool Balloon::isVisible() { +auto Balloon::isVisible() const -> bool { return visible; } @@ -678,7 +679,7 @@ void Balloon::setInvulnerable(bool value) { } // Obtiene del valor de la variable -bool Balloon::isInvulnerable() { +auto Balloon::isInvulnerable() const -> bool { return invulnerable; } @@ -688,7 +689,7 @@ void Balloon::setBeingCreated(bool value) { } // Obtiene del valor de la variable -bool Balloon::isBeingCreated() { +auto Balloon::isBeingCreated() const -> bool { return beingCreated; } @@ -698,7 +699,7 @@ void Balloon::setPopping(bool value) { } // Obtiene del valor de la variable -bool Balloon::isPopping() { +auto Balloon::isPopping() const -> bool { return popping; } @@ -708,17 +709,17 @@ void Balloon::setStoppedTimer(Uint16 time) { } // Obtiene del valor de la variable -Uint16 Balloon::getStoppedTimer() { +auto Balloon::getStoppedTimer() const -> Uint16 { return stoppedCounter; } // Obtiene del valor de la variable -Uint16 Balloon::getScore() { +auto Balloon::getScore() const -> Uint16 { return score; } // Obtiene el circulo de colisión -circle_t &Balloon::getCollider() { +auto Balloon::getCollider() -> circle_t & { return collider; } @@ -729,16 +730,15 @@ void Balloon::updateColliders() { } // Obtiene le valor de la variable -Uint8 Balloon::getMenace() { +auto Balloon::getMenace() const -> Uint8 { if (isEnabled()) { return menace; - } else { - return 0; } + return 0; } // Obtiene le valor de la variable -Uint8 Balloon::getPower() { +auto Balloon::getPower() const -> Uint8 { return power; } @@ -755,12 +755,12 @@ void Balloon::bounceStart() { void Balloon::bounceStop() { bouncing.enabled = false; bouncing.counter = 0; - bouncing.zoomW = 1.0f; - bouncing.zoomH = 1.0f; + bouncing.zoomW = 1.0F; + bouncing.zoomH = 1.0F; sprite->setZoomW(bouncing.zoomW); sprite->setZoomH(bouncing.zoomH); - bouncing.despX = 0.0f; - bouncing.despY = 0.0f; + bouncing.despX = 0.0F; + bouncing.despY = 0.0F; } void Balloon::updateBounce() { diff --git a/source/game/entities/balloon.h b/source/game/entities/balloon.h index 568da6d..1e9591b 100644 --- a/source/game/entities/balloon.h +++ b/source/game/entities/balloon.h @@ -40,8 +40,8 @@ constexpr int BALLOON_CLASS = 0; constexpr int HEXAGON_CLASS = 1; // Velocidad del globo -constexpr float BALLOON_VELX_POSITIVE = 0.7f; -constexpr float BALLOON_VELX_NEGATIVE = -0.7f; +constexpr float BALLOON_VELX_POSITIVE = 0.7F; +constexpr float BALLOON_VELX_NEGATIVE = -0.7F; // Índice para las animaciones de los globos constexpr int BALLOON_MOVING_ANIMATION = 0; @@ -52,11 +52,11 @@ constexpr int BALLOON_BORN_ANIMATION = 2; constexpr int MAX_BALLOONS = 100; // Velocidades a las que se mueven los globos -constexpr float BALLOON_SPEED_1 = 0.60f; -constexpr float BALLOON_SPEED_2 = 0.70f; -constexpr float BALLOON_SPEED_3 = 0.80f; -constexpr float BALLOON_SPEED_4 = 0.90f; -constexpr float BALLOON_SPEED_5 = 1.00f; +constexpr float BALLOON_SPEED_1 = 0.60F; +constexpr float BALLOON_SPEED_2 = 0.70F; +constexpr float BALLOON_SPEED_3 = 0.80F; +constexpr float BALLOON_SPEED_4 = 0.90F; +constexpr float BALLOON_SPEED_5 = 1.00F; // Tamaño de los globos constexpr int BALLOON_WIDTH_1 = 8; @@ -147,7 +147,7 @@ class Balloon { ~Balloon(); Balloon(const Balloon &) = delete; - Balloon &operator=(const Balloon &) = delete; + auto operator=(const Balloon &) -> Balloon & = delete; // Centra el globo en la posición X void allignTo(int x); @@ -168,22 +168,22 @@ class Balloon { void update(); // Comprueba si el globo está habilitado - bool isEnabled(); + [[nodiscard]] auto isEnabled() const -> bool; // Obtiene del valor de la variable - float getPosX(); + [[nodiscard]] auto getPosX() const -> float; // Obtiene del valor de la variable - float getPosY(); + [[nodiscard]] auto getPosY() const -> float; // Obtiene del valor de la variable - float getVelY(); + [[nodiscard]] auto getVelY() const -> float; // Obtiene del valor de la variable - int getWidth(); + [[nodiscard]] auto getWidth() const -> int; // Obtiene del valor de la variable - int getHeight(); + [[nodiscard]] auto getHeight() const -> int; // Establece el valor de la variable void setVelY(float velY); @@ -192,62 +192,62 @@ class Balloon { void setSpeed(float speed); // Obtiene del valor de la variable - int getKind(); + [[nodiscard]] auto getKind() const -> int; // Obtiene del valor de la variable - Uint8 getSize(); + [[nodiscard]] auto getSize() const -> Uint8; // Obtiene la clase a la que pertenece el globo - Uint8 getClass(); + [[nodiscard]] auto getClass() const -> Uint8; // Establece el valor de la variable - void setStop(bool value); + void setStop(bool state); // Obtiene del valor de la variable - bool isStopped(); + [[nodiscard]] auto isStopped() const -> bool; // Establece el valor de la variable void setBlink(bool value); // Obtiene del valor de la variable - bool isBlinking(); + [[nodiscard]] auto isBlinking() const -> bool; // Establece el valor de la variable void setVisible(bool value); // Obtiene del valor de la variable - bool isVisible(); + [[nodiscard]] auto isVisible() const -> bool; // Establece el valor de la variable void setInvulnerable(bool value); // Obtiene del valor de la variable - bool isInvulnerable(); + [[nodiscard]] auto isInvulnerable() const -> bool; // Obtiene del valor de la variable - bool isBeingCreated(); + [[nodiscard]] auto isBeingCreated() const -> bool; // Establece el valor de la variable void setPopping(bool value); // Obtiene del valor de la variable - bool isPopping(); + [[nodiscard]] auto isPopping() const -> bool; // Establece el valor de la variable void setStoppedTimer(Uint16 time); // Obtiene del valor de la variable - Uint16 getStoppedTimer(); + [[nodiscard]] auto getStoppedTimer() const -> Uint16; // Obtiene del valor de la variable - Uint16 getScore(); + [[nodiscard]] auto getScore() const -> Uint16; // Obtiene el circulo de colisión - circle_t &getCollider(); + auto getCollider() -> circle_t &; // Obtiene le valor de la variable - Uint8 getMenace(); + [[nodiscard]] auto getMenace() const -> Uint8; // Obtiene le valor de la variable - Uint8 getPower(); + [[nodiscard]] auto getPower() const -> Uint8; }; diff --git a/source/game/entities/bullet.cpp b/source/game/entities/bullet.cpp index e636a31..0afa357 100644 --- a/source/game/entities/bullet.cpp +++ b/source/game/entities/bullet.cpp @@ -1,11 +1,11 @@ #include "game/entities/bullet.h" #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; // 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); // 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 switch (kind) { - case BULLET_UP: + case BulletKind::UP: // Establece la velocidad inicial velX = 0; @@ -39,7 +39,7 @@ Bullet::Bullet(int x, int y, int kind, bool poweredUp, int owner, Texture *textu } break; - case BULLET_LEFT: + case BulletKind::LEFT: // Establece la velocidad inicial velX = -2; @@ -51,7 +51,7 @@ Bullet::Bullet(int x, int y, int kind, bool poweredUp, int owner, Texture *textu } break; - case BULLET_RIGHT: + case BulletKind::RIGHT: // Establece la velocidad inicial velX = 2; @@ -85,7 +85,7 @@ void Bullet::render() { } // Actualiza la posición y estado del objeto en horizontal -Uint8 Bullet::move() { +auto Bullet::move() -> Uint8 { // Variable con el valor de retorno Uint8 msg = BULLET_MOVE_OK; @@ -95,19 +95,19 @@ Uint8 Bullet::move() { // Si el objeto se sale del area de juego por los laterales if ((posX < PLAY_AREA_LEFT - width) || (posX > PLAY_AREA_RIGHT)) { // Se deshabilita - kind = NO_KIND; + kind = BulletKind::NONE; // Mensaje de salida msg = BULLET_MOVE_OUT; } // 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 if (posY < PLAY_AREA_TOP - height) { // Se deshabilita - kind = NO_KIND; + kind = BulletKind::NONE; // Mensaje de salida msg = BULLET_MOVE_OUT; @@ -124,26 +124,22 @@ Uint8 Bullet::move() { } // Comprueba si el objeto está habilitado -bool Bullet::isEnabled() { - if (kind == NO_KIND) { - return false; - } else { - return true; - } +auto Bullet::isEnabled() const -> bool { + return kind != BulletKind::NONE; } // Deshabilita el objeto void Bullet::disable() { - kind = NO_KIND; + kind = BulletKind::NONE; } // Obtiene el valor de la variable -int Bullet::getPosX() { +auto Bullet::getPosX() const -> int { return posX; } // Obtiene el valor de la variable -int Bullet::getPosY() { +auto Bullet::getPosY() const -> int { return posY; } @@ -158,22 +154,22 @@ void Bullet::setPosY(int y) { } // Obtiene el valor de la variable -int Bullet::getVelY() { +auto Bullet::getVelY() const -> int { return velY; } // Obtiene el valor de la variable -int Bullet::getKind() { +auto Bullet::getKind() const -> BulletKind { return kind; } // Obtiene el valor de la variable -int Bullet::getOwner() { +auto Bullet::getOwner() const -> int { return owner; } // Obtiene el circulo de colisión -circle_t &Bullet::getCollider() { +auto Bullet::getCollider() -> circle_t & { return collider; } diff --git a/source/game/entities/bullet.h b/source/game/entities/bullet.h index af6d264..a3827f0 100644 --- a/source/game/entities/bullet.h +++ b/source/game/entities/bullet.h @@ -2,14 +2,19 @@ #include +#include // for uint8_t #include "utils/utils.h" // for circle_t class Sprite; class Texture; -// Tipos de bala -constexpr int BULLET_UP = 1; -constexpr int BULLET_LEFT = 2; -constexpr int BULLET_RIGHT = 3; +// Tipus de bala. Enum class fortament tipat per evitar confusió accidental +// amb altres `int`/`Uint8` (p.ex. el `owner` a `createBullet`). +enum class BulletKind : std::uint8_t { + NONE = 0, // bala desactivada / fora de pantalla + UP = 1, + LEFT = 2, + RIGHT = 3, +}; // Tipos de retorno de la función move de la bala constexpr int BULLET_MOVE_OK = 0; @@ -28,7 +33,7 @@ class Bullet { Uint8 height; // Alto del objeto int velX; // Velocidad en el eje X 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 circle_t collider; // Circulo de colisión del objeto @@ -37,31 +42,31 @@ class Bullet { public: // 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 ~Bullet(); Bullet(const Bullet &) = delete; - Bullet &operator=(const Bullet &) = delete; + auto operator=(const Bullet &) -> Bullet & = delete; // Pinta el objeto en pantalla void render(); // Actualiza la posición y estado del objeto - Uint8 move(); + auto move() -> Uint8; // Comprueba si el objeto está habilitado - bool isEnabled(); + [[nodiscard]] auto isEnabled() const -> bool; // Deshabilita el objeto void disable(); // Obtiene el valor de la variable - int getPosX(); + [[nodiscard]] auto getPosX() const -> int; // Obtiene el valor de la variable - int getPosY(); + [[nodiscard]] auto getPosY() const -> int; // Establece el valor de la variable void setPosX(int x); @@ -70,14 +75,14 @@ class Bullet { void setPosY(int y); // Obtiene el valor de la variable - int getVelY(); + [[nodiscard]] auto getVelY() const -> int; // Obtiene el valor de la variable - int getKind(); + [[nodiscard]] auto getKind() const -> BulletKind; // Obtiene el valor de la variable - int getOwner(); + [[nodiscard]] auto getOwner() const -> int; // Obtiene el circulo de colisión - circle_t &getCollider(); + auto getCollider() -> circle_t &; }; diff --git a/source/game/entities/item.cpp b/source/game/entities/item.cpp index c9817bf..618a3d4 100644 --- a/source/game/entities/item.cpp +++ b/source/game/entities/item.cpp @@ -1,6 +1,6 @@ #include "game/entities/item.h" -#include // for rand +#include // for rand #include "core/rendering/animatedsprite.h" // for AnimatedSprite #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::vectorkind = kind; enabled = true; timeToLive = 600; - accelX = 0.0f; + accelX = 0.0F; floorCollision = false; if (kind == ITEM_COFFEE_MACHINE) { @@ -21,18 +21,18 @@ Item::Item(Uint8 kind, float x, float y, Texture *texture, std::vector 200) { - sprite->render(); - } else if (timeToLive % 20 > 10) { - sprite->render(); - } + // Mentre quede temps de sobra (>200) es renderitza sempre; quan està a + // punt d'expirar, parpalleja alternant 10 frames visibles i 10 invisibles. + if (enabled && (timeToLive > 200 || timeToLive % 20 > 10)) { + sprite->render(); } } @@ -146,42 +144,43 @@ void Item::updateTimeToLive() { // Comprueba si el objeto sigue vivo void Item::checkTimeToLive() { - if (timeToLive == 0) + if (timeToLive == 0) { disable(); + } } // Obtiene del valor de la variable -float Item::getPosX() { +auto Item::getPosX() const -> float { return posX; } // Obtiene del valor de la variable -float Item::getPosY() { +auto Item::getPosY() const -> float { return posY; } // Obtiene del valor de la variable -int Item::getWidth() { +auto Item::getWidth() const -> int { return width; } // Obtiene del valor de la variable -int Item::getHeight() { +auto Item::getHeight() const -> int { return height; } // Obtiene del valor de la variable -int Item::getClass() { +auto Item::getClass() const -> int { return kind; } // Obtiene el valor de la variable -bool Item::isEnabled() { +auto Item::isEnabled() const -> bool { return enabled; } // Obtiene el circulo de colisión -circle_t &Item::getCollider() { +auto Item::getCollider() -> circle_t & { return collider; } @@ -192,6 +191,6 @@ void Item::shiftColliders() { } // Informa si el objeto ha colisionado con el suelo -bool Item::isOnFloor() { +auto Item::isOnFloor() const -> bool { return floorCollision; } \ No newline at end of file diff --git a/source/game/entities/item.h b/source/game/entities/item.h index 32506fb..5779802 100644 --- a/source/game/entities/item.h +++ b/source/game/entities/item.h @@ -53,7 +53,7 @@ class Item { ~Item(); Item(const Item &) = delete; - Item &operator=(const Item &) = delete; + auto operator=(const Item &) -> Item & = delete; // Centra el objeto en la posición X void allignTo(int x); @@ -74,26 +74,26 @@ class Item { void checkTimeToLive(); // Obtiene del valor de la variable - float getPosX(); + [[nodiscard]] auto getPosX() const -> float; // Obtiene del valor de la variable - float getPosY(); + [[nodiscard]] auto getPosY() const -> float; // Obtiene del valor de la variable - int getWidth(); + [[nodiscard]] auto getWidth() const -> int; // Obtiene del valor de la variable - int getHeight(); + [[nodiscard]] auto getHeight() const -> int; // Obtiene del valor de la variable - int getClass(); + [[nodiscard]] auto getClass() const -> int; // Obtiene el valor de la variable - bool isEnabled(); + [[nodiscard]] auto isEnabled() const -> bool; // Obtiene el circulo de colisión - circle_t &getCollider(); + auto getCollider() -> circle_t &; // Informa si el objeto ha colisionado con el suelo - bool isOnFloor(); + [[nodiscard]] auto isOnFloor() const -> bool; }; diff --git a/source/game/entities/player.cpp b/source/game/entities/player.cpp index ae1d20a..bd228a4 100644 --- a/source/game/entities/player.cpp +++ b/source/game/entities/player.cpp @@ -1,6 +1,7 @@ #include "game/entities/player.h" -#include // for rand +#include +#include // for rand #include "core/input/input.h" // for inputs_e #include "core/rendering/animatedsprite.h" // for AnimatedSprite @@ -72,7 +73,7 @@ void Player::init() { score = 0; // Establece el multiplicador de puntos inicial - scoreMultiplier = 1.0f; + scoreMultiplier = 1.0F; // Inicia el contador para la cadencia de disparo cooldown = 10; @@ -200,8 +201,8 @@ void Player::setFiringStatus(Uint8 status) { // Establece la animación correspondiente al estado void Player::setAnimation() { // Crea cadenas de texto para componer el nombre de la animación - std::string aBodyCoffees = ""; - std::string aHeadCoffees = ""; + std::string aBodyCoffees; + std::string aHeadCoffees; if (coffees > 0) { aBodyCoffees = coffees == 1 ? "_1C" : "_2C"; aHeadCoffees = "_1C"; @@ -239,33 +240,29 @@ void Player::setAnimation() { } // Obtiene el valor de la variable -int Player::getPosX() { +auto Player::getPosX() const -> int { return int(posX); } // Obtiene el valor de la variable -int Player::getPosY() { +auto Player::getPosY() const -> int { return posY; } // Obtiene el valor de la variable -int Player::getWidth() { +auto Player::getWidth() const -> int { return width; } // Obtiene el valor de la variable -int Player::getHeight() { +auto Player::getHeight() const -> int { return height; } // 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 - if (cooldown > 0) { - return false; - } else { - return true; - } + return cooldown <= 0; } // Establece el valor de la variable @@ -298,7 +295,7 @@ void Player::update() { } // Obtiene la puntuación del jugador -Uint32 Player::getScore() { +auto Player::getScore() const -> Uint32 { return score; } @@ -313,7 +310,7 @@ void Player::addScore(Uint32 score) { } // Obtiene el valor de la variable -bool Player::isAlive() { +auto Player::isAlive() const -> bool { return alive; } @@ -324,17 +321,17 @@ void Player::setAlive(bool value) { if (!value) { deathSprite->setPosX(headSprite->getRect().x); deathSprite->setPosY(headSprite->getRect().y); - deathSprite->setAccelY(0.2f); - deathSprite->setVelY(-6.6f); - deathSprite->setVelX(3.3f); + deathSprite->setAccelY(0.2F); + deathSprite->setVelY(-6.6F); + deathSprite->setVelX(3.3F); if (rand() % 2 == 0) { - deathSprite->setVelX(-3.3f); + deathSprite->setVelX(-3.3F); } } } // Obtiene el valor de la variable -float Player::getScoreMultiplier() { +auto Player::getScoreMultiplier() const -> float { return scoreMultiplier; } @@ -345,24 +342,24 @@ void Player::setScoreMultiplier(float value) { // Aumenta el valor de la variable hasta un máximo void Player::incScoreMultiplier() { - if (scoreMultiplier < 5.0f) { - scoreMultiplier += 0.1f; + if (scoreMultiplier < 5.0F) { + scoreMultiplier += 0.1F; } else { - scoreMultiplier = 5.0f; + scoreMultiplier = 5.0F; } } // Decrementa el valor de la variable hasta un mínimo void Player::decScoreMultiplier() { - if (scoreMultiplier > 1.0f) { - scoreMultiplier -= 0.1f; + if (scoreMultiplier > 1.0F) { + scoreMultiplier -= 0.1F; } else { - scoreMultiplier = 1.0f; + scoreMultiplier = 1.0F; } } // Obtiene el valor de la variable -bool Player::isInvulnerable() { +auto Player::isInvulnerable() const -> bool { return invulnerable; } @@ -372,7 +369,7 @@ void Player::setInvulnerable(bool value) { } // Obtiene el valor de la variable -Uint16 Player::getInvulnerableCounter() { +auto Player::getInvulnerableCounter() const -> Uint16 { return invulnerableCounter; } @@ -403,7 +400,7 @@ void Player::updateDeathCounter() { } // Obtiene el valor de la variable -bool Player::isPowerUp() { +auto Player::isPowerUp() const -> bool { return powerUp; } @@ -413,7 +410,7 @@ void Player::setPowerUp(bool value) { } // Obtiene el valor de la variable -Uint16 Player::getPowerUpCounter() { +auto Player::getPowerUpCounter() const -> Uint16 { return powerUpCounter; } @@ -433,7 +430,7 @@ void Player::updatePowerUpCounter() { } // Obtiene el valor de la variable -bool Player::hasExtraHit() { +auto Player::hasExtraHit() const -> bool { return extraHit; } @@ -441,9 +438,7 @@ bool Player::hasExtraHit() { void Player::giveExtraHit() { extraHit = true; coffees++; - if (coffees > 2) { - coffees = 2; - } + coffees = std::min(coffees, 2); } // Quita el toque extra al jugador @@ -469,29 +464,29 @@ void Player::disableInput() { } // Devuelve el numero de cafes actuales -Uint8 Player::getCoffees() { +auto Player::getCoffees() const -> Uint8 { return coffees; } // Obtiene el circulo de colisión -circle_t &Player::getCollider() { +auto Player::getCollider() -> circle_t & { return collider; } // Actualiza el circulo de colisión a la posición del jugador void Player::shiftColliders() { 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 -Texture *Player::getDeadTexture() { +auto Player::getDeadTexture() -> Texture * { return deathSprite->getTexture(); ; } // Obtiene el valor de la variable -Uint16 Player::getDeathCounter() { +auto Player::getDeathCounter() const -> Uint16 { return deathCounter; } diff --git a/source/game/entities/player.h b/source/game/entities/player.h index 7a213f4..f4d4a21 100644 --- a/source/game/entities/player.h +++ b/source/game/entities/player.h @@ -87,7 +87,7 @@ class Player { ~Player(); Player(const Player &) = delete; - Player &operator=(const Player &) = delete; + auto operator=(const Player &) -> Player & = delete; // Iniciador void init(); @@ -117,19 +117,19 @@ class Player { void setAnimation(); // Obtiene el valor de la variable - int getPosX(); + [[nodiscard]] auto getPosX() const -> int; // Obtiene el valor de la variable - int getPosY(); + [[nodiscard]] auto getPosY() const -> int; // Obtiene el valor de la variable - int getWidth(); + [[nodiscard]] auto getWidth() const -> int; // Obtiene el valor de la variable - int getHeight(); + [[nodiscard]] auto getHeight() const -> int; // Indica si el jugador puede disparar - bool canFire(); + [[nodiscard]] auto canFire() const -> bool; // Establece el valor de la variable void setFireCooldown(int time); @@ -138,7 +138,7 @@ class Player { void updateCooldown(); // Obtiene la puntuación del jugador - Uint32 getScore(); + [[nodiscard]] auto getScore() const -> Uint32; // Asigna un valor a la puntuación del jugador void setScore(Uint32 score); @@ -147,13 +147,13 @@ class Player { void addScore(Uint32 score); // Obtiene el valor de la variable - bool isAlive(); + [[nodiscard]] auto isAlive() const -> bool; // Establece el valor de la variable void setAlive(bool value); // Obtiene el valor de la variable - float getScoreMultiplier(); + [[nodiscard]] auto getScoreMultiplier() const -> float; // Establece el valor de la variable void setScoreMultiplier(float value); @@ -165,25 +165,25 @@ class Player { void decScoreMultiplier(); // Obtiene el valor de la variable - bool isInvulnerable(); + [[nodiscard]] auto isInvulnerable() const -> bool; // Establece el valor de la variable void setInvulnerable(bool value); // Obtiene el valor de la variable - Uint16 getInvulnerableCounter(); + [[nodiscard]] auto getInvulnerableCounter() const -> Uint16; // Establece el valor de la variable void setInvulnerableCounter(Uint16 value); // Obtiene el valor de la variable - bool isPowerUp(); + [[nodiscard]] auto isPowerUp() const -> bool; // Establece el valor de la variable void setPowerUp(bool value); // Obtiene el valor de la variable - Uint16 getPowerUpCounter(); + [[nodiscard]] auto getPowerUpCounter() const -> Uint16; // Establece el valor de la variable void setPowerUpCounter(Uint16 value); @@ -192,7 +192,7 @@ class Player { void updatePowerUpCounter(); // Obtiene el valor de la variable - bool hasExtraHit(); + [[nodiscard]] auto hasExtraHit() const -> bool; // Concede un toque extra al jugador void giveExtraHit(); @@ -207,14 +207,14 @@ class Player { void disableInput(); // Devuelve el numero de cafes actuales - Uint8 getCoffees(); + [[nodiscard]] auto getCoffees() const -> Uint8; // 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 - Texture *getDeadTexture(); + auto getDeadTexture() -> Texture *; // Obtiene el valor de la variable - Uint16 getDeathCounter(); + [[nodiscard]] auto getDeathCounter() const -> Uint16; }; diff --git a/source/game/game.cpp b/source/game/game.cpp index 5cca53b..c33b4d4 100644 --- a/source/game/game.cpp +++ b/source/game/game.cpp @@ -1,9 +1,9 @@ #include "game/game.h" #include -#include // for rand #include // for max, min +#include // for rand #include // for basic_ifstream #include // for basic_ostream, char_traits, operator<< #include // for accumulate @@ -23,7 +23,7 @@ #include "core/resources/resource.h" #include "game/defaults.hpp" // for PLAY_AREA_CENTER_X, BLOCK, PLAY_AREA_CEN... #include "game/entities/balloon.h" // for Balloon, BALLOON_VELX_NEGATIVE, BALLOON_... -#include "game/entities/bullet.h" // for Bullet, BULLET_LEFT, BULLET_RIGHT, BULLE... +#include "game/entities/bullet.h" // for Bullet, BulletKind::LEFT, BulletKind::RIGHT, BULLE... #include "game/entities/item.h" // for Item, ITEM_COFFEE_MACHINE, ITEM_CLOCK #include "game/entities/player.h" // for Player, DEATH_COUNTER #include "game/options.hpp" // for Options @@ -64,10 +64,10 @@ Game::Game(int numPlayers, int currentStage, SDL_Renderer *renderer, bool demo, // Establece la máxima puntuación desde fichero o desde las puntuaciones online setHiScore(); - clouds1A = new MovingSprite(0, 0, 256, 52, -0.4f, 0.0f, 0.0f, 0.0f, gameCloudsTexture, renderer); - clouds1B = new MovingSprite(256, 0, 256, 52, -0.4f, 0.0f, 0.0f, 0.0f, gameCloudsTexture, renderer); - clouds2A = new MovingSprite(0, 52, 256, 32, -0.2f, 0.0f, 0.0f, 0.0f, gameCloudsTexture, renderer); - clouds2B = new MovingSprite(256, 52, 256, 32, -0.2f, 0.0f, 0.0f, 0.0f, gameCloudsTexture, renderer); + clouds1A = new MovingSprite(0, 0, 256, 52, -0.4F, 0.0F, 0.0F, 0.0F, gameCloudsTexture, renderer); + clouds1B = new MovingSprite(256, 0, 256, 52, -0.4F, 0.0F, 0.0F, 0.0F, gameCloudsTexture, renderer); + clouds2A = new MovingSprite(0, 52, 256, 32, -0.2F, 0.0F, 0.0F, 0.0F, gameCloudsTexture, renderer); + clouds2B = new MovingSprite(256, 52, 256, 32, -0.2F, 0.0F, 0.0F, 0.0F, gameCloudsTexture, renderer); n1000Sprite = new SmartSprite(gameTextTexture, renderer); n2500Sprite = new SmartSprite(gameTextTexture, renderer); @@ -79,7 +79,7 @@ Game::Game(int numPlayers, int currentStage, SDL_Renderer *renderer, bool demo, grassSprite = new Sprite(0, 0, 256, 6, gameGrassTexture, renderer); powerMeterSprite = new Sprite(PLAY_AREA_CENTER_X - 20, 170, 40, 7, gamePowerMeterTexture, renderer); gameOverSprite = new Sprite(16, 80, 128, 96, gameOverTexture, renderer); - gameOverEndSprite = new Sprite(PLAY_AREA_CENTER_X - gameOverEndTexture->getWidth() / 2, 80, 128, 96, gameOverEndTexture, renderer); + gameOverEndSprite = new Sprite(PLAY_AREA_CENTER_X - (gameOverEndTexture->getWidth() / 2), 80, 128, 96, gameOverEndTexture, renderer); // Inicializa las variables necesarias para la sección 'Game' init(); @@ -134,20 +134,20 @@ void Game::init() { ticksSpeed = 15; // Elimina qualquier jugador que hubiese antes de crear los nuevos - for (auto player : players) { + for (auto *player : players) { delete player; }; players.clear(); // Crea los jugadores if (numPlayers == 1) { - Player *player = new Player(PLAY_AREA_CENTER_X - 11, PLAY_AREA_BOTTOM - 24, renderer, playerTextures[Options::settings.player_selected], playerAnimations); + auto *player = new Player(PLAY_AREA_CENTER_X - 11, PLAY_AREA_BOTTOM - 24, renderer, playerTextures[Options::settings.player_selected], playerAnimations); players.push_back(player); } else if (numPlayers == 2) { - Player *player1 = new Player((PLAY_AREA_CENTER_FIRST_QUARTER_X * ((0 * 2) + 1)) - 11, PLAY_AREA_BOTTOM - 24, renderer, playerTextures[0], playerAnimations); - Player *player2 = new Player((PLAY_AREA_CENTER_FIRST_QUARTER_X * ((1 * 2) + 1)) - 11, PLAY_AREA_BOTTOM - 24, renderer, playerTextures[1], playerAnimations); + auto *player1 = new Player((PLAY_AREA_CENTER_FIRST_QUARTER_X * ((0 * 2) + 1)) - 11, PLAY_AREA_BOTTOM - 24, renderer, playerTextures[0], playerAnimations); + auto *player2 = new Player((PLAY_AREA_CENTER_FIRST_QUARTER_X * ((1 * 2) + 1)) - 11, PLAY_AREA_BOTTOM - 24, renderer, playerTextures[1], playerAnimations); players.push_back(player1); players.push_back(player2); } @@ -156,7 +156,7 @@ void Game::init() { switch (difficulty) { case DIFFICULTY_EASY: defaultEnemySpeed = BALLOON_SPEED_1; - difficultyScoreMultiplier = 0.5f; + difficultyScoreMultiplier = 0.5F; difficultyColor = {75, 105, 47}; pauseMenu->setSelectorColor(difficultyColor, 255); gameOverMenu->setSelectorColor(difficultyColor, 255); @@ -164,7 +164,7 @@ void Game::init() { case DIFFICULTY_NORMAL: defaultEnemySpeed = BALLOON_SPEED_1; - difficultyScoreMultiplier = 1.0f; + difficultyScoreMultiplier = 1.0F; difficultyColor = {255, 122, 0}; pauseMenu->setSelectorColor(difficultyColor, 255); gameOverMenu->setSelectorColor(difficultyColor, 255); @@ -172,7 +172,7 @@ void Game::init() { case DIFFICULTY_HARD: defaultEnemySpeed = BALLOON_SPEED_5; - difficultyScoreMultiplier = 1.5f; + difficultyScoreMultiplier = 1.5F; difficultyColor = {118, 66, 138}; pauseMenu->setSelectorColor(difficultyColor, 255); gameOverMenu->setSelectorColor(difficultyColor, 255); @@ -248,8 +248,8 @@ void Game::init() { } totalPowerToCompleteGame = 0; - for (int i = 0; i < 10; ++i) { - totalPowerToCompleteGame += stage[i].powerToComplete; + for (auto &i : stage) { + totalPowerToCompleteGame += i.powerToComplete; } // Modo demo @@ -276,10 +276,10 @@ void Game::init() { n1000Sprite->setPosY(0); n1000Sprite->setWidth(26); n1000Sprite->setHeight(9); - n1000Sprite->setVelX(0.0f); - n1000Sprite->setVelY(-0.5f); - n1000Sprite->setAccelX(0.0f); - n1000Sprite->setAccelY(-0.1f); + n1000Sprite->setVelX(0.0F); + n1000Sprite->setVelY(-0.5F); + n1000Sprite->setAccelX(0.0F); + n1000Sprite->setAccelY(-0.1F); n1000Sprite->setSpriteClip(0, 0, 26, 9); n1000Sprite->setEnabled(false); n1000Sprite->setEnabledCounter(0); @@ -291,10 +291,10 @@ void Game::init() { n2500Sprite->setPosY(0); n2500Sprite->setWidth(28); n2500Sprite->setHeight(9); - n2500Sprite->setVelX(0.0f); - n2500Sprite->setVelY(-0.5f); - n2500Sprite->setAccelX(0.0f); - n2500Sprite->setAccelY(-0.1f); + n2500Sprite->setVelX(0.0F); + n2500Sprite->setVelY(-0.5F); + n2500Sprite->setAccelX(0.0F); + n2500Sprite->setAccelY(-0.1F); n2500Sprite->setSpriteClip(26, 0, 28, 9); n2500Sprite->setEnabled(false); n2500Sprite->setEnabledCounter(0); @@ -306,10 +306,10 @@ void Game::init() { n5000Sprite->setPosY(0); n5000Sprite->setWidth(28); n5000Sprite->setHeight(9); - n5000Sprite->setVelX(0.0f); - n5000Sprite->setVelY(-0.5f); - n5000Sprite->setAccelX(0.0f); - n5000Sprite->setAccelY(-0.1f); + n5000Sprite->setVelX(0.0F); + n5000Sprite->setVelY(-0.5F); + n5000Sprite->setAccelX(0.0F); + n5000Sprite->setAccelY(-0.1F); n5000Sprite->setSpriteClip(54, 0, 28, 9); n5000Sprite->setEnabled(false); n5000Sprite->setEnabledCounter(0); @@ -317,17 +317,17 @@ void Game::init() { n5000Sprite->setDestY(0); // Los fondos - skyColorsRect[0] = {0, 0, GAMECANVAS_WIDTH, GAMECANVAS_HEIGHT}; - skyColorsRect[1] = {256, 0, GAMECANVAS_WIDTH, GAMECANVAS_HEIGHT}; - skyColorsRect[2] = {0, 192, GAMECANVAS_WIDTH, GAMECANVAS_HEIGHT}; - skyColorsRect[3] = {256, 192, GAMECANVAS_WIDTH, GAMECANVAS_HEIGHT}; + skyColorsRect[0] = {.x = 0, .y = 0, .w = GAMECANVAS_WIDTH, .h = GAMECANVAS_HEIGHT}; + skyColorsRect[1] = {.x = 256, .y = 0, .w = GAMECANVAS_WIDTH, .h = GAMECANVAS_HEIGHT}; + skyColorsRect[2] = {.x = 0, .y = 192, .w = GAMECANVAS_WIDTH, .h = GAMECANVAS_HEIGHT}; + skyColorsRect[3] = {.x = 256, .y = 192, .w = GAMECANVAS_WIDTH, .h = GAMECANVAS_HEIGHT}; } // Carga los recursos necesarios para la sección 'Game' void Game::loadMedia() { if (Options::settings.console) { - std::cout << std::endl - << "** LOADING RESOURCES FOR GAME SECTION" << std::endl; + std::cout << '\n' + << "** LOADING RESOURCES FOR GAME SECTION" << '\n'; } Resource *R = Resource::get(); @@ -432,13 +432,13 @@ void Game::loadMedia() { gameMusic = R->getMusic("playing.ogg"); if (Options::settings.console) { - std::cout << "** RESOURCES FOR GAME SECTION LOADED" << std::endl - << std::endl; + std::cout << "** RESOURCES FOR GAME SECTION LOADED" << '\n' + << '\n'; } } // Carga el fichero de puntos -bool Game::loadScoreFile() { +auto Game::loadScoreFile() -> bool { // Indicador de éxito en la carga bool success = true; const std::string p = Asset::get()->get("score.bin"); @@ -448,27 +448,27 @@ bool Game::loadScoreFile() { // El fichero no existe if (file == nullptr) { if (Options::settings.console) { - std::cout << "Warning: Unable to open " << filename.c_str() << " file" << std::endl; + std::cout << "Warning: Unable to open " << filename.c_str() << " file" << '\n'; } // Creamos el fichero para escritura file = SDL_IOFromFile(p.c_str(), "w+b"); if (file != nullptr) { if (Options::settings.console) { - std::cout << "New file (" << filename.c_str() << ") created!" << std::endl; + std::cout << "New file (" << filename.c_str() << ") created!" << '\n'; } // Inicializamos los datos - for (int i = 0; i < TOTAL_SCORE_DATA; ++i) { - scoreDataFile[i] = 0; - SDL_WriteIO(file, &scoreDataFile[i], sizeof(Uint32)); + for (unsigned int &i : scoreDataFile) { + i = 0; + SDL_WriteIO(file, &i, sizeof(Uint32)); } // Cerramos el fichero SDL_CloseIO(file); } else { if (Options::settings.console) { - std::cout << "Error: Unable to create file " << filename.c_str() << std::endl; + std::cout << "Error: Unable to create file " << filename.c_str() << '\n'; } success = false; } @@ -477,21 +477,19 @@ bool Game::loadScoreFile() { else { // Cargamos los datos if (Options::settings.console) { - std::cout << "Reading file " << filename.c_str() << std::endl; + std::cout << "Reading file " << filename.c_str() << '\n'; + } + for (unsigned int &i : scoreDataFile) { + SDL_ReadIO(file, &i, sizeof(Uint32)); } - for (int i = 0; i < TOTAL_SCORE_DATA; ++i) - SDL_ReadIO(file, &scoreDataFile[i], sizeof(Uint32)); // Cierra el fichero SDL_CloseIO(file); } - // Establece el valor de la máxima puntuación a partir del vector con los datos - if (scoreDataFile[0] == 0) { - hiScore = 10000; - } - // Comprueba el checksum para ver si se ha modificado el fichero - else if (scoreDataFile[0] % 43 == scoreDataFile[1]) { + // Estableix el hi-score si el fitxer és vàlid (≠ 0) i el checksum quadra; + // en qualsevol altre cas (fitxer absent, corrupte o manipulat) usa el default. + if (scoreDataFile[0] != 0 && scoreDataFile[0] % 43 == scoreDataFile[1]) { hiScore = scoreDataFile[0]; } else { hiScore = 10000; @@ -501,63 +499,63 @@ bool Game::loadScoreFile() { } // Carga el fichero de datos para la demo -bool Game::loadDemoFile() { +auto Game::loadDemoFile() -> bool { // Lee los datos de la demo desde Resource (precargados al arrancar). const auto &bytes = Resource::get()->getDemoBytes(); const size_t expected = sizeof(demoKeys_t) * TOTAL_DEMO_DATA; if (bytes.size() >= expected) { for (int i = 0; i < TOTAL_DEMO_DATA; ++i) { - memcpy(&demo.dataFile[i], bytes.data() + i * sizeof(demoKeys_t), sizeof(demoKeys_t)); + memcpy(&demo.dataFile[i], bytes.data() + (i * sizeof(demoKeys_t)), sizeof(demoKeys_t)); } if (Options::settings.console) { - std::cout << "Demo data loaded (" << bytes.size() << " bytes)" << std::endl; + std::cout << "Demo data loaded (" << bytes.size() << " bytes)" << '\n'; } } else { // Si no hay datos (bytes vacíos o tamaño inválido), inicializamos a cero. if (Options::settings.console) { - std::cout << "Warning: demo data missing or too small, initializing to zero" << std::endl; + std::cout << "Warning: demo data missing or too small, initializing to zero" << '\n'; } - for (int i = 0; i < TOTAL_DEMO_DATA; ++i) { + for (auto &i : demo.dataFile) { demo.keys.left = 0; demo.keys.right = 0; demo.keys.noInput = 0; demo.keys.fire = 0; demo.keys.fireLeft = 0; demo.keys.fireRight = 0; - demo.dataFile[i] = demo.keys; + i = demo.keys; } } return true; } // Guarda el fichero de puntos -bool Game::saveScoreFile() { +auto Game::saveScoreFile() -> bool { bool success = true; const std::string p = Asset::get()->get("score.bin"); const std::string filename = p.substr(p.find_last_of("\\/") + 1); SDL_IOStream *file = SDL_IOFromFile(p.c_str(), "w+b"); if (file != nullptr) { // Guardamos los datos - for (int i = 0; i < TOTAL_SCORE_DATA; ++i) { - SDL_WriteIO(file, &scoreDataFile[i], sizeof(Uint32)); + for (unsigned int &i : scoreDataFile) { + SDL_WriteIO(file, &i, sizeof(Uint32)); } if (Options::settings.console) { - std::cout << "Writing file " << filename.c_str() << std::endl; + std::cout << "Writing file " << filename.c_str() << '\n'; } // Cerramos el fichero SDL_CloseIO(file); } else { if (Options::settings.console) { - std::cout << "Error: Unable to save " << filename.c_str() << " file! " << SDL_GetError() << std::endl; + std::cout << "Error: Unable to save " << filename.c_str() << " file! " << SDL_GetError() << '\n'; } } return success; } // Guarda el fichero de datos para la demo -bool Game::saveDemoFile() { +auto Game::saveDemoFile() -> bool { bool success = true; const std::string p = Asset::get()->get("demo.bin"); const std::string filename = p.substr(p.find_last_of("\\/") + 1); @@ -565,19 +563,19 @@ bool Game::saveDemoFile() { SDL_IOStream *file = SDL_IOFromFile(p.c_str(), "w+b"); if (file != nullptr) { // Guardamos los datos - for (int i = 0; i < TOTAL_DEMO_DATA; ++i) { - SDL_WriteIO(file, &demo.dataFile[i], sizeof(demoKeys_t)); + for (auto &i : demo.dataFile) { + SDL_WriteIO(file, &i, sizeof(demoKeys_t)); } if (Options::settings.console) { - std::cout << "Writing file " << filename.c_str() << std::endl; + std::cout << "Writing file " << filename.c_str() << '\n'; } // Cerramos el fichero SDL_CloseIO(file); } else { if (Options::settings.console) { - std::cout << "Error: Unable to save " << filename.c_str() << " file! " << SDL_GetError() << std::endl; + std::cout << "Error: Unable to save " << filename.c_str() << " file! " << SDL_GetError() << '\n'; } } } @@ -604,14 +602,14 @@ void Game::initEnemyFormations() { const int x1_100 = (PLAY_AREA_RIGHT)-BALLOON_WIDTH_1; // Inicializa a cero las variables - for (int i = 0; i < NUMBER_OF_ENEMY_FORMATIONS; i++) { - enemyFormation[i].numberOfEnemies = 0; - for (int j = 0; j < MAX_NUMBER_OF_ENEMIES_IN_A_FORMATION; j++) { - enemyFormation[i].init[j].x = 0; - enemyFormation[i].init[j].y = 0; - enemyFormation[i].init[j].velX = 0; - enemyFormation[i].init[j].kind = 0; - enemyFormation[i].init[j].creationCounter = 0; + for (auto &i : enemyFormation) { + i.numberOfEnemies = 0; + for (auto &j : i.init) { + j.x = 0; + j.y = 0; + j.velX = 0; + j.kind = 0; + j.creationCounter = 0; } } @@ -1262,8 +1260,9 @@ void Game::deployEnemyFormation() { Uint8 set = (rand() % 10); // Evita repetir la ultima formación enemiga desplegada - if (set == lastEnemyDeploy) + if (set == lastEnemyDeploy) { ++set %= 10; + } lastEnemyDeploy = set; @@ -1295,7 +1294,7 @@ void Game::setHiScore(Uint32 score) { // Actualiza el valor de hiScore en caso necesario void Game::updateHiScore() { // Si la puntuación actual es mayor que la máxima puntuación - for (auto player : players) + for (auto *player : players) { if (player->getScore() > hiScore) { // Actualiza la máxima puntuación hiScore = player->getScore(); @@ -1305,15 +1304,16 @@ void Game::updateHiScore() { scoreDataFile[1] = hiScore % 43; // Si se supera la máxima puntuación emite sonido - if (hiScoreAchieved == false) { + if (!hiScoreAchieved) { hiScoreAchieved = true; Audio::get()->playSound(hiScoreSound); } } + } } // Transforma un valor numérico en una cadena de 6 cifras -std::string Game::updateScoreText(Uint32 num) { +auto Game::updateScoreText(Uint32 num) -> std::string { if ((num >= 0) && (num <= 9)) { return ("000000" + std::to_string(num)); } @@ -1402,7 +1402,7 @@ void Game::renderScoreBoard() { powerMeterSprite->setPosY(offset2); powerMeterSprite->setSpriteClip(0, 0, 40, 7); powerMeterSprite->render(); - const float percent = (stage[currentStage].currentPower * 40.0f) / stage[currentStage].powerToComplete; + const float percent = (stage[currentStage].currentPower * 40.0F) / stage[currentStage].powerToComplete; powerMeterSprite->setSpriteClip(40, 0, (int)percent, 7); powerMeterSprite->render(); @@ -1413,7 +1413,7 @@ void Game::renderScoreBoard() { // Actualiza las variables del jugador void Game::updatePlayers() { - for (auto player : players) { + for (auto *player : players) { player->update(); // Comprueba la colisión entre el jugador y los globos @@ -1435,7 +1435,7 @@ void Game::updatePlayers() { // Dibuja a los jugadores void Game::renderPlayers() { - for (auto player : players) { + for (auto *player : players) { player->render(); } } @@ -1453,7 +1453,7 @@ void Game::updateStage() { destroyAllBalloons(); // Destruye a todos los enemigos stage[currentStage].currentPower = 0; // Vuelve a dejar el poder a cero, por lo que hubiera podido subir al destruir todos lo globos menaceCurrent = 255; // Sube el nivel de amenaza para que no cree mas globos - for (auto player : players) { // Añade un millon de puntos a los jugadores que queden vivos + for (auto *player : players) { // Añade un millon de puntos a los jugadores que queden vivos if (player->isAlive()) { player->addScore(1000000); } @@ -1476,9 +1476,7 @@ void Game::updateStage() { // Si el juego se ha completado, el bitmap se detiene en el centro de la pantalla if (gameCompleted) { - if (stageBitmapCounter > 100) { - stageBitmapCounter = 100; - } + stageBitmapCounter = std::min(stageBitmapCounter, 100); } } @@ -1486,7 +1484,7 @@ void Game::updateStage() { void Game::updateDeath() { // Comprueba si todos los jugadores estan muertos bool allDead = true; - for (auto player : players) { + for (auto *player : players) { allDead &= (!player->isAlive()); } @@ -1515,7 +1513,7 @@ void Game::renderDeathFade(int counter) { // Counter debe ir de 0 a 150 if (counter < 150) { // 192 / 6 = 32, 6 cuadrados de 32 pixeles SDL_FRect rect[12]; - float h = (float)(counter / 3); + auto h = (float)(counter / 3); for (int i = 0; i < 12; ++i) { rect[i].x = 0; rect[i].y = (float)(i * 16); @@ -1523,7 +1521,7 @@ void Game::renderDeathFade(int counter) { // Counter debe ir de 0 a 150 if (i == 0) { rect[i].h = h; } else { - rect[i].h = std::max(rect[i - 1].h - 3.0f, 0.0f); + rect[i].h = std::max(rect[i - 1].h - 3.0F, 0.0F); } SDL_RenderFillRect(renderer, &rect[i]); } @@ -1535,22 +1533,22 @@ void Game::renderDeathFade(int counter) { // Counter debe ir de 0 a 150 // Actualiza los globos void Game::updateBalloons() { - for (auto balloon : balloons) { + for (auto *balloon : balloons) { balloon->update(); } } // Pinta en pantalla todos los globos activos void Game::renderBalloons() { - for (auto balloon : balloons) { + for (auto *balloon : balloons) { balloon->render(); } } // Crea un globo nuevo en el vector de globos -Uint8 Game::createBalloon(float x, int y, Uint8 kind, float velx, float speed, Uint16 creationtimer) { +auto Game::createBalloon(float x, float y, Uint8 kind, float velx, float speed, Uint16 creationtimer) -> Uint8 { const int index = (kind - 1) % 4; - Balloon *b = new Balloon(x, y, kind, velx, speed, creationtimer, balloonTextures[index], balloonAnimations[index], renderer); + auto *b = new Balloon(x, y, kind, velx, speed, creationtimer, balloonTextures[index], balloonAnimations[index], renderer); balloons.push_back(b); return (Uint8)(balloons.size() - 1); } @@ -1567,7 +1565,7 @@ void Game::createPowerBall() { const int x[3] = {left, center, right}; const float vx[3] = {BALLOON_VELX_POSITIVE, BALLOON_VELX_POSITIVE, BALLOON_VELX_NEGATIVE}; - Balloon *b = new Balloon(x[luck], posY, POWER_BALL, vx[luck], enemySpeed, 100, balloonTextures[3], balloonAnimations[3], renderer); + auto *b = new Balloon(x[luck], posY, POWER_BALL, vx[luck], enemySpeed, 100, balloonTextures[3], balloonAnimations[3], renderer); balloons.push_back(b); powerBallEnabled = true; @@ -1576,7 +1574,7 @@ void Game::createPowerBall() { // Establece la velocidad de los globos void Game::setBalloonSpeed(float speed) { - for (auto balloon : balloons) { + for (auto *balloon : balloons) { if (balloon->isEnabled()) { balloon->setSpeed(speed); } @@ -1611,25 +1609,25 @@ void Game::incBalloonSpeed() { void Game::updateBalloonSpeed() { const float percent = (float)stage[currentStage].currentPower / (float)stage[currentStage].powerToComplete; if (enemySpeed == BALLOON_SPEED_1) { - if (percent > 0.2f) { + if (percent > 0.2F) { incBalloonSpeed(); } } else if (enemySpeed == BALLOON_SPEED_2) { - if (percent > 0.4f) { + if (percent > 0.4F) { incBalloonSpeed(); } } else if (enemySpeed == BALLOON_SPEED_3) { - if (percent > 0.6f) { + if (percent > 0.6F) { incBalloonSpeed(); } } else if (enemySpeed == BALLOON_SPEED_4) { - if (percent > 0.8f) { + if (percent > 0.8F) { incBalloonSpeed(); } } @@ -1643,11 +1641,8 @@ void Game::popBalloon(Balloon *balloon) { const Uint8 kind = balloon->getKind(); switch (kind) { - // Si es del tipo más pequeño, simplemente elimina el globo + // Tipus més petits: simplement elimina el globó case BALLOON_1: - balloon->pop(); - break; - case HEXAGON_1: balloon->pop(); break; @@ -1664,7 +1659,7 @@ void Game::popBalloon(Balloon *balloon) { const int index = createBalloon(0, balloon->getPosY(), balloon->getKind() - 1, BALLOON_VELX_NEGATIVE, enemySpeed, 0); balloons[index]->allignTo(balloon->getPosX() + (balloon->getWidth() / 2)); if (balloons[index]->getClass() == BALLOON_CLASS) { - balloons[index]->setVelY(-2.50f); + balloons[index]->setVelY(-2.50F); } else { balloons[index]->setVelY(BALLOON_VELX_NEGATIVE); } @@ -1672,7 +1667,7 @@ void Game::popBalloon(Balloon *balloon) { const int index2 = createBalloon(0, balloon->getPosY(), balloon->getKind() - 1, BALLOON_VELX_POSITIVE, enemySpeed, 0); balloons[index2]->allignTo(balloon->getPosX() + (balloon->getWidth() / 2)); if (balloons[index2]->getClass() == BALLOON_CLASS) { - balloons[index2]->setVelY(-2.50f); + balloons[index2]->setVelY(-2.50F); } else { balloons[index2]->setVelY(BALLOON_VELX_NEGATIVE); } @@ -1720,7 +1715,7 @@ void Game::destroyBalloon(Balloon *balloon) { } // Otorga los puntos correspondientes al globo - for (auto player : players) { + for (auto *player : players) { player->addScore(Uint32(score * player->getScoreMultiplier() * difficultyScoreMultiplier)); } updateHiScore(); @@ -1738,7 +1733,7 @@ void Game::destroyBalloon(Balloon *balloon) { // Destruye todos los globos void Game::destroyAllBalloons() { - for (auto balloon : balloons) { + for (auto *balloon : balloons) { if ((balloon->isEnabled()) && (!balloon->isPopping())) { destroyBalloon(balloon); } @@ -1754,7 +1749,7 @@ void Game::destroyAllBalloons() { // Detiene todos los globos void Game::stopAllBalloons(Uint16 time) { - for (auto balloon : balloons) { + for (auto *balloon : balloons) { if (balloon->isEnabled()) { balloon->setStop(true); balloon->setStoppedTimer(time); @@ -1764,7 +1759,7 @@ void Game::stopAllBalloons(Uint16 time) { // Pone en marcha todos los globos void Game::startAllBalloons() { - for (auto balloon : balloons) { + for (auto *balloon : balloons) { if ((balloon->isEnabled()) && (!balloon->isBeingCreated())) { balloon->setStop(false); balloon->setStoppedTimer(0); @@ -1774,9 +1769,9 @@ void Game::startAllBalloons() { // Vacia el vector de globos void Game::freeBalloons() { - if (balloons.empty() == false) { + if (!balloons.empty()) { for (int i = balloons.size() - 1; i >= 0; --i) { - if (balloons[i]->isEnabled() == false) { + if (!balloons[i]->isEnabled()) { delete balloons[i]; balloons.erase(balloons.begin() + i); } @@ -1785,8 +1780,8 @@ void Game::freeBalloons() { } // Comprueba la colisión entre el jugador y los globos activos -bool Game::checkPlayerBalloonCollision(Player *player) { - for (auto balloon : balloons) { +auto Game::checkPlayerBalloonCollision(Player *player) -> bool { + for (auto *balloon : balloons) { if ((balloon->isEnabled()) && !(balloon->isStopped()) && !(balloon->isInvulnerable())) { if (checkCollision(player->getCollider(), balloon->getCollider())) { return true; @@ -1803,7 +1798,7 @@ void Game::checkPlayerItemCollision(Player *player) { return; } - for (auto item : items) { + for (auto *item : items) { if (item->isEnabled()) { if (checkCollision(player->getCollider(), item->getCollider())) { switch (item->getClass()) { @@ -1861,8 +1856,8 @@ void Game::checkPlayerItemCollision(Player *player) { // Comprueba y procesa la colisión entre las balas y los globos void Game::checkBulletBalloonCollision() { - for (auto bullet : bullets) { - for (auto balloon : balloons) { + for (auto *bullet : bullets) { + for (auto *balloon : balloons) { if (balloon->isEnabled() && (!balloon->isInvulnerable()) && bullet->isEnabled()) { if (checkCollision(balloon->getCollider(), bullet->getCollider())) { // Otorga los puntos correspondientes al globo al jugador que disparó la bala @@ -1903,7 +1898,7 @@ void Game::checkBulletBalloonCollision() { // Mueve las balas activas void Game::moveBullets() { - for (auto bullet : bullets) { + for (auto *bullet : bullets) { if (bullet->isEnabled()) { if (bullet->move() == BULLET_MOVE_OUT) { players[bullet->getOwner()]->decScoreMultiplier(); @@ -1914,7 +1909,7 @@ void Game::moveBullets() { // Pinta las balas activas void Game::renderBullets() { - for (auto bullet : bullets) { + for (auto *bullet : bullets) { if (bullet->isEnabled()) { bullet->render(); } @@ -1922,16 +1917,16 @@ void Game::renderBullets() { } // Crea un objeto bala -void Game::createBullet(int x, int y, Uint8 kind, bool poweredUp, int owner) { - Bullet *b = new Bullet(x, y, kind, poweredUp, owner, bulletTexture, renderer); +void Game::createBullet(int x, int y, BulletKind kind, bool poweredUp, int owner) { + auto *b = new Bullet(x, y, kind, poweredUp, owner, bulletTexture, renderer); bullets.push_back(b); } // Vacia el vector de balas void Game::freeBullets() { - if (bullets.empty() == false) { + if (!bullets.empty()) { for (int i = bullets.size() - 1; i >= 0; --i) { - if (bullets[i]->isEnabled() == false) { + if (!bullets[i]->isEnabled()) { delete bullets[i]; bullets.erase(bullets.begin() + i); } @@ -1941,7 +1936,7 @@ void Game::freeBullets() { // Actualiza los items void Game::updateItems() { - for (auto item : items) { + for (auto *item : items) { if (item->isEnabled()) { item->update(); if (item->isOnFloor()) { @@ -1954,13 +1949,13 @@ void Game::updateItems() { // Pinta los items activos void Game::renderItems() { - for (auto item : items) { + for (auto *item : items) { item->render(); } } // Devuelve un item en función del azar -Uint8 Game::dropItem() { +auto Game::dropItem() -> Uint8 { const Uint8 luckyNumber = rand() % 100; const Uint8 item = rand() % 6; @@ -2028,9 +2023,9 @@ void Game::createItem(Uint8 kind, float x, float y) { // Vacia el vector de items void Game::freeItems() { - if (items.empty() == false) { + if (!items.empty()) { for (int i = items.size() - 1; i >= 0; --i) { - if (items[i]->isEnabled() == false) { + if (!items[i]->isEnabled()) { delete items[i]; items.erase(items.begin() + i); } @@ -2040,7 +2035,7 @@ void Game::freeItems() { // Crea un objeto SmartSprite para mostrar la puntuación al coger un objeto void Game::createItemScoreSprite(int x, int y, const SmartSprite *sprite) { - SmartSprite *ss = new SmartSprite(nullptr, renderer); + auto *ss = new SmartSprite(nullptr, renderer); smartSprites.push_back(ss); // Crea una copia del objeto @@ -2055,7 +2050,7 @@ void Game::createItemScoreSprite(int x, int y, const SmartSprite *sprite) { // Vacia el vector de smartsprites void Game::freeSmartSprites() { - if (smartSprites.empty() == false) { + if (!smartSprites.empty()) { for (int i = smartSprites.size() - 1; i >= 0; --i) { if (smartSprites[i]->hasFinished()) { delete smartSprites[i]; @@ -2090,17 +2085,17 @@ void Game::updateShakeEffect() { // Crea un SmartSprite para arrojar el item café al recibir un impacto void Game::throwCoffee(int x, int y) { - SmartSprite *ss = new SmartSprite(itemTextures[4], renderer); + auto *ss = new SmartSprite(itemTextures[4], renderer); smartSprites.push_back(ss); ss->setPosX(x - 8); ss->setPosY(y - 8); ss->setWidth(16); ss->setHeight(16); - ss->setVelX(-1.0f + ((rand() % 5) * 0.5f)); - ss->setVelY(-4.0f); - ss->setAccelX(0.0f); - ss->setAccelY(0.2f); + ss->setVelX(-1.0F + ((rand() % 5) * 0.5F)); + ss->setVelY(-4.0F); + ss->setAccelX(0.0F); + ss->setAccelY(0.2F); ss->setDestX(x + (ss->getVelX() * 50)); ss->setDestY(GAMECANVAS_HEIGHT + 1); ss->setEnabled(true); @@ -2113,14 +2108,14 @@ void Game::throwCoffee(int x, int y) { // Actualiza los SmartSprites void Game::updateSmartSprites() { - for (auto ss : smartSprites) { + for (auto *ss : smartSprites) { ss->update(); } } // Pinta los SmartSprites activos void Game::renderSmartSprites() { - for (auto ss : smartSprites) { + for (auto *ss : smartSprites) { ss->render(); } } @@ -2188,7 +2183,7 @@ void Game::evaluateAndSetMenace() { } // Obtiene el valor de la variable -Uint8 Game::getMenace() { +auto Game::getMenace() const -> Uint8 { return menaceCurrent; } @@ -2198,7 +2193,7 @@ void Game::setTimeStopped(bool value) { } // Obtiene el valor de la variable -bool Game::isTimeStopped() { +auto Game::isTimeStopped() const -> bool { return timeStopped; } @@ -2321,7 +2316,7 @@ void Game::updateBackground() { } // Calcula la velocidad en función de los globos explotados y el total de globos a explotar para acabar el juego - const float speed = (-0.2f) + (-3.00f * ((float)cloudsSpeed / (float)totalPowerToCompleteGame)); + const float speed = (-0.2F) + (-3.00F * ((float)cloudsSpeed / (float)totalPowerToCompleteGame)); // Aplica la velocidad calculada a las nubes clouds1A->setVelX(speed); @@ -2368,7 +2363,7 @@ void Game::updateBackground() { // Dibuja el fondo void Game::renderBackground() { - const float gradientNumber = std::min(((float)balloonsPopped / 1250.0f), 3.0f); + const float gradientNumber = std::min(((float)balloonsPopped / 1250.0F), 3.0F); const float percent = gradientNumber - (int)gradientNumber; const int alpha = std::max((255 - (int)(255 * percent)), 0); @@ -2479,7 +2474,7 @@ void Game::checkGameInput() { if (demo.dataFile[demo.counter].fire == 1) { if (players[index]->canFire()) { players[index]->setInput(input_fire_center); - createBullet(players[index]->getPosX() + (players[index]->getWidth() / 2) - 4, players[index]->getPosY() + (players[index]->getHeight() / 2), BULLET_UP, players[index]->isPowerUp(), index); + createBullet(players[index]->getPosX() + (players[index]->getWidth() / 2) - 4, players[index]->getPosY() + (players[index]->getHeight() / 2), BulletKind::UP, players[index]->isPowerUp(), index); players[index]->setFireCooldown(10); } } @@ -2487,7 +2482,7 @@ void Game::checkGameInput() { if (demo.dataFile[demo.counter].fireLeft == 1) { if (players[index]->canFire()) { players[index]->setInput(input_fire_left); - createBullet(players[index]->getPosX() + (players[index]->getWidth() / 2) - 4, players[index]->getPosY() + (players[index]->getHeight() / 2), BULLET_LEFT, players[index]->isPowerUp(), index); + createBullet(players[index]->getPosX() + (players[index]->getWidth() / 2) - 4, players[index]->getPosY() + (players[index]->getHeight() / 2), BulletKind::LEFT, players[index]->isPowerUp(), index); players[index]->setFireCooldown(10); } } @@ -2495,7 +2490,7 @@ void Game::checkGameInput() { if (demo.dataFile[demo.counter].fireRight == 1) { if (players[index]->canFire()) { players[index]->setInput(input_fire_right); - createBullet(players[index]->getPosX() + (players[index]->getWidth() / 2) - 4, players[index]->getPosY() + (players[index]->getHeight() / 2), BULLET_RIGHT, players[index]->isPowerUp(), index); + createBullet(players[index]->getPosX() + (players[index]->getWidth() / 2) - 4, players[index]->getPosY() + (players[index]->getHeight() / 2), BulletKind::RIGHT, players[index]->isPowerUp(), index); players[index]->setFireCooldown(10); } } @@ -2516,7 +2511,7 @@ void Game::checkGameInput() { // Modo Demo no activo else { int i = 0; - for (auto player : players) { + for (auto *player : players) { if (player->isAlive()) { // Input a la izquierda if (Input::get()->checkInput(input_left, REPEAT_TRUE, Options::inputs[i].deviceType, Options::inputs[i].id)) { @@ -2537,7 +2532,7 @@ void Game::checkGameInput() { if (Input::get()->checkInput(input_fire_center, REPEAT_TRUE, Options::inputs[i].deviceType, Options::inputs[i].id)) { if (player->canFire()) { player->setInput(input_fire_center); - createBullet(player->getPosX() + (player->getWidth() / 2) - 4, player->getPosY() + (player->getHeight() / 2), BULLET_UP, player->isPowerUp(), i); + createBullet(player->getPosX() + (player->getWidth() / 2) - 4, player->getPosY() + (player->getHeight() / 2), BulletKind::UP, player->isPowerUp(), i); player->setFireCooldown(10); // Reproduce el sonido de disparo @@ -2551,7 +2546,7 @@ void Game::checkGameInput() { if (Input::get()->checkInput(input_fire_left, REPEAT_TRUE, Options::inputs[i].deviceType, Options::inputs[i].id)) { if (player->canFire()) { player->setInput(input_fire_left); - createBullet(player->getPosX() + (player->getWidth() / 2) - 4, player->getPosY() + (player->getHeight() / 2), BULLET_LEFT, player->isPowerUp(), i); + createBullet(player->getPosX() + (player->getWidth() / 2) - 4, player->getPosY() + (player->getHeight() / 2), BulletKind::LEFT, player->isPowerUp(), i); player->setFireCooldown(10); // Reproduce el sonido de disparo @@ -2565,7 +2560,7 @@ void Game::checkGameInput() { if (Input::get()->checkInput(input_fire_right, REPEAT_TRUE, Options::inputs[i].deviceType, Options::inputs[i].id)) { if (player->canFire()) { player->setInput(input_fire_right); - createBullet(player->getPosX() + (player->getWidth() / 2) - 4, player->getPosY() + (player->getHeight() / 2), BULLET_RIGHT, player->isPowerUp(), i); + createBullet(player->getPosX() + (player->getWidth() / 2) - 4, player->getPosY() + (player->getHeight() / 2), BulletKind::RIGHT, player->isPowerUp(), i); player->setFireCooldown(10); // Reproduce el sonido de disparo @@ -2676,7 +2671,9 @@ void Game::shakeScreen() { // Actualiza el efecto de agitación intensa void Game::updateDeathShake() { - if (!deathShake.active) return; + if (!deathShake.active) { + return; + } Uint32 now = SDL_GetTicks(); if (now - deathShake.lastStepTicks >= 50) { @@ -2689,7 +2686,7 @@ void Game::updateDeathShake() { } // Indica si el efecto de agitación intensa está activo -bool Game::isDeathShaking() { +auto Game::isDeathShaking() const -> bool { return deathShake.active; } @@ -2752,7 +2749,7 @@ void Game::iterate() { } // Indica si el juego ha terminado -bool Game::hasFinished() const { +auto Game::hasFinished() const -> bool { return section->name != SECTION_PROG_GAME; } @@ -2777,7 +2774,7 @@ void Game::handleEvent(const SDL_Event *event) { // Eventos específicos de la pantalla de game over if (section->subsection == SUBSECTION_GAME_GAMEOVER) { - if (event->type == SDL_EVENT_KEY_DOWN && event->key.repeat == 0) { + if (event->type == SDL_EVENT_KEY_DOWN && static_cast(event->key.repeat) == 0) { if (gameCompleted) { gameOverPostFade = 1; fade->activateFade(); @@ -3014,7 +3011,7 @@ void Game::renderGameOverScreen() { // Continue? if (!gameCompleted) { // Solo dibuja el menu de continuar en el caso de no haber completado la partida - text->writeCentered(199, PLAY_AREA_CENTER_Y + BLOCK * 3, Lang::get()->getText(45)); + text->writeCentered(199, PLAY_AREA_CENTER_Y + (BLOCK * 3), Lang::get()->getText(45)); gameOverMenu->render(); } @@ -3037,16 +3034,12 @@ void Game::enterGameOverScreen() { } // Indica si se puede crear una powerball -bool Game::canPowerBallBeCreated() { - if ((!powerBallEnabled) && (calculateScreenPower() > POWERBALL_SCREENPOWER_MINIMUM) && (powerBallCounter == 0)) { - return true; - } - - return false; +auto Game::canPowerBallBeCreated() -> bool { + return (!powerBallEnabled) && (calculateScreenPower() > POWERBALL_SCREENPOWER_MINIMUM) && (powerBallCounter == 0); } // Calcula el poder actual de los globos en pantalla -int Game::calculateScreenPower() { +auto Game::calculateScreenPower() -> int { return std::accumulate(balloons.begin(), balloons.end(), 0, [](int acc, Balloon *b) { return b->isEnabled() ? acc + b->getPower() : acc; }); } @@ -3055,7 +3048,7 @@ void Game::initPaths() { // Vector con los valores del seno para 360 grados float sin[360]; 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); } // Letrero de STAGE # @@ -3066,7 +3059,7 @@ void Game::initPaths() { for (int i = 0; i < STAGE_COUNTER; ++i) { if (i < firstPart) { - stageBitmapPath[i] = (sin[(int)((i * 1.8f) + 90)] * (distance) + centerPoint); + stageBitmapPath[i] = (sin[(int)((i * 1.8F) + 90)] * (distance) + centerPoint); } else if (i < secondPart) { @@ -3074,7 +3067,7 @@ void Game::initPaths() { } else { - stageBitmapPath[i] = (sin[(int)(((i - 149) * 1.8f) + 90)] * (centerPoint + 17) - 17); + stageBitmapPath[i] = (sin[(int)(((i - 149) * 1.8F) + 90)] * (centerPoint + 17) - 17); } } @@ -3092,7 +3085,7 @@ void Game::initPaths() { for (int i = 0; i < STAGE_COUNTER; ++i) { if (i < firstPart) { - getReadyBitmapPath[i] = sin[(int)(i * 1.8f)]; + getReadyBitmapPath[i] = sin[(int)(i * 1.8F)]; getReadyBitmapPath[i] *= distance1; getReadyBitmapPath[i] -= size; } @@ -3102,7 +3095,7 @@ void Game::initPaths() { } else { - getReadyBitmapPath[i] = sin[(int)((i - 150) * 1.8f)]; + getReadyBitmapPath[i] = sin[(int)((i - 150) * 1.8F)]; getReadyBitmapPath[i] *= distance2; getReadyBitmapPath[i] += finish1; } @@ -3124,18 +3117,10 @@ void Game::updateGameCompleted() { void Game::updateHelper() { // Solo ofrece ayuda cuando la amenaza es elevada if (menaceCurrent > 15) { - for (auto player : players) { - if (player->getCoffees() == 0) { - helper.needCoffee = true; - } else { - helper.needCoffee = false; - } + for (auto *player : players) { + helper.needCoffee = player->getCoffees() == 0; - if (!player->isPowerUp()) { - helper.needCoffeeMachine = true; - } else { - helper.needCoffeeMachine = false; - } + helper.needCoffeeMachine = !player->isPowerUp(); } } else { helper.needCoffee = false; @@ -3144,9 +3129,9 @@ void Game::updateHelper() { } // Comprueba si todos los jugadores han muerto -bool Game::allPlayersAreDead() { +auto Game::allPlayersAreDead() -> bool { bool success = true; - for (auto player : players) { + for (auto *player : players) { success &= (!player->isAlive()); } @@ -3155,27 +3140,27 @@ bool Game::allPlayersAreDead() { // Elimina todos los objetos contenidos en vectores void Game::deleteAllVectorObjects() { - for (auto player : players) { + for (auto *player : players) { delete player; }; players.clear(); - for (auto ballon : balloons) { + for (auto *ballon : balloons) { delete ballon; }; balloons.clear(); - for (auto bullet : bullets) { + for (auto *bullet : bullets) { delete bullet; }; bullets.clear(); - for (auto item : items) { + for (auto *item : items) { delete item; }; items.clear(); - for (auto smartSprite : smartSprites) { + for (auto *smartSprite : smartSprites) { delete smartSprite; }; smartSprites.clear(); diff --git a/source/game/game.h b/source/game/game.h index 2a101ee..59eddf0 100644 --- a/source/game/game.h +++ b/source/game/game.h @@ -2,10 +2,12 @@ #include -#include // for string, basic_string -#include // for vector +#include // for uint8_t +#include // for string, basic_string +#include // 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 Bullet; class Fade; @@ -92,7 +94,7 @@ class Game { }; // Fases de la secuencia de muerte del jugador - enum class DeathPhase { None, + enum class DeathPhase : std::uint8_t { None, Shaking, Waiting, Done }; @@ -299,7 +301,7 @@ class Game { void updateHiScore(); // 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 void renderScoreBoard(); @@ -326,7 +328,7 @@ class Game { void renderBalloons(); // 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 void createPowerBall(); @@ -374,7 +376,7 @@ class Game { void renderBullets(); // 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 void freeBullets(); @@ -422,13 +424,13 @@ class Game { void evaluateAndSetMenace(); // Obtiene el valor de la variable - auto getMenace() -> Uint8; + [[nodiscard]] auto getMenace() const -> Uint8; // Establece el valor de la variable void setTimeStopped(bool value); // Obtiene el valor de la variable - auto isTimeStopped() -> bool; + [[nodiscard]] auto isTimeStopped() const -> bool; // Establece el valor de la variable void setTimeStoppedCounter(Uint16 value); @@ -470,7 +472,7 @@ class Game { void updateDeathShake(); // 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 void updateDeathSequence(); diff --git a/source/game/options.cpp b/source/game/options.cpp index cd199cf..0e9514e 100644 --- a/source/game/options.cpp +++ b/source/game/options.cpp @@ -30,30 +30,38 @@ namespace Options { std::string crtpi_file_path; 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 + 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(); + 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 --- namespace { void parseBoolField(const fkyaml::node &node, const std::string &key, bool &target) { - if (node.contains(key)) { - try { - target = node[key].get_value(); - } catch (...) {} - } + tryGet(node, key, target); } void parseIntField(const fkyaml::node &node, const std::string &key, int &target) { - if (node.contains(key)) { - try { - target = node[key].get_value(); - } catch (...) {} - } + tryGet(node, key, target); } void parseStringField(const fkyaml::node &node, const std::string &key, std::string &target) { - if (node.contains(key)) { - try { - target = node[key].get_value(); - } catch (...) {} - } + tryGet(node, key, target); } void loadWindowFromYaml(const fkyaml::node &yaml) { @@ -72,10 +80,9 @@ namespace Options { parseBoolField(vid, "fullscreen", video.fullscreen); parseBoolField(vid, "vsync", video.vsync); parseBoolField(vid, "integer_scale", video.integer_scale); - if (vid.contains("scale_mode")) { - try { - video.scale_mode = static_cast(vid["scale_mode"].get_value()); - } catch (...) {} + int scale_mode_int = static_cast(video.scale_mode); + if (tryGet(vid, "scale_mode", scale_mode_int)) { + video.scale_mode = static_cast(scale_mode_int); } if (vid.contains("gpu")) { @@ -94,13 +101,11 @@ namespace Options { if (vid.contains("shader")) { const auto &sh = vid["shader"]; parseBoolField(sh, "enabled", video.shader.enabled); - if (sh.contains("current_shader")) { - try { - auto s = sh["current_shader"].get_value(); - video.shader.current_shader = (s == "crtpi" || s == "CRTPI") - ? Rendering::ShaderType::CRTPI - : Rendering::ShaderType::POSTFX; - } catch (...) {} + std::string shader_kind; + if (tryGet(sh, "current_shader", shader_kind)) { + video.shader.current_shader = (shader_kind == "crtpi" || shader_kind == "CRTPI") + ? Rendering::ShaderType::CRTPI + : Rendering::ShaderType::POSTFX; } parseStringField(sh, "current_postfx_preset", video.shader.current_postfx_preset_name); parseStringField(sh, "current_crtpi_preset", video.shader.current_crtpi_preset_name); @@ -112,27 +117,21 @@ namespace Options { const auto &aud = yaml["audio"]; parseBoolField(aud, "enabled", audio.enabled); - if (aud.contains("volume")) { - try { - audio.volume = std::clamp(aud["volume"].get_value(), 0.0F, 1.0F); - } catch (...) {} + if (tryGet(aud, "volume", audio.volume)) { + audio.volume = std::clamp(audio.volume, 0.0F, 1.0F); } if (aud.contains("music")) { const auto &mus = aud["music"]; parseBoolField(mus, "enabled", audio.music.enabled); - if (mus.contains("volume")) { - try { - audio.music.volume = std::clamp(mus["volume"].get_value(), 0.0F, 1.0F); - } catch (...) {} + if (tryGet(mus, "volume", audio.music.volume)) { + audio.music.volume = std::clamp(audio.music.volume, 0.0F, 1.0F); } } if (aud.contains("sound")) { const auto &snd = aud["sound"]; parseBoolField(snd, "enabled", audio.sound.enabled); - if (snd.contains("volume")) { - try { - audio.sound.volume = std::clamp(snd["volume"].get_value(), 0.0F, 1.0F); - } catch (...) {} + if (tryGet(snd, "volume", audio.sound.volume)) { + audio.sound.volume = std::clamp(audio.sound.volume, 0.0F, 1.0F); } } } @@ -162,10 +161,9 @@ namespace Options { size_t i = 0; for (const auto &entry : ins) { if (i >= inputs.size()) { break; } - if (entry.contains("device_type")) { - try { - inputs[i].deviceType = static_cast(entry["device_type"].get_value()); - } catch (...) {} + int device_type_int = inputs[i].deviceType; + if (tryGet(entry, "device_type", device_type_int)) { + inputs[i].deviceType = static_cast(device_type_int); } ++i; } @@ -229,11 +227,7 @@ namespace Options { auto yaml = fkyaml::node::deserialize(CONTENT); int file_version = 0; - if (yaml.contains("config_version")) { - try { - file_version = yaml["config_version"].get_value(); - } catch (...) {} - } + tryGet(yaml, "config_version", file_version); if (file_version != Settings::CURRENT_CONFIG_VERSION) { std::cout << "Config version " << file_version << " != expected " << Settings::CURRENT_CONFIG_VERSION @@ -352,31 +346,27 @@ namespace Options { namespace { void parseFloatField(const fkyaml::node &node, const std::string &key, float &target) { - if (node.contains(key)) { - try { - target = node[key].get_value(); - } catch (...) {} - } + tryGet(node, key, target); } auto defaultPostFXPresets() -> const std::vector & { static const std::vector DEFAULTS = { - {"CRT", 0.6F, 0.7F, 0.15F, 0.6F, 0.8F}, - {"NTSC", 0.4F, 0.5F, 0.2F, 0.4F, 0.5F, 0.0F, 0.6F}, - {"CURVED", 0.5F, 0.6F, 0.1F, 0.5F, 0.7F, 0.8F}, - {"SCANLINES", 0.0F, 0.8F}, - {"SUBTLE", 0.3F, 0.4F, 0.05F, 0.0F, 0.3F}, - {"CRT LIVE", 0.5F, 0.6F, 0.3F, 0.3F, 0.4F, 0.3F, 0.4F, 0.8F}, + {.name = "CRT", .vignette = 0.6F, .scanlines = 0.7F, .chroma = 0.15F, .mask = 0.6F, .gamma = 0.8F}, + {.name = "NTSC", .vignette = 0.4F, .scanlines = 0.5F, .chroma = 0.2F, .mask = 0.4F, .gamma = 0.5F, .curvature = 0.0F, .bleeding = 0.6F}, + {.name = "CURVED", .vignette = 0.5F, .scanlines = 0.6F, .chroma = 0.1F, .mask = 0.5F, .gamma = 0.7F, .curvature = 0.8F}, + {.name = "SCANLINES", .vignette = 0.0F, .scanlines = 0.8F}, + {.name = "SUBTLE", .vignette = 0.3F, .scanlines = 0.4F, .chroma = 0.05F, .mask = 0.0F, .gamma = 0.3F}, + {.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; } auto defaultCrtPiPresets() -> const std::vector & { static const std::vector DEFAULTS = { - {"Default", 6.0F, 0.12F, 3.5F, 2.4F, 2.2F, 0.80F, 0.05F, 0.10F, 2, true, true, true, false, false}, - {"Curved", 6.0F, 0.12F, 3.5F, 2.4F, 2.2F, 0.80F, 0.05F, 0.10F, 2, true, true, true, true, false}, - {"Sharp", 6.0F, 0.12F, 3.5F, 2.4F, 2.2F, 0.80F, 0.05F, 0.10F, 2, true, false, true, false, 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 = "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}, + {.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}, + {.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}, + {.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; } @@ -449,11 +439,7 @@ namespace Options { if (yaml.contains("presets")) { for (const auto &p : yaml["presets"]) { PostFXPreset preset; - if (p.contains("name")) { - try { - preset.name = p["name"].get_value(); - } catch (...) {} - } + tryGet(p, "name", preset.name); parseFloatField(p, "vignette", preset.vignette); parseFloatField(p, "scanlines", preset.scanlines); parseFloatField(p, "chroma", preset.chroma); @@ -506,11 +492,7 @@ namespace Options { if (yaml.contains("presets")) { for (const auto &p : yaml["presets"]) { CrtPiPreset preset; - if (p.contains("name")) { - try { - preset.name = p["name"].get_value(); - } catch (...) {} - } + tryGet(p, "name", preset.name); parseFloatField(p, "scanline_weight", preset.scanline_weight); parseFloatField(p, "scanline_gap_brightness", preset.scanline_gap_brightness); parseFloatField(p, "bloom_factor", preset.bloom_factor); @@ -519,36 +501,12 @@ namespace Options { parseFloatField(p, "mask_brightness", preset.mask_brightness); parseFloatField(p, "curvature_x", preset.curvature_x); parseFloatField(p, "curvature_y", preset.curvature_y); - if (p.contains("mask_type")) { - try { - preset.mask_type = p["mask_type"].get_value(); - } catch (...) {} - } - if (p.contains("enable_scanlines")) { - try { - preset.enable_scanlines = p["enable_scanlines"].get_value(); - } catch (...) {} - } - if (p.contains("enable_multisample")) { - try { - preset.enable_multisample = p["enable_multisample"].get_value(); - } catch (...) {} - } - if (p.contains("enable_gamma")) { - try { - preset.enable_gamma = p["enable_gamma"].get_value(); - } catch (...) {} - } - if (p.contains("enable_curvature")) { - try { - preset.enable_curvature = p["enable_curvature"].get_value(); - } catch (...) {} - } - if (p.contains("enable_sharper")) { - try { - preset.enable_sharper = p["enable_sharper"].get_value(); - } catch (...) {} - } + tryGet(p, "mask_type", preset.mask_type); + tryGet(p, "enable_scanlines", preset.enable_scanlines); + tryGet(p, "enable_multisample", preset.enable_multisample); + tryGet(p, "enable_gamma", preset.enable_gamma); + tryGet(p, "enable_curvature", preset.enable_curvature); + tryGet(p, "enable_sharper", preset.enable_sharper); crtpi_presets.push_back(preset); } } diff --git a/source/game/scenes/instructions.cpp b/source/game/scenes/instructions.cpp index cbb6dc3..ef1386b 100644 --- a/source/game/scenes/instructions.cpp +++ b/source/game/scenes/instructions.cpp @@ -43,7 +43,7 @@ Instructions::Instructions(SDL_Renderer *renderer, section_t *section) { if (backbuffer != nullptr) { SDL_SetTextureScaleMode(backbuffer, Texture::currentScaleMode); } 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 @@ -197,7 +197,7 @@ void Instructions::render() { void Instructions::checkEvents() { #ifndef __EMSCRIPTEN__ // Comprueba los eventos que hay en la cola - while (SDL_PollEvent(eventHandler) != 0) { + while (static_cast(SDL_PollEvent(eventHandler)) != 0) { // Evento de salida de la aplicación if (eventHandler->type == SDL_EVENT_QUIT) { quitRequested = true; @@ -260,11 +260,11 @@ void Instructions::start(mode_e mode) { } // Indica si las instrucciones han terminado -bool Instructions::hasFinished() const { +auto Instructions::hasFinished() const -> bool { return finished; } // Indica si se ha solicitado salir de la aplicación -bool Instructions::isQuitRequested() const { +auto Instructions::isQuitRequested() const -> bool { return quitRequested; } diff --git a/source/game/scenes/instructions.h b/source/game/scenes/instructions.h index 32f6cde..a9b8ca3 100644 --- a/source/game/scenes/instructions.h +++ b/source/game/scenes/instructions.h @@ -2,13 +2,14 @@ #include -#include // for vector +#include // for uint8_t +#include // for vector class Sprite; class Text; class Texture; struct section_t; -enum mode_e { +enum mode_e : std::uint8_t { m_manual, m_auto }; diff --git a/source/game/scenes/intro.cpp b/source/game/scenes/intro.cpp index cf9f24c..e020623 100644 --- a/source/game/scenes/intro.cpp +++ b/source/game/scenes/intro.cpp @@ -39,7 +39,7 @@ Intro::Intro(SDL_Renderer *renderer, section_t *section) { // Inicializa los bitmaps de la intro const int totalBitmaps = 6; for (int i = 0; i < totalBitmaps; ++i) { - SmartSprite *ss = new SmartSprite(texture, renderer); + auto *ss = new SmartSprite(texture, renderer); ss->setWidth(128); ss->setHeight(96); ss->setEnabledCounter(20); @@ -50,57 +50,57 @@ Intro::Intro(SDL_Renderer *renderer, section_t *section) { bitmaps[0]->setPosX(-128); bitmaps[0]->setPosY(GAMECANVAS_FIRST_QUARTER_Y - 24); - bitmaps[0]->setVelX(0.0f); - bitmaps[0]->setVelY(0.0f); - bitmaps[0]->setAccelX(0.6f); - bitmaps[0]->setAccelY(0.0f); + bitmaps[0]->setVelX(0.0F); + bitmaps[0]->setVelY(0.0F); + bitmaps[0]->setAccelX(0.6F); + bitmaps[0]->setAccelY(0.0F); bitmaps[0]->setSpriteClip(0, 0, 128, 96); bitmaps[1]->setPosX(GAMECANVAS_WIDTH); bitmaps[1]->setPosY(GAMECANVAS_FIRST_QUARTER_Y - 24); - bitmaps[1]->setVelX(-1.0f); - bitmaps[1]->setVelY(0.0f); - bitmaps[1]->setAccelX(-0.3f); - bitmaps[1]->setAccelY(0.0f); + bitmaps[1]->setVelX(-1.0F); + bitmaps[1]->setVelY(0.0F); + bitmaps[1]->setAccelX(-0.3F); + bitmaps[1]->setAccelY(0.0F); bitmaps[1]->setSpriteClip(128, 0, 128, 96); bitmaps[2]->setPosX(GAMECANVAS_CENTER_X - 64); bitmaps[2]->setPosY(-96); - bitmaps[2]->setVelX(0.0f); - bitmaps[2]->setVelY(3.0f); - bitmaps[2]->setAccelX(0.1f); - bitmaps[2]->setAccelY(0.3f); + bitmaps[2]->setVelX(0.0F); + bitmaps[2]->setVelY(3.0F); + bitmaps[2]->setAccelX(0.1F); + bitmaps[2]->setAccelY(0.3F); bitmaps[2]->setSpriteClip(0, 96, 128, 96); bitmaps[2]->setEnabledCounter(250); bitmaps[3]->setPosX(GAMECANVAS_CENTER_X - 64); bitmaps[3]->setPosY(GAMECANVAS_HEIGHT); - bitmaps[3]->setVelX(0.0f); - bitmaps[3]->setVelY(-0.7f); - bitmaps[3]->setAccelX(0.0f); - bitmaps[3]->setAccelY(0.0f); + bitmaps[3]->setVelX(0.0F); + bitmaps[3]->setVelY(-0.7F); + bitmaps[3]->setAccelX(0.0F); + bitmaps[3]->setAccelY(0.0F); bitmaps[3]->setSpriteClip(128, 96, 128, 96); bitmaps[4]->setPosX(GAMECANVAS_CENTER_X - 64); bitmaps[4]->setPosY(-96); - bitmaps[4]->setVelX(0.0f); - bitmaps[4]->setVelY(3.0f); - bitmaps[4]->setAccelX(0.1f); - bitmaps[4]->setAccelY(0.3f); + bitmaps[4]->setVelX(0.0F); + bitmaps[4]->setVelY(3.0F); + bitmaps[4]->setAccelX(0.1F); + bitmaps[4]->setAccelY(0.3F); bitmaps[4]->setSpriteClip(0, 192, 128, 96); bitmaps[5]->setPosX(GAMECANVAS_WIDTH); bitmaps[5]->setPosY(GAMECANVAS_FIRST_QUARTER_Y - 24); - bitmaps[5]->setVelX(-0.7f); - bitmaps[5]->setVelY(0.0f); - bitmaps[5]->setAccelX(0.0f); - bitmaps[5]->setAccelY(0.0f); + bitmaps[5]->setVelX(-0.7F); + bitmaps[5]->setVelY(0.0F); + bitmaps[5]->setAccelX(0.0F); + bitmaps[5]->setAccelY(0.0F); bitmaps[5]->setSpriteClip(128, 192, 128, 96); // Inicializa los textos de la intro const int totalTexts = 9; for (int i = 0; i < totalTexts; ++i) { - Writer *w = new Writer(text); + auto *w = new Writer(text); w->setPosX(BLOCK * 0); w->setPosY(GAMECANVAS_HEIGHT - (BLOCK * 6)); w->setKerning(-1); @@ -157,11 +157,11 @@ Intro::~Intro() { delete eventHandler; // texture, text, music son propiedad de Resource — no liberar aquí. - for (auto bitmap : bitmaps) { + for (auto *bitmap : bitmaps) { delete bitmap; } - for (auto t : texts) { + for (auto *t : texts) { delete t; } } @@ -329,7 +329,7 @@ void Intro::update() { ticks = SDL_GetTicks(); // Actualiza los objetos - for (auto bitmap : bitmaps) { + for (auto *bitmap : bitmaps) { bitmap->update(); } @@ -351,7 +351,7 @@ void Intro::render() { Screen::get()->clean(bgColor); // Dibuja los objetos - for (auto bitmap : bitmaps) { + for (auto *bitmap : bitmaps) { bitmap->render(); } diff --git a/source/game/scenes/title.cpp b/source/game/scenes/title.cpp index be31454..fcd2842 100644 --- a/source/game/scenes/title.cpp +++ b/source/game/scenes/title.cpp @@ -1,8 +1,8 @@ #include "game/scenes/title.h" #include -#include // for rand +#include // for rand #include // for basic_ostream, operator<<, basic_ostrea... #include // for basic_string, operator+, char_traits @@ -147,10 +147,10 @@ void Title::init() { coffeeBitmap->setPosY(11 - 200); coffeeBitmap->setWidth(167); coffeeBitmap->setHeight(46); - coffeeBitmap->setVelX(0.0f); - coffeeBitmap->setVelY(2.5f); - coffeeBitmap->setAccelX(0.0f); - coffeeBitmap->setAccelY(0.1f); + coffeeBitmap->setVelX(0.0F); + coffeeBitmap->setVelY(2.5F); + coffeeBitmap->setAccelX(0.0F); + coffeeBitmap->setAccelY(0.1F); coffeeBitmap->setSpriteClip(0, 0, 167, 46); coffeeBitmap->setEnabled(true); coffeeBitmap->setEnabledCounter(0); @@ -163,10 +163,10 @@ void Title::init() { crisisBitmap->setPosY(57 + 200); crisisBitmap->setWidth(137); crisisBitmap->setHeight(46); - crisisBitmap->setVelX(0.0f); - crisisBitmap->setVelY(-2.5f); - crisisBitmap->setAccelX(0.0f); - crisisBitmap->setAccelY(-0.1f); + crisisBitmap->setVelX(0.0F); + crisisBitmap->setVelY(-2.5F); + crisisBitmap->setAccelX(0.0F); + crisisBitmap->setAccelY(-0.1F); crisisBitmap->setSpriteClip(0, 0, 137, 46); crisisBitmap->setEnabled(true); crisisBitmap->setEnabledCounter(0); @@ -202,7 +202,7 @@ void Title::init() { // Inicializa los valores del vector con los valores del seno 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 @@ -313,8 +313,9 @@ void Title::update() { if (demo) { demoThenInstructions = true; runDemoGame(); - } else + } else { section->name = SECTION_PROG_LOGO; + } break; default: @@ -326,7 +327,7 @@ void Title::update() { updateBG(); // Comprueba las entradas para el menu - if (menuVisible == true && !fade->isEnabled()) { + if (menuVisible && !fade->isEnabled()) { menu.active->update(); } @@ -393,12 +394,13 @@ void Title::update() { if (menu.active->getName() == "OPTIONS") { switch (menu.active->getItemSelected()) { case 0: // Difficulty - if (Options::settings.difficulty == DIFFICULTY_EASY) + if (Options::settings.difficulty == DIFFICULTY_EASY) { Options::settings.difficulty = DIFFICULTY_NORMAL; - else if (Options::settings.difficulty == DIFFICULTY_NORMAL) + } else if (Options::settings.difficulty == DIFFICULTY_NORMAL) { Options::settings.difficulty = DIFFICULTY_HARD; - else + } else { Options::settings.difficulty = DIFFICULTY_EASY; + } updateMenuLabels(); break; @@ -414,8 +416,9 @@ void Title::update() { case 5: // Language Options::settings.language++; - if (Options::settings.language == 3) + if (Options::settings.language == 3) { Options::settings.language = 0; + } updateMenuLabels(); break; @@ -433,8 +436,9 @@ void Title::update() { case 8: // Windows size Options::window.zoom++; - if (Options::window.zoom > Options::window.max_zoom) + if (Options::window.zoom > Options::window.max_zoom) { Options::window.zoom = 1; + } updateMenuLabels(); 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); } - if (menuVisible == true) { + if (menuVisible) { menu.active->render(); } @@ -593,7 +597,7 @@ void Title::render() { dustBitmapL->render(); // 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); } @@ -638,7 +642,7 @@ void Title::switchFullScreenModeVar() { } // Actualiza los elementos de los menus -void Title::updateMenuLabels() { +void Title::updateMenuLabels() const { int i = 0; // DIFFICULTY switch (Options::settings.difficulty) { @@ -673,9 +677,9 @@ void Title::updateMenuLabels() { case INPUT_USE_GAMECONTROLLER: menu.options->setItemCaption(i, Lang::get()->getText(70)); // GAME CONTROLLER - if (!Input::get()->gameControllerFound()) + if (!Input::get()->gameControllerFound()) { menu.options->setGreyed(i, true); - else { + } else { menu.options->setGreyed(i, false); menu.options->setItemCaption(i, Options::inputs[0].name); } @@ -700,9 +704,9 @@ void Title::updateMenuLabels() { case INPUT_USE_GAMECONTROLLER: menu.options->setItemCaption(i, Lang::get()->getText(70)); // GAME CONTROLLER - if (!Input::get()->gameControllerFound()) + if (!Input::get()->gameControllerFound()) { menu.options->setGreyed(i, true); - else { + } else { menu.options->setGreyed(i, false); menu.options->setItemCaption(i, Options::inputs[1].name); } @@ -725,11 +729,9 @@ void Title::updateMenuLabels() { break; case en_UK: - menu.options->setItemCaption(i, Lang::get()->getText(8) + ": " + Lang::get()->getText(26)); // ENGLISH - break; - 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; } @@ -747,17 +749,19 @@ void Title::updateMenuLabels() { i++; // 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 - else + } else { menu.options->setItemCaption(i, Lang::get()->getText(60) + ": " + Lang::get()->getText(72)); // LINEAL + } i++; // VSYNC - if (Options::video.vsync) + if (Options::video.vsync) { 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 + } i++; // HOW TO PLAY @@ -893,12 +897,12 @@ void Title::iterate() { // Procesa un evento individual void Title::handleEvent(const SDL_Event *event) { // Si hay un sub-estado activo, delega el evento - if (instructionsActive && instructions) { + if (instructionsActive && (instructions != nullptr)) { // SDL_EVENT_QUIT ya lo maneja Director return; } - if (demoGameActive && demoGame) { + if (demoGameActive && (demoGame != nullptr)) { demoGame->handleEvent(event); return; } @@ -944,7 +948,7 @@ void Title::runDemoGame() { } // 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(); 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; return true; - } else { // Si hay mas de un dispositivo, se recorre el vector - if (Options::settings.console) { - std::cout << "numplayer:" << numPlayer << std::endl; - std::cout << "deviceindex:" << deviceIndex[numPlayer] << std::endl; - } - - // 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; + } // Si hay mas de un dispositivo, se recorre el vector + if (Options::settings.console) { + std::cout << "numplayer:" << numPlayer << '\n'; + 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] << '\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 @@ -1002,13 +1005,13 @@ void Title::createTiledBackground() { } if (background == nullptr) { 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 - Texture *bgTileTexture = new Texture(renderer, Asset::get()->get("title_bg_tile.png")); - Sprite *tile = new Sprite({0, 0, 64, 64}, bgTileTexture, renderer); + auto *bgTileTexture = new Texture(renderer, Asset::get()->get("title_bg_tile.png")); + auto *tile = new Sprite({0, 0, 64, 64}, bgTileTexture, renderer); // Prepara para dibujar sobre la textura SDL_SetRenderTarget(renderer, background); @@ -1039,23 +1042,24 @@ void Title::createTiledBackground() { // así que aquí solo leemos la lista actual sin reescanear. void Title::checkInputDevices() { 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(); availableInputDevices.clear(); input_t temp; // Añade todos los mandos - if (numControllers > 0) + if (numControllers > 0) { for (int i = 0; i < numControllers; ++i) { temp.id = i; temp.name = Input::get()->getControllerName(i); temp.deviceType = INPUT_USE_GAMECONTROLLER; availableInputDevices.push_back(temp); 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 temp.id = -1; @@ -1063,8 +1067,8 @@ void Title::checkInputDevices() { temp.deviceType = INPUT_USE_KEYBOARD; availableInputDevices.push_back(temp); if (Options::settings.console) { - std::cout << "Device " << (int)availableInputDevices.size() << " - " << temp.name.c_str() << std::endl; - std::cout << std::endl; + std::cout << "Device " << (int)availableInputDevices.size() << " - " << temp.name.c_str() << '\n'; + std::cout << '\n'; } } diff --git a/source/game/scenes/title.h b/source/game/scenes/title.h index a9dc38a..70dcc1c 100644 --- a/source/game/scenes/title.h +++ b/source/game/scenes/title.h @@ -114,10 +114,10 @@ class Title { void updateBG(); // Cambia el valor de la variable de modo de pantalla completa - void switchFullScreenModeVar(); + static void switchFullScreenModeVar(); // Actualiza los elementos de los menus - void updateMenuLabels(); + void updateMenuLabels() const; // Aplica las opciones de menu seleccionadas void applyOptions(); diff --git a/source/game/ui/menu.cpp b/source/game/ui/menu.cpp index f1abaab..6a28d8f 100644 --- a/source/game/ui/menu.cpp +++ b/source/game/ui/menu.cpp @@ -14,9 +14,7 @@ // Constructor Menu::Menu(SDL_Renderer *renderer, const std::string &file) - : colorGreyed{128, 128, 128}, - font_png(""), - font_txt("") { + : colorGreyed{128, 128, 128} { // Copia punteros this->renderer = renderer; @@ -32,7 +30,7 @@ Menu::Menu(SDL_Renderer *renderer, const std::string &file) x = 0; y = 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.a = 0; backgroundType = MENU_BACKGROUND_SOLID; @@ -51,12 +49,12 @@ Menu::Menu(SDL_Renderer *renderer, const std::string &file) selector.originH = 0; selector.targetH = 0; selector.incH = 0; - selector.y = 0.0f; - selector.h = 0.0f; + selector.y = 0.0F; + selector.h = 0.0F; selector.numJumps = 8; selector.moving = 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.itemColor = {0, 0, 0}; selector.a = 255; @@ -74,25 +72,23 @@ Menu::Menu(SDL_Renderer *renderer, const std::string &file) Menu::~Menu() { renderer = nullptr; - if (soundMove) { + if (soundMove != nullptr) { JA_DeleteSound(soundMove); } - if (soundAccept) { + if (soundAccept != nullptr) { JA_DeleteSound(soundAccept); } - if (soundCancel) { + if (soundCancel != nullptr) { JA_DeleteSound(soundCancel); } - if (text != nullptr) { delete text; - } } // 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 textAllocated = false; 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 // d'items queda buit → reset() accedeix a item[0] i crasheja. 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)) { @@ -119,9 +117,11 @@ bool Menu::parseFromStream(std::istream &file, const std::string &filename) { newItem.line = false; do { - if (!std::getline(file, line)) break; + if (!std::getline(file, line)) { + break; + } strip_cr(line); - int pos = line.find("="); + int pos = line.find('='); if (!setItem(&newItem, line.substr(0, pos), line.substr(pos + 1, line.length()))) { success = false; } @@ -129,14 +129,14 @@ bool Menu::parseFromStream(std::istream &file, const std::string &filename) { addItem(newItem); } else { - int pos = line.find("="); + int pos = line.find('='); if (!setVars(line.substr(0, pos), line.substr(pos + 1, line.length()))) { success = false; } // 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. - if (font_png != "" && font_txt != "" && !textAllocated) { + if (!font_png.empty() && !font_txt.empty() && !textAllocated) { auto pngBytes = ResourceHelper::loadFile(Asset::get()->get(font_png)); auto txtBytes = ResourceHelper::loadFile(Asset::get()->get(font_txt)); 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) -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); auto bytes = ResourceHelper::loadFile(file_path); if (bytes.empty()) { @@ -158,8 +158,10 @@ bool Menu::load(const std::string &file_path) { } // Carga el menu desde bytes en memoria -bool Menu::loadFromBytes(const std::vector &bytes, const std::string &nameForLogs) { - if (bytes.empty()) return false; +auto Menu::loadFromBytes(const std::vector &bytes, const std::string &nameForLogs) -> bool { + if (bytes.empty()) { + return false; + } std::string content(reinterpret_cast(bytes.data()), bytes.size()); std::stringstream ss(content); bool ok = parseFromStream(ss, nameForLogs); @@ -169,7 +171,7 @@ bool Menu::loadFromBytes(const std::vector &bytes, const std::string &n } // 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 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") { - item->selectable = value == "true" ? true : false; + item->selectable = value == "true"; } else if (var == "greyed") { - item->greyed = value == "true" ? true : false; + item->greyed = value == "true"; } else if (var == "linkedDown") { - item->linkedDown = value == "true" ? true : false; + item->linkedDown = value == "true"; } else if (var == "visible") { - item->visible = value == "true" ? true : false; + item->visible = value == "true"; } 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 { @@ -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 -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 bool success = true; @@ -226,17 +228,23 @@ bool Menu::setVars(const std::string &var, const std::string &value) { else if (var == "sound_cancel") { 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") { 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") { 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") { @@ -304,22 +312,22 @@ bool Menu::setVars(const std::string &var, const std::string &value) { } else if (var == "areElementsCenteredOnX") { - areElementsCenteredOnX = value == "true" ? true : false; + areElementsCenteredOnX = value == "true"; } else if (var == "isCenteredOnX") { - isCenteredOnX = value == "true" ? true : false; + isCenteredOnX = value == "true"; } else if (var == "isCenteredOnY") { - isCenteredOnY = value == "true" ? true : false; + isCenteredOnY = value == "true"; } else if (var == "defaultActionWhenCancel") { defaultActionWhenCancel = std::stoi(value); } - else if (var == "") { + else if (var.empty()) { } else { @@ -350,12 +358,12 @@ void Menu::loadAudioFile(const std::string &file, int sound) { } // Obtiene el nombre del menu -const std::string &Menu::getName() const { +auto Menu::getName() const -> const std::string & { return name; } // 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 const int temp = itemSelected; itemSelected = MENU_NO_OPTION; @@ -440,7 +448,7 @@ void Menu::setSelectorPos(int index) { } // 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); }); } @@ -729,20 +737,18 @@ void Menu::centerMenuElementsOnX() { } // Añade un item al menu -void Menu::addItem(item_t temp) { - // item_t temp; - +void Menu::addItem(item_t new_item) { 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 - 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[item.size() - 2].linkedDown) { @@ -771,40 +777,40 @@ void Menu::setDefaultActionWhenCancel(int item) { void Menu::checkInput() { if (Input::get()->checkInput(input_up, REPEAT_FALSE)) { decreaseSelectorIndex(); - if (soundMove) { + if (soundMove != nullptr) { Audio::get()->playSound(soundMove); } } if (Input::get()->checkInput(input_down, REPEAT_FALSE)) { increaseSelectorIndex(); - if (soundMove) { + if (soundMove != nullptr) { Audio::get()->playSound(soundMove); } } if (Input::get()->checkInput(input_accept, REPEAT_FALSE)) { itemSelected = selector.index; - if (soundAccept) { + if (soundAccept != nullptr) { Audio::get()->playSound(soundAccept); } } if (Input::get()->checkInput(input_cancel, REPEAT_FALSE)) { itemSelected = defaultActionWhenCancel; - if (soundCancel) { + if (soundCancel != nullptr) { Audio::get()->playSound(soundCancel); } } } // Calcula el ancho del menu -int Menu::findWidth() { +auto Menu::findWidth() -> int { return getWidestItem(); } // 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; }); return height - item.back().hPaddingDown; @@ -840,12 +846,11 @@ void Menu::setVisible(int index, bool value) { } // Calcula la altura del selector -int Menu::getSelectorHeight(int value) { +auto Menu::getSelectorHeight(int value) -> int { if (item[value].linkedDown) { 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 @@ -866,7 +871,7 @@ void Menu::setBackgroundType(int value) { // Establece la fuente de texto que se utilizará 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); } } diff --git a/source/game/ui/menu.h b/source/game/ui/menu.h index 0cd2769..5d064c3 100644 --- a/source/game/ui/menu.h +++ b/source/game/ui/menu.h @@ -105,7 +105,7 @@ class Menu { auto setVars(const std::string &var, const std::string &value) -> bool; // 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 void reorganize(); @@ -190,7 +190,7 @@ class Menu { void centerMenuElementsOnX(); // Añade un item al menu - void addItem(item_t item); + void addItem(item_t new_item); // Cambia el texto de un item void setItemCaption(int index, const std::string &text); diff --git a/source/main.cpp b/source/main.cpp index aac7132..09bb255 100644 --- a/source/main.cpp +++ b/source/main.cpp @@ -44,17 +44,17 @@ Reescribiendo el código el 27/09/2022 #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(argv)); *appstate = director; return SDL_APP_CONTINUE; } -SDL_AppResult SDL_AppIterate(void *appstate) { +auto SDL_AppIterate(void *appstate) -> SDL_AppResult { return static_cast(appstate)->iterate(); } -SDL_AppResult SDL_AppEvent(void *appstate, SDL_Event *event) { +auto SDL_AppEvent(void *appstate, SDL_Event *event) -> SDL_AppResult { return static_cast(appstate)->handleEvent(event); }