clang-tidy modernize

This commit is contained in:
2025-07-20 12:51:24 +02:00
parent bfda842d3c
commit 1f0184fde2
74 changed files with 658 additions and 665 deletions

View File

@@ -1,5 +1,6 @@
Checks: >
readability-identifier-naming
readability-identifier-naming,
modernize-*
WarningsAsErrors: '*'
# Solo incluir archivos de tu código fuente

View File

@@ -1,8 +1,8 @@
#pragma once
#include <SDL3/SDL.h> // Para SDL_FRect, SDL_FPoint, SDL_Texture, SDL_Renderer
#include <stddef.h> // Para size_t
#include <cstddef> // Para size_t
#include <memory> // Para unique_ptr, shared_ptr
#include <vector> // Para vector

View File

@@ -77,23 +77,23 @@ class Balloon {
void useNormalColor(); // Pone el color normal en el globo
// --- Getters ---
float getPosX() const { return x_; }
float getPosY() const { return y_; }
int getWidth() const { return w_; }
int getHeight() const { return h_; }
BalloonSize getSize() const { return size_; }
BalloonType getType() const { return type_; }
Uint16 getScore() const { return score_; }
Circle &getCollider() { return collider_; }
Uint8 getMenace() const { return isEnabled() ? menace_ : 0; }
Uint8 getPower() const { return power_; }
bool isStopped() const { return stopped_; }
bool isPowerBall() const { return type_ == BalloonType::POWERBALL; }
bool isInvulnerable() const { return invulnerable_; }
bool isBeingCreated() const { return being_created_; }
bool isEnabled() const { return enabled_; }
bool isUsingReversedColor() { return use_reversed_colors_; }
bool canBePopped() const { return !isBeingCreated(); }
[[nodiscard]] auto getPosX() const -> float { return x_; }
[[nodiscard]] auto getPosY() const -> float { return y_; }
[[nodiscard]] auto getWidth() const -> int { return w_; }
[[nodiscard]] auto getHeight() const -> int { return h_; }
[[nodiscard]] auto getSize() const -> BalloonSize { return size_; }
[[nodiscard]] auto getType() const -> BalloonType { return type_; }
[[nodiscard]] auto getScore() const -> Uint16 { return score_; }
auto getCollider() -> Circle & { return collider_; }
[[nodiscard]] auto getMenace() const -> Uint8 { return isEnabled() ? menace_ : 0; }
[[nodiscard]] auto getPower() const -> Uint8 { return power_; }
[[nodiscard]] auto isStopped() const -> bool { return stopped_; }
[[nodiscard]] auto isPowerBall() const -> bool { return type_ == BalloonType::POWERBALL; }
[[nodiscard]] auto isInvulnerable() const -> bool { return invulnerable_; }
[[nodiscard]] auto isBeingCreated() const -> bool { return being_created_; }
[[nodiscard]] auto isEnabled() const -> bool { return enabled_; }
auto isUsingReversedColor() -> bool { return use_reversed_colors_; }
[[nodiscard]] auto canBePopped() const -> bool { return !isBeingCreated(); }
// --- Setters ---
void setVelY(float vel_y) { vy_ = vel_y; }

View File

@@ -52,9 +52,9 @@ class BalloonFormations {
~BalloonFormations() = default;
// --- Getters ---
const BalloonFormationPool &getPool(int pool) { return balloon_formation_pool_.at(pool); }
const BalloonFormationUnit &getSet(int pool, int set) { return *balloon_formation_pool_.at(pool).at(set); }
const BalloonFormationUnit &getSet(int set) const { return balloon_formation_.at(set); }
auto getPool(int pool) -> const BalloonFormationPool & { return balloon_formation_pool_.at(pool); }
auto getSet(int pool, int set) -> const BalloonFormationUnit & { return *balloon_formation_pool_.at(pool).at(set); }
[[nodiscard]] auto getSet(int set) const -> const BalloonFormationUnit & { return balloon_formation_.at(set); }
private:
// --- Datos ---

View File

@@ -1,8 +1,7 @@
#include "balloon_manager.h"
#include <stdlib.h> // Para rand
#include <algorithm> // Para remove_if
#include <cstdlib> // Para rand
#include <numeric> // Para accumulate
#include "balloon.h" // Para Balloon, BALLOON_SCORE, BALLOON_VELX...
@@ -149,15 +148,15 @@ void BalloonManager::updateBalloonDeployCounter() {
}
// Indica si se puede crear una powerball
bool BalloonManager::canPowerBallBeCreated() { return (!power_ball_enabled_) && (calculateScreenPower() > POWERBALL_SCREENPOWER_MINIMUM) && (power_ball_counter_ == 0); }
auto BalloonManager::canPowerBallBeCreated() -> bool { return (!power_ball_enabled_) && (calculateScreenPower() > POWERBALL_SCREENPOWER_MINIMUM) && (power_ball_counter_ == 0); }
// Calcula el poder actual de los globos en pantalla
int BalloonManager::calculateScreenPower() {
auto BalloonManager::calculateScreenPower() -> int {
return std::accumulate(balloons_.begin(), balloons_.end(), 0, [](int sum, const auto &balloon) { return sum + (balloon->isEnabled() ? balloon->getPower() : 0); });
}
// Crea un globo nuevo en el vector de globos
std::shared_ptr<Balloon> BalloonManager::createBalloon(float x, int y, BalloonType type, BalloonSize size, float velx, float speed, int creation_timer) {
auto BalloonManager::createBalloon(float x, int y, BalloonType type, BalloonSize size, float velx, float speed, int creation_timer) -> std::shared_ptr<Balloon> {
if (can_deploy_balloons_) {
const int INDEX = static_cast<int>(size);
balloons_.emplace_back(std::make_shared<Balloon>(x, y, type, size, velx, speed, creation_timer, play_area_, balloon_textures_.at(INDEX), balloon_animations_.at(INDEX)));
@@ -230,7 +229,7 @@ void BalloonManager::setBalloonSpeed(float speed) {
}
// Explosiona un globo. Lo destruye y crea otros dos si es el caso
int BalloonManager::popBalloon(std::shared_ptr<Balloon> balloon) {
auto BalloonManager::popBalloon(std::shared_ptr<Balloon> balloon) -> int {
Stage::addPower(1);
int score = 0;
@@ -255,7 +254,7 @@ int BalloonManager::popBalloon(std::shared_ptr<Balloon> balloon) {
}
// Explosiona un globo. Lo destruye = no crea otros globos
int BalloonManager::destroyBalloon(std::shared_ptr<Balloon> &balloon) {
auto BalloonManager::destroyBalloon(std::shared_ptr<Balloon> &balloon) -> int {
int score = 0;
// Calcula la puntuación y el poder que generaria el globo en caso de romperlo a él y a sus hijos
@@ -288,7 +287,7 @@ int BalloonManager::destroyBalloon(std::shared_ptr<Balloon> &balloon) {
}
// Destruye todos los globos
int BalloonManager::destroyAllBalloons() {
auto BalloonManager::destroyAllBalloons() -> int {
int score = 0;
for (auto &balloon : balloons_) {
score += destroyBalloon(balloon);
@@ -344,7 +343,7 @@ void BalloonManager::createRandomBalloons() {
for (int i = 0; i < NUM_BALLOONS; ++i) {
const float X = param.game.game_area.rect.x + (rand() % static_cast<int>(param.game.game_area.rect.w)) - BALLOON_SIZE[3];
const int Y = param.game.game_area.rect.y + (rand() % 50);
const BalloonSize SIZE = static_cast<BalloonSize>(rand() % 4);
const auto SIZE = static_cast<BalloonSize>(rand() % 4);
const float VEL_X = (rand() % 2 == 0) ? BALLOON_VELX_POSITIVE : BALLOON_VELX_NEGATIVE;
const int CREATION_COUNTER = 0;
createBalloon(X, Y, BalloonType::BALLOON, SIZE, VEL_X, balloon_speed_, CREATION_COUNTER);
@@ -352,7 +351,7 @@ void BalloonManager::createRandomBalloons() {
}
// Obtiene el nivel de ameza actual generado por los globos
int BalloonManager::getMenace() {
auto BalloonManager::getMenace() -> int {
return std::accumulate(balloons_.begin(), balloons_.end(), 0, [](int sum, const auto &balloon) { return sum + (balloon->isEnabled() ? balloon->getMenace() : 0); });
}

View File

@@ -36,7 +36,7 @@ class BalloonManager {
void deploySet(int set, int y); // Crea una formación específica con coordenadas
// Creación de globos
std::shared_ptr<Balloon> createBalloon(float x, int y, BalloonType type, BalloonSize size, float velx, float speed, int creation_timer); // Crea un nuevo globo
auto createBalloon(float x, int y, BalloonType type, BalloonSize size, float velx, float speed, int creation_timer) -> std::shared_ptr<Balloon>; // Crea un nuevo globo
void createChildBalloon(const std::shared_ptr<Balloon> &balloon, const std::string &direction); // Crea un globo a partir de otro
void createPowerBall(); // Crea una PowerBall
void createTwoBigBalloons(); // Crea dos globos grandes
@@ -47,13 +47,13 @@ class BalloonManager {
void setDefaultBalloonSpeed(float speed) { default_balloon_speed_ = speed; }; // Establece la velocidad base
void resetBalloonSpeed() { setBalloonSpeed(default_balloon_speed_); }; // Restablece la velocidad de los globos
void updateBalloonDeployCounter(); // Actualiza el contador de despliegue
bool canPowerBallBeCreated(); // Indica si se puede crear una PowerBall
int calculateScreenPower(); // Calcula el poder de los globos en pantalla
auto canPowerBallBeCreated() -> bool; // Indica si se puede crear una PowerBall
auto calculateScreenPower() -> int; // Calcula el poder de los globos en pantalla
// Manipulación de globos existentes
int popBalloon(std::shared_ptr<Balloon> balloon); // Explosiona un globo, creando otros si aplica
int destroyBalloon(std::shared_ptr<Balloon> &balloon); // Explosiona un globo sin crear otros
int destroyAllBalloons(); // Destruye todos los globos
auto popBalloon(std::shared_ptr<Balloon> balloon) -> int; // Explosiona un globo, creando otros si aplica
auto destroyBalloon(std::shared_ptr<Balloon> &balloon) -> int; // Explosiona un globo sin crear otros
auto destroyAllBalloons() -> int; // Destruye todos los globos
void stopAllBalloons(); // Detiene el movimiento de los globos
void startAllBalloons(); // Reactiva el movimiento de los globos
@@ -72,10 +72,10 @@ class BalloonManager {
void enableBalloonDeployment(bool value) { can_deploy_balloons_ = value; }; // Activa o desactiva la generación de globos
// Obtención de información
int getMenace(); // Obtiene el nivel de amenaza generado por los globos
float getBalloonSpeed() const { return balloon_speed_; }
Balloons &getBalloons() { return balloons_; }
int getNumBalloons() const { return balloons_.size(); }
auto getMenace() -> int; // Obtiene el nivel de amenaza generado por los globos
[[nodiscard]] auto getBalloonSpeed() const -> float { return balloon_speed_; }
auto getBalloons() -> Balloons & { return balloons_; }
[[nodiscard]] auto getNumBalloons() const -> int { return balloons_.size(); }
private:
Balloons balloons_; // Vector con los globos activos

View File

@@ -46,13 +46,13 @@ void Bullet::render() {
}
// Actualiza el estado del objeto
BulletMoveStatus Bullet::update() {
auto Bullet::update() -> BulletMoveStatus {
sprite_->update();
return move();
}
// Implementación del movimiento usando BulletMoveStatus
BulletMoveStatus Bullet::move() {
auto Bullet::move() -> BulletMoveStatus {
pos_x_ += vel_x_;
if (pos_x_ < param.game.play_area.rect.x - WIDTH || pos_x_ > param.game.play_area.rect.w) {
disable();
@@ -71,7 +71,7 @@ BulletMoveStatus Bullet::move() {
return BulletMoveStatus::OK;
}
bool Bullet::isEnabled() const {
auto Bullet::isEnabled() const -> bool {
return bullet_type_ != BulletType::NONE;
}
@@ -79,11 +79,11 @@ void Bullet::disable() {
bullet_type_ = BulletType::NONE;
}
int Bullet::getOwner() const {
auto Bullet::getOwner() const -> int {
return owner_;
}
Circle &Bullet::getCollider() {
auto Bullet::getCollider() -> Circle& {
return collider_;
}

View File

@@ -34,15 +34,15 @@ class Bullet {
// Métodos principales
void render(); // Dibuja la bala en pantalla
BulletMoveStatus update(); // Actualiza el estado del objeto
auto update() -> BulletMoveStatus; // Actualiza el estado del objeto
// Estado de la bala
bool isEnabled() const; // Comprueba si está activa
[[nodiscard]] auto isEnabled() const -> bool; // Comprueba si está activa
void disable(); // Desactiva la bala
// Getters
int getOwner() const; // Devuelve el identificador del dueño
Circle &getCollider(); // Devuelve el círculo de colisión
[[nodiscard]] auto getOwner() const -> int; // Devuelve el identificador del dueño
auto getCollider() -> Circle &; // Devuelve el círculo de colisión
private:
// Constantes
@@ -64,5 +64,5 @@ class Bullet {
// Métodos internos
void shiftColliders(); // Ajusta el círculo de colisión
void shiftSprite(); // Ajusta el sprite
BulletMoveStatus move(); // Mueve la bala y devuelve su estado
auto move() -> BulletMoveStatus; // Mueve la bala y devuelve su estado
};

View File

@@ -73,7 +73,7 @@ void DefineButtons::checkEvents(const SDL_Event &event) {
}
// Habilita el objeto
bool DefineButtons::enable(int index) {
auto DefineButtons::enable(int index) -> bool {
if (index < input_->getNumControllers()) {
enabled_ = true;
finished_ = false;
@@ -87,7 +87,7 @@ bool DefineButtons::enable(int index) {
}
// Comprueba si está habilitado
bool DefineButtons::isEnabled() const { return enabled_; }
auto DefineButtons::isEnabled() const -> bool { return enabled_; }
// Incrementa el indice de los botones
void DefineButtons::incIndexButton() {
@@ -109,7 +109,7 @@ void DefineButtons::saveBindingsToOptions() {
}
// Comprueba que un botón no esté ya asignado
bool DefineButtons::checkButtonNotInUse(SDL_GamepadButton button) {
auto DefineButtons::checkButtonNotInUse(SDL_GamepadButton button) -> bool {
for (const auto &b : buttons_) {
if (b.button == button) {
return false;

View File

@@ -1,10 +1,11 @@
#pragma once
#include <SDL3/SDL.h> // Para SDL_GamepadButton, SDL_Event, SDL_GamepadButtonEvent
#include <stddef.h> // Para size_t
#include <cstddef> // Para size_t
#include <memory> // Para shared_ptr
#include <string> // Para basic_string, string
#include <utility>
#include <vector> // Para vector
// Declaraciones adelantadas
@@ -18,8 +19,8 @@ struct DefineButtonsButton {
InputAction input; // Acción asociada
SDL_GamepadButton button; // Botón del mando
DefineButtonsButton(const std::string &lbl, InputAction inp, SDL_GamepadButton btn)
: label(lbl), input(inp), button(btn) {}
DefineButtonsButton(std::string lbl, InputAction inp, SDL_GamepadButton btn)
: label(std::move(lbl)), input(inp), button(btn) {}
};
// Clase DefineButtons
@@ -30,8 +31,8 @@ class DefineButtons {
void render(); // Dibuja el objeto en pantalla
void checkEvents(const SDL_Event &event); // Procesa los eventos
bool enable(int index_controller); // Habilita la redefinición de botones
bool isEnabled() const; // Comprueba si está habilitado
auto enable(int index_controller) -> bool; // Habilita la redefinición de botones
[[nodiscard]] auto isEnabled() const -> bool; // Comprueba si está habilitado
private:
// Objetos
@@ -52,7 +53,7 @@ class DefineButtons {
void doControllerButtonDown(const SDL_GamepadButtonEvent &event); // Procesa pulsaciones
void bindButtons(); // Asigna botones al sistema de entrada
void saveBindingsToOptions(); // Guarda configuraciones
bool checkButtonNotInUse(SDL_GamepadButton button); // Verifica uso de botones
auto checkButtonNotInUse(SDL_GamepadButton button) -> bool; // Verifica uso de botones
void clearButtons(); // Limpia asignaciones actuales
void checkEnd(); // Comprueba si ha finalizado
};

View File

@@ -2,12 +2,12 @@
#include "director.h"
#include <SDL3/SDL.h> // Para SDL_Scancode, SDL_GamepadButton
#include <errno.h> // Para errno, EEXIST, EACCES, ENAMETOOLONG
#include <stdio.h> // Para printf, perror
#include <sys/stat.h> // Para mkdir, stat, S_IRWXU
#include <unistd.h> // Para getuid
#include <algorithm> // Para min
#include <cerrno> // Para errno, EEXIST, EACCES, ENAMETOOLONG
#include <cstdio> // Para printf, perror
#include <cstdlib> // Para exit, EXIT_FAILURE, size_t, srand
#include <ctime> // Para time
#include <memory> // Para make_unique, unique_ptr
@@ -596,7 +596,7 @@ void Director::reset() {
Section::name = Section::Name::LOGO;
}
int Director::run() {
auto Director::run() -> int {
// Bucle principal
while (Section::name != Section::Name::QUIT) {
switch (Section::name) {

View File

@@ -13,7 +13,7 @@ class Director {
~Director();
// --- Bucle principal ---
int run();
auto run() -> int;
private:
// --- Variables internas ---
@@ -46,7 +46,7 @@ class Director {
void reset(); // Reinicia objetos y vuelve a la sección inicial
// --- Gestión de archivos de idioma ---
std::string getLangFile(Lang::Code code); // Obtiene un fichero de idioma según el código
auto getLangFile(Lang::Code code) -> std::string; // Obtiene un fichero de idioma según el código
// --- Apagado del sistema ---
void shutdownSystem(bool should_shutdown); // Apaga el sistema

View File

@@ -1,8 +1,7 @@
#include "enter_name.h"
#include <stddef.h> // Para size_t
#include <stdlib.h> // Para rand
#include <cstddef> // Para size_t
#include <cstdlib> // Para rand
#include <string_view> // Para basic_string_view, string_view
#include "utils.h" // Para trim
@@ -133,7 +132,7 @@ void EnterName::initCharacterIndex(const std::string &name) {
}
// Encuentra el indice de un caracter en "character_list_"
int EnterName::findIndex(char character) const {
auto EnterName::findIndex(char character) const -> int {
for (size_t i = 0; i < character_list_.size(); ++i) {
if (character == character_list_.at(i)) {
return i;
@@ -143,13 +142,13 @@ int EnterName::findIndex(char character) const {
}
// Devuelve un nombre al azar
std::string EnterName::getRandomName() {
auto EnterName::getRandomName() -> std::string {
static constexpr std::array<std::string_view, 8> NAMES = {
"BAL1", "TABE", "DOC", "MON", "SAM1", "JORDI", "JDES", "PEPE"};
return std::string(NAMES[rand() % NAMES.size()]);
}
// Obtiene el nombre final introducido
std::string EnterName::getFinalName() {
auto EnterName::getFinalName() -> std::string {
auto name = trim(name_.substr(0, position_));
if (name.empty()) {
name = getRandomName();

View File

@@ -1,8 +1,7 @@
#pragma once
#include <stddef.h> // Para size_t
#include <array> // Para array
#include <cstddef> // Para size_t
#include <string> // Para string, basic_string
#include "utils.h" // Para trim
@@ -23,11 +22,11 @@ class EnterName {
void incIndex(); // Incrementa el índice del carácter en la lista
void decIndex(); // Decrementa el índice del carácter en la lista
std::string getFinalName(); // Obtiene el nombre final introducido
std::string getCurrentName() const { return trim(name_); } // Obtiene el nombre actual en proceso
auto getFinalName() -> std::string; // Obtiene el nombre final introducido
[[nodiscard]] auto getCurrentName() const -> std::string { return trim(name_); } // Obtiene el nombre actual en proceso
int getPosition() const { return position_; } // Posición actual del carácter editado
bool getPositionOverflow() const { return position_overflow_; } // Indica si la posición excede el límite
[[nodiscard]] auto getPosition() const -> int { return position_; } // Posición actual del carácter editado
[[nodiscard]] auto getPositionOverflow() const -> bool { return position_overflow_; } // Indica si la posición excede el límite
private:
std::string character_list_; // Lista de caracteres permitidos
@@ -38,6 +37,6 @@ class EnterName {
void updateNameFromCharacterIndex(); // Actualiza "name_" según "character_index_"
void initCharacterIndex(const std::string &name); // Inicializa índices desde el nombre
int findIndex(char character) const; // Busca el índice de un carácter en "character_list_"
static std::string getRandomName(); // Devuelve un nombre al azar
[[nodiscard]] auto findIndex(char character) const -> int; // Busca el índice de un carácter en "character_list_"
static auto getRandomName() -> std::string; // Devuelve un nombre al azar
};

View File

@@ -23,7 +23,7 @@ void Explosions::render() {
// Añade texturas al objeto
void Explosions::addTexture(int size, std::shared_ptr<Texture> texture, const std::vector<std::string> &animation) {
textures_.emplace_back(ExplosionTexture(size, texture, animation));
textures_.emplace_back(size, texture, animation);
}
// Añade una explosión
@@ -45,7 +45,7 @@ void Explosions::freeExplosions() {
}
// Busca una textura a partir del tamaño
int Explosions::getIndexBySize(int size) {
auto Explosions::getIndexBySize(int size) -> int {
for (int i = 0; i < (int)textures_.size(); ++i) {
if (size == textures_[i].size) {
return i;

View File

@@ -2,6 +2,7 @@
#include <memory> // Para unique_ptr, shared_ptr
#include <string> // Para string
#include <utility>
#include <vector> // Para vector
#include "animated_sprite.h" // Para AnimatedSprite
@@ -15,7 +16,7 @@ struct ExplosionTexture {
std::vector<std::string> animation; // Animación para la textura
ExplosionTexture(int sz, std::shared_ptr<Texture> tex, const std::vector<std::string> &anim)
: size(sz), texture(tex), animation(anim) {}
: size(sz), texture(std::move(tex)), animation(anim) {}
};
// Clase Explosions
@@ -48,5 +49,5 @@ class Explosions {
void freeExplosions();
// Busca una textura a partir del tamaño
int getIndexBySize(int size);
auto getIndexBySize(int size) -> int;
};

View File

@@ -6059,7 +6059,7 @@ inline void to_json(BasicJsonType& j, const std::pair<T1, T2>& p)
j = { p.first, p.second };
}
// Para https://github.com/nlohmann/json/pull/1134
// for https://github.com/nlohmann/json/pull/1134
template<typename BasicJsonType, typename T,
enable_if_t<std::is_same<T, iteration_proxy_value<typename BasicJsonType::iterator>>::value, int> = 0>
inline void to_json(BasicJsonType& j, const T& b)
@@ -6624,7 +6624,7 @@ class iterator_input_adapter
return char_traits<char_type>::eof();
}
// Para general iterators, we cannot really do something better than falling back to processing the range one-by-one
// for general iterators, we cannot really do something better than falling back to processing the range one-by-one
template<class T>
std::size_t get_elements(T* dest, std::size_t count = 1)
{
@@ -14558,7 +14558,7 @@ class json_pointer
};
public:
// Para backwards compatibility accept BasicJsonType
// for backwards compatibility accept BasicJsonType
using string_t = typename string_t_helper<RefStringType>::type;
/// @brief create JSON pointer
@@ -18087,7 +18087,7 @@ inline cached_power get_cached_power_for_binary_exponent(int e)
// This computation gives exactly the same results for k as
// k = ceil((kAlpha - e - 1) * 0.30102999566398114)
// Para |e| <= 1500, but doesn't require floating-point operations.
// for |e| <= 1500, but doesn't require floating-point operations.
// NB: log_10(2) ~= 78913 / 2^18
JSON_ASSERT(e >= -1500);
JSON_ASSERT(e <= 1500);
@@ -19727,7 +19727,7 @@ NLOHMANN_JSON_NAMESPACE_END
#include <initializer_list> // initializer_list
#include <iterator> // input_iterator_tag, iterator_traits
#include <memory> // allocator
#include <stdexcept> // Para out_of_range
#include <stdexcept> // for out_of_range
#include <type_traits> // enable_if, is_convertible
#include <utility> // pair
#include <vector> // vector
@@ -19740,7 +19740,7 @@ NLOHMANN_JSON_NAMESPACE_END
NLOHMANN_JSON_NAMESPACE_BEGIN
/// ordered_map: a minimal map-like container that preserves insertion order
/// Para use within nlohmann::basic_json<ordered_map>
/// for use within nlohmann::basic_json<ordered_map>
template <class Key, class T, class IgnoredLess = std::less<Key>,
class Allocator = std::allocator<std::pair<const Key, T>>>
struct ordered_map : std::vector<std::pair<const Key, T>, Allocator>

View File

@@ -1,9 +1,9 @@
#include "fade.h"
#include <SDL3/SDL.h> // Para SDL_SetRenderTarget, SDL_FRect, SDL_GetRenderT...
#include <stdlib.h> // Para rand, size_t
#include <algorithm> // Para min, max
#include <cstdlib> // Para rand, size_t
#include "param.h" // Para Param, param, ParamGame, ParamFade
#include "screen.h" // Para Screen
@@ -312,7 +312,7 @@ void Fade::cleanBackbuffer(Uint8 r, Uint8 g, Uint8 b, Uint8 a) {
}
// Calcula el valor del estado del fade
int Fade::calculateValue(int min, int max, int current) {
auto Fade::calculateValue(int min, int max, int current) -> int {
if (current < min) {
return 0;
}

View File

@@ -50,9 +50,9 @@ class Fade {
void setPreDuration(int value) { pre_duration_ = value; }
// --- Getters ---
int getValue() const { return value_; }
bool isEnabled() const { return state_ != FadeState::NOT_ENABLED; }
bool hasEnded() const { return state_ == FadeState::FINISHED; }
[[nodiscard]] auto getValue() const -> int { return value_; }
[[nodiscard]] auto isEnabled() const -> bool { return state_ != FadeState::NOT_ENABLED; }
[[nodiscard]] auto hasEnded() const -> bool { return state_ == FadeState::FINISHED; }
private:
// --- Objetos y punteros ---
@@ -86,5 +86,5 @@ class Fade {
// --- Métodos internos ---
void init(); // Inicializa variables
void cleanBackbuffer(Uint8 r, Uint8 g, Uint8 b, Uint8 a); // Limpia el backbuffer
int calculateValue(int min, int max, int current); // Calcula el valor del fade
auto calculateValue(int min, int max, int current) -> int; // Calcula el valor del fade
};

View File

@@ -219,12 +219,12 @@ void GameLogo::enable() {
}
// Indica si ha terminado la animación
bool GameLogo::hasFinished() const {
auto GameLogo::hasFinished() const -> bool {
return post_finished_counter_ == 0;
}
// Calcula el desplazamiento vertical inicial
int GameLogo::getInitialVerticalDesp() {
auto GameLogo::getInitialVerticalDesp() -> int {
const float OFFSET_UP = y_;
const float OFFSET_DOWN = param.game.height - y_;

View File

@@ -21,7 +21,7 @@ class GameLogo {
void enable(); // Activa la clase
// --- Getters ---
bool hasFinished() const; // Indica si ha terminado la animación
[[nodiscard]] auto hasFinished() const -> bool; // Indica si ha terminado la animación
private:
// --- Tipos internos ---
@@ -78,5 +78,5 @@ class GameLogo {
// --- Métodos internos ---
void init(); // Inicializa las variables
int getInitialVerticalDesp(); // Calcula el desplazamiento vertical inicial
auto getInitialVerticalDesp() -> int; // Calcula el desplazamiento vertical inicial
};

View File

@@ -65,7 +65,7 @@ void toggleShaders() {
}
// Obtiene una fichero a partir de un lang::Code
std::string getLangFile(Lang::Code code) {
auto getLangFile(Lang::Code code) -> std::string {
switch (code) {
case Lang::Code::VALENCIAN:
return Asset::get()->get("ba_BA.json");
@@ -80,7 +80,7 @@ std::string getLangFile(Lang::Code code) {
}
// Obtiene una cadena a partir de un lang::Code
std::string getLangName(Lang::Code code) {
auto getLangName(Lang::Code code) -> std::string {
switch (code) {
case Lang::Code::VALENCIAN:
return " \"ba_BA\"";
@@ -161,7 +161,7 @@ void incWindowSize() {
}
// Comprueba el boton de servicio
bool checkServiceButton() {
auto checkServiceButton() -> bool {
// Teclado
if (Input::get()->checkInput(InputAction::SERVICE, INPUT_DO_NOT_ALLOW_REPEAT, InputDevice::KEYBOARD)) {
toggleServiceMenu();
@@ -181,7 +181,7 @@ bool checkServiceButton() {
}
// Comprueba las entradas del menú de servicio
bool checkServiceInputs() {
auto checkServiceInputs() -> bool {
if (!ServiceMenu::get()->isEnabled())
return false;
@@ -268,7 +268,7 @@ bool checkServiceInputs() {
}
// Comprueba las entradas fuera del menú de servicio
bool checkInputs() {
auto checkInputs() -> bool {
// Teclado
{
// Comprueba el teclado para cambiar entre pantalla completa y ventana
@@ -361,7 +361,7 @@ bool checkInputs() {
}
// Comprueba los inputs que se pueden introducir en cualquier sección del juego
bool check() {
auto check() -> bool {
if (checkServiceButton())
return true;
if (checkServiceInputs())

View File

@@ -2,5 +2,5 @@
namespace GlobalInputs {
// Comprueba los inputs que se pueden introducir en cualquier sección del juego
bool check();
auto check() -> bool;
} // namespace GlobalInputs

View File

@@ -1,9 +1,9 @@
#include "input.h"
#include <SDL3/SDL.h> // Para SDL_LogInfo, SDL_LogCategory, SDL_GetGamepa...
#include <stddef.h> // Para size_t
#include <algorithm> // Para find
#include <cstddef> // Para size_t
#include <iterator> // Para distance
#include <unordered_map> // Para unordered_map, _Node_const_iterator, operat...
#include <utility> // Para pair
@@ -18,11 +18,11 @@ void Input::init(const std::string &game_controller_db_path) { Input::instance =
void Input::destroy() { delete Input::instance; }
// Obtiene la instancia
Input *Input::get() { return Input::instance; }
auto Input::get() -> Input * { return Input::instance; }
// Constructor
Input::Input(const std::string &game_controller_db_path)
: game_controller_db_path_(game_controller_db_path) {
Input::Input(std::string game_controller_db_path)
: game_controller_db_path_(std::move(game_controller_db_path)) {
// Inicializa el subsistema SDL_INIT_GAMEPAD
initSDLGamePad();
@@ -54,7 +54,7 @@ void Input::bindGameControllerButton(int controller_index, InputAction input_tar
}
// Comprueba si un input esta activo
bool Input::checkInput(InputAction input, bool repeat, InputDevice device, int controller_index) {
auto Input::checkInput(InputAction input, bool repeat, InputDevice device, int controller_index) -> bool {
bool success_keyboard = false;
bool success_controller = false;
const int INPUT_INDEX = static_cast<int>(input);
@@ -85,7 +85,7 @@ bool Input::checkInput(InputAction input, bool repeat, InputDevice device, int c
}
// Comprueba si hay almenos un input activo
bool Input::checkAnyInput(InputDevice device, int controller_index) {
auto Input::checkAnyInput(InputDevice device, int controller_index) -> bool {
// Obtenemos el número total de acciones posibles para iterar sobre ellas.
const int NUM_ACTIONS = static_cast<int>(InputAction::SIZE);
@@ -119,7 +119,7 @@ bool Input::checkAnyInput(InputDevice device, int controller_index) {
}
// Comprueba si hay algún botón pulsado. Devuelve 0 en caso de no encontrar nada o el indice del dispositivo + 1. Se hace así para poder gastar el valor devuelto como un valor "booleano"
int Input::checkAnyButton(bool repeat) {
auto Input::checkAnyButton(bool repeat) -> int {
// Solo comprueba los botones definidos previamente
for (auto bi : button_inputs_) {
// Comprueba el teclado
@@ -139,7 +139,7 @@ int Input::checkAnyButton(bool repeat) {
}
// Busca si hay mandos conectados
bool Input::discoverGameControllers() {
auto Input::discoverGameControllers() -> bool {
bool found = false;
if (SDL_AddGamepadMappingsFromFile(game_controller_db_path_.c_str()) < 0) {
@@ -207,16 +207,16 @@ bool Input::discoverGameControllers() {
}
// Comprueba si hay algun mando conectado
bool Input::gameControllerFound() { return num_gamepads_ > 0 ? true : false; }
auto Input::gameControllerFound() -> bool { return num_gamepads_ > 0 ? true : false; }
// Obten el nombre de un mando de juego
std::string Input::getControllerName(int controller_index) const { return num_gamepads_ > 0 ? controller_names_.at(controller_index) : std::string(); }
auto Input::getControllerName(int controller_index) const -> std::string { return num_gamepads_ > 0 ? controller_names_.at(controller_index) : std::string(); }
// Obten el número de mandos conectados
int Input::getNumControllers() const { return num_gamepads_; }
auto Input::getNumControllers() const -> int { return num_gamepads_; }
// Obtiene el indice del controlador a partir de un event.id
int Input::getJoyIndex(SDL_JoystickID id) const {
auto Input::getJoyIndex(SDL_JoystickID id) const -> int {
for (int i = 0; i < num_joysticks_; ++i) {
if (SDL_GetJoystickID(joysticks_[i]) == id) {
return i;
@@ -247,18 +247,18 @@ void Input::printBindings(InputDevice device, int controller_index) const {
}
// Obtiene el SDL_GamepadButton asignado a un input
SDL_GamepadButton Input::getControllerBinding(int controller_index, InputAction input) const {
auto Input::getControllerBinding(int controller_index, InputAction input) const -> SDL_GamepadButton {
return controller_bindings_[controller_index][static_cast<int>(input)].button;
}
// Obtiene el indice a partir del nombre del mando
int Input::getIndexByName(const std::string &name) const {
auto Input::getIndexByName(const std::string &name) const -> int {
auto it = std::find(controller_names_.begin(), controller_names_.end(), name);
return it != controller_names_.end() ? std::distance(controller_names_.begin(), it) : -1;
}
// Convierte un InputAction a std::string
std::string Input::inputToString(InputAction input) const {
auto Input::inputToString(InputAction input) const -> std::string {
switch (input) {
case InputAction::FIRE_LEFT:
return "input_fire_left";
@@ -276,7 +276,7 @@ std::string Input::inputToString(InputAction input) const {
}
// Convierte un std::string a InputAction
InputAction Input::stringToInput(const std::string &name) const {
auto Input::stringToInput(const std::string &name) const -> InputAction {
static const std::unordered_map<std::string, InputAction> INPUT_MAP = {
{"input_fire_left", InputAction::FIRE_LEFT},
{"input_fire_center", InputAction::FIRE_CENTER},
@@ -289,7 +289,7 @@ InputAction Input::stringToInput(const std::string &name) const {
}
// Comprueba el eje del mando
bool Input::checkAxisInput(InputAction input, int controller_index, bool repeat) {
auto Input::checkAxisInput(InputAction input, int controller_index, bool repeat) -> bool {
// Umbral para considerar el eje como activo
bool axis_active_now = false;
@@ -362,12 +362,12 @@ void Input::update() {
// --- TECLADO ---
const bool *key_states = SDL_GetKeyboardState(nullptr);
for (size_t i = 0; i < key_bindings_.size(); ++i) {
bool key_is_down_now = key_states[key_bindings_[i].scancode];
for (auto &key_binding : key_bindings_) {
bool key_is_down_now = key_states[key_binding.scancode];
// El estado .is_held del fotograma anterior nos sirve para saber si es un pulso nuevo
key_bindings_[i].just_pressed = key_is_down_now && !key_bindings_[i].is_held;
key_bindings_[i].is_held = key_is_down_now;
key_binding.just_pressed = key_is_down_now && !key_binding.is_held;
key_binding.is_held = key_is_down_now;
}
// --- MANDOS ---

View File

@@ -72,7 +72,7 @@ class Input {
// --- Métodos de singleton ---
static void init(const std::string &game_controller_db_path); // Inicializa el singleton
static void destroy(); // Libera el singleton
static Input *get(); // Obtiene la instancia
static auto get() -> Input *; // Obtiene la instancia
// --- Métodos de configuración de controles ---
void bindKey(InputAction input, SDL_Scancode code); // Asigna inputs a teclas
@@ -81,23 +81,23 @@ class Input {
// --- Métodos de consulta de entrada ---
void update(); // Comprueba fisicamente los botones y teclas que se han pulsado
bool checkInput(InputAction input, bool repeat = true, InputDevice device = InputDevice::ANY, int controller_index = 0); // Comprueba si un input está activo
bool checkAnyInput(InputDevice device = InputDevice::ANY, int controller_index = 0); // Comprueba si hay al menos un input activo
int checkAnyButton(bool repeat = INPUT_DO_NOT_ALLOW_REPEAT); // Comprueba si hay algún botón pulsado
auto checkInput(InputAction input, bool repeat = true, InputDevice device = InputDevice::ANY, int controller_index = 0) -> bool; // Comprueba si un input está activo
auto checkAnyInput(InputDevice device = InputDevice::ANY, int controller_index = 0) -> bool; // Comprueba si hay al menos un input activo
auto checkAnyButton(bool repeat = INPUT_DO_NOT_ALLOW_REPEAT) -> int; // Comprueba si hay algún botón pulsado
// --- Métodos de gestión de mandos ---
bool discoverGameControllers(); // Busca si hay mandos conectados
bool gameControllerFound(); // Comprueba si hay algún mando conectado
int getNumControllers() const; // Obtiene el número de mandos conectados
std::string getControllerName(int controller_index) const; // Obtiene el nombre de un mando de juego
int getJoyIndex(SDL_JoystickID id) const; // Obtiene el índice del controlador a partir de un event.id
auto discoverGameControllers() -> bool; // Busca si hay mandos conectados
auto gameControllerFound() -> bool; // Comprueba si hay algún mando conectado
[[nodiscard]] auto getNumControllers() const -> int; // Obtiene el número de mandos conectados
[[nodiscard]] auto getControllerName(int controller_index) const -> std::string; // Obtiene el nombre de un mando de juego
[[nodiscard]] auto getJoyIndex(SDL_JoystickID id) const -> int; // Obtiene el índice del controlador a partir de un event.id
// --- Métodos de consulta y utilidades ---
void printBindings(InputDevice device = InputDevice::KEYBOARD, int controller_index = 0) const; // Muestra por consola los controles asignados
SDL_GamepadButton getControllerBinding(int controller_index, InputAction input) const; // Obtiene el SDL_GamepadButton asignado a un input
std::string inputToString(InputAction input) const; // Convierte un InputAction a std::string
InputAction stringToInput(const std::string &name) const; // Convierte un std::string a InputAction
int getIndexByName(const std::string &name) const; // Obtiene el índice a partir del nombre del mando
[[nodiscard]] auto getControllerBinding(int controller_index, InputAction input) const -> SDL_GamepadButton; // Obtiene el SDL_GamepadButton asignado a un input
[[nodiscard]] auto inputToString(InputAction input) const -> std::string; // Convierte un InputAction a std::string
[[nodiscard]] auto stringToInput(const std::string &name) const -> InputAction; // Convierte un std::string a InputAction
[[nodiscard]] auto getIndexByName(const std::string &name) const -> int; // Obtiene el índice a partir del nombre del mando
// --- Métodos de reseteo de estado de entrada ---
void resetInputStates(); // Pone todos los KeyBindings.active y ControllerBindings.active a false
@@ -139,10 +139,10 @@ class Input {
// --- Métodos internos ---
void initSDLGamePad(); // Inicializa SDL para la gestión de mandos
bool checkAxisInput(InputAction input, int controller_index, bool repeat); // Comprueba el eje del mando
auto checkAxisInput(InputAction input, int controller_index, bool repeat) -> bool; // Comprueba el eje del mando
// --- Constructor y destructor ---
explicit Input(const std::string &game_controller_db_path); // Constructor privado
explicit Input(std::string game_controller_db_path); // Constructor privado
~Input() = default; // Destructor privado
// --- Singleton ---

View File

@@ -1,8 +1,7 @@
#include "item.h"
#include <stdlib.h> // Para rand
#include <algorithm> // Para clamp
#include <cstdlib> // Para rand
#include "animated_sprite.h" // Para AnimatedSprite
#include "param.h" // Para Param, ParamGame, param
@@ -161,7 +160,7 @@ void Item::shiftSprite() {
}
// Calcula la zona de aparición de la máquina de café
int Item::getCoffeeMachineSpawn(int player_x, int item_width, int area_width, int margin) {
auto Item::getCoffeeMachineSpawn(int player_x, int item_width, int area_width, int margin) -> int {
// Distancia mínima del jugador (ajusta según necesites)
const int MIN_DISTANCE_FROM_PLAYER = area_width / 2;

View File

@@ -54,14 +54,14 @@ class Item {
void update();
// Getters
float getPosX() const { return pos_x_; }
float getPosY() const { return pos_y_; }
int getWidth() const { return width_; }
int getHeight() const { return height_; }
ItemType getType() const { return type_; }
bool isEnabled() const { return enabled_; }
bool isOnFloor() const { return floor_collision_; }
Circle &getCollider() { return collider_; }
[[nodiscard]] auto getPosX() const -> float { return pos_x_; }
[[nodiscard]] auto getPosY() const -> float { return pos_y_; }
[[nodiscard]] auto getWidth() const -> int { return width_; }
[[nodiscard]] auto getHeight() const -> int { return height_; }
[[nodiscard]] auto getType() const -> ItemType { return type_; }
[[nodiscard]] auto isEnabled() const -> bool { return enabled_; }
[[nodiscard]] auto isOnFloor() const -> bool { return floor_collision_; }
auto getCollider() -> Circle & { return collider_; }
private:
// Objetos y punteros
@@ -100,5 +100,5 @@ class Item {
void updateTimeToLive();
// Calcula la zona de aparición de la máquina de café
int getCoffeeMachineSpawn(int player_x, int item_width, int area_width, int margin = 2);
auto getCoffeeMachineSpawn(int player_x, int item_width, int area_width, int margin = 2) -> int;
};

View File

@@ -1,7 +1,6 @@
#include "lang.h"
#include <stddef.h> // Para size_t
#include <cstddef> // Para size_t
#include <exception> // Para exception
#include <fstream> // Para basic_ifstream, basic_istream, ifstream
#include <unordered_map> // Para unordered_map, _Node_iterator, operator==
@@ -24,7 +23,7 @@ std::vector<Language> languages = {
{Code::ENGLISH, "Ingles", "en_UK.json"}};
// Inicializa los textos del juego en el idioma seleccionado
bool loadFromFile(const std::string &file_path) {
auto loadFromFile(const std::string &file_path) -> bool {
texts.clear();
std::ifstream rfile(file_path);
@@ -47,7 +46,7 @@ bool loadFromFile(const std::string &file_path) {
}
// Obtiene el texto por clave
std::string getText(const std::string &key) {
auto getText(const std::string &key) -> std::string {
auto it = texts.find(key);
if (it != texts.end())
return it->second;
@@ -56,7 +55,7 @@ std::string getText(const std::string &key) {
}
// Obtiene el código del siguiente idioma disponible
Code getNextLangCode(Code lang) {
auto getNextLangCode(Code lang) -> Code {
for (size_t i = 0; i < languages.size(); ++i) {
if (languages[i].code == lang) {
return languages[(i + 1) % languages.size()].code;
@@ -67,7 +66,7 @@ Code getNextLangCode(Code lang) {
}
// Obtiene un idioma del vector de idiomas a partir de un código
Language getLanguage(Code code) {
auto getLanguage(Code code) -> Language {
for (const auto &lang : languages) {
if (lang.code == code)
return lang;
@@ -77,7 +76,7 @@ Language getLanguage(Code code) {
}
// Devuelve el código de un idioma a partir de un nombre
Code getCodeFromName(const std::string &name) {
auto getCodeFromName(const std::string &name) -> Code {
for (const auto &lang : languages) {
if (lang.name == name)
return lang.code;
@@ -87,7 +86,7 @@ Code getCodeFromName(const std::string &name) {
}
// Devuelve el nombre de un idioma a partir de un código
std::string getNameFromCode(Code code) {
auto getNameFromCode(Code code) -> std::string {
for (const auto &lang : languages) {
if (lang.code == code)
return lang.name;
@@ -137,7 +136,7 @@ void updateDifficultyNames() {
}
// Obtiene una fichero a partir de un lang::Code
std::string getLanguageFileName(Lang::Code code) {
auto getLanguageFileName(Lang::Code code) -> std::string {
for (const auto &lang : languages) {
if (lang.code == code)
return Asset::get()->get(lang.file_name);

View File

@@ -11,7 +11,7 @@ Actualizando a la versión "Arcade Edition" en 08/05/2024
#include "director.h" // Para Director
int main(int argc, char *argv[]) {
auto main(int argc, char *argv[]) -> int {
// Crea el objeto Director
auto director = std::make_unique<Director>(argc, const_cast<const char **>(argv));

View File

@@ -13,22 +13,22 @@ void ManageHiScoreTable::clear() {
table_.clear();
// Añade 10 entradas predefinidas
table_.push_back(HiScoreEntry("BRY", 1000000));
table_.push_back(HiScoreEntry("USUFO", 500000));
table_.push_back(HiScoreEntry("GLUCA", 100000));
table_.push_back(HiScoreEntry("PARRA", 50000));
table_.push_back(HiScoreEntry("CAGAM", 10000));
table_.push_back(HiScoreEntry("PEPE", 5000));
table_.push_back(HiScoreEntry("ROSIT", 1000));
table_.push_back(HiScoreEntry("SAM", 500));
table_.push_back(HiScoreEntry("PACMQ", 200));
table_.push_back(HiScoreEntry("PELEC", 100));
table_.emplace_back("BRY", 1000000);
table_.emplace_back("USUFO", 500000);
table_.emplace_back("GLUCA", 100000);
table_.emplace_back("PARRA", 50000);
table_.emplace_back("CAGAM", 10000);
table_.emplace_back("PEPE", 5000);
table_.emplace_back("ROSIT", 1000);
table_.emplace_back("SAM", 500);
table_.emplace_back("PACMQ", 200);
table_.emplace_back("PELEC", 100);
sort();
}
// Añade un elemento a la tabla
int ManageHiScoreTable::add(const HiScoreEntry &entry) {
auto ManageHiScoreTable::add(const HiScoreEntry &entry) -> int {
// Añade la entrada a la tabla
table_.push_back(entry);
@@ -63,14 +63,14 @@ int ManageHiScoreTable::add(const HiScoreEntry &entry) {
void ManageHiScoreTable::sort() {
struct
{
bool operator()(const HiScoreEntry &a, const HiScoreEntry &b) const { return a.score > b.score; }
auto operator()(const HiScoreEntry &a, const HiScoreEntry &b) const -> bool { return a.score > b.score; }
} score_descending_comparator;
std::sort(table_.begin(), table_.end(), score_descending_comparator);
}
// Carga la tabla desde un fichero
bool ManageHiScoreTable::loadFromFile(const std::string &file_path) {
auto ManageHiScoreTable::loadFromFile(const std::string &file_path) -> bool {
clear();
auto success = true;
auto file = SDL_IOFromFile(file_path.c_str(), "rb");
@@ -117,7 +117,7 @@ bool ManageHiScoreTable::loadFromFile(const std::string &file_path) {
}
// Guarda la tabla en un fichero
bool ManageHiScoreTable::saveToFile(const std::string &file_path) {
auto ManageHiScoreTable::saveToFile(const std::string &file_path) -> bool {
auto success = true;
auto file = SDL_IOFromFile(file_path.c_str(), "w+b");

View File

@@ -36,13 +36,13 @@ class ManageHiScoreTable {
void clear();
// Añade un elemento a la tabla (devuelve la posición en la que se inserta)
int add(const HiScoreEntry &entry);
auto add(const HiScoreEntry &entry) -> int;
// Carga la tabla con los datos de un fichero
bool loadFromFile(const std::string &file_path);
auto loadFromFile(const std::string &file_path) -> bool;
// Guarda la tabla en un fichero
bool saveToFile(const std::string &file_path);
auto saveToFile(const std::string &file_path) -> bool;
private:
// Referencia a la tabla con los records

View File

@@ -23,8 +23,7 @@ MovingSprite::MovingSprite(std::shared_ptr<Texture> texture, SDL_FRect pos)
MovingSprite::MovingSprite(std::shared_ptr<Texture> texture)
: Sprite(texture),
x_(0.0f),
y_(0.0f),
rotate_(Rotate()),
zoom_w_(1.0f),
zoom_h_(1.0f),

View File

@@ -4,6 +4,7 @@
#include <algorithm> // Para remove_if
#include <string> // Para basic_string, string
#include <utility>
#include <vector> // Para vector
#include "audio.h" // Para Audio
@@ -23,13 +24,13 @@ void Notifier::init(const std::string &icon_file, std::shared_ptr<Text> text) {
void Notifier::destroy() { delete Notifier::instance; }
// Obtiene la instancia
Notifier *Notifier::get() { return Notifier::instance; }
auto Notifier::get() -> Notifier * { return Notifier::instance; }
// Constructor
Notifier::Notifier(std::string icon_file, std::shared_ptr<Text> text)
: renderer_(Screen::get()->getRenderer()),
icon_texture_(!icon_file.empty() ? std::make_unique<Texture>(renderer_, icon_file) : nullptr),
text_(text),
text_(std::move(text)),
bg_color_(param.notification.color),
wait_time_(150),
stack_(false),
@@ -264,7 +265,7 @@ void Notifier::clearAllNotifications() {
}
// Obtiene los códigos de las notificaciones
std::vector<std::string> Notifier::getCodes() {
auto Notifier::getCodes() -> std::vector<std::string> {
std::vector<std::string> codes;
for (const auto &notification : notifications_) {
codes.emplace_back(notification.code);

View File

@@ -18,7 +18,7 @@ class Notifier {
// --- Métodos de singleton ---
static void init(const std::string &icon_file, std::shared_ptr<Text> text); // Inicializa el singleton
static void destroy(); // Libera el singleton
static Notifier *get(); // Obtiene la instancia
static auto get() -> Notifier *; // Obtiene la instancia
// --- Métodos principales ---
void render(); // Dibuja las notificaciones por pantalla
@@ -26,9 +26,9 @@ class Notifier {
// --- Gestión de notificaciones ---
void show(std::vector<std::string> texts, int icon = -1, const std::string &code = std::string()); // Muestra una notificación de texto por pantalla
bool isActive() const { return !notifications_.empty(); } // Indica si hay notificaciones activas
std::vector<std::string> getCodes(); // Obtiene los códigos de las notificaciones activas
bool checkCode(const std::string &code) { return stringInVector(getCodes(), code); } // Comprueba si hay alguna notificación con un código concreto
[[nodiscard]] auto isActive() const -> bool { return !notifications_.empty(); } // Indica si hay notificaciones activas
auto getCodes() -> std::vector<std::string>; // Obtiene los códigos de las notificaciones activas
auto checkCode(const std::string &code) -> bool { return stringInVector(getCodes(), code); } // Comprueba si hay alguna notificación con un código concreto
private:
// --- Singleton ---
@@ -52,17 +52,17 @@ class Notifier {
std::shared_ptr<Texture> texture; // Textura de la notificación
std::shared_ptr<Sprite> sprite; // Sprite asociado
std::vector<std::string> texts; // Textos a mostrar
int counter; // Contador de tiempo
NotificationStatus state; // Estado de la notificación
NotificationShape shape; // Forma de la notificación
int counter{0}; // Contador de tiempo
NotificationStatus state{NotificationStatus::RISING}; // Estado de la notificación
NotificationShape shape{NotificationShape::SQUARED}; // Forma de la notificación
SDL_FRect rect; // Rectángulo de la notificación
int y; // Posición vertical
int travel_dist; // Distancia a recorrer
int y{0}; // Posición vertical
int travel_dist{0}; // Distancia a recorrer
std::string code; // Código identificador de la notificación
// Constructor
explicit Notification()
: texture(nullptr), sprite(nullptr), texts(), counter(0), state(NotificationStatus::RISING), shape(NotificationShape::SQUARED), rect{0, 0, 0, 0}, y(0), travel_dist(0), code("") {}
: texture(nullptr), sprite(nullptr), texts(), rect{0, 0, 0, 0}, code("") {}
};
// --- Objetos y punteros ---

View File

@@ -28,7 +28,7 @@ std::vector<Difficulty> difficulties = {
{DifficultyCode::HARD, "Hard"}};
// Declaraciones
bool set(const std::string &var, const std::string &value);
auto set(const std::string &var, const std::string &value) -> bool;
// Inicializa las opciones del programa
void init() {
@@ -49,7 +49,7 @@ void init() {
}
// Carga el fichero de configuración
bool loadFromFile() {
auto loadFromFile() -> bool {
// Inicializa las opciones del programa
init();
@@ -94,7 +94,7 @@ bool loadFromFile() {
}
// Guarda el fichero de configuración
bool saveToFile() {
auto saveToFile() -> bool {
std::ofstream file(settings.config_file);
if (!file.good()) {
@@ -167,7 +167,7 @@ bool saveToFile() {
}
// Asigna variables a partir de dos cadenas
bool set(const std::string &var, const std::string &value) {
auto set(const std::string &var, const std::string &value) -> bool {
// Indicador de éxito en la asignación
auto success = true;
@@ -281,7 +281,7 @@ void swapControllers() {
}
// Averigua quien está usando el teclado
int getPlayerWhoUsesKeyboard() {
auto getPlayerWhoUsesKeyboard() -> int {
for (const auto &controller : controllers) {
if (controller.type == InputDevice::ANY) {
return controller.player_id;
@@ -308,7 +308,7 @@ void checkPendingChanges() {
}
}
DifficultyCode getDifficultyCodeFromName(const std::string &name) {
auto getDifficultyCodeFromName(const std::string &name) -> DifficultyCode {
for (const auto &difficulty : difficulties) {
if (difficulty.name == name)
return difficulty.code;
@@ -317,7 +317,7 @@ DifficultyCode getDifficultyCodeFromName(const std::string &name) {
return difficulties[0].code;
}
std::string getDifficultyNameFromCode(DifficultyCode code) {
auto getDifficultyNameFromCode(DifficultyCode code) -> std::string {
for (const auto &difficulty : difficulties) {
if (difficulty.code == code)
return difficulty.name;

View File

@@ -3,6 +3,7 @@
#include <SDL3/SDL.h> // Para SDL_GamepadButton, SDL_ScaleMode
#include <string> // Para string, basic_string
#include <utility>
#include <vector> // Para vector
#include "input.h" // Para InputAction, InputDevice
@@ -24,96 +25,83 @@ struct Difficulty {
DifficultyCode code; // Código que identifica la dificultad
std::string name; // Nombre que identifica la dificultad
Difficulty(DifficultyCode c, const std::string &n)
: code(c), name(n) {}
Difficulty(DifficultyCode c, std::string n)
: code(c), name(std::move(n)) {}
};
// --- Opciones de ventana ---
struct WindowOptions {
std::string caption; // Texto que aparece en la barra de título de la ventana
int size; // Valor por el que se multiplica el tamaño de la ventana
int max_size; // Tamaño máximo para que la ventana no sea mayor que la pantalla
int size{2}; // Valor por el que se multiplica el tamaño de la ventana
int max_size{2}; // Tamaño máximo para que la ventana no sea mayor que la pantalla
// Constructor por defecto con valores iniciales
WindowOptions()
: caption("Coffee Crisis Arcade Edition"),
size(2),
max_size(2) {}
: caption("Coffee Crisis Arcade Edition") {}
};
// --- Opciones de vídeo ---
struct VideoOptions {
SDL_ScaleMode scale_mode; // Filtro usado para el escalado de la imagen
bool fullscreen; // Indica si se usa pantalla completa
bool v_sync; // Indica si se usa vsync
bool integer_scale; // Indica si se usa escalado entero
bool shaders; // Indica si se usan shaders para los filtros de vídeo
SDL_ScaleMode scale_mode{SDL_ScaleMode::SDL_SCALEMODE_NEAREST}; // Filtro usado para el escalado de la imagen
bool fullscreen{false}; // Indica si se usa pantalla completa
bool v_sync{true}; // Indica si se usa vsync
bool integer_scale{true}; // Indica si se usa escalado entero
bool shaders{false}; // Indica si se usan shaders para los filtros de vídeo
std::string info; // Información sobre el modo de vídeo
// Constructor por defecto con valores iniciales
VideoOptions()
: scale_mode(SDL_ScaleMode::SDL_SCALEMODE_NEAREST),
fullscreen(false),
v_sync(true),
integer_scale(true),
shaders(false),
info() {}
: info() {}
};
// --- Opciones de música ---
struct MusicOptions {
bool enabled; // Indica si la música suena o no
int volume; // Volumen de la música
bool enabled{true}; // Indica si la música suena o no
int volume{100}; // Volumen de la música
// Constructor por defecto
MusicOptions()
: enabled(true),
volume(100) {}
{}
};
// --- Opciones de sonido ---
struct SoundOptions {
bool enabled; // Indica si los sonidos suenan o no
int volume; // Volumen de los sonidos
bool enabled{true}; // Indica si los sonidos suenan o no
int volume{100}; // Volumen de los sonidos
// Constructor por defecto
SoundOptions()
: enabled(true),
volume(100) {}
{}
};
// --- Opciones de audio ---
struct AudioOptions {
MusicOptions music; // Opciones para la música
SoundOptions sound; // Opciones para los efectos de sonido
bool enabled; // Indica si el audio está activo o no
int volume; // Volumen general del audio
bool enabled{true}; // Indica si el audio está activo o no
int volume{100}; // Volumen general del audio
// Constructor por defecto
AudioOptions()
: music(),
sound(),
enabled(true),
volume(100) {}
sound() {}
};
// --- Opciones de configuración ---
struct SettingsOptions {
DifficultyCode difficulty; // Dificultad del juego
Lang::Code language; // Idioma usado en el juego
bool autofire; // Indicador de autofire
bool shutdown_enabled; // Especifica si se puede apagar el sistema
DifficultyCode difficulty{DifficultyCode::NORMAL}; // Dificultad del juego
Lang::Code language{Lang::Code::VALENCIAN}; // Idioma usado en el juego
bool autofire{true}; // Indicador de autofire
bool shutdown_enabled{false}; // Especifica si se puede apagar el sistema
std::vector<HiScoreEntry> hi_score_table; // Tabla de mejores puntuaciones
std::vector<int> last_hi_score_entry; // Últimas posiciones de entrada en la tabla
std::string config_file; // Ruta al fichero donde guardar la configuración y las opciones del juego
// Constructor por defecto con valores iniciales
SettingsOptions()
: difficulty(DifficultyCode::NORMAL),
language(Lang::Code::VALENCIAN),
autofire(true),
shutdown_enabled(false),
last_hi_score_entry({INVALID_INDEX, INVALID_INDEX}),
: last_hi_score_entry({INVALID_INDEX, INVALID_INDEX}),
config_file() {}
// Reinicia las últimas entradas de puntuación
@@ -127,9 +115,9 @@ struct SettingsOptions {
struct GamepadOptions {
int index; // Índice en el vector de mandos
int player_id; // Jugador asociado al mando
InputDevice type; // Indica si se usará teclado, mando o ambos
InputDevice type{InputDevice::CONTROLLER}; // Indica si se usará teclado, mando o ambos
std::string name; // Nombre del dispositivo
bool plugged; // Indica si el mando está conectado
bool plugged{false}; // Indica si el mando está conectado
std::vector<InputAction> inputs; // Listado de acciones asignadas
std::vector<SDL_GamepadButton> buttons; // Listado de botones asignados a cada acción
@@ -137,9 +125,9 @@ struct GamepadOptions {
GamepadOptions()
: index(INVALID_INDEX),
player_id(INVALID_INDEX),
type(InputDevice::CONTROLLER),
name(),
plugged(false),
inputs{
InputAction::FIRE_LEFT,
InputAction::FIRE_CENTER,
@@ -156,15 +144,14 @@ struct GamepadOptions {
// --- Opciones pendientes de aplicar ---
struct PendingChanges {
Lang::Code new_language; // Idioma en espera de aplicar
DifficultyCode new_difficulty; // Dificultad en espera de aplicar
bool has_pending_changes; // Indica si hay cambios pendientes
Lang::Code new_language{Lang::Code::VALENCIAN}; // Idioma en espera de aplicar
DifficultyCode new_difficulty{DifficultyCode::NORMAL}; // Dificultad en espera de aplicar
bool has_pending_changes{false}; // Indica si hay cambios pendientes
// Constructor por defecto con valores iniciales
PendingChanges()
: new_language(Lang::Code::VALENCIAN),
new_difficulty(DifficultyCode::NORMAL),
has_pending_changes(false) {}
{}
};
// --- Variables globales ---
@@ -178,14 +165,14 @@ extern std::vector<Difficulty> difficulties; // Lista de los diferentes tipo
// --- Funciones de configuración ---
void init(); // Inicializa las opciones del programa
bool loadFromFile(); // Carga el fichero de configuración
bool saveToFile(); // Guarda el fichero de configuración
auto loadFromFile() -> bool; // Carga el fichero de configuración
auto saveToFile() -> bool; // Guarda el fichero de configuración
void setKeyboardToPlayer(int player_id); // Asigna el teclado al jugador
void swapKeyboard(); // Intercambia el teclado de jugador
void swapControllers(); // Intercambia los jugadores asignados a los dos primeros mandos
int getPlayerWhoUsesKeyboard(); // Averigua quién está usando el teclado
auto getPlayerWhoUsesKeyboard() -> int; // Averigua quién está usando el teclado
void applyPendingChanges(); // Aplica los cambios pendientes copiando los valores a sus variables
void checkPendingChanges(); // Verifica si hay cambios pendientes
DifficultyCode getDifficultyCodeFromName(const std::string &name); // Obtiene el código de dificultad a partir del nombre
std::string getDifficultyNameFromCode(DifficultyCode code); // Obtiene el nombre de la dificultad a partir del código
auto getDifficultyCodeFromName(const std::string &name) -> DifficultyCode; // Obtiene el código de dificultad a partir del nombre
auto getDifficultyNameFromCode(DifficultyCode code) -> std::string; // Obtiene el nombre de la dificultad a partir del código
} // namespace Options

View File

@@ -15,7 +15,7 @@ Param param;
void precalculateZones();
// Asigna variables a partir de dos cadenas
bool setParams(const std::string &var, const std::string &value);
auto setParams(const std::string &var, const std::string &value) -> bool;
// Establece valores por defecto a las variables
void initParam() {
@@ -127,7 +127,7 @@ void loadParamsFromFile(const std::string &file_path) {
}
// Asigna variables a partir de dos cadenas
bool setParams(const std::string &var, const std::string &value) {
auto setParams(const std::string &var, const std::string &value) -> bool {
// Indicador de éxito en la asignación
auto success = true;

View File

@@ -6,7 +6,7 @@
#include <utility> // Para move
// Devuelve un vector con los puntos que conforman la ruta
std::vector<SDL_FPoint> createPath(float start, float end, PathType type, float fixed_pos, int steps, const std::function<double(double)> &easing_function) {
auto createPath(float start, float end, PathType type, float fixed_pos, int steps, const std::function<double(double)> &easing_function) -> std::vector<SDL_FPoint> {
std::vector<SDL_FPoint> v;
v.reserve(steps);
@@ -141,4 +141,4 @@ void PathSprite::goToNextPathOrDie() {
}
// Indica si ha terminado todos los recorridos
bool PathSprite::hasFinished() { return has_finished_; }
auto PathSprite::hasFinished() -> bool { return has_finished_; }

View File

@@ -37,7 +37,7 @@ struct Path {
};
// Devuelve un vector con los puntos que conforman la ruta
std::vector<SDL_FPoint> createPath(float start, float end, PathType type, float fixed_pos, int steps, const std::function<double(double)> &easing_function);
auto createPath(float start, float end, PathType type, float fixed_pos, int steps, const std::function<double(double)> &easing_function) -> std::vector<SDL_FPoint>;
// --- Clase PathSprite: Sprite que sigue uno o varios recorridos ---
class PathSprite : public Sprite {
@@ -58,10 +58,10 @@ class PathSprite : public Sprite {
// --- Estado y control ---
void enable(); // Habilita el objeto
bool hasFinished(); // Indica si ha terminado todos los recorridos
auto hasFinished() -> bool; // Indica si ha terminado todos los recorridos
// --- Getters ---
int getCurrentPath() const { return current_path_; } // Devuelve el índice del recorrido actual
[[nodiscard]] auto getCurrentPath() const -> int { return current_path_; } // Devuelve el índice del recorrido actual
private:
// --- Variables internas ---

View File

@@ -1,9 +1,9 @@
#include "player.h"
#include <SDL3/SDL.h> // Para SDL_GetTicks, SDL_FlipMode, SDL_FRect
#include <stdlib.h> // Para rand
#include <algorithm> // Para clamp, max, min
#include <cstdlib> // Para rand
#include "animated_sprite.h" // Para AnimatedSprite
#include "asset.h" // Para Asset
@@ -772,7 +772,7 @@ void Player::decNameEntryCounter() {
}
// Obtiene la posición que se está editando del nombre del jugador para la tabla de mejores puntuaciones
int Player::getRecordNamePos() const {
auto Player::getRecordNamePos() const -> int {
if (enter_name_) {
return enter_name_->getPosition();
}

View File

@@ -101,50 +101,50 @@ class Player {
void decContinueCounter(); // Decrementa el contador de continuar
// --- Getters y comprobaciones de estado ---
int getRecordNamePos() const; // Obtiene la posición que se está editando del nombre del jugador para la tabla de mejores puntuaciones
[[nodiscard]] auto getRecordNamePos() const -> int; // Obtiene la posición que se está editando del nombre del jugador para la tabla de mejores puntuaciones
// Comprobación de playing_state
bool isLyingOnTheFloorForever() const { return playing_state_ == PlayerState::LYING_ON_THE_FLOOR_FOREVER; }
bool isCelebrating() const { return playing_state_ == PlayerState::CELEBRATING; }
bool isContinue() const { return playing_state_ == PlayerState::CONTINUE; }
bool isDying() const { return playing_state_ == PlayerState::ROLLING; }
bool isEnteringName() const { return playing_state_ == PlayerState::ENTERING_NAME; }
bool isShowingName() const { return playing_state_ == PlayerState::SHOWING_NAME; }
bool isEnteringNameGameCompleted() const { return playing_state_ == PlayerState::ENTERING_NAME_GAME_COMPLETED; }
bool isLeavingScreen() const { return playing_state_ == PlayerState::LEAVING_SCREEN; }
bool isGameOver() const { return playing_state_ == PlayerState::GAME_OVER; }
bool isPlaying() const { return playing_state_ == PlayerState::PLAYING; }
bool isWaiting() const { return playing_state_ == PlayerState::WAITING; }
bool isTitleHidden() const { return playing_state_ == PlayerState::TITLE_HIDDEN; }
[[nodiscard]] auto isLyingOnTheFloorForever() const -> bool { return playing_state_ == PlayerState::LYING_ON_THE_FLOOR_FOREVER; }
[[nodiscard]] auto isCelebrating() const -> bool { return playing_state_ == PlayerState::CELEBRATING; }
[[nodiscard]] auto isContinue() const -> bool { return playing_state_ == PlayerState::CONTINUE; }
[[nodiscard]] auto isDying() const -> bool { return playing_state_ == PlayerState::ROLLING; }
[[nodiscard]] auto isEnteringName() const -> bool { return playing_state_ == PlayerState::ENTERING_NAME; }
[[nodiscard]] auto isShowingName() const -> bool { return playing_state_ == PlayerState::SHOWING_NAME; }
[[nodiscard]] auto isEnteringNameGameCompleted() const -> bool { return playing_state_ == PlayerState::ENTERING_NAME_GAME_COMPLETED; }
[[nodiscard]] auto isLeavingScreen() const -> bool { return playing_state_ == PlayerState::LEAVING_SCREEN; }
[[nodiscard]] auto isGameOver() const -> bool { return playing_state_ == PlayerState::GAME_OVER; }
[[nodiscard]] auto isPlaying() const -> bool { return playing_state_ == PlayerState::PLAYING; }
[[nodiscard]] auto isWaiting() const -> bool { return playing_state_ == PlayerState::WAITING; }
[[nodiscard]] auto isTitleHidden() const -> bool { return playing_state_ == PlayerState::TITLE_HIDDEN; }
// Getters
bool canFire() const { return cant_fire_counter_ <= 0; }
bool hasExtraHit() const { return extra_hit_; }
bool isCooling() const { return firing_state_ == PlayerState::COOLING_LEFT || firing_state_ == PlayerState::COOLING_UP || firing_state_ == PlayerState::COOLING_RIGHT; }
bool isRecoiling() const { return firing_state_ == PlayerState::RECOILING_LEFT || firing_state_ == PlayerState::RECOILING_UP || firing_state_ == PlayerState::RECOILING_RIGHT; }
bool isEligibleForHighScore() const { return score_ > Options::settings.hi_score_table.back().score; }
bool isInvulnerable() const { return invulnerable_; }
bool isPowerUp() const { return power_up_; }
Circle &getCollider() { return collider_; }
float getScoreMultiplier() const { return score_multiplier_; }
int getCoffees() const { return coffees_; }
int getContinueCounter() const { return continue_counter_; }
int getController() const { return controller_index_; }
int getHeight() const { return HEIGHT; }
int getId() const { return id_; }
int getInvulnerableCounter() const { return invulnerable_counter_; }
int getPosX() const { return static_cast<int>(pos_x_); }
int getPosY() const { return pos_y_; }
int getPowerUpCounter() const { return power_up_counter_; }
std::string getRecordName() const { return enter_name_ ? enter_name_->getFinalName() : "xxx"; }
std::string getLastEnterName() const { return last_enter_name_; }
int getScore() const { return score_; }
int getScoreBoardPanel() const { return scoreboard_panel_; }
int getWidth() const { return WIDTH; }
PlayerState getPlayingState() const { return playing_state_; }
const std::string &getName() const { return name_; }
bool get1CC() const { return game_completed_ && credits_used_ == 1; }
bool getEnterNamePositionOverflow() const { return enter_name_ ? enter_name_->getPositionOverflow() : false; }
[[nodiscard]] auto canFire() const -> bool { return cant_fire_counter_ <= 0; }
[[nodiscard]] auto hasExtraHit() const -> bool { return extra_hit_; }
[[nodiscard]] auto isCooling() const -> bool { return firing_state_ == PlayerState::COOLING_LEFT || firing_state_ == PlayerState::COOLING_UP || firing_state_ == PlayerState::COOLING_RIGHT; }
[[nodiscard]] auto isRecoiling() const -> bool { return firing_state_ == PlayerState::RECOILING_LEFT || firing_state_ == PlayerState::RECOILING_UP || firing_state_ == PlayerState::RECOILING_RIGHT; }
[[nodiscard]] auto isEligibleForHighScore() const -> bool { return score_ > Options::settings.hi_score_table.back().score; }
[[nodiscard]] auto isInvulnerable() const -> bool { return invulnerable_; }
[[nodiscard]] auto isPowerUp() const -> bool { return power_up_; }
auto getCollider() -> Circle & { return collider_; }
[[nodiscard]] auto getScoreMultiplier() const -> float { return score_multiplier_; }
[[nodiscard]] auto getCoffees() const -> int { return coffees_; }
[[nodiscard]] auto getContinueCounter() const -> int { return continue_counter_; }
[[nodiscard]] auto getController() const -> int { return controller_index_; }
[[nodiscard]] auto getHeight() const -> int { return HEIGHT; }
[[nodiscard]] auto getId() const -> int { return id_; }
[[nodiscard]] auto getInvulnerableCounter() const -> int { return invulnerable_counter_; }
[[nodiscard]] auto getPosX() const -> int { return static_cast<int>(pos_x_); }
[[nodiscard]] auto getPosY() const -> int { return pos_y_; }
[[nodiscard]] auto getPowerUpCounter() const -> int { return power_up_counter_; }
[[nodiscard]] auto getRecordName() const -> std::string { return enter_name_ ? enter_name_->getFinalName() : "xxx"; }
[[nodiscard]] auto getLastEnterName() const -> std::string { return last_enter_name_; }
[[nodiscard]] auto getScore() const -> int { return score_; }
[[nodiscard]] auto getScoreBoardPanel() const -> int { return scoreboard_panel_; }
[[nodiscard]] auto getWidth() const -> int { return WIDTH; }
[[nodiscard]] auto getPlayingState() const -> PlayerState { return playing_state_; }
[[nodiscard]] auto getName() const -> const std::string & { return name_; }
[[nodiscard]] auto get1CC() const -> bool { return game_completed_ && credits_used_ == 1; }
[[nodiscard]] auto getEnterNamePositionOverflow() const -> bool { return enter_name_ ? enter_name_->getPositionOverflow() : false; }
// Setters inline
void setController(int index) { controller_index_ = index; }
@@ -226,6 +226,6 @@ class Player {
void updateScoreboard(); // Actualiza el panel del marcador
void setScoreboardMode(ScoreboardMode mode); // Cambia el modo del marcador
void playSound(const std::string &name); // Hace sonar un sonido
bool isRenderable() const { return !isWaiting() && !isGameOver() && !isTitleHidden(); }
[[nodiscard]] auto isRenderable() const -> bool { return !isWaiting() && !isGameOver() && !isTitleHidden(); }
void addScoreToScoreBoard(); // Añade una puntuación a la tabla de records
};

View File

@@ -1,11 +1,12 @@
#include "resource.h"
#include <SDL3/SDL.h> // Para SDL_LogInfo, SDL_LogCategory, SDL_L...
#include <stdlib.h> // Para exit
#include <algorithm> // Para find_if
#include <array> // Para array
#include <cstdlib> // Para exit
#include <stdexcept> // Para runtime_error
#include <utility>
#include "asset.h" // Para Asset, AssetType
#include "external/jail_audio.h" // Para JA_DeleteMusic, JA_DeleteSound, JA_...
@@ -27,7 +28,7 @@ void Resource::init() { Resource::instance = new Resource(); }
void Resource::destroy() { delete Resource::instance; }
// Obtiene la instancia
Resource *Resource::get() { return Resource::instance; }
auto Resource::get() -> Resource * { return Resource::instance; }
// Constructor
Resource::Resource() : loading_text_(Screen::get()->getText()) { load(); }
@@ -87,7 +88,7 @@ void Resource::reloadTextures() {
}
// Obtiene el sonido a partir de un nombre. Lanza excepción si no existe.
JA_Sound_t *Resource::getSound(const std::string &name) {
auto Resource::getSound(const std::string &name) -> JA_Sound_t * {
auto it = std::find_if(sounds_.begin(), sounds_.end(), [&name](const auto &s) { return s.name == name; });
if (it != sounds_.end()) {
@@ -99,7 +100,7 @@ JA_Sound_t *Resource::getSound(const std::string &name) {
}
// Obtiene la música a partir de un nombre. Lanza excepción si no existe.
JA_Music_t *Resource::getMusic(const std::string &name) {
auto Resource::getMusic(const std::string &name) -> JA_Music_t * {
auto it = std::find_if(musics_.begin(), musics_.end(), [&name](const auto &m) { return m.name == name; });
if (it != musics_.end()) {
@@ -111,7 +112,7 @@ JA_Music_t *Resource::getMusic(const std::string &name) {
}
// Obtiene la textura a partir de un nombre. Lanza excepción si no existe.
std::shared_ptr<Texture> Resource::getTexture(const std::string &name) {
auto Resource::getTexture(const std::string &name) -> std::shared_ptr<Texture> {
auto it = std::find_if(textures_.begin(), textures_.end(), [&name](const auto &t) { return t.name == name; });
if (it != textures_.end()) {
@@ -123,7 +124,7 @@ std::shared_ptr<Texture> Resource::getTexture(const std::string &name) {
}
// Obtiene el fichero de texto a partir de un nombre. Lanza excepción si no existe.
std::shared_ptr<TextFile> Resource::getTextFile(const std::string &name) {
auto Resource::getTextFile(const std::string &name) -> std::shared_ptr<TextFile> {
auto it = std::find_if(text_files_.begin(), text_files_.end(), [&name](const auto &t) { return t.name == name; });
if (it != text_files_.end()) {
@@ -135,7 +136,7 @@ std::shared_ptr<TextFile> Resource::getTextFile(const std::string &name) {
}
// Obtiene el objeto de texto a partir de un nombre. Lanza excepción si no existe.
std::shared_ptr<Text> Resource::getText(const std::string &name) {
auto Resource::getText(const std::string &name) -> std::shared_ptr<Text> {
auto it = std::find_if(texts_.begin(), texts_.end(), [&name](const auto &t) { return t.name == name; });
if (it != texts_.end()) {
@@ -147,7 +148,7 @@ std::shared_ptr<Text> Resource::getText(const std::string &name) {
}
// Obtiene la animación a partir de un nombre. Lanza excepción si no existe.
AnimationsFileBuffer &Resource::getAnimation(const std::string &name) {
auto Resource::getAnimation(const std::string &name) -> AnimationsFileBuffer & {
auto it = std::find_if(animations_.begin(), animations_.end(), [&name](const auto &a) { return a.name == name; });
if (it != animations_.end()) {
@@ -159,7 +160,7 @@ AnimationsFileBuffer &Resource::getAnimation(const std::string &name) {
}
// Obtiene el fichero con los datos para el modo demostración a partir de un índice
DemoData &Resource::getDemoData(int index) {
auto Resource::getDemoData(int index) -> DemoData & {
return demos_.at(index);
}
@@ -172,7 +173,7 @@ void Resource::loadSounds() {
for (const auto &l : list) {
auto name = getFileName(l);
updateLoadingProgress(name);
sounds_.emplace_back(Resource::ResourceSound(name, JA_LoadSound(l.c_str())));
sounds_.emplace_back(name, JA_LoadSound(l.c_str()));
printWithDots("Sound : ", name, "[ LOADED ]");
}
}
@@ -186,7 +187,7 @@ void Resource::loadMusics() {
for (const auto &l : list) {
auto name = getFileName(l);
updateLoadingProgress(name);
musics_.emplace_back(Resource::ResourceMusic(name, JA_LoadMusic(l.c_str())));
musics_.emplace_back(name, JA_LoadMusic(l.c_str()));
printWithDots("Music : ", name, "[ LOADED ]");
}
}
@@ -200,7 +201,7 @@ void Resource::loadTextures() {
for (const auto &l : list) {
auto name = getFileName(l);
updateLoadingProgress(name);
textures_.emplace_back(Resource::ResourceTexture(name, std::make_shared<Texture>(Screen::get()->getRenderer(), l)));
textures_.emplace_back(name, std::make_shared<Texture>(Screen::get()->getRenderer(), l));
}
}
@@ -213,7 +214,7 @@ void Resource::loadTextFiles() {
for (const auto &l : list) {
auto name = getFileName(l);
updateLoadingProgress(name);
text_files_.emplace_back(Resource::ResourceTextFile(name, loadTextFile(l)));
text_files_.emplace_back(name, loadTextFile(l));
}
}
@@ -226,7 +227,7 @@ void Resource::loadAnimations() {
for (const auto &l : list) {
auto name = getFileName(l);
updateLoadingProgress(name);
animations_.emplace_back(Resource::ResourceAnimation(name, loadAnimationsFromFile(l)));
animations_.emplace_back(name, loadAnimationsFromFile(l));
}
}
@@ -263,8 +264,8 @@ void Resource::createTextures() {
std::string name;
std::string text;
NameAndText(const std::string &name_init, const std::string &text_init)
: name(name_init), text(text_init) {}
NameAndText(std::string name_init, std::string text_init)
: name(std::move(name_init)), text(std::move(text_init)) {}
};
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "\n>> CREATING TEXTURES");
@@ -281,7 +282,7 @@ void Resource::createTextures() {
auto text = getText("04b_25");
for (const auto &s : strings) {
textures_.emplace_back(Resource::ResourceTexture(s.name, text->writeToTexture(s.text, 1, -2)));
textures_.emplace_back(s.name, text->writeToTexture(s.text, 1, -2));
printWithDots("Texture : ", s.name, "[ DONE ]");
}
@@ -295,7 +296,7 @@ void Resource::createTextures() {
auto text2 = getText("04b_25_2x");
for (const auto &s : strings2_x) {
textures_.emplace_back(Resource::ResourceTexture(s.name, text2->writeToTexture(s.text, 1, -4)));
textures_.emplace_back(s.name, text2->writeToTexture(s.text, 1, -4));
printWithDots("Texture : ", s.name, "[ DONE ]");
}
}
@@ -307,8 +308,8 @@ void Resource::createText() {
std::string texture_file;
std::string text_file;
ResourceInfo(const std::string &k, const std::string &t_file, const std::string &txt_file)
: key(k), texture_file(t_file), text_file(txt_file) {}
ResourceInfo(std::string k, std::string t_file, std::string txt_file)
: key(std::move(k)), texture_file(std::move(t_file)), text_file(std::move(txt_file)) {}
};
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "\n>> CREATING TEXT OBJECTS");
@@ -328,7 +329,7 @@ void Resource::createText() {
{"smb2_grad", "smb2_grad.png", "smb2.txt"}};
for (const auto &resource : resources) {
texts_.emplace_back(Resource::ResourceText(resource.key, std::make_shared<Text>(getTexture(resource.texture_file), getTextFile(resource.text_file))));
texts_.emplace_back(resource.key, std::make_shared<Text>(getTexture(resource.texture_file), getTextFile(resource.text_file)));
printWithDots("Text : ", resource.key, "[ DONE ]");
}
}

View File

@@ -1,8 +1,8 @@
#pragma once
#include <SDL3/SDL.h> // Para SDL_FRect
#include <stddef.h> // Para size_t
#include <cstddef> // Para size_t
#include <memory> // Para shared_ptr
#include <string> // Para basic_string, string
#include <utility>

View File

@@ -1,8 +1,8 @@
#include "scoreboard.h"
#include <SDL3/SDL.h> // Para SDL_DestroyTexture, SDL_SetRenderDrawColor
#include <math.h> // Para roundf
#include <cmath> // Para roundf
#include <iomanip> // Para operator<<, setfill, setw
#include <sstream> // Para basic_ostringstream, basic_ostream, basic_os...
@@ -29,7 +29,7 @@ void Scoreboard::destroy() {
}
// [SINGLETON] Con este método obtenemos el objeto score_board y podemos trabajar con él
Scoreboard *Scoreboard::get() {
auto Scoreboard::get() -> Scoreboard * {
return Scoreboard::instance;
}
@@ -88,7 +88,7 @@ Scoreboard::~Scoreboard() {
}
// Transforma un valor numérico en una cadena de 7 cifras
std::string Scoreboard::updateScoreText(int num) {
auto Scoreboard::updateScoreText(int num) -> std::string {
std::ostringstream oss;
oss << std::setw(7) << std::setfill('0') << num;
return oss.str();
@@ -385,8 +385,8 @@ void Scoreboard::createPanelTextures() {
panel_texture_.clear();
// Crea las texturas para cada panel_
for (int i = 0; i < SCOREBOARD_MAX_PANELS; ++i) {
SDL_Texture *tex = SDL_CreateTexture(renderer_, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, panel_[i].pos.w, panel_[i].pos.h);
for (auto &i : panel_) {
SDL_Texture *tex = SDL_CreateTexture(renderer_, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, i.pos.w, i.pos.h);
SDL_SetTextureBlendMode(tex, SDL_BLENDMODE_BLEND);
panel_texture_.push_back(tex);
}

View File

@@ -1,8 +1,8 @@
#pragma once
#include <SDL3/SDL.h> // Para SDL_FPoint, SDL_GetTicks, SDL_FRect, SDL_Texture, SDL_Renderer, Uint64
#include <stddef.h> // Para size_t
#include <cstddef> // Para size_t
#include <memory> // Para shared_ptr, unique_ptr
#include <string> // Para basic_string, string
#include <vector> // Para vector
@@ -45,7 +45,7 @@ class Scoreboard {
// --- Métodos de singleton ---
static void init(); // Crea el objeto Scoreboard
static void destroy(); // Libera el objeto Scoreboard
static Scoreboard *get(); // Obtiene el puntero al objeto Scoreboard
static auto get() -> Scoreboard *; // Obtiene el puntero al objeto Scoreboard
// --- Métodos principales ---
void update(); // Actualiza la lógica del marcador
@@ -103,7 +103,7 @@ class Scoreboard {
// --- Métodos internos ---
void recalculateAnchors(); // Recalcula las anclas de los elementos
std::string updateScoreText(int num); // Transforma un valor numérico en una cadena de 7 cifras
auto updateScoreText(int num) -> std::string; // Transforma un valor numérico en una cadena de 7 cifras
void createBackgroundTexture(); // Crea la textura de fondo
void createPanelTextures(); // Crea las texturas de los paneles
void fillPanelTextures(); // Rellena los diferentes paneles del marcador

View File

@@ -18,7 +18,7 @@ class Screen {
// --- Métodos de singleton ---
static void init(); // Inicializa el objeto Screen
static void destroy(); // Libera el objeto Screen
static Screen *get(); // Obtiene el puntero al objeto Screen
static auto get() -> Screen *; // Obtiene el puntero al objeto Screen
// --- Métodos principales ---
void update(); // Actualiza la lógica de la clase
@@ -32,8 +32,8 @@ class Screen {
void setFullscreenMode(); // Establece el modo de pantalla completa
void toggleFullscreen(); // Cambia entre pantalla completa y ventana
void setWindowZoom(int size); // Cambia el tamaño de la ventana
bool decWindowSize(); // Reduce el tamaño de la ventana
bool incWindowSize(); // Aumenta el tamaño de la ventana
auto decWindowSize() -> bool; // Reduce el tamaño de la ventana
auto incWindowSize() -> bool; // Aumenta el tamaño de la ventana
void applySettings(); // Aplica los valores de las opciones
void initShaders(); // Inicializa los shaders
@@ -47,12 +47,12 @@ class Screen {
void attenuate(bool value) { attenuate_effect_ = value; } // Atenúa la pantalla
// --- Getters ---
SDL_Renderer *getRenderer() { return renderer_; } // Obtiene el renderizador
auto getRenderer() -> SDL_Renderer * { return renderer_; } // Obtiene el renderizador
void show() { SDL_ShowWindow(window_); } // Muestra la ventana
void hide() { SDL_HideWindow(window_); } // Oculta la ventana
void getSingletons(); // Obtiene los punteros a los singletones
bool getVSync() const { return Options::video.v_sync; } // Obtiene el valor de V-Sync
std::shared_ptr<Text> getText() const { return text_; } // Obtiene el puntero al texto de Screen
[[nodiscard]] auto getVSync() const -> bool { return Options::video.v_sync; } // Obtiene el valor de V-Sync
[[nodiscard]] auto getText() const -> std::shared_ptr<Text> { return text_; } // Obtiene el puntero al texto de Screen
#ifdef DEBUG
// --- Debug ---
@@ -66,13 +66,13 @@ class Screen {
// --- Estructuras internas ---
struct FPS {
Uint32 ticks; // Tiempo en milisegundos desde que se comenzó a contar.
int frame_count; // Número acumulado de frames en el intervalo.
int last_value; // Número de frames calculado en el último segundo.
Uint32 ticks{0}; // Tiempo en milisegundos desde que se comenzó a contar.
int frame_count{0}; // Número acumulado de frames en el intervalo.
int last_value{0}; // Número de frames calculado en el último segundo.
FPS() : ticks(0), frame_count(0), last_value(0) {}
FPS() {}
void increment() { frame_count++; }
int calculate(Uint32 current_ticks) {
auto calculate(Uint32 current_ticks) -> int {
if (current_ticks - ticks >= 1000) {
last_value = frame_count;
frame_count = 0;
@@ -94,7 +94,7 @@ class Screen {
: enabled(enabled), lenght(lenght), delay(delay), counter(lenght), color(color) {}
void update() { (enabled && counter > 0) ? counter-- : enabled = false; }
bool isRendarable() { return enabled && counter < lenght - delay; }
auto isRendarable() -> bool { return enabled && counter < lenght - delay; }
};
// Efecto de sacudida/agitación de pantalla: mueve la imagen para simular un temblor
@@ -156,7 +156,7 @@ class Screen {
}
}
bool isEnabled() const { return enabled; }
[[nodiscard]] auto isEnabled() const -> bool { return enabled; }
};
#ifdef DEBUG
@@ -193,7 +193,7 @@ class Screen {
std::shared_ptr<Text> text_; // Objeto para escribir texto en pantalla
// --- Métodos internos ---
bool initSDLVideo(); // Arranca SDL VIDEO y crea la ventana
auto initSDLVideo() -> bool; // Arranca SDL VIDEO y crea la ventana
void renderFlash(); // Dibuja el efecto de flash en la pantalla
void renderShake(); // Aplica el efecto de agitar la pantalla
void renderInfo(); // Muestra información por pantalla

View File

@@ -451,9 +451,9 @@ void Credits::cycleColors() {
constexpr int UPPER_LIMIT = 140; // Límite superior
constexpr int LOWER_LIMIT = 30; // Límite inferior
static float r_ = static_cast<float>(UPPER_LIMIT);
static float g_ = static_cast<float>(LOWER_LIMIT);
static float b_ = static_cast<float>(LOWER_LIMIT);
static auto r_ = static_cast<float>(UPPER_LIMIT);
static auto g_ = static_cast<float>(LOWER_LIMIT);
static auto b_ = static_cast<float>(LOWER_LIMIT);
static float step_r_ = -0.5f; // Paso flotante para transiciones suaves
static float step_g_ = 0.3f;
static float step_b_ = 0.1f;

View File

@@ -1,9 +1,9 @@
#include "game.h"
#include <SDL3/SDL.h> // Para SDL_GetTicks, SDL_SetRenderTarget
#include <stdlib.h> // Para rand, size_t
#include <algorithm> // Para find_if, clamp, find, min
#include <cstdlib> // Para rand, size_t
#include <functional> // Para function
#include <iterator> // Para distance, size
@@ -399,7 +399,7 @@ void Game::destroyAllItems() {
}
// Comprueba la colisión entre el jugador y los globos activos
std::shared_ptr<Balloon> Game::checkPlayerBalloonCollision(std::shared_ptr<Player> &player) {
auto Game::checkPlayerBalloonCollision(std::shared_ptr<Player> &player) -> std::shared_ptr<Balloon> {
for (auto &balloon : balloon_manager_->getBalloons()) {
if (!balloon->isInvulnerable() && !balloon->isPowerBall()) {
if (checkCollision(player->getCollider(), balloon->getCollider())) {
@@ -594,7 +594,7 @@ void Game::renderItems() {
}
// Devuelve un item al azar y luego segun sus probabilidades
ItemType Game::dropItem() {
auto Game::dropItem() -> ItemType {
const auto LUCKY_NUMBER = rand() % 100;
const auto ITEM = rand() % 6;
@@ -960,8 +960,8 @@ void Game::initPaths() {
const int X1 = param.game.play_area.center_x - W / 2;
const int X2 = param.game.play_area.rect.w;
const int Y = param.game.play_area.center_y;
paths_.emplace_back(Path(createPath(X0, X1, PathType::HORIZONTAL, Y, 80, easeOutQuint), 20));
paths_.emplace_back(Path(createPath(X1, X2, PathType::HORIZONTAL, Y, 80, easeInQuint), 0));
paths_.emplace_back(createPath(X0, X1, PathType::HORIZONTAL, Y, 80, easeOutQuint), 20);
paths_.emplace_back(createPath(X1, X2, PathType::HORIZONTAL, Y, 80, easeInQuint), 0);
}
// Recorrido para el texto de "Last Stage!" o de "X stages left" o "Game Over" (2,3)
@@ -972,8 +972,8 @@ void Game::initPaths() {
const int Y1 = param.game.play_area.center_y - H / 2;
const int Y2 = -H;
const int X = param.game.play_area.center_x;
paths_.emplace_back(Path(createPath(Y0, Y1, PathType::VERTICAL, X, 80, easeOutQuint), 20));
paths_.emplace_back(Path(createPath(Y1, Y2, PathType::VERTICAL, X, 80, easeInQuint), 0));
paths_.emplace_back(createPath(Y0, Y1, PathType::VERTICAL, X, 80, easeOutQuint), 20);
paths_.emplace_back(createPath(Y1, Y2, PathType::VERTICAL, X, 80, easeInQuint), 0);
}
// Recorrido para el texto de "Congratulations!!" (3,4)
@@ -985,8 +985,8 @@ void Game::initPaths() {
const int X1 = param.game.play_area.center_x - W / 2;
const int X2 = param.game.play_area.rect.w;
const int Y = param.game.play_area.center_y - H / 2 - 20;
paths_.emplace_back(Path(createPath(X0, X1, PathType::HORIZONTAL, Y, 80, easeOutQuint), 400));
paths_.emplace_back(Path(createPath(X1, X2, PathType::HORIZONTAL, Y, 80, easeInQuint), 0));
paths_.emplace_back(createPath(X0, X1, PathType::HORIZONTAL, Y, 80, easeOutQuint), 400);
paths_.emplace_back(createPath(X1, X2, PathType::HORIZONTAL, Y, 80, easeInQuint), 0);
}
// Recorrido para el texto de "1.000.000 points!" (5,6)
@@ -998,8 +998,8 @@ void Game::initPaths() {
const int X1 = param.game.play_area.center_x - W / 2;
const int X2 = -W;
const int Y = param.game.play_area.center_y + H / 2 - 20;
paths_.emplace_back(Path(createPath(X0, X1, PathType::HORIZONTAL, Y, 80, easeOutQuint), 400));
paths_.emplace_back(Path(createPath(X1, X2, PathType::HORIZONTAL, Y, 80, easeInQuint), 0));
paths_.emplace_back(createPath(X0, X1, PathType::HORIZONTAL, Y, 80, easeOutQuint), 400);
paths_.emplace_back(createPath(X1, X2, PathType::HORIZONTAL, Y, 80, easeInQuint), 0);
}
}
@@ -1021,7 +1021,7 @@ void Game::updateHelper() {
}
// Comprueba si todos los jugadores han terminado de jugar
bool Game::allPlayersAreWaitingOrGameOver() {
auto Game::allPlayersAreWaitingOrGameOver() -> bool {
auto success = true;
for (const auto &player : players_)
success &= player->isWaiting() || player->isGameOver();
@@ -1030,7 +1030,7 @@ bool Game::allPlayersAreWaitingOrGameOver() {
}
// Comprueba si todos los jugadores han terminado de jugar
bool Game::allPlayersAreGameOver() {
auto Game::allPlayersAreGameOver() -> bool {
auto success = true;
for (const auto &player : players_)
success &= player->isGameOver();
@@ -1039,7 +1039,7 @@ bool Game::allPlayersAreGameOver() {
}
// Comprueba si todos los jugadores han terminado de jugar
bool Game::allPlayersAreNotPlaying() {
auto Game::allPlayersAreNotPlaying() -> bool {
auto success = true;
for (const auto &player : players_)
success &= !player->isPlaying();
@@ -1131,7 +1131,7 @@ void Game::checkPlayersStatusPlaying() {
}
// Obtiene un jugador a partir de su "id"
std::shared_ptr<Player> Game::getPlayer(int id) {
auto Game::getPlayer(int id) -> std::shared_ptr<Player> {
auto it = std::find_if(players_.begin(), players_.end(), [id](const auto &player) { return player->getId() == id; });
if (it != players_.end()) {
@@ -1141,7 +1141,7 @@ std::shared_ptr<Player> Game::getPlayer(int id) {
}
// Obtiene un controlador a partir del "id" del jugador
int Game::getController(int player_id) {
auto Game::getController(int player_id) -> int {
auto it = std::find_if(Options::controllers.begin(), Options::controllers.end(), [player_id](const auto &controller) { return controller.player_id == player_id; });
if (it != Options::controllers.end()) {

View File

@@ -74,9 +74,9 @@ class Game {
// --- Estructuras ---
struct Helper {
bool need_coffee; // Indica si se necesitan cafes
bool need_coffee_machine; // Indica si se necesita PowerUp
bool need_power_ball; // Indica si se necesita una PowerBall
bool need_coffee{false}; // Indica si se necesitan cafes
bool need_coffee_machine{false}; // Indica si se necesita PowerUp
bool need_power_ball{false}; // Indica si se necesita una PowerBall
int counter; // Contador para no dar ayudas consecutivas
int item_disk_odds; // Probabilidad de aparición del objeto
int item_gavina_odds; // Probabilidad de aparición del objeto
@@ -86,10 +86,7 @@ class Game {
int item_coffee_machine_odds; // Probabilidad de aparición del objeto
Helper()
: need_coffee(false),
need_coffee_machine(false),
need_power_ball(false),
counter(HELP_COUNTER),
: counter(HELP_COUNTER),
item_disk_odds(ITEM_POINTS_1_DISK_ODDS),
item_gavina_odds(ITEM_POINTS_2_GAVINA_ODDS),
item_pacmar_odds(ITEM_POINTS_3_PACMAR_ODDS),
@@ -170,7 +167,7 @@ class Game {
void updateStage(); // Comprueba si hay cambio de fase y actualiza las variables
void updateGameStateGameOver(); // Actualiza el estado de fin de la partida
void destroyAllItems(); // Destruye todos los items
std::shared_ptr<Balloon> checkPlayerBalloonCollision(std::shared_ptr<Player> &player); // Comprueba la colisión entre el jugador y los globos activos
auto checkPlayerBalloonCollision(std::shared_ptr<Player> &player) -> std::shared_ptr<Balloon>; // Comprueba la colisión entre el jugador y los globos activos
void checkPlayerItemCollision(std::shared_ptr<Player> &player); // Comprueba la colisión entre el jugador y los items
void checkBulletCollision(); // Comprueba y procesa la colisión de las balas
void updateBullets(); // Mueve las balas activas
@@ -179,7 +176,7 @@ class Game {
void freeBullets(); // Vacia el vector de balas
void updateItems(); // Actualiza los items
void renderItems(); // Pinta los items activos
ItemType dropItem(); // Devuelve un item en función del azar
auto dropItem() -> ItemType; // Devuelve un item en función del azar
void createItem(ItemType type, float x, float y); // Crea un objeto item
void freeItems(); // Vacia el vector de items
void createItemText(int x, std::shared_ptr<Texture> texture); // Crea un objeto PathSprite
@@ -198,17 +195,17 @@ class Game {
void enableTimeStopItem(); // Habilita el efecto del item de detener el tiempo
void disableTimeStopItem(); // Deshabilita el efecto del item de detener el tiempo
void updateHelper(); // Actualiza las variables de ayuda
bool allPlayersAreWaitingOrGameOver(); // Comprueba si todos los jugadores han terminado de jugar
bool allPlayersAreGameOver(); // Comprueba si todos los jugadores han terminado de jugar
bool allPlayersAreNotPlaying(); // Comprueba si todos los jugadores han terminado de jugar
auto allPlayersAreWaitingOrGameOver() -> bool; // Comprueba si todos los jugadores han terminado de jugar
auto allPlayersAreGameOver() -> bool; // Comprueba si todos los jugadores han terminado de jugar
auto allPlayersAreNotPlaying() -> bool; // Comprueba si todos los jugadores han terminado de jugar
void updateScoreboard(); // Actualiza el marcador
void fillCanvas(); // Dibuja los elementos de la zona de juego en su textura
void pause(bool value); // Pausa el juego
void addScoreToScoreBoard(const std::shared_ptr<Player> &player); // Añade una puntuación a la tabla de records
void checkAndUpdatePlayerStatus(int active_player_index, int inactive_player_index); // Saca del estado de GAME OVER al jugador si el otro está activo
void checkPlayersStatusPlaying(); // Comprueba el estado de juego de los jugadores
std::shared_ptr<Player> getPlayer(int id); // Obtiene un jugador a partir de su "id"
int getController(int player_id); // Obtiene un controlador a partir del "id" del jugador
auto getPlayer(int id) -> std::shared_ptr<Player>; // Obtiene un jugador a partir de su "id"
auto getController(int player_id) -> int; // Obtiene un controlador a partir del "id" del jugador
void checkInput(); // Gestiona la entrada durante el juego
void checkPauseInput(); // Verifica si alguno de los controladores ha solicitado una pausa y actualiza el estado de pausa del juego.
void demoHandleInput(); // Gestiona las entradas de los jugadores en el modo demo, incluyendo movimientos y disparos automáticos.

View File

@@ -1,9 +1,9 @@
#include "hiscore_table.h"
#include <SDL3/SDL.h> // Para SDL_GetTicks, SDL_SetRenderTarget
#include <stdlib.h> // Para rand, size_t
#include <algorithm> // Para max
#include <cstdlib> // Para rand, size_t
#include <functional> // Para function
#include <vector> // Para vector
@@ -32,7 +32,7 @@ HiScoreTable::HiScoreTable()
backbuffer_(SDL_CreateTexture(renderer_, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, param.game.width, param.game.height)),
fade_(std::make_unique<Fade>()),
background_(std::make_unique<Background>()),
counter_(0),
ticks_(0),
view_area_(SDL_FRect{0, 0, static_cast<float>(param.game.width), static_cast<float>(param.game.height)}),
fade_mode_(FadeMode::IN),
@@ -168,7 +168,7 @@ void HiScoreTable::updateFade() {
}
// Convierte un entero a un string con separadores de miles
std::string HiScoreTable::format(int number) {
auto HiScoreTable::format(int number) -> std::string {
const std::string SEPARATOR = ".";
const std::string SCORE = std::to_string(number);
@@ -341,7 +341,7 @@ void HiScoreTable::initBackground() {
}
// Obtiene un color del vector de colores de entradas
Color HiScoreTable::getEntryColor(int counter) {
auto HiScoreTable::getEntryColor(int counter) -> Color {
int cycle_length = entry_colors_.size() * 2 - 2;
size_t n = counter % cycle_length;

View File

@@ -64,14 +64,14 @@ class HiScoreTable {
void render(); // Pinta en pantalla
void checkEvents(); // Comprueba los eventos
void checkInput(); // Comprueba las entradas
std::string format(int number); // Convierte un entero a un string con separadores de miles
auto format(int number) -> std::string; // Convierte un entero a un string con separadores de miles
void fillTexture(); // Dibuja los sprites en la textura
void updateFade(); // Gestiona el fade
void createSprites(); // Crea los sprites con los textos
void updateSprites(); // Actualiza las posiciones de los sprites de texto
void initFade(); // Inicializa el fade
void initBackground(); // Inicializa el fondo
Color getEntryColor(int counter); // Obtiene un color del vector de colores de entradas
auto getEntryColor(int counter) -> Color; // Obtiene un color del vector de colores de entradas
void iniEntryColors(); // Inicializa los colores de las entradas
void glowEntryNames(); // Hace brillar los nombres de la tabla de records
void updateCounter(); // Gestiona el contador

View File

@@ -279,7 +279,7 @@ void Instructions::run() {
}
// Método para inicializar las líneas
std::vector<Line> Instructions::initializeLines(int height) {
auto Instructions::initializeLines(int height) -> std::vector<Line> {
std::vector<Line> lines;
for (int y = 0; y < height; y++) {
int direction = (y % 2 == 0) ? -1 : 1; // Pares a la izquierda, impares a la derecha
@@ -289,7 +289,7 @@ std::vector<Line> Instructions::initializeLines(int height) {
}
// Método para mover las líneas con suavizado
bool Instructions::moveLines(std::vector<Line> &lines, int width, float duration, Uint32 start_delay) {
auto Instructions::moveLines(std::vector<Line> &lines, int width, float duration, Uint32 start_delay) -> bool {
Uint32 current_time = SDL_GetTicks();
bool all_lines_off_screen = true;

View File

@@ -29,11 +29,11 @@ struct Line {
int y; // Coordenada Y de la línea
float x; // Coordenada X inicial (usamos float para mayor precisión en el suavizado)
int direction; // Dirección de movimiento: -1 para izquierda, 1 para derecha
Uint32 start_time; // Tiempo de inicio del movimiento
Uint32 start_time{0}; // Tiempo de inicio del movimiento
// Constructor de Line
Line(int y, float x, int direction)
: y(y), x(x), direction(direction), start_time(0) {}
: y(y), x(x), direction(direction) {}
};
// Clase Instructions
@@ -80,8 +80,8 @@ class Instructions {
void fillBackbuffer(); // Rellena el backbuffer
void iniSprites(); // Inicializa los sprites de los items
void updateSprites(); // Actualiza los sprites
std::vector<Line> initializeLines(int height); // Inicializa las líneas animadas
bool moveLines(std::vector<Line> &lines, int width, float duration, Uint32 start_delay); // Mueve las líneas
auto initializeLines(int height) -> std::vector<Line>; // Inicializa las líneas animadas
auto moveLines(std::vector<Line> &lines, int width, float duration, Uint32 start_delay) -> bool; // Mueve las líneas
void renderLines(SDL_Renderer *renderer, SDL_Texture *texture, const std::vector<Line> &lines); // Renderiza las líneas
void updateBackbuffer(); // Gestiona la textura con los gráficos
};

View File

@@ -46,14 +46,14 @@ Logo::Logo()
}
// Inicializa el vector de colores
color_.push_back(Color(0x00, 0x00, 0x00)); // Black
color_.push_back(Color(0x00, 0x00, 0xd8)); // Blue
color_.push_back(Color(0xd8, 0x00, 0x00)); // Red
color_.push_back(Color(0xd8, 0x00, 0xd8)); // Magenta
color_.push_back(Color(0x00, 0xd8, 0x00)); // Green
color_.push_back(Color(0x00, 0xd8, 0xd8)); // Cyan
color_.push_back(Color(0xd8, 0xd8, 0x00)); // Yellow
color_.push_back(Color(0xFF, 0xFF, 0xFF)); // Bright white
color_.emplace_back(0x00, 0x00, 0x00); // Black
color_.emplace_back(0x00, 0x00, 0xd8); // Blue
color_.emplace_back(0xd8, 0x00, 0x00); // Red
color_.emplace_back(0xd8, 0x00, 0xd8); // Magenta
color_.emplace_back(0x00, 0xd8, 0x00); // Green
color_.emplace_back(0x00, 0xd8, 0xd8); // Cyan
color_.emplace_back(0xd8, 0xd8, 0x00); // Yellow
color_.emplace_back(0xFF, 0xFF, 0xFF); // Bright white
}
// Destructor

View File

@@ -1,9 +1,9 @@
#include "title.h"
#include <SDL3/SDL.h> // Para SDL_GetTicks, Uint32, SDL_EventType
#include <stddef.h> // Para size_t
#include <algorithm> // Para find_if
#include <cstddef> // Para size_t
#include <iostream> // Para basic_ostream, basic_ostream::operator<<
#include <string> // Para basic_string, char_traits, operator+
#include <vector> // Para vector
@@ -513,7 +513,7 @@ void Title::renderPlayers() {
}
// Obtiene un jugador a partir de su "id"
std::shared_ptr<Player> Title::getPlayer(int id) {
auto Title::getPlayer(int id) -> std::shared_ptr<Player> {
auto it = std::find_if(players_.begin(), players_.end(), [id](const auto &player) { return player->getId() == id; });
if (it != players_.end()) {

View File

@@ -92,5 +92,5 @@ class Title {
void initPlayers(); // Inicializa los jugadores
void renderPlayers(); // Renderiza los jugadores
void updatePlayers(); // Actualza los jugadores
std::shared_ptr<Player> getPlayer(int id); // Obtiene un jugador a partir de su "id"
auto getPlayer(int id) -> std::shared_ptr<Player>; // Obtiene un jugador a partir de su "id"
};

View File

@@ -19,10 +19,10 @@ class SmartSprite : public AnimatedSprite {
void render() override; // Dibuja el sprite
// --- Getters ---
int getDestX() const { return dest_x_; } // Obtiene la posición de destino en X
int getDestY() const { return dest_y_; } // Obtiene la posición de destino en Y
bool isOnDestination() const { return on_destination_; } // Indica si está en el destino
bool hasFinished() const { return finished_; } // Indica si ya ha terminado
auto getDestX() const -> int { return dest_x_; } // Obtiene la posición de destino en X
auto getDestY() const -> int { return dest_y_; } // Obtiene la posición de destino en Y
auto isOnDestination() const -> bool { return on_destination_; } // Indica si está en el destino
auto hasFinished() const -> bool { return finished_; } // Indica si ya ha terminado
// --- Setters ---
void setFinishedCounter(int value) { finished_counter_ = value; } // Establece el contador para deshabilitarlo

View File

@@ -1,20 +1,22 @@
#include "sprite.h"
#include <utility>
#include "texture.h" // Para Texture
// Constructor
Sprite::Sprite(std::shared_ptr<Texture> texture, float pos_x, float pos_y, float width, float height)
: texture_(texture),
: texture_(std::move(texture)),
pos_((SDL_FRect){pos_x, pos_y, width, height}),
sprite_clip_((SDL_FRect){0, 0, pos_.w, pos_.h}) {}
Sprite::Sprite(std::shared_ptr<Texture> texture, SDL_FRect rect)
: texture_(texture),
: texture_(std::move(texture)),
pos_(rect),
sprite_clip_((SDL_FRect){0, 0, pos_.w, pos_.h}) {}
Sprite::Sprite(std::shared_ptr<Texture> texture)
: texture_(texture),
: texture_(std::move(texture)),
pos_(SDL_FRect{0, 0, static_cast<float>(texture_->getWidth()), static_cast<float>(texture_->getHeight())}),
sprite_clip_(pos_) {}

View File

@@ -12,21 +12,21 @@ int number = 0; // Fase actual
bool power_can_be_added = true; // Habilita la recolecta de poder
// Devuelve una fase
Stage get(int index) { return stages.at(std::min(9, index)); }
auto get(int index) -> Stage { return stages.at(std::min(9, index)); }
// Inicializa las variables del namespace Stage
void init() {
stages.clear();
stages.emplace_back(Stage(200, 7 + (4 * 1), 7 + (4 * 3)));
stages.emplace_back(Stage(300, 7 + (4 * 2), 7 + (4 * 4)));
stages.emplace_back(Stage(600, 7 + (4 * 3), 7 + (4 * 5)));
stages.emplace_back(Stage(600, 7 + (4 * 3), 7 + (4 * 5)));
stages.emplace_back(Stage(600, 7 + (4 * 4), 7 + (4 * 6)));
stages.emplace_back(Stage(600, 7 + (4 * 4), 7 + (4 * 6)));
stages.emplace_back(Stage(650, 7 + (4 * 5), 7 + (4 * 7)));
stages.emplace_back(Stage(750, 7 + (4 * 5), 7 + (4 * 7)));
stages.emplace_back(Stage(850, 7 + (4 * 6), 7 + (4 * 8)));
stages.emplace_back(Stage(950, 7 + (4 * 7), 7 + (4 * 10)));
stages.emplace_back(200, 7 + (4 * 1), 7 + (4 * 3));
stages.emplace_back(300, 7 + (4 * 2), 7 + (4 * 4));
stages.emplace_back(600, 7 + (4 * 3), 7 + (4 * 5));
stages.emplace_back(600, 7 + (4 * 3), 7 + (4 * 5));
stages.emplace_back(600, 7 + (4 * 4), 7 + (4 * 6));
stages.emplace_back(600, 7 + (4 * 4), 7 + (4 * 6));
stages.emplace_back(650, 7 + (4 * 5), 7 + (4 * 7));
stages.emplace_back(750, 7 + (4 * 5), 7 + (4 * 7));
stages.emplace_back(850, 7 + (4 * 6), 7 + (4 * 8));
stages.emplace_back(950, 7 + (4 * 7), 7 + (4 * 10));
power = 0;
total_power = 0;

View File

@@ -27,7 +27,7 @@ extern int number; // Índice de la fase actual
extern bool power_can_be_added; // Indica si se puede añadir poder a la fase
// --- Funciones principales ---
Stage get(int index); // Devuelve una fase por índice
auto get(int index) -> Stage; // Devuelve una fase por índice
void init(); // Inicializa las variables del namespace Stage
void addPower(int amount); // Añade poder a la fase actual
} // namespace Stage

View File

@@ -1,8 +1,8 @@
#include "text.h"
#include <SDL3/SDL.h> // Para SDL_SetRenderTarget, SDL_GetRenderTarget, Uint8
#include <stddef.h> // Para size_t
#include <cstddef> // Para size_t
#include <fstream> // Para basic_ifstream, basic_istream, basic_ostream
#include <iostream> // Para cerr
#include <stdexcept> // Para runtime_error
@@ -13,14 +13,14 @@
#include "utils.h" // Para Color, getFileName, printWithDots
// Llena una estructuta TextFile desde un fichero
std::shared_ptr<TextFile> loadTextFile(const std::string &file_path) {
auto loadTextFile(const std::string &file_path) -> std::shared_ptr<TextFile> {
auto tf = std::make_shared<TextFile>();
// Inicializa a cero el vector con las coordenadas
for (int i = 0; i < 128; ++i) {
tf->offset[i].x = 0;
tf->offset[i].y = 0;
tf->offset[i].w = 0;
for (auto &i : tf->offset) {
i.x = 0;
i.y = 0;
i.w = 0;
tf->box_width = 0;
tf->box_height = 0;
}
@@ -141,7 +141,7 @@ void Text::write2X(int x, int y, const std::string &text, int kerning) {
}
// Escribe el texto en una textura
std::shared_ptr<Texture> Text::writeToTexture(const std::string &text, int zoom, int kerning) {
auto Text::writeToTexture(const std::string &text, int zoom, int kerning) -> std::shared_ptr<Texture> {
auto renderer = Screen::get()->getRenderer();
auto texture = std::make_shared<Texture>(renderer);
auto width = lenght(text, kerning) * zoom;
@@ -159,7 +159,7 @@ std::shared_ptr<Texture> Text::writeToTexture(const std::string &text, int zoom,
}
// Escribe el texto con extras en una textura
std::shared_ptr<Texture> Text::writeDXToTexture(Uint8 flags, const std::string &text, int kerning, Color text_color, Uint8 shadow_distance, Color shadow_color, int lenght) {
auto Text::writeDXToTexture(Uint8 flags, const std::string &text, int kerning, Color text_color, Uint8 shadow_distance, Color shadow_color, int lenght) -> std::shared_ptr<Texture> {
auto renderer = Screen::get()->getRenderer();
auto texture = std::make_shared<Texture>(renderer);
auto width = Text::lenght(text, kerning) + shadow_distance;
@@ -230,7 +230,7 @@ void Text::writeDX(Uint8 flags, int x, int y, const std::string &text, int kerni
}
// Obtiene la longitud en pixels de una cadena
int Text::lenght(const std::string &text, int kerning) const {
auto Text::lenght(const std::string &text, int kerning) const -> int {
int shift = 0;
for (size_t i = 0; i < text.length(); ++i)
shift += (offset_[static_cast<int>(text[i])].w + kerning);
@@ -240,7 +240,7 @@ int Text::lenght(const std::string &text, int kerning) const {
}
// Devuelve el valor de la variable
int Text::getCharacterSize() const {
auto Text::getCharacterSize() const -> int {
return box_width_;
}

View File

@@ -2,13 +2,14 @@
#include "texture.h"
#include <SDL3/SDL.h> // Para SDL_LogError, SDL_LogCategory, Uint8, SDL_...
#include <stdint.h> // Para uint32_t
#include <cstdint> // Para uint32_t
#include <cstring> // Para memcpy
#include <fstream> // Para basic_ifstream, basic_istream, basic_ios
#include <sstream> // Para basic_istringstream
#include <stdexcept> // Para runtime_error
#include <string> // Para basic_string, char_traits, operator+, string
#include <utility>
#include <vector> // Para vector
#include "external/gif.h" // Para Gif
@@ -16,9 +17,9 @@
#include "utils.h" // Para getFileName, Color, printWithDots
// Constructor
Texture::Texture(SDL_Renderer *renderer, const std::string &path)
Texture::Texture(SDL_Renderer *renderer, std::string path)
: renderer_(renderer),
path_(path) {
path_(std::move(path)) {
// Carga el fichero en la textura
if (!path_.empty()) {
// Obtiene la extensión
@@ -53,7 +54,7 @@ Texture::~Texture() {
}
// Carga una imagen desde un fichero
bool Texture::loadFromFile(const std::string &file_path) {
auto Texture::loadFromFile(const std::string &file_path) -> bool {
if (file_path.empty())
return false;
@@ -106,7 +107,7 @@ bool Texture::loadFromFile(const std::string &file_path) {
}
// Crea una textura en blanco
bool Texture::createBlank(int width, int height, SDL_PixelFormat format, SDL_TextureAccess access) {
auto Texture::createBlank(int width, int height, SDL_PixelFormat format, SDL_TextureAccess access) -> bool {
// Crea una textura sin inicializar
texture_ = SDL_CreateTexture(renderer_, format, access, width, height);
if (!texture_) {
@@ -179,22 +180,22 @@ void Texture::setAsRenderTarget(SDL_Renderer *renderer) {
}
// Obtiene el ancho de la imagen
int Texture::getWidth() {
auto Texture::getWidth() -> int {
return width_;
}
// Obtiene el alto de la imagen
int Texture::getHeight() {
auto Texture::getHeight() -> int {
return height_;
}
// Recarga la textura
bool Texture::reLoad() {
auto Texture::reLoad() -> bool {
return loadFromFile(path_);
}
// Obtiene la textura
SDL_Texture *Texture::getSDLTexture() {
auto Texture::getSDLTexture() -> SDL_Texture * {
return texture_;
}
@@ -206,7 +207,7 @@ void Texture::unloadSurface() {
}
// Crea una surface desde un fichero .gif
std::shared_ptr<Surface> Texture::loadSurface(const std::string &file_path) {
auto Texture::loadSurface(const std::string &file_path) -> std::shared_ptr<Surface> {
// Libera la superficie actual
unloadSurface();
@@ -277,7 +278,7 @@ void Texture::setPaletteColor(int palette, int index, Uint32 color) {
}
// Carga una paleta desde un fichero
Palette Texture::loadPaletteFromFile(const std::string &file_path) {
auto Texture::loadPaletteFromFile(const std::string &file_path) -> Palette {
Palette palette;
// Abrir el archivo GIF
@@ -337,10 +338,10 @@ void Texture::setPalette(size_t palette) {
}
// Obtiene el renderizador
SDL_Renderer *Texture::getRenderer() { return renderer_; }
auto Texture::getRenderer() -> SDL_Renderer * { return renderer_; }
// Carga una paleta desde un archivo .pal
Palette Texture::readPalFile(const std::string &file_path) {
auto Texture::readPalFile(const std::string &file_path) -> Palette {
Palette palette{};
palette.fill(0); // Inicializar todo con 0 (transparente por defecto)

View File

@@ -1,9 +1,9 @@
#pragma once
#include <SDL3/SDL.h> // Para Uint8, SDL_Renderer, Uint16, SDL_FlipMode, SDL_PixelFormat, SDL_TextureAccess, SDL_Texture, Uint32, SDL_BlendMode, SDL_FPoint, SDL_FRect
#include <stddef.h> // Para size_t
#include <array> // Para array
#include <cstddef> // Para size_t
#include <memory> // Para shared_ptr
#include <string> // Para string, basic_string
#include <utility>
@@ -28,7 +28,7 @@ struct Surface {
class Texture {
public:
// --- Constructores y destructor ---
explicit Texture(SDL_Renderer *renderer, const std::string &path = std::string());
explicit Texture(SDL_Renderer *renderer, std::string path = std::string());
~Texture();
// --- Carga y creación ---

View File

@@ -1,10 +1,11 @@
#include "tiled_bg.h"
#include <SDL3/SDL.h> // Para SDL_SetRenderTarget, SDL_CreateTexture, SDL_De...
#include <stdlib.h> // Para rand
#include <cmath> // Para sin
#include <cstdlib> // Para rand
#include <memory> // Para unique_ptr, make_unique
#include <numbers>
#include <string> // Para basic_string
#include "resource.h" // Para Resource
@@ -41,7 +42,7 @@ TiledBG::TiledBG(SDL_FRect pos, TiledBGMode mode)
// Inicializa los valores del vector con los valores del seno
for (int i = 0; i < 360; ++i) {
sin_[i] = std::sin(i * 3.14159 / 180.0); // Convierte grados a radianes y calcula el seno
sin_[i] = std::sin(i * std::numbers::pi / 180.0); // Convierte grados a radianes y calcula el seno
}
}

View File

@@ -35,7 +35,7 @@ class TiledBG {
void setColor(Color color) { SDL_SetTextureColorMod(canvas_, color.r, color.g, color.b); } // Cambia el color de la textura
// --- Getters ---
bool isStopped() const { return speed_ == 0.0f; } // Indica si está parado
[[nodiscard]] auto isStopped() const -> bool { return speed_ == 0.0f; } // Indica si está parado
private:
// --- Constantes ---

View File

@@ -26,19 +26,19 @@ class MenuOption {
virtual ~MenuOption() = default;
const std::string &getCaption() const { return caption_; }
ServiceMenu::SettingsGroup getGroup() const { return group_; }
bool isHidden() const { return hidden_; }
[[nodiscard]] auto getCaption() const -> const std::string & { return caption_; }
[[nodiscard]] auto getGroup() const -> ServiceMenu::SettingsGroup { return group_; }
[[nodiscard]] auto isHidden() const -> bool { return hidden_; }
void setHidden(bool hidden) { hidden_ = hidden; }
virtual Behavior getBehavior() const = 0;
virtual std::string getValueAsString() const { return ""; }
[[nodiscard]] virtual auto getBehavior() const -> Behavior = 0;
[[nodiscard]] virtual auto getValueAsString() const -> std::string { return ""; }
virtual void adjustValue(bool adjust_up) {}
virtual ServiceMenu::SettingsGroup getTargetGroup() const { return ServiceMenu::SettingsGroup::MAIN; }
[[nodiscard]] virtual auto getTargetGroup() const -> ServiceMenu::SettingsGroup { return ServiceMenu::SettingsGroup::MAIN; }
virtual void executeAction() {}
// Método virtual para que cada opción calcule el ancho de su valor más largo.
virtual int getMaxValueWidth(Text *text_renderer) const { return 0; }
virtual auto getMaxValueWidth(Text *text_renderer) const -> int { return 0; }
protected:
std::string caption_;
@@ -53,14 +53,14 @@ class BoolOption : public MenuOption {
BoolOption(const std::string &cap, ServiceMenu::SettingsGroup grp, bool *var)
: MenuOption(cap, grp), linked_variable_(var) {}
Behavior getBehavior() const override { return Behavior::ADJUST; }
std::string getValueAsString() const override {
[[nodiscard]] auto getBehavior() const -> Behavior override { return Behavior::ADJUST; }
[[nodiscard]] auto getValueAsString() const -> std::string override {
return *linked_variable_ ? Lang::getText("[SERVICE_MENU] ON") : Lang::getText("[SERVICE_MENU] OFF");
}
void adjustValue(bool /*adjust_up*/) override {
*linked_variable_ = !*linked_variable_;
}
int getMaxValueWidth(Text *text_renderer) const override {
auto getMaxValueWidth(Text *text_renderer) const -> int override {
return std::max(
text_renderer->lenght(Lang::getText("[SERVICE_MENU] ON"), -2),
text_renderer->lenght(Lang::getText("[SERVICE_MENU] OFF"), -2));
@@ -75,13 +75,13 @@ class IntOption : public MenuOption {
IntOption(const std::string &cap, ServiceMenu::SettingsGroup grp, int *var, int min, int max, int step)
: MenuOption(cap, grp), linked_variable_(var), min_value_(min), max_value_(max), step_value_(step) {}
Behavior getBehavior() const override { return Behavior::ADJUST; }
std::string getValueAsString() const override { return std::to_string(*linked_variable_); }
[[nodiscard]] auto getBehavior() const -> Behavior override { return Behavior::ADJUST; }
[[nodiscard]] auto getValueAsString() const -> std::string override { return std::to_string(*linked_variable_); }
void adjustValue(bool adjust_up) override {
int new_value = *linked_variable_ + (adjust_up ? step_value_ : -step_value_);
*linked_variable_ = std::clamp(new_value, min_value_, max_value_);
}
int getMaxValueWidth(Text *text_renderer) const override {
auto getMaxValueWidth(Text *text_renderer) const -> int override {
int max_width = 0;
// Iterar por todos los valores posibles en el rango
@@ -104,8 +104,7 @@ class ListOption : public MenuOption {
: MenuOption(cap, grp),
value_list_(std::move(values)),
getter_(std::move(current_value_getter)),
setter_(std::move(new_value_setter)),
list_index_(0) {
setter_(std::move(new_value_setter)) {
sync();
}
@@ -119,8 +118,8 @@ class ListOption : public MenuOption {
}
}
Behavior getBehavior() const override { return Behavior::ADJUST; }
std::string getValueAsString() const override {
[[nodiscard]] auto getBehavior() const -> Behavior override { return Behavior::ADJUST; }
[[nodiscard]] auto getValueAsString() const -> std::string override {
return value_list_.empty() ? "" : value_list_[list_index_];
}
void adjustValue(bool adjust_up) override {
@@ -131,7 +130,7 @@ class ListOption : public MenuOption {
: (list_index_ + size - 1) % size;
setter_(value_list_[list_index_]);
}
int getMaxValueWidth(Text *text_renderer) const override {
auto getMaxValueWidth(Text *text_renderer) const -> int override {
int max_w = 0;
for (const auto &val : value_list_) {
max_w = std::max(max_w, text_renderer->lenght(val, -2));
@@ -143,7 +142,7 @@ class ListOption : public MenuOption {
std::vector<std::string> value_list_;
std::function<std::string()> getter_;
std::function<void(const std::string &)> setter_;
size_t list_index_;
size_t list_index_{0};
};
class FolderOption : public MenuOption {
@@ -151,8 +150,8 @@ class FolderOption : public MenuOption {
FolderOption(const std::string &cap, ServiceMenu::SettingsGroup grp, ServiceMenu::SettingsGroup target)
: MenuOption(cap, grp), target_group_(target) {}
Behavior getBehavior() const override { return Behavior::SELECT; }
ServiceMenu::SettingsGroup getTargetGroup() const override { return target_group_; }
[[nodiscard]] auto getBehavior() const -> Behavior override { return Behavior::SELECT; }
[[nodiscard]] auto getTargetGroup() const -> ServiceMenu::SettingsGroup override { return target_group_; }
private:
ServiceMenu::SettingsGroup target_group_;
@@ -163,7 +162,7 @@ class ActionOption : public MenuOption {
ActionOption(const std::string &cap, ServiceMenu::SettingsGroup grp, std::function<void()> action, bool hidden = false)
: MenuOption(cap, grp, hidden), action_(std::move(action)) {}
Behavior getBehavior() const override { return Behavior::SELECT; }
[[nodiscard]] auto getBehavior() const -> Behavior override { return Behavior::SELECT; }
void executeAction() override {
if (action_)
action_();

View File

@@ -100,7 +100,7 @@ void MenuRenderer::setAnchors(const ServiceMenu *menu_state) {
height_ = upper_height_ + lower_height_;
}
SDL_FRect MenuRenderer::calculateNewRect(const ServiceMenu *menu_state) {
auto MenuRenderer::calculateNewRect(const ServiceMenu *menu_state) -> SDL_FRect {
width_ = getMenuWidthForGroup(menu_state->getCurrentGroup());
const auto &display_options = menu_state->getDisplayOptions();
lower_height_ = ((display_options.size() > 0 ? display_options.size() - 1 : 0) * (options_height_ + options_padding_)) + options_height_ + (lower_padding_ * 2);
@@ -172,7 +172,7 @@ void MenuRenderer::precalculateMenuWidths(const std::vector<std::unique_ptr<Menu
}
}
int MenuRenderer::getMenuWidthForGroup(ServiceMenu::SettingsGroup group) const {
auto MenuRenderer::getMenuWidthForGroup(ServiceMenu::SettingsGroup group) const -> int {
return group_menu_widths_[static_cast<int>(group)];
}
@@ -185,12 +185,12 @@ void MenuRenderer::updateColorCounter() {
}
}
Color MenuRenderer::getAnimatedSelectedColor() {
auto MenuRenderer::getAnimatedSelectedColor() -> Color {
static auto color_cycle_ = generateMirroredCycle(param.service_menu.selected_color, ColorCycleStyle::HUE_WAVE);
return color_cycle_.at(color_counter_ % color_cycle_.size());
}
SDL_FRect MenuRenderer::setRect(SDL_FRect rect) {
auto MenuRenderer::setRect(SDL_FRect rect) -> SDL_FRect {
border_rect_ = {rect.x - 1, rect.y + 1, rect.w + 2, rect.h - 2};
return rect;
}

View File

@@ -1,8 +1,8 @@
#pragma once
#include <SDL3/SDL.h> // Para SDL_FRect, Uint32
#include <stddef.h> // Para size_t
#include <cstddef> // Para size_t
#include <memory> // Para shared_ptr, unique_ptr
#include <vector> // Para vector
@@ -26,7 +26,7 @@ class MenuRenderer {
void setLayout(const ServiceMenu *menu_state);
// Getters
const SDL_FRect &getRect() const { return rect_; }
[[nodiscard]] auto getRect() const -> const SDL_FRect & { return rect_; }
private:
// --- Referencias a los renderizadores de texto ---
@@ -60,13 +60,13 @@ class MenuRenderer {
// --- Métodos privados de la vista ---
void setAnchors(const ServiceMenu *menu_state);
SDL_FRect calculateNewRect(const ServiceMenu *menu_state);
auto calculateNewRect(const ServiceMenu *menu_state) -> SDL_FRect;
void resize(const ServiceMenu *menu_state);
void setSize(const ServiceMenu *menu_state);
void updateResizeAnimation();
void precalculateMenuWidths(const std::vector<std::unique_ptr<MenuOption>> &all_options, const ServiceMenu *menu_state);
int getMenuWidthForGroup(ServiceMenu::SettingsGroup group) const;
Color getAnimatedSelectedColor();
[[nodiscard]] auto getMenuWidthForGroup(ServiceMenu::SettingsGroup group) const -> int;
auto getAnimatedSelectedColor() -> Color;
void updateColorCounter();
SDL_FRect setRect(SDL_FRect rect);
auto setRect(SDL_FRect rect) -> SDL_FRect;
};

View File

@@ -16,7 +16,7 @@
ServiceMenu *ServiceMenu::instance = nullptr;
void ServiceMenu::init() { ServiceMenu::instance = new ServiceMenu(); }
void ServiceMenu::destroy() { delete ServiceMenu::instance; }
ServiceMenu *ServiceMenu::get() { return ServiceMenu::instance; }
auto ServiceMenu::get() -> ServiceMenu * { return ServiceMenu::instance; }
// Constructor
ServiceMenu::ServiceMenu()
@@ -106,7 +106,13 @@ void ServiceMenu::selectOption() {
return;
if (current_settings_group_ == SettingsGroup::MAIN)
main_menu_selected_ = selected_;
auto &selected_option = display_options_.at(selected_);
auto *selected_option = display_options_.at(selected_);
if (!selected_option) {
// This shouldn't happen in normal operation, but protects against null pointer
return;
}
if (auto folder = dynamic_cast<FolderOption *>(selected_option)) {
previous_settings_group_ = current_settings_group_;
current_settings_group_ = folder->getTargetGroup();
@@ -184,7 +190,7 @@ void ServiceMenu::applySettingsSettings() {
setHiddenOptions();
}
MenuOption *ServiceMenu::getOptionByCaption(const std::string &caption) const {
auto ServiceMenu::getOptionByCaption(const std::string &caption) const -> MenuOption * {
for (const auto &option : options_) {
if (option->getCaption() == caption) {
return option.get();
@@ -195,7 +201,7 @@ MenuOption *ServiceMenu::getOptionByCaption(const std::string &caption) const {
// --- Getters y otros ---
ServiceMenu::GroupAlignment ServiceMenu::getCurrentGroupAlignment() const {
auto ServiceMenu::getCurrentGroupAlignment() const -> ServiceMenu::GroupAlignment {
switch (current_settings_group_) {
case SettingsGroup::VIDEO:
case SettingsGroup::AUDIO:
@@ -206,7 +212,7 @@ ServiceMenu::GroupAlignment ServiceMenu::getCurrentGroupAlignment() const {
}
}
size_t ServiceMenu::countOptionsInGroup(SettingsGroup group) const {
auto ServiceMenu::countOptionsInGroup(SettingsGroup group) const -> size_t {
size_t count = 0;
for (const auto &option : options_) {
if (option->getGroup() == group && !option->isHidden()) {
@@ -269,7 +275,7 @@ void ServiceMenu::playSelectSound() { Audio::get()->playSound("service_menu_sele
void ServiceMenu::playBackSound() { Audio::get()->playSound("service_menu_select.wav", Audio::Group::INTERFACE); }
// Devuelve el nombre del grupo como string para el título
std::string ServiceMenu::settingsGroupToString(SettingsGroup group) const {
auto ServiceMenu::settingsGroupToString(SettingsGroup group) const -> std::string {
switch (group) {
case SettingsGroup::MAIN:
return Lang::getText("[SERVICE_MENU] TITLE");

View File

@@ -1,7 +1,6 @@
#pragma once
#include <stddef.h> // Para size_t
#include <cstddef> // Para size_t
#include <memory> // Para unique_ptr
#include <string> // Para basic_string, string
#include <utility> // Para pair
@@ -34,7 +33,7 @@ class ServiceMenu {
static void init();
static void destroy();
static ServiceMenu *get();
static auto get() -> ServiceMenu *;
void toggle();
void render();
@@ -49,15 +48,15 @@ class ServiceMenu {
void moveBack();
// --- Getters para que el Renderer pueda leer el estado ---
bool isEnabled() const { return enabled_; }
const std::string &getTitle() const { return title_; }
SettingsGroup getCurrentGroup() const { return current_settings_group_; }
GroupAlignment getCurrentGroupAlignment() const;
const std::vector<MenuOption *> &getDisplayOptions() const { return display_options_; }
const std::vector<std::unique_ptr<MenuOption>> &getAllOptions() const { return options_; }
size_t getSelectedIndex() const { return selected_; }
const std::vector<std::pair<std::string, std::string>> &getOptionPairs() const { return option_pairs_; }
size_t countOptionsInGroup(SettingsGroup group) const;
[[nodiscard]] auto isEnabled() const -> bool { return enabled_; }
[[nodiscard]] auto getTitle() const -> const std::string & { return title_; }
[[nodiscard]] auto getCurrentGroup() const -> SettingsGroup { return current_settings_group_; }
[[nodiscard]] auto getCurrentGroupAlignment() const -> GroupAlignment;
[[nodiscard]] auto getDisplayOptions() const -> const std::vector<MenuOption *> & { return display_options_; }
[[nodiscard]] auto getAllOptions() const -> const std::vector<std::unique_ptr<MenuOption>> & { return options_; }
[[nodiscard]] auto getSelectedIndex() const -> size_t { return selected_; }
[[nodiscard]] auto getOptionPairs() const -> const std::vector<std::pair<std::string, std::string>> & { return option_pairs_; }
[[nodiscard]] auto countOptionsInGroup(SettingsGroup group) const -> size_t;
private:
// --- Lógica de estado del menú (Modelo) ---
@@ -88,19 +87,19 @@ class ServiceMenu {
void applyVideoSettings();
void applyAudioSettings();
void applySettingsSettings();
MenuOption *getOptionByCaption(const std::string &caption) const;
[[nodiscard]] auto getOptionByCaption(const std::string &caption) const -> MenuOption *;
void adjustListValues();
void playMoveSound();
void playAdjustSound();
void playSelectSound();
void playBackSound();
std::string settingsGroupToString(SettingsGroup group) const;
[[nodiscard]] auto settingsGroupToString(SettingsGroup group) const -> std::string;
void setHiddenOptions();
// --- Singleton ---
ServiceMenu();
~ServiceMenu() = default;
ServiceMenu(const ServiceMenu &) = delete;
ServiceMenu &operator=(const ServiceMenu &) = delete;
auto operator=(const ServiceMenu &) -> ServiceMenu & = delete;
static ServiceMenu *instance;
};

View File

@@ -1,12 +1,13 @@
#include "ui_message.h"
#include <cmath> // Para pow
#include <utility>
#include "text.h" // Para TEXT_CENTER, TEXT_COLOR, Text
// Constructor: inicializa el renderizador, el texto y el color del mensaje
UIMessage::UIMessage(std::shared_ptr<Text> text_renderer, const std::string &message_text, const Color &color)
: text_renderer_(text_renderer), text_(message_text), color_(color) {}
UIMessage::UIMessage(std::shared_ptr<Text> text_renderer, std::string message_text, const Color &color)
: text_renderer_(std::move(text_renderer)), text_(std::move(message_text)), color_(color) {}
// Muestra el mensaje en la posición base_x, base_y con animación de entrada desde arriba
void UIMessage::show() {
@@ -76,7 +77,7 @@ void UIMessage::render() {
}
// Devuelve true si el mensaje está visible actualmente
bool UIMessage::isVisible() const {
auto UIMessage::isVisible() const -> bool {
return visible_;
}

View File

@@ -11,7 +11,7 @@ class Text;
class UIMessage {
public:
// Constructor: recibe el renderizador de texto, el mensaje y el color
UIMessage(std::shared_ptr<Text> text_renderer, const std::string &message_text, const Color &color);
UIMessage(std::shared_ptr<Text> text_renderer, std::string message_text, const Color &color);
// Muestra el mensaje con animación de entrada
void show();
@@ -26,7 +26,7 @@ class UIMessage {
void render();
// Indica si el mensaje está visible actualmente
bool isVisible() const;
[[nodiscard]] auto isVisible() const -> bool;
// Permite actualizar la posición del mensaje (por ejemplo, si el menú se mueve)
void setPosition(float new_base_x, float new_base_y);

View File

@@ -67,7 +67,7 @@ void Writer::setEnabled(bool value) {
}
// Obtiene el valor de la variable
bool Writer::isEnabled() const {
auto Writer::isEnabled() const -> bool {
return enabled_;
}
@@ -82,6 +82,6 @@ void Writer::center(int x) {
}
// Obtiene el valor de la variable
bool Writer::hasFinished() const {
auto Writer::hasFinished() const -> bool {
return finished_;
}

View File

@@ -2,6 +2,7 @@
#include <memory> // Para shared_ptr
#include <string> // Para string
#include <utility>
class Text;
@@ -10,7 +11,7 @@ class Writer {
public:
// Constructor
explicit Writer(std::shared_ptr<Text> text)
: text_(text) {}
: text_(std::move(text)) {}
// Destructor
~Writer() = default;
@@ -34,8 +35,8 @@ class Writer {
void center(int x);
// Getters
bool isEnabled() const; // Indica si el objeto está habilitado
bool hasFinished() const; // Indica si ya ha terminado
[[nodiscard]] auto isEnabled() const -> bool; // Indica si el objeto está habilitado
[[nodiscard]] auto hasFinished() const -> bool; // Indica si ya ha terminado
private:
// --- Objetos y punteros ---