clang-tidy (amb el fuck de que no feien bona parella el clang de macos i el tidy de llvm)

This commit is contained in:
2026-03-23 12:03:07 +01:00
parent 3ca744ee46
commit a1d17ccf99
72 changed files with 487 additions and 484 deletions

View File

@@ -193,9 +193,21 @@ list(FILTER ALL_SOURCE_FILES EXCLUDE REGEX ".*/external/.*")
# Targets de clang-tidy # Targets de clang-tidy
if(CLANG_TIDY_EXE) if(CLANG_TIDY_EXE)
# En macOS con clang-tidy de Homebrew LLVM, es necesario pasar el sysroot
# explícitamente para que encuentre los headers del sistema (string, memory, etc.)
if(APPLE)
execute_process(
COMMAND xcrun --show-sdk-path
OUTPUT_VARIABLE MACOS_SDK_PATH
OUTPUT_STRIP_TRAILING_WHITESPACE
)
set(TIDY_EXTRA_ARGS --extra-arg=-isysroot --extra-arg=${MACOS_SDK_PATH})
endif()
add_custom_target(tidy add_custom_target(tidy
COMMAND ${CLANG_TIDY_EXE} COMMAND ${CLANG_TIDY_EXE}
-p ${CMAKE_BINARY_DIR} -p ${CMAKE_BINARY_DIR}
${TIDY_EXTRA_ARGS}
${ALL_SOURCE_FILES} ${ALL_SOURCE_FILES}
WORKING_DIRECTORY ${CMAKE_SOURCE_DIR} WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}
COMMENT "Running clang-tidy..." COMMENT "Running clang-tidy..."
@@ -205,6 +217,7 @@ if(CLANG_TIDY_EXE)
COMMAND ${CLANG_TIDY_EXE} COMMAND ${CLANG_TIDY_EXE}
-p ${CMAKE_BINARY_DIR} -p ${CMAKE_BINARY_DIR}
--fix --fix
${TIDY_EXTRA_ARGS}
${ALL_SOURCE_FILES} ${ALL_SOURCE_FILES}
WORKING_DIRECTORY ${CMAKE_SOURCE_DIR} WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}
COMMENT "Running clang-tidy with fixes..." COMMENT "Running clang-tidy with fixes..."

View File

@@ -283,7 +283,7 @@ void AnimatedSprite::processAnimationParameter(const std::string& line, Animatio
void AnimatedSprite::parseFramesParameter(const std::string& frames_str, Animation& animation, const AnimationConfig& config) { void AnimatedSprite::parseFramesParameter(const std::string& frames_str, Animation& animation, const AnimationConfig& config) {
std::stringstream stream(frames_str); std::stringstream stream(frames_str);
std::string tmp; std::string tmp;
SDL_FRect rect = {0, 0, config.frame_width, config.frame_height}; SDL_FRect rect = {.x = 0, .y = 0, .w = config.frame_width, .h = config.frame_height};
while (getline(stream, tmp, ',')) { while (getline(stream, tmp, ',')) {
const int NUM_TILE = std::stoi(tmp); const int NUM_TILE = std::stoi(tmp);

View File

@@ -61,10 +61,10 @@ class AnimatedSprite : public MovingSprite {
void setCurrentAnimation(int index = 0, bool reset = true); // Establece la animación por índice void setCurrentAnimation(int index = 0, bool reset = true); // Establece la animación por índice
void resetAnimation(); // Reinicia la animación actual void resetAnimation(); // Reinicia la animación actual
void setAnimationSpeed(float value); // Establece la velocidad de la animación void setAnimationSpeed(float value); // Establece la velocidad de la animación
auto getAnimationSpeed() const -> float { return animations_[current_animation_].speed; } // Obtiene la velocidad de la animación actual [[nodiscard]] auto getAnimationSpeed() const -> float { return animations_[current_animation_].speed; } // Obtiene la velocidad de la animación actual
void animtionPause() { animations_[current_animation_].paused = true; } // Detiene la animación void animtionPause() { animations_[current_animation_].paused = true; } // Detiene la animación
void animationResume() { animations_[current_animation_].paused = false; } // Reanuda la animación void animationResume() { animations_[current_animation_].paused = false; } // Reanuda la animación
auto getCurrentAnimationFrame() const -> size_t { return animations_[current_animation_].current_frame; } // Obtiene el numero de frame de la animación actual [[nodiscard]] auto getCurrentAnimationFrame() const -> size_t { return animations_[current_animation_].current_frame; } // Obtiene el numero de frame de la animación actual
// --- Consultas --- // --- Consultas ---
auto animationIsCompleted() -> bool; // Comprueba si la animación ha terminado auto animationIsCompleted() -> bool; // Comprueba si la animación ha terminado

View File

@@ -36,7 +36,7 @@ void Asset::addToMap(const std::string& file_path, Type type, bool required, boo
std::string filename = getFileName(full_path); std::string filename = getFileName(full_path);
// Verificar si ya existe el archivo // Verificar si ya existe el archivo
if (file_list_.find(filename) != file_list_.end()) { if (file_list_.contains(filename)) {
SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION, SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION,
"Warning: Asset '%s' already exists, overwriting", "Warning: Asset '%s' already exists, overwriting",
filename.c_str()); filename.c_str());
@@ -130,7 +130,7 @@ void Asset::loadFromFile(const std::string& config_file_path, const std::string&
} }
// Devuelve la ruta completa a un fichero (búsqueda O(1)) // Devuelve la ruta completa a un fichero (búsqueda O(1))
auto Asset::get(const std::string& filename) const -> std::string { auto Asset::getPath(const std::string& filename) const -> std::string {
auto it = file_list_.find(filename); auto it = file_list_.find(filename);
if (it != file_list_.end()) { if (it != file_list_.end()) {
return it->second.file; return it->second.file;
@@ -153,7 +153,7 @@ auto Asset::loadData(const std::string& filename) const -> std::vector<uint8_t>
// Verifica si un recurso existe // Verifica si un recurso existe
auto Asset::exists(const std::string& filename) const -> bool { auto Asset::exists(const std::string& filename) const -> bool {
return file_list_.find(filename) != file_list_.end(); return file_list_.contains(filename);
} }
// Comprueba que existen todos los elementos // Comprueba que existen todos los elementos
@@ -176,7 +176,7 @@ auto Asset::check() const -> bool {
for (int type = 0; type < static_cast<int>(Type::SIZE); ++type) { for (int type = 0; type < static_cast<int>(Type::SIZE); ++type) {
Type asset_type = static_cast<Type>(type); Type asset_type = static_cast<Type>(type);
if (by_type.find(asset_type) != by_type.end()) { if (by_type.contains(asset_type)) {
Logger::info(getTypeName(asset_type) + " FILES"); Logger::info(getTypeName(asset_type) + " FILES");
bool type_success = true; bool type_success = true;

View File

@@ -33,7 +33,7 @@ class Asset {
// --- Métodos para la gestión de recursos --- // --- Métodos para la gestión de recursos ---
void add(const std::string& file_path, Type type, bool required = true, bool absolute = false); void add(const std::string& file_path, Type type, bool required = true, bool absolute = false);
void loadFromFile(const std::string& config_file_path, const std::string& prefix = "", const std::string& system_folder = ""); // Con soporte para variables void loadFromFile(const std::string& config_file_path, const std::string& prefix = "", const std::string& system_folder = ""); // Con soporte para variables
[[nodiscard]] auto get(const std::string& filename) const -> std::string; // Mantener nombre original [[nodiscard]] auto getPath(const std::string& filename) const -> std::string;
[[nodiscard]] auto loadData(const std::string& filename) const -> std::vector<uint8_t>; // Carga datos del archivo [[nodiscard]] auto loadData(const std::string& filename) const -> std::vector<uint8_t>; // Carga datos del archivo
[[nodiscard]] auto check() const -> bool; [[nodiscard]] auto check() const -> bool;
[[nodiscard]] auto getListByType(Type type) const -> std::vector<std::string>; [[nodiscard]] auto getListByType(Type type) const -> std::vector<std::string>;

View File

@@ -13,11 +13,10 @@ void AssetIntegrated::initWithResourcePack(const std::string& executable_path,
// Inicializar ResourceLoader // Inicializar ResourceLoader
auto& loader = ResourceLoader::getInstance(); auto& loader = ResourceLoader::getInstance();
if (loader.initialize(resource_pack_path, true)) { resource_pack_enabled = loader.initialize(resource_pack_path, true);
resource_pack_enabled = true; if (resource_pack_enabled) {
std::cout << "Asset system initialized with resource pack: " << resource_pack_path << '\n'; std::cout << "Asset system initialized with resource pack: " << resource_pack_path << '\n';
} else { } else {
resource_pack_enabled = false;
std::cout << "Asset system initialized in fallback mode (filesystem)" << '\n'; std::cout << "Asset system initialized in fallback mode (filesystem)" << '\n';
} }
} }

View File

@@ -34,7 +34,7 @@ Background::Background(float total_progress_to_complete)
sun_completion_progress_(total_progress_to_complete_ * SUN_COMPLETION_FACTOR), sun_completion_progress_(total_progress_to_complete_ * SUN_COMPLETION_FACTOR),
minimum_completed_progress_(total_progress_to_complete_ * MINIMUM_COMPLETED_PROGRESS_PERCENTAGE), minimum_completed_progress_(total_progress_to_complete_ * MINIMUM_COMPLETED_PROGRESS_PERCENTAGE),
rect_(SDL_FRect{0, 0, static_cast<float>(gradients_texture_->getWidth() / 2), static_cast<float>(gradients_texture_->getHeight() / 2)}), rect_(SDL_FRect{.x = 0, .y = 0, .w = static_cast<float>(gradients_texture_->getWidth() / 2), .h = static_cast<float>(gradients_texture_->getHeight() / 2)}),
src_rect_({.x = 0, .y = 0, .w = 320, .h = 240}), src_rect_({.x = 0, .y = 0, .w = 320, .h = 240}),
dst_rect_({.x = 0, .y = 0, .w = 320, .h = 240}), dst_rect_({.x = 0, .y = 0, .w = 320, .h = 240}),
attenuate_color_(Color(param.background.attenuate_color.r, param.background.attenuate_color.g, param.background.attenuate_color.b)), attenuate_color_(Color(param.background.attenuate_color.r, param.background.attenuate_color.g, param.background.attenuate_color.b)),
@@ -82,11 +82,11 @@ void Background::initializeSprites() {
const float TOP_CLOUDS_Y = base_ - 165; const float TOP_CLOUDS_Y = base_ - 165;
const float BOTTOM_CLOUDS_Y = base_ - 101; const float BOTTOM_CLOUDS_Y = base_ - 101;
top_clouds_sprite_a_ = std::make_unique<MovingSprite>(top_clouds_texture_, (SDL_FRect){0, TOP_CLOUDS_Y, rect_.w, static_cast<float>(top_clouds_texture_->getHeight())}); top_clouds_sprite_a_ = std::make_unique<MovingSprite>(top_clouds_texture_, (SDL_FRect){.x = 0, .y = TOP_CLOUDS_Y, .w = rect_.w, .h = static_cast<float>(top_clouds_texture_->getHeight())});
top_clouds_sprite_b_ = std::make_unique<MovingSprite>(top_clouds_texture_, (SDL_FRect){rect_.w, TOP_CLOUDS_Y, rect_.w, static_cast<float>(top_clouds_texture_->getHeight())}); top_clouds_sprite_b_ = std::make_unique<MovingSprite>(top_clouds_texture_, (SDL_FRect){.x = rect_.w, .y = TOP_CLOUDS_Y, .w = rect_.w, .h = static_cast<float>(top_clouds_texture_->getHeight())});
bottom_clouds_sprite_a_ = std::make_unique<MovingSprite>(bottom_clouds_texture_, (SDL_FRect){0, BOTTOM_CLOUDS_Y, rect_.w, static_cast<float>(bottom_clouds_texture_->getHeight())}); bottom_clouds_sprite_a_ = std::make_unique<MovingSprite>(bottom_clouds_texture_, (SDL_FRect){.x = 0, .y = BOTTOM_CLOUDS_Y, .w = rect_.w, .h = static_cast<float>(bottom_clouds_texture_->getHeight())});
bottom_clouds_sprite_b_ = std::make_unique<MovingSprite>(bottom_clouds_texture_, (SDL_FRect){rect_.w, BOTTOM_CLOUDS_Y, rect_.w, static_cast<float>(bottom_clouds_texture_->getHeight())}); bottom_clouds_sprite_b_ = std::make_unique<MovingSprite>(bottom_clouds_texture_, (SDL_FRect){.x = rect_.w, .y = BOTTOM_CLOUDS_Y, .w = rect_.w, .h = static_cast<float>(bottom_clouds_texture_->getHeight())});
buildings_sprite_ = std::make_unique<Sprite>(buildings_texture_); buildings_sprite_ = std::make_unique<Sprite>(buildings_texture_);
gradient_sprite_ = std::make_unique<Sprite>(gradients_texture_, 0, 0, rect_.w, rect_.h); gradient_sprite_ = std::make_unique<Sprite>(gradients_texture_, 0, 0, rect_.w, rect_.h);
@@ -152,7 +152,7 @@ void Background::update(float delta_time) {
grass_sprite_->update(delta_time); grass_sprite_->update(delta_time);
// Calcula el valor de alpha // Calcula el valor de alpha
alpha_ = std::max((255 - (int)(255 * transition_)), 0); alpha_ = std::max((255 - static_cast<int>(255 * transition_)), 0);
// Mueve el sol y la luna según la progresión // Mueve el sol y la luna según la progresión
sun_sprite_->setPosition(sun_path_.at(sun_index_)); sun_sprite_->setPosition(sun_path_.at(sun_index_));
@@ -537,14 +537,14 @@ void Background::createSunPath() {
double theta = M_PI / 2 + (i * STEP); double theta = M_PI / 2 + (i * STEP);
float x = CENTER_X + (RADIUS * cos(theta)); float x = CENTER_X + (RADIUS * cos(theta));
float y = CENTER_Y - (RADIUS * sin(theta)); float y = CENTER_Y - (RADIUS * sin(theta));
sun_path_.push_back({x, y}); sun_path_.push_back({.x = x, .y = y});
} }
// Agregar puntos en línea recta después de la curva // Agregar puntos en línea recta después de la curva
constexpr int EXTRA_PIXELS = 40; constexpr int EXTRA_PIXELS = 40;
SDL_FPoint last_point = sun_path_.back(); SDL_FPoint last_point = sun_path_.back();
for (int i = 1; i <= EXTRA_PIXELS; ++i) { for (int i = 1; i <= EXTRA_PIXELS; ++i) {
sun_path_.push_back({last_point.x, last_point.y + i}); sun_path_.push_back({.x = last_point.x, .y = last_point.y + i});
} }
} }
@@ -569,7 +569,7 @@ void Background::createMoonPath() {
if (i >= FREEZE_START_INDEX && !moon_path_.empty()) { if (i >= FREEZE_START_INDEX && !moon_path_.empty()) {
moon_path_.push_back(moon_path_.back()); // Repite el último punto válido moon_path_.push_back(moon_path_.back()); // Repite el último punto válido
} else { } else {
moon_path_.push_back({x, y}); moon_path_.push_back({.x = x, .y = y});
} }
} }
} }

View File

@@ -116,7 +116,7 @@ void Balloon::render() {
// Renderiza la estrella // Renderiza la estrella
if (!invulnerable_) { if (!invulnerable_) {
SDL_FPoint p = {24.0F, 24.0F}; SDL_FPoint p = {.x = 24.0F, .y = 24.0F};
sprite_->setRotatingCenter(p); sprite_->setRotatingCenter(p);
sprite_->render(); sprite_->render();
} }
@@ -131,7 +131,7 @@ void Balloon::render() {
// Renderizado para el resto de globos // Renderizado para el resto de globos
if (isBeingCreated()) { if (isBeingCreated()) {
// Renderizado con transparencia // Renderizado con transparencia
sprite_->getTexture()->setAlpha(255 - (int)(creation_counter_ * (255.0F / creation_counter_ini_))); sprite_->getTexture()->setAlpha(255 - static_cast<int>(creation_counter_ * (255.0F / creation_counter_ini_)));
sprite_->render(); sprite_->render();
sprite_->getTexture()->setAlpha(255); sprite_->getTexture()->setAlpha(255);
} else { } else {

View File

@@ -1,6 +1,7 @@
#include "balloon_formations.hpp" #include "balloon_formations.hpp"
#include <algorithm> // Para max, min, copy #include <algorithm> // Para max, min, copy
#include <utility> // Para std::cmp_less
#include <array> // Para array #include <array> // Para array
#include <cctype> // Para isdigit #include <cctype> // Para isdigit
#include <cstddef> // Para size_t #include <cstddef> // Para size_t
@@ -52,7 +53,7 @@ void BalloonFormations::initFormations() {
{"RIGHT", Balloon::VELX_POSITIVE}, {"RIGHT", Balloon::VELX_POSITIVE},
{"LEFT", Balloon::VELX_NEGATIVE}}; {"LEFT", Balloon::VELX_NEGATIVE}};
if (!loadFormationsFromFile(Asset::get()->get("formations.txt"), variables)) { if (!loadFormationsFromFile(Asset::get()->getPath("formations.txt"), variables)) {
// Fallback: cargar formaciones por defecto si falla la carga del archivo // Fallback: cargar formaciones por defecto si falla la carga del archivo
loadDefaultFormations(); loadDefaultFormations();
} }
@@ -78,7 +79,7 @@ auto BalloonFormations::loadFormationsFromFile(const std::string& filename, cons
} }
// Verificar si es una nueva formación // Verificar si es una nueva formación
if (line.substr(0, 10) == "formation:") { if (line.starts_with("formation:")) {
// Guardar formación anterior si existe // Guardar formación anterior si existe
if (current_formation >= 0 && !current_params.empty()) { if (current_formation >= 0 && !current_params.empty()) {
formations_.emplace_back(current_params); formations_.emplace_back(current_params);
@@ -172,7 +173,7 @@ auto BalloonFormations::evaluateExpression(const std::string& expr, const std::m
} }
// Si es una variable simple // Si es una variable simple
if (variables.find(trimmed_expr) != variables.end()) { if (variables.contains(trimmed_expr)) {
return variables.at(trimmed_expr); return variables.at(trimmed_expr);
} }
@@ -205,7 +206,7 @@ auto BalloonFormations::evaluateSimpleExpression(const std::string& expr, const
} }
// Si no se encuentra operador, intentar como variable o número // Si no se encuentra operador, intentar como variable o número
return variables.find(expr) != variables.end() ? variables.at(expr) : std::stof(expr); return variables.contains(expr) ? variables.at(expr) : std::stof(expr);
} }
auto BalloonFormations::trim(const std::string& str) -> std::string { auto BalloonFormations::trim(const std::string& str) -> std::string {
@@ -262,7 +263,7 @@ void BalloonFormations::loadDefaultFormations() {
void BalloonFormations::initFormationPools() { void BalloonFormations::initFormationPools() {
// Intentar cargar pools desde archivo // Intentar cargar pools desde archivo
if (!loadPoolsFromFile(Asset::get()->get("pools.txt"))) { if (!loadPoolsFromFile(Asset::get()->getPath("pools.txt"))) {
// Fallback: cargar pools por defecto si falla la carga del archivo // Fallback: cargar pools por defecto si falla la carga del archivo
loadDefaultPools(); loadDefaultPools();
} }
@@ -346,7 +347,7 @@ auto BalloonFormations::parsePoolLine(const std::string& line) -> std::optional<
int formation_id = std::stoi(token); int formation_id = std::stoi(token);
// Validar que el ID de formación existe // Validar que el ID de formación existe
if (formation_id >= 0 && formation_id < static_cast<int>(formations_.size())) { if (formation_id >= 0 && std::cmp_less(formation_id, formations_.size())) {
formation_ids.push_back(formation_id); formation_ids.push_back(formation_id);
} }
} }
@@ -376,7 +377,7 @@ void BalloonFormations::loadDefaultPools() {
// Pool 0: Primeras 10 formaciones (o las que haya disponibles) // Pool 0: Primeras 10 formaciones (o las que haya disponibles)
Pool pool0; Pool pool0;
for (size_t i = 0; i < std::min(size_t(10), total_formations); ++i) { for (size_t i = 0; i < std::min(static_cast<size_t>(10), total_formations); ++i) {
pool0.push_back(static_cast<int>(i)); pool0.push_back(static_cast<int>(i));
} }
if (!pool0.empty()) { if (!pool0.empty()) {
@@ -386,7 +387,7 @@ void BalloonFormations::loadDefaultPools() {
// Pool 1: Formaciones 10-19 (si existen) // Pool 1: Formaciones 10-19 (si existen)
if (total_formations > 10) { if (total_formations > 10) {
Pool pool1; Pool pool1;
for (size_t i = 10; i < std::min(size_t(20), total_formations); ++i) { for (size_t i = 10; i < std::min(static_cast<size_t>(20), total_formations); ++i) {
pool1.push_back(static_cast<int>(i)); pool1.push_back(static_cast<int>(i));
} }
if (!pool1.empty()) { if (!pool1.empty()) {
@@ -398,11 +399,11 @@ void BalloonFormations::loadDefaultPools() {
if (total_formations > 50) { if (total_formations > 50) {
Pool pool2; Pool pool2;
// Agregar algunas formaciones básicas // Agregar algunas formaciones básicas
for (size_t i = 0; i < std::min(size_t(5), total_formations); ++i) { for (size_t i = 0; i < std::min(static_cast<size_t>(5), total_formations); ++i) {
pool2.push_back(static_cast<int>(i)); pool2.push_back(static_cast<int>(i));
} }
// Agregar algunas floaters si existen // Agregar algunas floaters si existen
for (size_t i = 50; i < std::min(size_t(55), total_formations); ++i) { for (size_t i = 50; i < std::min(static_cast<size_t>(55), total_formations); ++i) {
pool2.push_back(static_cast<int>(i)); pool2.push_back(static_cast<int>(i));
} }
if (!pool2.empty()) { if (!pool2.empty()) {
@@ -413,7 +414,7 @@ void BalloonFormations::loadDefaultPools() {
// Pool 3: Solo floaters (si existen formaciones 50+) // Pool 3: Solo floaters (si existen formaciones 50+)
if (total_formations > 50) { if (total_formations > 50) {
Pool pool3; Pool pool3;
for (size_t i = 50; i < std::min(size_t(70), total_formations); ++i) { for (size_t i = 50; i < std::min(static_cast<size_t>(70), total_formations); ++i) {
pool3.push_back(static_cast<int>(i)); pool3.push_back(static_cast<int>(i));
} }
if (!pool3.empty()) { if (!pool3.empty()) {

View File

@@ -158,7 +158,7 @@ void BalloonManager::deployFormation(int formation_id, float y) {
// Vacia del vector de globos los globos que ya no sirven // Vacia del vector de globos los globos que ya no sirven
void BalloonManager::freeBalloons() { void BalloonManager::freeBalloons() {
std::erase_if(balloons_, [](const auto& balloon) { std::erase_if(balloons_, [](const auto& balloon) -> auto {
return !balloon->isEnabled(); return !balloon->isEnabled();
}); });
} }
@@ -174,7 +174,7 @@ auto BalloonManager::canPowerBallBeCreated() -> bool { return (!power_ball_enabl
// Calcula el poder actual de los globos en pantalla // Calcula el poder actual de los globos en pantalla
auto BalloonManager::calculateScreenPower() -> int { auto BalloonManager::calculateScreenPower() -> int {
return std::accumulate(balloons_.begin(), balloons_.end(), 0, [](int sum, const auto& balloon) { return sum + (balloon->isEnabled() ? balloon->getPower() : 0); }); return std::accumulate(balloons_.begin(), balloons_.end(), 0, [](int sum, const auto& balloon) -> auto { return sum + (balloon->isEnabled() ? balloon->getPower() : 0); });
} }
// Crea un globo nuevo en el vector de globos // Crea un globo nuevo en el vector de globos
@@ -400,7 +400,7 @@ void BalloonManager::createTwoBigBalloons() {
// Obtiene el nivel de ameza actual generado por los globos // Obtiene el nivel de ameza actual generado por los globos
auto BalloonManager::getMenace() -> int { auto BalloonManager::getMenace() -> int {
return std::accumulate(balloons_.begin(), balloons_.end(), 0, [](int sum, const auto& balloon) { return sum + (balloon->isEnabled() ? balloon->getMenace() : 0); }); return std::accumulate(balloons_.begin(), balloons_.end(), 0, [](int sum, const auto& balloon) -> auto { return sum + (balloon->isEnabled() ? balloon->getMenace() : 0); });
} }
// Establece el sonido de los globos // Establece el sonido de los globos

View File

@@ -37,7 +37,7 @@ void BulletManager::createBullet(int x, int y, Bullet::Type type, Bullet::Color
// Libera balas que ya no están habilitadas // Libera balas que ya no están habilitadas
void BulletManager::freeBullets() { void BulletManager::freeBullets() {
std::erase_if(bullets_, [](const std::shared_ptr<Bullet>& bullet) { std::erase_if(bullets_, [](const std::shared_ptr<Bullet>& bullet) -> bool {
return !bullet->isEnabled(); return !bullet->isEnabled();
}); });
} }

View File

@@ -125,7 +125,7 @@ namespace Colors {
if (n < colors.size()) { if (n < colors.size()) {
index = n; // Avanza: 0,1,2,3 index = n; // Avanza: 0,1,2,3
} else { } else {
index = 2 * (colors.size() - 1) - n; // Retrocede: 2,1 index = (2 * (colors.size() - 1)) - n; // Retrocede: 2,1
} }
return colors[index]; return colors[index];

View File

@@ -198,13 +198,13 @@ void DefineButtons::incIndexButton() {
} }
auto DefineButtons::checkButtonNotInUse(SDL_GamepadButton button) -> bool { auto DefineButtons::checkButtonNotInUse(SDL_GamepadButton button) -> bool {
return std::ranges::all_of(buttons_, [button](const auto& b) { return std::ranges::all_of(buttons_, [button](const auto& b) -> auto {
return b.button != button; return b.button != button;
}); });
} }
auto DefineButtons::checkTriggerNotInUse(int trigger_button) -> bool { auto DefineButtons::checkTriggerNotInUse(int trigger_button) -> bool {
return std::ranges::all_of(buttons_, [trigger_button](const auto& b) { return std::ranges::all_of(buttons_, [trigger_button](const auto& b) -> auto {
return b.button != trigger_button; return b.button != trigger_button;
}); });
} }

View File

@@ -100,11 +100,11 @@ void Director::init() {
loadAssets(); // Crea el índice de archivos loadAssets(); // Crea el índice de archivos
Logger::section("INIT INPUT"); Logger::section("INIT INPUT");
Input::init(Asset::get()->get("gamecontrollerdb.txt"), Asset::get()->get("controllers.json")); // Carga configuración de controles Input::init(Asset::get()->getPath("gamecontrollerdb.txt"), Asset::get()->getPath("controllers.json")); // Carga configuración de controles
Logger::section("INIT CONFIG"); Logger::section("INIT CONFIG");
Options::setConfigFile(Asset::get()->get("config_v2.txt")); // Establece el fichero de configuración Options::setConfigFile(Asset::get()->getPath("config_v2.txt")); // Establece el fichero de configuración
Options::setControllersFile(Asset::get()->get("controllers.json")); // Establece el fichero de configuración de mandos Options::setControllersFile(Asset::get()->getPath("controllers.json")); // Establece el fichero de configuración de mandos
Options::loadFromFile(); // Carga el archivo de configuración Options::loadFromFile(); // Carga el archivo de configuración
loadParams(); // Carga los parámetros del programa loadParams(); // Carga los parámetros del programa
loadScoreFile(); // Carga el archivo de puntuaciones loadScoreFile(); // Carga el archivo de puntuaciones
@@ -156,9 +156,9 @@ void Director::close() {
void Director::loadParams() { void Director::loadParams() {
// Carga los parametros para configurar el juego // Carga los parametros para configurar el juego
#ifdef ANBERNIC #ifdef ANBERNIC
const std::string PARAM_FILE_PATH = Asset::get()->get("param_320x240.txt"); const std::string PARAM_FILE_PATH = Asset::get()->getPath("param_320x240.txt");
#else #else
const std::string PARAM_FILE_PATH = Asset::get()->get(Options::settings.params_file); const std::string PARAM_FILE_PATH = Asset::get()->getPath(Options::settings.params_file);
#endif #endif
loadParamsFromFile(PARAM_FILE_PATH); loadParamsFromFile(PARAM_FILE_PATH);
} }
@@ -172,7 +172,7 @@ void Director::loadScoreFile() {
if (overrides.clear_hi_score_table) { if (overrides.clear_hi_score_table) {
manager->clear(); manager->clear();
} else { } else {
manager->loadFromFile(Asset::get()->get("score.bin")); manager->loadFromFile(Asset::get()->getPath("score.bin"));
} }
#endif #endif
} }

View File

@@ -5,8 +5,7 @@
#include <string_view> // Para basic_string_view, string_view #include <string_view> // Para basic_string_view, string_view
// Constructor // Constructor
EnterName::EnterName() EnterName::EnterName() = default;
: character_list_("ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789{") {}
// Inicializa el objeto // Inicializa el objeto
void EnterName::init(const std::string& name) { void EnterName::init(const std::string& name) {

View File

@@ -32,7 +32,7 @@ class EnterName {
private: private:
// --- Variables de estado --- // --- Variables de estado ---
std::string character_list_; // Lista de caracteres permitidos std::string character_list_{"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789{"}; // Lista de caracteres permitidos
std::string name_; // Nombre en proceso std::string name_; // Nombre en proceso
size_t selected_index_ = 0; // Índice del carácter seleccionado en "character_list_" size_t selected_index_ = 0; // Índice del carácter seleccionado en "character_list_"

View File

@@ -1,5 +1,7 @@
#include "explosions.hpp" #include "explosions.hpp"
#include <utility> // Para std::cmp_less
#include "animated_sprite.hpp" // Para AnimatedSprite #include "animated_sprite.hpp" // Para AnimatedSprite
class Texture; // lines 4-4 class Texture; // lines 4-4
@@ -46,7 +48,7 @@ void Explosions::freeExplosions() {
// Busca una textura a partir del tamaño // Busca una textura a partir del tamaño
auto Explosions::getIndexBySize(int size) -> int { auto Explosions::getIndexBySize(int size) -> int {
for (int i = 0; i < (int)textures_.size(); ++i) { for (int i = 0; std::cmp_less(i, textures_.size()); ++i) {
if (size == textures_[i].size) { if (size == textures_[i].size) {
return i; return i;
} }

View File

@@ -4,6 +4,7 @@
#include <algorithm> #include <algorithm>
#include <cstdlib> #include <cstdlib>
#include <utility>
#include "color.hpp" #include "color.hpp"
#include "param.hpp" #include "param.hpp"
@@ -86,7 +87,7 @@ void Fade::update(float delta_time) {
void Fade::updatePreState() { void Fade::updatePreState() {
Uint32 elapsed_time = SDL_GetTicks() - pre_start_time_; Uint32 elapsed_time = SDL_GetTicks() - pre_start_time_;
if (elapsed_time >= static_cast<Uint32>(pre_duration_)) { if (std::cmp_greater_equal(elapsed_time, pre_duration_)) {
state_ = State::FADING; state_ = State::FADING;
fading_start_time_ = SDL_GetTicks(); // Inicia el temporizador del fade AQUI fading_start_time_ = SDL_GetTicks(); // Inicia el temporizador del fade AQUI
} }
@@ -125,7 +126,7 @@ void Fade::changeToPostState() {
void Fade::updatePostState() { void Fade::updatePostState() {
Uint32 elapsed_time = SDL_GetTicks() - post_start_time_; Uint32 elapsed_time = SDL_GetTicks() - post_start_time_;
if (elapsed_time >= static_cast<Uint32>(post_duration_)) { if (std::cmp_greater_equal(elapsed_time, post_duration_)) {
state_ = State::FINISHED; state_ = State::FINISHED;
} }
@@ -147,7 +148,7 @@ void Fade::updateFullscreenFade() {
value_ = static_cast<int>(progress * 100); value_ = static_cast<int>(progress * 100);
// Comprueba si ha terminado // Comprueba si ha terminado
if (elapsed_time >= static_cast<Uint32>(fading_duration_)) { if (std::cmp_greater_equal(elapsed_time, fading_duration_)) {
changeToPostState(); changeToPostState();
} }
} }
@@ -171,7 +172,7 @@ void Fade::updateCenterFade() {
value_ = static_cast<int>(progress * 100); value_ = static_cast<int>(progress * 100);
// Comprueba si ha terminado // Comprueba si ha terminado
if (elapsed_time >= static_cast<Uint32>(fading_duration_)) { if (std::cmp_greater_equal(elapsed_time, fading_duration_)) {
a_ = (mode_ == Mode::OUT) ? 255 : 0; a_ = (mode_ == Mode::OUT) ? 255 : 0;
changeToPostState(); changeToPostState();
} }
@@ -202,7 +203,7 @@ void Fade::updateRandomSquareFade() {
value_ = static_cast<int>(progress * 100); value_ = static_cast<int>(progress * 100);
// Comprueba si ha terminado // Comprueba si ha terminado
if (elapsed_time >= static_cast<Uint32>(fading_duration_)) { if (std::cmp_greater_equal(elapsed_time, fading_duration_)) {
changeToPostState(); changeToPostState();
} }
} }
@@ -216,7 +217,7 @@ void Fade::updateRandomSquare2Fade() {
int squares_to_activate = 0; int squares_to_activate = 0;
if (mode_ == Mode::OUT) { if (mode_ == Mode::OUT) {
if (elapsed_time < static_cast<Uint32>(activation_time)) { if (std::cmp_less(elapsed_time, activation_time)) {
float activation_progress = static_cast<float>(elapsed_time) / activation_time; float activation_progress = static_cast<float>(elapsed_time) / activation_time;
squares_to_activate = static_cast<int>(activation_progress * total_squares); squares_to_activate = static_cast<int>(activation_progress * total_squares);
} else { } else {
@@ -237,7 +238,7 @@ void Fade::updateRandomSquare2Fade() {
drawRandomSquares2(); drawRandomSquares2();
value_ = calculateValue(0, total_squares, squares_to_activate); value_ = calculateValue(0, total_squares, squares_to_activate);
if (elapsed_time >= static_cast<Uint32>(fading_duration_)) { if (std::cmp_greater_equal(elapsed_time, fading_duration_)) {
Uint8 final_alpha = (mode_ == Mode::OUT) ? 255 : 0; Uint8 final_alpha = (mode_ == Mode::OUT) ? 255 : 0;
cleanBackbuffer(r_, g_, b_, final_alpha); cleanBackbuffer(r_, g_, b_, final_alpha);
changeToPostState(); changeToPostState();
@@ -253,7 +254,7 @@ void Fade::updateDiagonalFade() {
int max_diagonal = num_squares_width_ + num_squares_height_ - 1; int max_diagonal = num_squares_width_ + num_squares_height_ - 1;
int active_diagonals = 0; int active_diagonals = 0;
if (mode_ == Mode::OUT) { if (mode_ == Mode::OUT) {
if (elapsed_time < static_cast<Uint32>(activation_time)) { if (std::cmp_less(elapsed_time, activation_time)) {
float activation_progress = static_cast<float>(elapsed_time) / activation_time; float activation_progress = static_cast<float>(elapsed_time) / activation_time;
active_diagonals = static_cast<int>(activation_progress * max_diagonal); active_diagonals = static_cast<int>(activation_progress * max_diagonal);
} else { } else {
@@ -264,7 +265,7 @@ void Fade::updateDiagonalFade() {
} }
} else { } else {
active_diagonals = max_diagonal; active_diagonals = max_diagonal;
if (elapsed_time < static_cast<Uint32>(activation_time)) { if (std::cmp_less(elapsed_time, activation_time)) {
float activation_progress = static_cast<float>(elapsed_time) / activation_time; float activation_progress = static_cast<float>(elapsed_time) / activation_time;
int diagonals_starting_transition = static_cast<int>(activation_progress * max_diagonal); int diagonals_starting_transition = static_cast<int>(activation_progress * max_diagonal);
for (int diagonal = 0; diagonal < diagonals_starting_transition; ++diagonal) { for (int diagonal = 0; diagonal < diagonals_starting_transition; ++diagonal) {
@@ -280,7 +281,7 @@ void Fade::updateDiagonalFade() {
drawDiagonal(); drawDiagonal();
value_ = calculateValue(0, max_diagonal, active_diagonals); value_ = calculateValue(0, max_diagonal, active_diagonals);
if (elapsed_time >= static_cast<Uint32>(fading_duration_)) { if (std::cmp_greater_equal(elapsed_time, fading_duration_)) {
Uint8 final_alpha = (mode_ == Mode::OUT) ? 255 : 0; Uint8 final_alpha = (mode_ == Mode::OUT) ? 255 : 0;
cleanBackbuffer(r_, g_, b_, final_alpha); cleanBackbuffer(r_, g_, b_, final_alpha);
changeToPostState(); changeToPostState();
@@ -292,7 +293,7 @@ void Fade::activateDiagonal(int diagonal_index, Uint32 current_time) {
int y = diagonal_index - x; int y = diagonal_index - x;
if (y >= 0 && y < num_squares_height_) { if (y >= 0 && y < num_squares_height_) {
int index = (y * num_squares_width_) + x; int index = (y * num_squares_width_) + x;
if (index >= 0 && index < static_cast<int>(square_age_.size()) && square_age_[index] == -1) { if (index >= 0 && std::cmp_less(index, square_age_.size()) && square_age_[index] == -1) {
square_age_[index] = current_time; square_age_[index] = current_time;
} }
} }
@@ -339,7 +340,7 @@ void Fade::drawRandomSquares(int active_count) {
SDL_SetRenderDrawColor(renderer_, r_, g_, b_, a_); SDL_SetRenderDrawColor(renderer_, r_, g_, b_, a_);
// Dibuja solo los cuadrados activos // Dibuja solo los cuadrados activos
for (int i = 0; i < active_count && i < static_cast<int>(square_.size()); ++i) { for (int i = 0; i < active_count && std::cmp_less(i, square_.size()); ++i) {
SDL_RenderFillRect(renderer_, &square_[i]); SDL_RenderFillRect(renderer_, &square_[i]);
} }
@@ -394,7 +395,7 @@ void Fade::updateVenetianFade() {
value_ = static_cast<int>(progress * 100); value_ = static_cast<int>(progress * 100);
// Comprueba si ha terminado // Comprueba si ha terminado
if (elapsed_time >= static_cast<Uint32>(fading_duration_)) { if (std::cmp_greater_equal(elapsed_time, fading_duration_)) {
changeToPostState(); changeToPostState();
} }
} }

View File

@@ -72,7 +72,7 @@ class Fade {
int num_squares_width_; // Cuadrados en horizontal int num_squares_width_; // Cuadrados en horizontal
int num_squares_height_; // Cuadrados en vertical int num_squares_height_; // Cuadrados en vertical
int square_transition_duration_; // Duración de transición de cada cuadrado en ms int square_transition_duration_; // Duración de transición de cada cuadrado en ms
int fading_duration_; // Duración del estado FADING en milisegundos int fading_duration_{0}; // Duración del estado FADING en milisegundos
Uint32 fading_start_time_ = 0; // Tiempo de inicio del estado FADING Uint32 fading_start_time_ = 0; // Tiempo de inicio del estado FADING
int post_duration_ = 0; // Duración posterior en milisegundos int post_duration_ = 0; // Duración posterior en milisegundos
Uint32 post_start_time_ = 0; // Tiempo de inicio del estado POST Uint32 post_start_time_ = 0; // Tiempo de inicio del estado POST

View File

@@ -64,7 +64,7 @@ class GamepadConfigManager {
// Escribir al archivo // Escribir al archivo
std::ofstream file(filename); std::ofstream file(filename);
if (!file.is_open()) { if (!file.is_open()) {
return false; return false; // NOLINT(readability-simplify-boolean-expr)
} }
file << j.dump(4); // Formato con indentación de 4 espacios file << j.dump(4); // Formato con indentación de 4 espacios
@@ -92,7 +92,7 @@ class GamepadConfigManager {
configs.clear(); configs.clear();
if (!j.contains("gamepads") || !j["gamepads"].is_array()) { if (!j.contains("gamepads") || !j["gamepads"].is_array()) {
return false; return false; // NOLINT(readability-simplify-boolean-expr)
} }
for (const auto& gamepad_json : j["gamepads"]) { for (const auto& gamepad_json : j["gamepads"]) {

View File

@@ -54,7 +54,7 @@ namespace GlobalEvents {
break; break;
case SDL_EVENT_WINDOW_RESIZED: case SDL_EVENT_WINDOW_RESIZED:
Screen::get()->initShaders(); Screen::initShaders();
break; break;
default: default:

View File

@@ -64,7 +64,7 @@ namespace GlobalInputs {
// Activa o desactiva los shaders // Activa o desactiva los shaders
void toggleShaders() { void toggleShaders() {
Screen::get()->toggleShaders(); Screen::toggleShaders();
Notifier::get()->show({Lang::getText("[NOTIFICATIONS] 13") + " " + boolToOnOff(Options::video.shaders)}); Notifier::get()->show({Lang::getText("[NOTIFICATIONS] 13") + " " + boolToOnOff(Options::video.shaders)});
} }
@@ -146,7 +146,7 @@ namespace GlobalInputs {
} }
// Mandos // Mandos
if (std::ranges::any_of(Input::get()->getGamepads(), [](const auto& gamepad) { if (std::ranges::any_of(Input::get()->getGamepads(), [](const auto& gamepad) -> auto {
return Input::get()->checkAction(Input::Action::SERVICE, Input::DO_NOT_ALLOW_REPEAT, Input::DO_NOT_CHECK_KEYBOARD, gamepad); return Input::get()->checkAction(Input::Action::SERVICE, Input::DO_NOT_ALLOW_REPEAT, Input::DO_NOT_CHECK_KEYBOARD, gamepad);
})) { })) {
toggleServiceMenu(); toggleServiceMenu();
@@ -173,11 +173,11 @@ namespace GlobalInputs {
{Action::TOGGLE_VIDEO_INTEGER_SCALE, toggleIntegerScale}, {Action::TOGGLE_VIDEO_INTEGER_SCALE, toggleIntegerScale},
{Action::TOGGLE_VIDEO_VSYNC, toggleVSync}, {Action::TOGGLE_VIDEO_VSYNC, toggleVSync},
#ifdef _DEBUG #ifdef _DEBUG
{Action::SHOW_INFO, [] { Screen::get()->toggleDebugInfo(); }}, {Action::SHOW_INFO, []() -> void { Screen::get()->toggleDebugInfo(); }},
#endif #endif
}; };
return std::ranges::any_of(ACTIONS, [](const auto& pair) { return std::ranges::any_of(ACTIONS, [](const auto& pair) -> auto {
if (Input::get()->checkAction(pair.first, Input::DO_NOT_ALLOW_REPEAT, Input::CHECK_KEYBOARD)) { if (Input::get()->checkAction(pair.first, Input::DO_NOT_ALLOW_REPEAT, Input::CHECK_KEYBOARD)) {
pair.second(); pair.second();
return true; return true;

View File

@@ -413,7 +413,7 @@ auto Input::addGamepad(int device_index) -> std::string {
} }
auto Input::removeGamepad(SDL_JoystickID id) -> std::string { auto Input::removeGamepad(SDL_JoystickID id) -> std::string {
auto it = std::ranges::find_if(gamepads_, [id](const std::shared_ptr<Gamepad>& gamepad) { auto it = std::ranges::find_if(gamepads_, [id](const std::shared_ptr<Gamepad>& gamepad) -> bool {
return gamepad->instance_id == id; return gamepad->instance_id == id;
}); });
@@ -457,7 +457,7 @@ void Input::applyGamepadConfig(std::shared_ptr<Gamepad> gamepad) {
} }
// --- Buscar configuración por RUTA (path) --- // --- Buscar configuración por RUTA (path) ---
auto config_it = std::ranges::find_if(gamepad_configs_, [&gamepad](const GamepadConfig& config) { auto config_it = std::ranges::find_if(gamepad_configs_, [&gamepad](const GamepadConfig& config) -> bool {
return config.path == gamepad->path; return config.path == gamepad->path;
}); });
@@ -465,7 +465,7 @@ void Input::applyGamepadConfig(std::shared_ptr<Gamepad> gamepad) {
// Se encontró una configuración específica para este puerto/dispositivo. La aplicamos. // Se encontró una configuración específica para este puerto/dispositivo. La aplicamos.
std::cout << "Applying custom config for gamepad at path: " << gamepad->path << '\n'; std::cout << "Applying custom config for gamepad at path: " << gamepad->path << '\n';
for (const auto& [action, button] : config_it->bindings) { for (const auto& [action, button] : config_it->bindings) {
if (gamepad->bindings.find(action) != gamepad->bindings.end()) { if (gamepad->bindings.contains(action)) {
gamepad->bindings[action].button = button; gamepad->bindings[action].button = button;
} }
} }
@@ -479,7 +479,7 @@ void Input::saveGamepadConfigFromGamepad(std::shared_ptr<Gamepad> gamepad) {
} }
// --- CAMBIO CLAVE: Buscar si ya existe una configuración por RUTA (path) --- // --- CAMBIO CLAVE: Buscar si ya existe una configuración por RUTA (path) ---
auto config_it = std::ranges::find_if(gamepad_configs_, [&gamepad](const GamepadConfig& config) { auto config_it = std::ranges::find_if(gamepad_configs_, [&gamepad](const GamepadConfig& config) -> bool {
return config.path == gamepad->path; return config.path == gamepad->path;
}); });
@@ -512,7 +512,7 @@ void Input::setGamepadConfigsFile(const std::string& filename) {
// Método para obtener configuración de un gamepad específico (opcional) // Método para obtener configuración de un gamepad específico (opcional)
auto Input::getGamepadConfig(const std::string& gamepad_name) -> GamepadConfig* { auto Input::getGamepadConfig(const std::string& gamepad_name) -> GamepadConfig* {
auto config_it = std::ranges::find_if(gamepad_configs_, [&gamepad_name](const GamepadConfig& config) { auto config_it = std::ranges::find_if(gamepad_configs_, [&gamepad_name](const GamepadConfig& config) -> bool {
return config.name == gamepad_name; return config.name == gamepad_name;
}); });
@@ -521,7 +521,7 @@ auto Input::getGamepadConfig(const std::string& gamepad_name) -> GamepadConfig*
// Método para eliminar configuración de gamepad (opcional) // Método para eliminar configuración de gamepad (opcional)
auto Input::removeGamepadConfig(const std::string& gamepad_name) -> bool { auto Input::removeGamepadConfig(const std::string& gamepad_name) -> bool {
auto config_it = std::ranges::find_if(gamepad_configs_, [&gamepad_name](const GamepadConfig& config) { auto config_it = std::ranges::find_if(gamepad_configs_, [&gamepad_name](const GamepadConfig& config) -> bool {
return config.name == gamepad_name; return config.name == gamepad_name;
}); });

View File

@@ -53,47 +53,46 @@ class Input {
}; };
struct Keyboard { struct Keyboard {
std::unordered_map<Action, KeyState> bindings; std::unordered_map<Action, KeyState> bindings{
// Movimiento del jugador
{Action::UP, KeyState(SDL_SCANCODE_UP)},
{Action::DOWN, KeyState(SDL_SCANCODE_DOWN)},
{Action::LEFT, KeyState(SDL_SCANCODE_LEFT)},
{Action::RIGHT, KeyState(SDL_SCANCODE_RIGHT)},
Keyboard() // Disparo del jugador
: bindings{ {Action::FIRE_LEFT, KeyState(SDL_SCANCODE_Q)},
// Movimiento del jugador {Action::FIRE_CENTER, KeyState(SDL_SCANCODE_W)},
{Action::UP, KeyState(SDL_SCANCODE_UP)}, {Action::FIRE_RIGHT, KeyState(SDL_SCANCODE_E)},
{Action::DOWN, KeyState(SDL_SCANCODE_DOWN)},
{Action::LEFT, KeyState(SDL_SCANCODE_LEFT)},
{Action::RIGHT, KeyState(SDL_SCANCODE_RIGHT)},
// Disparo del jugador // Interfaz
{Action::FIRE_LEFT, KeyState(SDL_SCANCODE_Q)}, {Action::START, KeyState(SDL_SCANCODE_RETURN)},
{Action::FIRE_CENTER, KeyState(SDL_SCANCODE_W)},
{Action::FIRE_RIGHT, KeyState(SDL_SCANCODE_E)},
// Interfaz // Menu de servicio
{Action::START, KeyState(SDL_SCANCODE_RETURN)}, {Action::SERVICE, KeyState(SDL_SCANCODE_F12)},
{Action::SM_SELECT, KeyState(SDL_SCANCODE_RETURN)},
{Action::SM_BACK, KeyState(SDL_SCANCODE_BACKSPACE)},
// Menu de servicio // Control del programa
{Action::SERVICE, KeyState(SDL_SCANCODE_F12)}, {Action::EXIT, KeyState(SDL_SCANCODE_ESCAPE)},
{Action::SM_SELECT, KeyState(SDL_SCANCODE_RETURN)}, {Action::PAUSE, KeyState(SDL_SCANCODE_P)},
{Action::SM_BACK, KeyState(SDL_SCANCODE_BACKSPACE)}, {Action::BACK, KeyState(SDL_SCANCODE_BACKSPACE)},
// Control del programa {Action::WINDOW_DEC_SIZE, KeyState(SDL_SCANCODE_F1)},
{Action::EXIT, KeyState(SDL_SCANCODE_ESCAPE)}, {Action::WINDOW_INC_SIZE, KeyState(SDL_SCANCODE_F2)},
{Action::PAUSE, KeyState(SDL_SCANCODE_P)}, {Action::WINDOW_FULLSCREEN, KeyState(SDL_SCANCODE_F3)},
{Action::BACK, KeyState(SDL_SCANCODE_BACKSPACE)}, {Action::TOGGLE_VIDEO_SHADERS, KeyState(SDL_SCANCODE_F4)},
{Action::TOGGLE_VIDEO_INTEGER_SCALE, KeyState(SDL_SCANCODE_F5)},
{Action::TOGGLE_VIDEO_VSYNC, KeyState(SDL_SCANCODE_F6)},
{Action::WINDOW_DEC_SIZE, KeyState(SDL_SCANCODE_F1)}, {Action::TOGGLE_AUDIO, KeyState(SDL_SCANCODE_F7)},
{Action::WINDOW_INC_SIZE, KeyState(SDL_SCANCODE_F2)}, {Action::TOGGLE_AUTO_FIRE, KeyState(SDL_SCANCODE_F8)},
{Action::WINDOW_FULLSCREEN, KeyState(SDL_SCANCODE_F3)}, {Action::CHANGE_LANG, KeyState(SDL_SCANCODE_F9)},
{Action::TOGGLE_VIDEO_SHADERS, KeyState(SDL_SCANCODE_F4)},
{Action::TOGGLE_VIDEO_INTEGER_SCALE, KeyState(SDL_SCANCODE_F5)},
{Action::TOGGLE_VIDEO_VSYNC, KeyState(SDL_SCANCODE_F6)},
{Action::TOGGLE_AUDIO, KeyState(SDL_SCANCODE_F7)}, {Action::RESET, KeyState(SDL_SCANCODE_F10)},
{Action::TOGGLE_AUTO_FIRE, KeyState(SDL_SCANCODE_F8)}, {Action::SHOW_INFO, KeyState(SDL_SCANCODE_F11)}};
{Action::CHANGE_LANG, KeyState(SDL_SCANCODE_F9)},
{Action::RESET, KeyState(SDL_SCANCODE_F10)}, Keyboard() = default;
{Action::SHOW_INFO, KeyState(SDL_SCANCODE_F11)}} {}
}; };
struct Gamepad { struct Gamepad {
@@ -162,11 +161,11 @@ class Input {
// --- Métodos de gestión de mandos --- // --- Métodos de gestión de mandos ---
[[nodiscard]] auto gameControllerFound() const -> bool; [[nodiscard]] auto gameControllerFound() const -> bool;
static auto getControllerName(const std::shared_ptr<Gamepad>& gamepad) -> std::string; static auto getControllerName(const std::shared_ptr<Gamepad>& gamepad) -> std::string;
auto getControllerNames() const -> std::vector<std::string>; [[nodiscard]] auto getControllerNames() const -> std::vector<std::string>;
[[nodiscard]] auto getNumGamepads() const -> int; [[nodiscard]] auto getNumGamepads() const -> int;
auto getGamepad(SDL_JoystickID id) const -> std::shared_ptr<Gamepad>; [[nodiscard]] auto getGamepad(SDL_JoystickID id) const -> std::shared_ptr<Gamepad>;
auto getGamepadByName(const std::string& name) const -> std::shared_ptr<Input::Gamepad>; [[nodiscard]] auto getGamepadByName(const std::string& name) const -> std::shared_ptr<Input::Gamepad>;
auto getGamepads() const -> const Gamepads& { return gamepads_; } [[nodiscard]] auto getGamepads() const -> const Gamepads& { return gamepads_; }
// --- Métodos de consulta y utilidades --- // --- Métodos de consulta y utilidades ---
[[nodiscard]] static auto getControllerBinding(const std::shared_ptr<Gamepad>& gamepad, Action action) -> SDL_GamepadButton; [[nodiscard]] static auto getControllerBinding(const std::shared_ptr<Gamepad>& gamepad, Action action) -> SDL_GamepadButton;

View File

@@ -157,17 +157,17 @@ namespace Lang {
auto getLanguageFileName(Lang::Code code) -> std::string { auto getLanguageFileName(Lang::Code code) -> std::string {
for (const auto& lang : languages) { for (const auto& lang : languages) {
if (lang.code == code) { if (lang.code == code) {
return Asset::get()->get(lang.file_name); return Asset::get()->getPath(lang.file_name);
} }
} }
// Si no se encuentra, devuelve el fichero del primer idioma por defecto // Si no se encuentra, devuelve el fichero del primer idioma por defecto
return Asset::get()->get(languages[0].file_name); return Asset::get()->getPath(languages[0].file_name);
} }
// Establece el idioma // Establece el idioma
void setLanguage(Code code) { void setLanguage(Code code) {
Options::settings.language = code; Options::settings.language = code;
loadFromFile(Asset::get()->get(getLanguage(code).file_name)); loadFromFile(Asset::get()->getPath(getLanguage(code).file_name));
updateLanguageNames(); updateLanguageNames();
updateDifficultyNames(); updateDifficultyNames();
} }
@@ -176,13 +176,13 @@ namespace Lang {
auto getLangFile(Code code) -> std::string { auto getLangFile(Code code) -> std::string {
switch (code) { switch (code) {
case Code::VALENCIAN: case Code::VALENCIAN:
return Asset::get()->get("ba_BA.json"); return Asset::get()->getPath("ba_BA.json");
break; break;
case Code::SPANISH: case Code::SPANISH:
return Asset::get()->get("es_ES.json"); return Asset::get()->getPath("es_ES.json");
break; break;
default: default:
return Asset::get()->get("en_UK.json"); return Asset::get()->getPath("en_UK.json");
break; break;
} }
} }

View File

@@ -67,7 +67,7 @@ auto ManageHiScoreTable::add(const HiScoreEntry& entry) -> int {
sort(); sort();
// Encontrar la posición del nuevo elemento // Encontrar la posición del nuevo elemento
auto it = std::ranges::find_if(table_, [&](const HiScoreEntry& e) { auto it = std::ranges::find_if(table_, [&](const HiScoreEntry& e) -> bool {
return e.name == entry.name && e.score == entry.score && e.one_credit_complete == entry.one_credit_complete; return e.name == entry.name && e.score == entry.score && e.one_credit_complete == entry.one_credit_complete;
}); });

View File

@@ -200,24 +200,24 @@ namespace Options {
// Un mapa estático asegura que se inicializa solo una vez // Un mapa estático asegura que se inicializa solo una vez
static const std::map<std::string, std::function<void(const std::string&)>> SETTINGS_MAP = { static const std::map<std::string, std::function<void(const std::string&)>> SETTINGS_MAP = {
// Configuración // Configuración
{"config.version", [](const auto& val) { settings.config_version = std::stoi(val); }}, {"config.version", [](const auto& val) -> auto { settings.config_version = std::stoi(val); }},
// Ventana // Ventana
{"window.zoom", [](const auto& val) { window.zoom = std::stoi(val); }}, {"window.zoom", [](const auto& val) -> auto { window.zoom = std::stoi(val); }},
// Vídeo // Vídeo
{"video.fullscreen", [](const auto& val) { video.fullscreen = stringToBool(val); }}, {"video.fullscreen", [](const auto& val) -> auto { video.fullscreen = stringToBool(val); }},
{"video.scale_mode", [](const auto& val) { video.scale_mode = static_cast<SDL_ScaleMode>(std::stoi(val)); }}, {"video.scale_mode", [](const auto& val) -> auto { video.scale_mode = static_cast<SDL_ScaleMode>(std::stoi(val)); }},
{"video.shaders", [](const auto& val) { video.shaders = stringToBool(val); }}, {"video.shaders", [](const auto& val) -> auto { video.shaders = stringToBool(val); }},
{"video.integer_scale", [](const auto& val) { video.integer_scale = stringToBool(val); }}, {"video.integer_scale", [](const auto& val) -> auto { video.integer_scale = stringToBool(val); }},
{"video.vsync", [](const auto& val) { video.vsync = stringToBool(val); }}, {"video.vsync", [](const auto& val) -> auto { video.vsync = stringToBool(val); }},
// Audio // Audio
{"audio.enabled", [](const auto& val) { audio.enabled = stringToBool(val); }}, {"audio.enabled", [](const auto& val) -> auto { audio.enabled = stringToBool(val); }},
{"audio.volume", [](const auto& val) { audio.volume = std::clamp(std::stoi(val), 0, 100); }}, {"audio.volume", [](const auto& val) -> auto { audio.volume = std::clamp(std::stoi(val), 0, 100); }},
{"audio.music.enabled", [](const auto& val) { audio.music.enabled = stringToBool(val); }}, {"audio.music.enabled", [](const auto& val) -> auto { audio.music.enabled = stringToBool(val); }},
{"audio.music.volume", [](const auto& val) { audio.music.volume = std::clamp(std::stoi(val), 0, 100); }}, {"audio.music.volume", [](const auto& val) -> auto { audio.music.volume = std::clamp(std::stoi(val), 0, 100); }},
{"audio.sound.enabled", [](const auto& val) { audio.sound.enabled = stringToBool(val); }}, {"audio.sound.enabled", [](const auto& val) -> auto { audio.sound.enabled = stringToBool(val); }},
{"audio.sound.volume", [](const auto& val) { audio.sound.volume = std::clamp(std::stoi(val), 0, 100); }}, {"audio.sound.volume", [](const auto& val) -> auto { audio.sound.volume = std::clamp(std::stoi(val), 0, 100); }},
// Juego // Juego
{"game.language", [](const auto& val) { {"game.language", [](const auto& val) -> auto {
settings.language = static_cast<Lang::Code>(std::stoi(val)); settings.language = static_cast<Lang::Code>(std::stoi(val));
if (settings.language != Lang::Code::ENGLISH && if (settings.language != Lang::Code::ENGLISH &&
@@ -227,15 +227,15 @@ namespace Options {
} }
pending_changes.new_language = settings.language; pending_changes.new_language = settings.language;
}}, }},
{"game.difficulty", [](const auto& val) { {"game.difficulty", [](const auto& val) -> auto {
settings.difficulty = static_cast<Difficulty::Code>(std::stoi(val)); settings.difficulty = static_cast<Difficulty::Code>(std::stoi(val));
pending_changes.new_difficulty = settings.difficulty; pending_changes.new_difficulty = settings.difficulty;
}}, }},
{"game.autofire", [](const auto& val) { settings.autofire = stringToBool(val); }}, {"game.autofire", [](const auto& val) -> auto { settings.autofire = stringToBool(val); }},
{"game.shutdown_enabled", [](const auto& val) { settings.shutdown_enabled = stringToBool(val); }}, {"game.shutdown_enabled", [](const auto& val) -> auto { settings.shutdown_enabled = stringToBool(val); }},
{"game.params_file", [](const auto& val) { settings.params_file = val; }}, {"game.params_file", [](const auto& val) -> auto { settings.params_file = val; }},
// Teclado // Teclado
{"keyboard.player", [](const auto& val) { keyboard.player_id = static_cast<Player::Id>(stoi(val)); }}}; {"keyboard.player", [](const auto& val) -> auto { keyboard.player_id = static_cast<Player::Id>(stoi(val)); }}};
// Maneja por separado la configuración general de los mandos // Maneja por separado la configuración general de los mandos
if (var.starts_with("controller.")) { if (var.starts_with("controller.")) {
@@ -351,7 +351,7 @@ namespace Options {
// --- PRIMERA PASADA: Intenta asignar mandos basándose en la ruta guardada --- // --- PRIMERA PASADA: Intenta asignar mandos basándose en la ruta guardada ---
void GamepadManager::assignGamepadsByPath( void GamepadManager::assignGamepadsByPath(
const std::array<std::string, MAX_PLAYERS>& desired_paths, const std::array<std::string, MAX_PLAYERS>& desired_paths,
const std::vector<std::shared_ptr<Input::Gamepad>>& physical_gamepads, const std::vector<std::shared_ptr<Input::Gamepad>>& physical_gamepads, // NOLINT(readability-named-parameter)
std::vector<std::shared_ptr<Input::Gamepad>>& assigned_instances) { std::vector<std::shared_ptr<Input::Gamepad>>& assigned_instances) {
for (size_t i = 0; i < MAX_PLAYERS; ++i) { for (size_t i = 0; i < MAX_PLAYERS; ++i) {
const std::string& desired_path = desired_paths[i]; const std::string& desired_path = desired_paths[i];
@@ -376,7 +376,7 @@ namespace Options {
// --- SEGUNDA PASADA: Asigna los mandos físicos restantes a los jugadores libres --- // --- SEGUNDA PASADA: Asigna los mandos físicos restantes a los jugadores libres ---
void GamepadManager::assignRemainingGamepads( void GamepadManager::assignRemainingGamepads(
const std::vector<std::shared_ptr<Input::Gamepad>>& physical_gamepads, const std::vector<std::shared_ptr<Input::Gamepad>>& physical_gamepads, // NOLINT(readability-named-parameter)
std::vector<std::shared_ptr<Input::Gamepad>>& assigned_instances) { std::vector<std::shared_ptr<Input::Gamepad>>& assigned_instances) {
for (size_t i = 0; i < MAX_PLAYERS; ++i) { for (size_t i = 0; i < MAX_PLAYERS; ++i) {
if (gamepads_[i].instance != nullptr) { if (gamepads_[i].instance != nullptr) {
@@ -418,9 +418,9 @@ namespace Options {
// Devuelve 'true' si ya ha sido asignado, 'false' en caso contrario. // Devuelve 'true' si ya ha sido asignado, 'false' en caso contrario.
auto GamepadManager::isGamepadAssigned( auto GamepadManager::isGamepadAssigned(
const std::shared_ptr<Input::Gamepad>& physical_gamepad, const std::shared_ptr<Input::Gamepad>& physical_gamepad,
const std::vector<std::shared_ptr<Input::Gamepad>>& assigned_instances) -> bool { const std::vector<std::shared_ptr<Input::Gamepad>>& assigned_instances) -> bool { // NOLINT(readability-named-parameter)
return std::ranges::any_of(assigned_instances, return std::ranges::any_of(assigned_instances,
[&physical_gamepad](const auto& assigned) { [&physical_gamepad](const auto& assigned) -> auto {
return assigned == physical_gamepad; return assigned == physical_gamepad;
}); });
} }

View File

@@ -242,15 +242,15 @@ namespace Options {
void assignGamepadsByPath( void assignGamepadsByPath(
const std::array<std::string, MAX_PLAYERS>& desired_paths, const std::array<std::string, MAX_PLAYERS>& desired_paths,
const std::vector<std::shared_ptr<Input::Gamepad>>& physical_gamepads, const std::vector<std::shared_ptr<Input::Gamepad>>& physical_gamepads, // NOLINT(readability-avoid-const-params-in-decls)
std::vector<std::shared_ptr<Input::Gamepad>>& assigned_instances); std::vector<std::shared_ptr<Input::Gamepad>>& assigned_instances);
void assignRemainingGamepads( void assignRemainingGamepads(
const std::vector<std::shared_ptr<Input::Gamepad>>& physical_gamepads, const std::vector<std::shared_ptr<Input::Gamepad>>& physical_gamepads, // NOLINT(readability-avoid-const-params-in-decls)
std::vector<std::shared_ptr<Input::Gamepad>>& assigned_instances); std::vector<std::shared_ptr<Input::Gamepad>>& assigned_instances);
void clearUnassignedGamepadSlots(); void clearUnassignedGamepadSlots();
[[nodiscard]] static auto isGamepadAssigned( [[nodiscard]] static auto isGamepadAssigned(
const std::shared_ptr<Input::Gamepad>& physical_gamepad, const std::shared_ptr<Input::Gamepad>& physical_gamepad,
const std::vector<std::shared_ptr<Input::Gamepad>>& assigned_instances) -> bool; const std::vector<std::shared_ptr<Input::Gamepad>>& assigned_instances) -> bool; // NOLINT(readability-avoid-const-params-in-decls)
}; };
struct Keyboard { struct Keyboard {

View File

@@ -88,109 +88,109 @@ namespace {
auto setParams(const std::string& var, const std::string& value) -> bool { auto setParams(const std::string& var, const std::string& value) -> bool {
// Mapas estáticos para diferentes tipos de parámetros // Mapas estáticos para diferentes tipos de parámetros
static const std::unordered_map<std::string, std::function<void(const std::string&)>> INT_PARAMS = { static const std::unordered_map<std::string, std::function<void(const std::string&)>> INT_PARAMS = {
{"game.width", [](const std::string& v) { param.game.width = std::stoi(v); }}, {"game.width", [](const std::string& v) -> void { param.game.width = std::stoi(v); }},
{"game.height", [](const std::string& v) { param.game.height = std::stoi(v); }}, {"game.height", [](const std::string& v) -> void { param.game.height = std::stoi(v); }},
{"game.play_area.rect.x", [](const std::string& v) { param.game.play_area.rect.x = std::stoi(v); }}, {"game.play_area.rect.x", [](const std::string& v) -> void { param.game.play_area.rect.x = std::stoi(v); }},
{"game.play_area.rect.y", [](const std::string& v) { param.game.play_area.rect.y = std::stoi(v); }}, {"game.play_area.rect.y", [](const std::string& v) -> void { param.game.play_area.rect.y = std::stoi(v); }},
{"game.play_area.rect.w", [](const std::string& v) { param.game.play_area.rect.w = std::stoi(v); }}, {"game.play_area.rect.w", [](const std::string& v) -> void { param.game.play_area.rect.w = std::stoi(v); }},
{"game.play_area.rect.h", [](const std::string& v) { param.game.play_area.rect.h = std::stoi(v); }}, {"game.play_area.rect.h", [](const std::string& v) -> void { param.game.play_area.rect.h = std::stoi(v); }},
{"game.name_entry_idle_time", [](const std::string& v) { param.game.name_entry_idle_time = std::stoi(v); }}, {"game.name_entry_idle_time", [](const std::string& v) -> void { param.game.name_entry_idle_time = std::stoi(v); }},
{"game.name_entry_total_time", [](const std::string& v) { param.game.name_entry_total_time = std::stoi(v); }}, {"game.name_entry_total_time", [](const std::string& v) -> void { param.game.name_entry_total_time = std::stoi(v); }},
{"fade.num_squares_width", [](const std::string& v) { param.fade.num_squares_width = std::stoi(v); }}, {"fade.num_squares_width", [](const std::string& v) -> void { param.fade.num_squares_width = std::stoi(v); }},
{"fade.num_squares_height", [](const std::string& v) { param.fade.num_squares_height = std::stoi(v); }}, {"fade.num_squares_height", [](const std::string& v) -> void { param.fade.num_squares_height = std::stoi(v); }},
{"fade.random_squares_duration_ms", [](const std::string& v) { param.fade.random_squares_duration_ms = std::stoi(v); }}, {"fade.random_squares_duration_ms", [](const std::string& v) -> void { param.fade.random_squares_duration_ms = std::stoi(v); }},
{"fade.post_duration_ms", [](const std::string& v) { param.fade.post_duration_ms = std::stoi(v); }}, {"fade.post_duration_ms", [](const std::string& v) -> void { param.fade.post_duration_ms = std::stoi(v); }},
{"fade.venetian_size", [](const std::string& v) { param.fade.venetian_size = std::stoi(v); }}, {"fade.venetian_size", [](const std::string& v) -> void { param.fade.venetian_size = std::stoi(v); }},
{"scoreboard.rect.x", [](const std::string& v) { param.scoreboard.rect.x = std::stoi(v); }}, {"scoreboard.rect.x", [](const std::string& v) -> void { param.scoreboard.rect.x = std::stoi(v); }},
{"scoreboard.rect.y", [](const std::string& v) { param.scoreboard.rect.y = std::stoi(v); }}, {"scoreboard.rect.y", [](const std::string& v) -> void { param.scoreboard.rect.y = std::stoi(v); }},
{"scoreboard.rect.w", [](const std::string& v) { param.scoreboard.rect.w = std::stoi(v); }}, {"scoreboard.rect.w", [](const std::string& v) -> void { param.scoreboard.rect.w = std::stoi(v); }},
{"scoreboard.rect.h", [](const std::string& v) { param.scoreboard.rect.h = std::stoi(v); }}, {"scoreboard.rect.h", [](const std::string& v) -> void { param.scoreboard.rect.h = std::stoi(v); }},
{"scoreboard.skip_countdown_value", [](const std::string& v) { param.scoreboard.skip_countdown_value = std::stoi(v); }}, {"scoreboard.skip_countdown_value", [](const std::string& v) -> void { param.scoreboard.skip_countdown_value = std::stoi(v); }},
{"title.press_start_position", [](const std::string& v) { param.title.press_start_position = std::stoi(v); }}, {"title.press_start_position", [](const std::string& v) -> void { param.title.press_start_position = std::stoi(v); }},
{"title.arcade_edition_position", [](const std::string& v) { param.title.arcade_edition_position = std::stoi(v); }}, {"title.arcade_edition_position", [](const std::string& v) -> void { param.title.arcade_edition_position = std::stoi(v); }},
{"title.title_c_c_position", [](const std::string& v) { param.title.title_c_c_position = std::stoi(v); }}, {"title.title_c_c_position", [](const std::string& v) -> void { param.title.title_c_c_position = std::stoi(v); }},
{"intro.text_distance_from_bottom", [](const std::string& v) { param.intro.text_distance_from_bottom = std::stoi(v); }}}; {"intro.text_distance_from_bottom", [](const std::string& v) -> void { param.intro.text_distance_from_bottom = std::stoi(v); }}};
static const std::unordered_map<std::string, std::function<void(const std::string&)>> COLOR_PARAMS = { static const std::unordered_map<std::string, std::function<void(const std::string&)>> COLOR_PARAMS = {
{"fade.color", [](const std::string& v) { param.fade.color = Color::fromHex(v); }}, {"fade.color", [](const std::string& v) -> void { param.fade.color = Color::fromHex(v); }},
{"scoreboard.separator_color", [](const std::string& v) { param.scoreboard.separator_color = Color::fromHex(v); }}, {"scoreboard.separator_color", [](const std::string& v) -> void { param.scoreboard.separator_color = Color::fromHex(v); }},
{"scoreboard.easy_color", [](const std::string& v) { param.scoreboard.easy_color = Color::fromHex(v); }}, {"scoreboard.easy_color", [](const std::string& v) -> void { param.scoreboard.easy_color = Color::fromHex(v); }},
{"scoreboard.normal_color", [](const std::string& v) { param.scoreboard.normal_color = Color::fromHex(v); }}, {"scoreboard.normal_color", [](const std::string& v) -> void { param.scoreboard.normal_color = Color::fromHex(v); }},
{"scoreboard.hard_color", [](const std::string& v) { param.scoreboard.hard_color = Color::fromHex(v); }}, {"scoreboard.hard_color", [](const std::string& v) -> void { param.scoreboard.hard_color = Color::fromHex(v); }},
{"scoreboard.text_color1", [](const std::string& v) { param.scoreboard.text_color1 = Color::fromHex(v); }}, {"scoreboard.text_color1", [](const std::string& v) -> void { param.scoreboard.text_color1 = Color::fromHex(v); }},
{"scoreboard.text_color2", [](const std::string& v) { param.scoreboard.text_color2 = Color::fromHex(v); }}, {"scoreboard.text_color2", [](const std::string& v) -> void { param.scoreboard.text_color2 = Color::fromHex(v); }},
{"title.bg_color", [](const std::string& v) { param.title.bg_color = Color::fromHex(v); }}, {"title.bg_color", [](const std::string& v) -> void { param.title.bg_color = Color::fromHex(v); }},
{"background.attenuate_color", [](const std::string& v) { param.background.attenuate_color = Color::fromHex(v); }}, {"background.attenuate_color", [](const std::string& v) -> void { param.background.attenuate_color = Color::fromHex(v); }},
{"notification.color", [](const std::string& v) { param.notification.color = Color::fromHex(v); }}, {"notification.color", [](const std::string& v) -> void { param.notification.color = Color::fromHex(v); }},
{"service_menu.title_color", [](const std::string& v) { param.service_menu.title_color = Color::fromHex(v); }}, {"service_menu.title_color", [](const std::string& v) -> void { param.service_menu.title_color = Color::fromHex(v); }},
{"service_menu.text_color", [](const std::string& v) { param.service_menu.text_color = Color::fromHex(v); }}, {"service_menu.text_color", [](const std::string& v) -> void { param.service_menu.text_color = Color::fromHex(v); }},
{"service_menu.selected_color", [](const std::string& v) { param.service_menu.selected_color = Color::fromHex(v); }}, {"service_menu.selected_color", [](const std::string& v) -> void { param.service_menu.selected_color = Color::fromHex(v); }},
{"service_menu.bg_color", [](const std::string& v) { param.service_menu.bg_color = Color::fromHex(v); }}, {"service_menu.bg_color", [](const std::string& v) -> void { param.service_menu.bg_color = Color::fromHex(v); }},
{"service_menu.window_message.bg_color", [](const std::string& v) { param.service_menu.window_message.bg_color = Color::fromHex(v); }}, {"service_menu.window_message.bg_color", [](const std::string& v) -> void { param.service_menu.window_message.bg_color = Color::fromHex(v); }},
{"service_menu.window_message.border_color", [](const std::string& v) { param.service_menu.window_message.border_color = Color::fromHex(v); }}, {"service_menu.window_message.border_color", [](const std::string& v) -> void { param.service_menu.window_message.border_color = Color::fromHex(v); }},
{"service_menu.window_message.title_color", [](const std::string& v) { param.service_menu.window_message.title_color = Color::fromHex(v); }}, {"service_menu.window_message.title_color", [](const std::string& v) -> void { param.service_menu.window_message.title_color = Color::fromHex(v); }},
{"service_menu.window_message.text_color", [](const std::string& v) { param.service_menu.window_message.text_color = Color::fromHex(v); }}, {"service_menu.window_message.text_color", [](const std::string& v) -> void { param.service_menu.window_message.text_color = Color::fromHex(v); }},
{"intro.bg_color", [](const std::string& v) { param.intro.bg_color = Color::fromHex(v); }}, {"intro.bg_color", [](const std::string& v) -> void { param.intro.bg_color = Color::fromHex(v); }},
{"intro.card_color", [](const std::string& v) { param.intro.card_color = Color::fromHex(v); }}, {"intro.card_color", [](const std::string& v) -> void { param.intro.card_color = Color::fromHex(v); }},
{"intro.shadow_color", [](const std::string& v) { param.intro.shadow_color = Color::fromHex(v); }}, {"intro.shadow_color", [](const std::string& v) -> void { param.intro.shadow_color = Color::fromHex(v); }},
{"debug.color", [](const std::string& v) { param.debug.color = Color::fromHex(v); }}, {"debug.color", [](const std::string& v) -> void { param.debug.color = Color::fromHex(v); }},
{"resource.color", [](const std::string& v) { param.resource.color = Color::fromHex(v); }}, {"resource.color", [](const std::string& v) -> void { param.resource.color = Color::fromHex(v); }},
{"game.item_text_outline_color", [](const std::string& v) { param.game.item_text_outline_color = Color::fromHex(v); }}, {"game.item_text_outline_color", [](const std::string& v) -> void { param.game.item_text_outline_color = Color::fromHex(v); }},
{"player.default_shirt[0].darkest", [](const std::string& v) { param.player.default_shirt[0].darkest = Color::fromHex(v); }}, {"player.default_shirt[0].darkest", [](const std::string& v) -> void { param.player.default_shirt[0].darkest = Color::fromHex(v); }},
{"player.default_shirt[0].dark", [](const std::string& v) { param.player.default_shirt[0].dark = Color::fromHex(v); }}, {"player.default_shirt[0].dark", [](const std::string& v) -> void { param.player.default_shirt[0].dark = Color::fromHex(v); }},
{"player.default_shirt[0].base", [](const std::string& v) { param.player.default_shirt[0].base = Color::fromHex(v); }}, {"player.default_shirt[0].base", [](const std::string& v) -> void { param.player.default_shirt[0].base = Color::fromHex(v); }},
{"player.default_shirt[0].light", [](const std::string& v) { param.player.default_shirt[0].light = Color::fromHex(v); }}, {"player.default_shirt[0].light", [](const std::string& v) -> void { param.player.default_shirt[0].light = Color::fromHex(v); }},
{"player.default_shirt[1].darkest", [](const std::string& v) { param.player.default_shirt[1].darkest = Color::fromHex(v); }}, {"player.default_shirt[1].darkest", [](const std::string& v) -> void { param.player.default_shirt[1].darkest = Color::fromHex(v); }},
{"player.default_shirt[1].dark", [](const std::string& v) { param.player.default_shirt[1].dark = Color::fromHex(v); }}, {"player.default_shirt[1].dark", [](const std::string& v) -> void { param.player.default_shirt[1].dark = Color::fromHex(v); }},
{"player.default_shirt[1].base", [](const std::string& v) { param.player.default_shirt[1].base = Color::fromHex(v); }}, {"player.default_shirt[1].base", [](const std::string& v) -> void { param.player.default_shirt[1].base = Color::fromHex(v); }},
{"player.default_shirt[1].light", [](const std::string& v) { param.player.default_shirt[1].light = Color::fromHex(v); }}, {"player.default_shirt[1].light", [](const std::string& v) -> void { param.player.default_shirt[1].light = Color::fromHex(v); }},
{"player.one_coffee_shirt[0].darkest", [](const std::string& v) { param.player.one_coffee_shirt[0].darkest = Color::fromHex(v); }}, {"player.one_coffee_shirt[0].darkest", [](const std::string& v) -> void { param.player.one_coffee_shirt[0].darkest = Color::fromHex(v); }},
{"player.one_coffee_shirt[0].dark", [](const std::string& v) { param.player.one_coffee_shirt[0].dark = Color::fromHex(v); }}, {"player.one_coffee_shirt[0].dark", [](const std::string& v) -> void { param.player.one_coffee_shirt[0].dark = Color::fromHex(v); }},
{"player.one_coffee_shirt[0].base", [](const std::string& v) { param.player.one_coffee_shirt[0].base = Color::fromHex(v); }}, {"player.one_coffee_shirt[0].base", [](const std::string& v) -> void { param.player.one_coffee_shirt[0].base = Color::fromHex(v); }},
{"player.one_coffee_shirt[0].light", [](const std::string& v) { param.player.one_coffee_shirt[0].light = Color::fromHex(v); }}, {"player.one_coffee_shirt[0].light", [](const std::string& v) -> void { param.player.one_coffee_shirt[0].light = Color::fromHex(v); }},
{"player.one_coffee_shirt[1].darkest", [](const std::string& v) { param.player.one_coffee_shirt[1].darkest = Color::fromHex(v); }}, {"player.one_coffee_shirt[1].darkest", [](const std::string& v) -> void { param.player.one_coffee_shirt[1].darkest = Color::fromHex(v); }},
{"player.one_coffee_shirt[1].dark", [](const std::string& v) { param.player.one_coffee_shirt[1].dark = Color::fromHex(v); }}, {"player.one_coffee_shirt[1].dark", [](const std::string& v) -> void { param.player.one_coffee_shirt[1].dark = Color::fromHex(v); }},
{"player.one_coffee_shirt[1].base", [](const std::string& v) { param.player.one_coffee_shirt[1].base = Color::fromHex(v); }}, {"player.one_coffee_shirt[1].base", [](const std::string& v) -> void { param.player.one_coffee_shirt[1].base = Color::fromHex(v); }},
{"player.one_coffee_shirt[1].light", [](const std::string& v) { param.player.one_coffee_shirt[1].light = Color::fromHex(v); }}, {"player.one_coffee_shirt[1].light", [](const std::string& v) -> void { param.player.one_coffee_shirt[1].light = Color::fromHex(v); }},
{"player.two_coffee_shirt[0].darkest", [](const std::string& v) { param.player.two_coffee_shirt[0].darkest = Color::fromHex(v); }}, {"player.two_coffee_shirt[0].darkest", [](const std::string& v) -> void { param.player.two_coffee_shirt[0].darkest = Color::fromHex(v); }},
{"player.two_coffee_shirt[0].dark", [](const std::string& v) { param.player.two_coffee_shirt[0].dark = Color::fromHex(v); }}, {"player.two_coffee_shirt[0].dark", [](const std::string& v) -> void { param.player.two_coffee_shirt[0].dark = Color::fromHex(v); }},
{"player.two_coffee_shirt[0].base", [](const std::string& v) { param.player.two_coffee_shirt[0].base = Color::fromHex(v); }}, {"player.two_coffee_shirt[0].base", [](const std::string& v) -> void { param.player.two_coffee_shirt[0].base = Color::fromHex(v); }},
{"player.two_coffee_shirt[0].light", [](const std::string& v) { param.player.two_coffee_shirt[0].light = Color::fromHex(v); }}, {"player.two_coffee_shirt[0].light", [](const std::string& v) -> void { param.player.two_coffee_shirt[0].light = Color::fromHex(v); }},
{"player.two_coffee_shirt[1].darkest", [](const std::string& v) { param.player.two_coffee_shirt[1].darkest = Color::fromHex(v); }}, {"player.two_coffee_shirt[1].darkest", [](const std::string& v) -> void { param.player.two_coffee_shirt[1].darkest = Color::fromHex(v); }},
{"player.two_coffee_shirt[1].dark", [](const std::string& v) { param.player.two_coffee_shirt[1].dark = Color::fromHex(v); }}, {"player.two_coffee_shirt[1].dark", [](const std::string& v) -> void { param.player.two_coffee_shirt[1].dark = Color::fromHex(v); }},
{"player.two_coffee_shirt[1].base", [](const std::string& v) { param.player.two_coffee_shirt[1].base = Color::fromHex(v); }}, {"player.two_coffee_shirt[1].base", [](const std::string& v) -> void { param.player.two_coffee_shirt[1].base = Color::fromHex(v); }},
{"player.two_coffee_shirt[1].light", [](const std::string& v) { param.player.two_coffee_shirt[1].light = Color::fromHex(v); }}, {"player.two_coffee_shirt[1].light", [](const std::string& v) -> void { param.player.two_coffee_shirt[1].light = Color::fromHex(v); }},
{"player.outline_color[0]", [](const std::string& v) { param.player.outline_color[0] = Color::fromHex(v); }}, {"player.outline_color[0]", [](const std::string& v) -> void { param.player.outline_color[0] = Color::fromHex(v); }},
{"player.outline_color[1]", [](const std::string& v) { param.player.outline_color[1] = Color::fromHex(v); }}}; {"player.outline_color[1]", [](const std::string& v) -> void { param.player.outline_color[1] = Color::fromHex(v); }}};
static const std::unordered_map<std::string, std::function<void(const std::string&)>> BOOL_PARAMS = { static const std::unordered_map<std::string, std::function<void(const std::string&)>> BOOL_PARAMS = {
{"scoreboard.separator_autocolor", [](const std::string& v) { param.scoreboard.separator_autocolor = stringToBool(v); }}, {"scoreboard.separator_autocolor", [](const std::string& v) -> void { param.scoreboard.separator_autocolor = stringToBool(v); }},
{"scoreboard.text_autocolor", [](const std::string& v) { param.scoreboard.text_autocolor = stringToBool(v); }}, {"scoreboard.text_autocolor", [](const std::string& v) -> void { param.scoreboard.text_autocolor = stringToBool(v); }},
{"balloon.bouncing_sound", [](const std::string& v) { param.balloon.bouncing_sound = stringToBool(v); }}, {"balloon.bouncing_sound", [](const std::string& v) -> void { param.balloon.bouncing_sound = stringToBool(v); }},
{"notification.sound", [](const std::string& v) { param.notification.sound = stringToBool(v); }}, {"notification.sound", [](const std::string& v) -> void { param.notification.sound = stringToBool(v); }},
{"service_menu.drop_shadow", [](const std::string& v) { param.service_menu.drop_shadow = stringToBool(v); }}}; {"service_menu.drop_shadow", [](const std::string& v) -> void { param.service_menu.drop_shadow = stringToBool(v); }}};
static const std::unordered_map<std::string, std::function<void(const std::string&)>> FLOAT_PARAMS = { static const std::unordered_map<std::string, std::function<void(const std::string&)>> FLOAT_PARAMS = {
{"balloon.settings[0].vel", [](const std::string& v) { param.balloon.settings.at(0).vel = std::stof(v); }}, {"balloon.settings[0].vel", [](const std::string& v) -> void { param.balloon.settings.at(0).vel = std::stof(v); }},
{"balloon.settings[0].grav", [](const std::string& v) { param.balloon.settings.at(0).grav = std::stof(v); }}, {"balloon.settings[0].grav", [](const std::string& v) -> void { param.balloon.settings.at(0).grav = std::stof(v); }},
{"balloon.settings[1].vel", [](const std::string& v) { param.balloon.settings.at(1).vel = std::stof(v); }}, {"balloon.settings[1].vel", [](const std::string& v) -> void { param.balloon.settings.at(1).vel = std::stof(v); }},
{"balloon.settings[1].grav", [](const std::string& v) { param.balloon.settings.at(1).grav = std::stof(v); }}, {"balloon.settings[1].grav", [](const std::string& v) -> void { param.balloon.settings.at(1).grav = std::stof(v); }},
{"balloon.settings[2].vel", [](const std::string& v) { param.balloon.settings.at(2).vel = std::stof(v); }}, {"balloon.settings[2].vel", [](const std::string& v) -> void { param.balloon.settings.at(2).vel = std::stof(v); }},
{"balloon.settings[2].grav", [](const std::string& v) { param.balloon.settings.at(2).grav = std::stof(v); }}, {"balloon.settings[2].grav", [](const std::string& v) -> void { param.balloon.settings.at(2).grav = std::stof(v); }},
{"balloon.settings[3].vel", [](const std::string& v) { param.balloon.settings.at(3).vel = std::stof(v); }}, {"balloon.settings[3].vel", [](const std::string& v) -> void { param.balloon.settings.at(3).vel = std::stof(v); }},
{"balloon.settings[3].grav", [](const std::string& v) { param.balloon.settings.at(3).grav = std::stof(v); }}, {"balloon.settings[3].grav", [](const std::string& v) -> void { param.balloon.settings.at(3).grav = std::stof(v); }},
{"tabe.min_spawn_time", [](const std::string& v) { param.tabe.min_spawn_time = std::stof(v); }}, {"tabe.min_spawn_time", [](const std::string& v) -> void { param.tabe.min_spawn_time = std::stof(v); }},
{"tabe.max_spawn_time", [](const std::string& v) { param.tabe.max_spawn_time = std::stof(v); }}, {"tabe.max_spawn_time", [](const std::string& v) -> void { param.tabe.max_spawn_time = std::stof(v); }},
{"title.title_duration", [](const std::string& v) { param.title.title_duration = std::stof(v); }}, {"title.title_duration", [](const std::string& v) -> void { param.title.title_duration = std::stof(v); }},
{"service_menu.window_message.padding", [](const std::string& v) { param.service_menu.window_message.padding = std::stof(v); }}, {"service_menu.window_message.padding", [](const std::string& v) -> void { param.service_menu.window_message.padding = std::stof(v); }},
{"service_menu.window_message.line_spacing", [](const std::string& v) { param.service_menu.window_message.line_spacing = std::stof(v); }}, {"service_menu.window_message.line_spacing", [](const std::string& v) -> void { param.service_menu.window_message.line_spacing = std::stof(v); }},
{"service_menu.window_message.title_separator_spacing", [](const std::string& v) { param.service_menu.window_message.title_separator_spacing = std::stof(v); }}, {"service_menu.window_message.title_separator_spacing", [](const std::string& v) -> void { param.service_menu.window_message.title_separator_spacing = std::stof(v); }},
{"service_menu.window_message.min_width", [](const std::string& v) { param.service_menu.window_message.min_width = std::stof(v); }}, {"service_menu.window_message.min_width", [](const std::string& v) -> void { param.service_menu.window_message.min_width = std::stof(v); }},
{"service_menu.window_message.min_height", [](const std::string& v) { param.service_menu.window_message.min_height = std::stof(v); }}, {"service_menu.window_message.min_height", [](const std::string& v) -> void { param.service_menu.window_message.min_height = std::stof(v); }},
{"service_menu.window_message.max_width_ratio", [](const std::string& v) { param.service_menu.window_message.max_width_ratio = std::stof(v); }}, {"service_menu.window_message.max_width_ratio", [](const std::string& v) -> void { param.service_menu.window_message.max_width_ratio = std::stof(v); }},
{"service_menu.window_message.max_height_ratio", [](const std::string& v) { param.service_menu.window_message.max_height_ratio = std::stof(v); }}, {"service_menu.window_message.max_height_ratio", [](const std::string& v) -> void { param.service_menu.window_message.max_height_ratio = std::stof(v); }},
{"service_menu.window_message.text_safety_margin", [](const std::string& v) { param.service_menu.window_message.text_safety_margin = std::stof(v); }}, {"service_menu.window_message.text_safety_margin", [](const std::string& v) -> void { param.service_menu.window_message.text_safety_margin = std::stof(v); }},
{"service_menu.window_message.animation_duration", [](const std::string& v) { param.service_menu.window_message.animation_duration = std::stof(v); }}}; {"service_menu.window_message.animation_duration", [](const std::string& v) -> void { param.service_menu.window_message.animation_duration = std::stof(v); }}};
static const std::unordered_map<std::string, std::function<void(const std::string&)>> INT_PARAMS_EXTRA = {}; static const std::unordered_map<std::string, std::function<void(const std::string&)>> INT_PARAMS_EXTRA = {};
@@ -202,11 +202,11 @@ namespace {
{"green", true}}; {"green", true}};
auto validate_balloon_color = [](const std::string& color) -> bool { auto validate_balloon_color = [](const std::string& color) -> bool {
return VALID_BALLOON_COLORS.find(color) != VALID_BALLOON_COLORS.end(); return VALID_BALLOON_COLORS.contains(color);
}; };
static const std::unordered_map<std::string, std::function<void(const std::string&)>> STRING_PARAMS = { static const std::unordered_map<std::string, std::function<void(const std::string&)>> STRING_PARAMS = {
{"balloon.color[0]", [validate_balloon_color](const std::string& v) { {"balloon.color[0]", [validate_balloon_color](const std::string& v) -> void {
if (!validate_balloon_color(v)) { if (!validate_balloon_color(v)) {
SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION, "Color de globo inválido '%s'. Usando 'blue' por defecto.", v.c_str()); SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION, "Color de globo inválido '%s'. Usando 'blue' por defecto.", v.c_str());
param.balloon.color.at(0) = "blue"; param.balloon.color.at(0) = "blue";
@@ -214,7 +214,7 @@ namespace {
param.balloon.color.at(0) = v; param.balloon.color.at(0) = v;
} }
}}, }},
{"balloon.color[1]", [validate_balloon_color](const std::string& v) { {"balloon.color[1]", [validate_balloon_color](const std::string& v) -> void {
if (!validate_balloon_color(v)) { if (!validate_balloon_color(v)) {
SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION, "Color de globo inválido '%s'. Usando 'orange' por defecto.", v.c_str()); SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION, "Color de globo inválido '%s'. Usando 'orange' por defecto.", v.c_str());
param.balloon.color.at(1) = "orange"; param.balloon.color.at(1) = "orange";
@@ -222,7 +222,7 @@ namespace {
param.balloon.color.at(1) = v; param.balloon.color.at(1) = v;
} }
}}, }},
{"balloon.color[2]", [validate_balloon_color](const std::string& v) { {"balloon.color[2]", [validate_balloon_color](const std::string& v) -> void {
if (!validate_balloon_color(v)) { if (!validate_balloon_color(v)) {
SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION, "Color de globo inválido '%s'. Usando 'red' por defecto.", v.c_str()); SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION, "Color de globo inválido '%s'. Usando 'red' por defecto.", v.c_str());
param.balloon.color.at(2) = "red"; param.balloon.color.at(2) = "red";
@@ -230,7 +230,7 @@ namespace {
param.balloon.color.at(2) = v; param.balloon.color.at(2) = v;
} }
}}, }},
{"balloon.color[3]", [validate_balloon_color](const std::string& v) { {"balloon.color[3]", [validate_balloon_color](const std::string& v) -> void {
if (!validate_balloon_color(v)) { if (!validate_balloon_color(v)) {
SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION, "Color de globo inválido '%s'. Usando 'green' por defecto.", v.c_str()); SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION, "Color de globo inválido '%s'. Usando 'green' por defecto.", v.c_str());
param.balloon.color.at(3) = "green"; param.balloon.color.at(3) = "green";

View File

@@ -82,10 +82,10 @@ struct ParamNotification {
// --- Parámetros del marcador --- // --- Parámetros del marcador ---
struct ParamScoreboard { struct ParamScoreboard {
SDL_FRect rect = { SDL_FRect rect = {
GameDefaults::Scoreboard::RECT_X, .x = GameDefaults::Scoreboard::RECT_X,
GameDefaults::Scoreboard::RECT_Y, .y = GameDefaults::Scoreboard::RECT_Y,
GameDefaults::Scoreboard::RECT_W, .w = GameDefaults::Scoreboard::RECT_W,
GameDefaults::Scoreboard::RECT_H}; .h = GameDefaults::Scoreboard::RECT_H};
bool separator_autocolor = GameDefaults::Scoreboard::SEPARATOR_AUTOCOLOR; bool separator_autocolor = GameDefaults::Scoreboard::SEPARATOR_AUTOCOLOR;
Color separator_color = Color::fromHex(GameDefaults::Scoreboard::SEPARATOR_COLOR); Color separator_color = Color::fromHex(GameDefaults::Scoreboard::SEPARATOR_COLOR);
Color easy_color = Color::fromHex(GameDefaults::Scoreboard::EASY_COLOR); Color easy_color = Color::fromHex(GameDefaults::Scoreboard::EASY_COLOR);

View File

@@ -22,15 +22,15 @@ auto createPath(float start, float end, PathType type, float fixed_pos, int step
double value = start + ((end - start) * easing_function(t)); double value = start + ((end - start) * easing_function(t));
if ((start > 0 && end < 0) || (start < 0 && end > 0)) { if ((start > 0 && end < 0) || (start < 0 && end > 0)) {
value = start + (end > 0 ? 1 : -1) * std::abs(end - start) * easing_function(t); value = start + ((end > 0 ? 1 : -1) * std::abs(end - start) * easing_function(t));
} }
switch (type) { switch (type) {
case PathType::HORIZONTAL: case PathType::HORIZONTAL:
v.emplace_back(SDL_FPoint{static_cast<float>(value), fixed_pos}); v.emplace_back(SDL_FPoint{.x = static_cast<float>(value), .y = fixed_pos});
break; break;
case PathType::VERTICAL: case PathType::VERTICAL:
v.emplace_back(SDL_FPoint{fixed_pos, static_cast<float>(value)}); v.emplace_back(SDL_FPoint{.x = fixed_pos, .y = static_cast<float>(value)});
break; break;
default: default:
break; break;
@@ -167,7 +167,7 @@ void PathSprite::moveThroughCurrentPath(float delta_time) {
if (!path.on_destination) { if (!path.on_destination) {
++path.counter; ++path.counter;
if (path.counter >= static_cast<int>(path.spots.size())) { if (std::cmp_greater_equal(path.counter, path.spots.size())) {
path.on_destination = true; path.on_destination = true;
path.counter = static_cast<int>(path.spots.size()) - 1; path.counter = static_cast<int>(path.spots.size()) - 1;
} }
@@ -223,7 +223,7 @@ void PathSprite::goToNextPathOrDie() {
} }
// Comprueba si quedan mas recorridos // Comprueba si quedan mas recorridos
if (current_path_ >= static_cast<int>(paths_.size())) { if (std::cmp_greater_equal(current_path_, paths_.size())) {
has_finished_ = true; has_finished_ = true;
current_path_ = 0; current_path_ = 0;
} }

View File

@@ -18,11 +18,11 @@ class PauseManager {
// --- Operadores friend --- // --- Operadores friend ---
friend auto operator|(Source a, Source b) -> Source { friend auto operator|(Source a, Source b) -> Source {
return static_cast<Source>(static_cast<uint8_t>(a) | static_cast<uint8_t>(b)); return static_cast<Source>(static_cast<uint8_t>(a) | static_cast<uint8_t>(b)); // NOLINT(readability-redundant-casting)
} }
friend auto operator&(Source a, Source b) -> Source { friend auto operator&(Source a, Source b) -> Source {
return static_cast<Source>(static_cast<uint8_t>(a) & static_cast<uint8_t>(b)); return static_cast<Source>(static_cast<uint8_t>(a) & static_cast<uint8_t>(b)); // NOLINT(readability-redundant-casting)
} }
friend auto operator~(Source a) -> uint8_t { friend auto operator~(Source a) -> uint8_t {

View File

@@ -423,7 +423,7 @@ void Player::handleWaitingMovement(float delta_time) {
} }
void Player::updateWalkingStateForCredits() { void Player::updateWalkingStateForCredits() {
if (pos_x_ > param.game.game_area.center_x - WIDTH / 2) { if (pos_x_ > param.game.game_area.center_x - (WIDTH / 2)) {
setWalkingState(State::WALKING_LEFT); setWalkingState(State::WALKING_LEFT);
} else { } else {
setWalkingState(State::WALKING_RIGHT); setWalkingState(State::WALKING_RIGHT);
@@ -891,7 +891,7 @@ void Player::shiftColliders() {
} }
// Pone las texturas del jugador // Pone las texturas del jugador
void Player::setPlayerTextures(const std::vector<std::shared_ptr<Texture>>& texture) { void Player::setPlayerTextures(const std::vector<std::shared_ptr<Texture>>& texture) { // NOLINT(readability-named-parameter)
player_sprite_->setTexture(texture[0]); player_sprite_->setTexture(texture[0]);
power_sprite_->setTexture(texture[1]); power_sprite_->setTexture(texture[1]);
} }
@@ -1026,7 +1026,7 @@ void Player::addScoreToScoreBoard() const {
*glowing_entry_ = manager->add(ENTRY); *glowing_entry_ = manager->add(ENTRY);
} }
manager->saveToFile(Asset::get()->get("score.bin")); manager->saveToFile(Asset::get()->getPath("score.bin"));
} }
void Player::addCredit() { void Player::addCredit() {

View File

@@ -132,7 +132,7 @@ class Player {
void setAnimation(float delta_time); // Establece la animación según el estado (time-based) void setAnimation(float delta_time); // Establece la animación según el estado (time-based)
// --- Texturas y animaciones --- // --- Texturas y animaciones ---
void setPlayerTextures(const std::vector<std::shared_ptr<Texture>>& texture); // Cambia las texturas del jugador void setPlayerTextures(const std::vector<std::shared_ptr<Texture>>& texture); // NOLINT(readability-avoid-const-params-in-decls) Cambia las texturas del jugador
// --- Gameplay: Puntuación y power-ups --- // --- Gameplay: Puntuación y power-ups ---
void addScore(int score, int lowest_hi_score_entry); // Añade puntos void addScore(int score, int lowest_hi_score_entry); // Añade puntos

View File

@@ -203,7 +203,7 @@ namespace Rendering {
checkGLError("glVertexAttribPointer(position)"); checkGLError("glVertexAttribPointer(position)");
// Atributo 1: Coordenadas de textura (2 floats) // Atributo 1: Coordenadas de textura (2 floats)
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(float), static_cast<const void*>(static_cast<const char*>(nullptr) + 2 * sizeof(float))); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(float), static_cast<const void*>(static_cast<const char*>(nullptr) + (2 * sizeof(float))));
glEnableVertexAttribArray(1); glEnableVertexAttribArray(1);
checkGLError("glVertexAttribPointer(texcoord)"); checkGLError("glVertexAttribPointer(texcoord)");
@@ -221,14 +221,14 @@ namespace Rendering {
GLuint texture_id = 0; GLuint texture_id = 0;
// Intentar obtener ID de textura OpenGL // Intentar obtener ID de textura OpenGL
texture_id = (GLuint)(uintptr_t)SDL_GetPointerProperty(props, "SDL.texture.opengl.texture", nullptr); texture_id = static_cast<GLuint>(reinterpret_cast<uintptr_t>(SDL_GetPointerProperty(props, "SDL.texture.opengl.texture", nullptr)));
if (texture_id == 0) { if (texture_id == 0) {
texture_id = (GLuint)(uintptr_t)SDL_GetPointerProperty(props, "texture.opengl.texture", nullptr); texture_id = static_cast<GLuint>(reinterpret_cast<uintptr_t>(SDL_GetPointerProperty(props, "texture.opengl.texture", nullptr)));
} }
if (texture_id == 0) { if (texture_id == 0) {
texture_id = (GLuint)SDL_GetNumberProperty(props, "SDL.texture.opengl.texture", 1); texture_id = static_cast<GLuint>(SDL_GetNumberProperty(props, "SDL.texture.opengl.texture", 1));
} }
if (texture_id == 0) { if (texture_id == 0) {

View File

@@ -36,8 +36,8 @@ namespace Rendering {
private: private:
// Funciones auxiliares // Funciones auxiliares
auto initGLExtensions() -> bool; auto initGLExtensions() -> bool;
auto compileShader(const std::string& source, GLenum shader_type) -> GLuint; static auto compileShader(const std::string& source, GLenum shader_type) -> GLuint;
auto linkProgram(GLuint vertex_shader, GLuint fragment_shader) -> GLuint; static auto linkProgram(GLuint vertex_shader, GLuint fragment_shader) -> GLuint;
void createQuadGeometry(); void createQuadGeometry();
static auto getTextureID(SDL_Texture* texture) -> GLuint; static auto getTextureID(SDL_Texture* texture) -> GLuint;
static void checkGLError(const char* operation); static void checkGLError(const char* operation);

View File

@@ -100,7 +100,7 @@ void Resource::loadTextFilesQuiet() {
for (const auto& l : list) { for (const auto& l : list) {
auto name = getFileName(l); auto name = getFileName(l);
// Buscar en nuestra lista y cargar directamente // Buscar en nuestra lista y cargar directamente
auto it = std::ranges::find_if(text_files_, [&name](const auto& t) { return t.name == name; }); auto it = std::ranges::find_if(text_files_, [&name](const auto& t) -> auto { return t.name == name; });
if (it != text_files_.end()) { if (it != text_files_.end()) {
it->text_file = Text::loadFile(l); it->text_file = Text::loadFile(l);
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "Text file loaded: %s", name.c_str()); SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "Text file loaded: %s", name.c_str());
@@ -131,7 +131,7 @@ void Resource::loadEssentialTextures() {
// Solo cargar texturas esenciales // Solo cargar texturas esenciales
if (std::ranges::find(ESSENTIAL_TEXTURES, name) != ESSENTIAL_TEXTURES.end()) { if (std::ranges::find(ESSENTIAL_TEXTURES, name) != ESSENTIAL_TEXTURES.end()) {
// Buscar en nuestra lista y cargar // Buscar en nuestra lista y cargar
auto it = std::ranges::find_if(textures_, [&name](const auto& t) { return t.name == name; }); auto it = std::ranges::find_if(textures_, [&name](const auto& t) -> auto { return t.name == name; });
if (it != textures_.end()) { if (it != textures_.end()) {
it->texture = std::make_shared<Texture>(Screen::get()->getRenderer(), file); it->texture = std::make_shared<Texture>(Screen::get()->getRenderer(), file);
} }
@@ -206,7 +206,7 @@ void Resource::initResourceLists() {
// Obtiene el sonido a partir de un nombre (con carga perezosa) // Obtiene el sonido a partir de un nombre (con carga perezosa)
auto Resource::getSound(const std::string& name) -> JA_Sound_t* { auto Resource::getSound(const std::string& name) -> JA_Sound_t* {
auto it = std::ranges::find_if(sounds_, [&name](const auto& s) { return s.name == name; }); auto it = std::ranges::find_if(sounds_, [&name](const auto& s) -> auto { return s.name == name; });
if (it != sounds_.end()) { if (it != sounds_.end()) {
// Si está en modo lazy y no se ha cargado aún, lo carga ahora // Si está en modo lazy y no se ha cargado aún, lo carga ahora
@@ -222,7 +222,7 @@ auto Resource::getSound(const std::string& name) -> JA_Sound_t* {
// Obtiene la música a partir de un nombre (con carga perezosa) // Obtiene la música a partir de un nombre (con carga perezosa)
auto Resource::getMusic(const std::string& name) -> JA_Music_t* { auto Resource::getMusic(const std::string& name) -> JA_Music_t* {
auto it = std::ranges::find_if(musics_, [&name](const auto& m) { return m.name == name; }); auto it = std::ranges::find_if(musics_, [&name](const auto& m) -> auto { return m.name == name; });
if (it != musics_.end()) { if (it != musics_.end()) {
// Si está en modo lazy y no se ha cargado aún, lo carga ahora // Si está en modo lazy y no se ha cargado aún, lo carga ahora
@@ -238,7 +238,7 @@ auto Resource::getMusic(const std::string& name) -> JA_Music_t* {
// Obtiene la textura a partir de un nombre (con carga perezosa) // Obtiene la textura a partir de un nombre (con carga perezosa)
auto Resource::getTexture(const std::string& name) -> std::shared_ptr<Texture> { auto Resource::getTexture(const std::string& name) -> std::shared_ptr<Texture> {
auto it = std::ranges::find_if(textures_, [&name](const auto& t) { return t.name == name; }); auto it = std::ranges::find_if(textures_, [&name](const auto& t) -> auto { return t.name == name; });
if (it != textures_.end()) { if (it != textures_.end()) {
// Si está en modo lazy y no se ha cargado aún, lo carga ahora // Si está en modo lazy y no se ha cargado aún, lo carga ahora
@@ -254,7 +254,7 @@ auto Resource::getTexture(const std::string& name) -> std::shared_ptr<Texture> {
// Obtiene el fichero de texto a partir de un nombre (con carga perezosa) // Obtiene el fichero de texto a partir de un nombre (con carga perezosa)
auto Resource::getTextFile(const std::string& name) -> std::shared_ptr<Text::File> { auto Resource::getTextFile(const std::string& name) -> std::shared_ptr<Text::File> {
auto it = std::ranges::find_if(text_files_, [&name](const auto& t) { return t.name == name; }); auto it = std::ranges::find_if(text_files_, [&name](const auto& t) -> auto { return t.name == name; });
if (it != text_files_.end()) { if (it != text_files_.end()) {
// Si está en modo lazy y no se ha cargado aún, lo carga ahora // Si está en modo lazy y no se ha cargado aún, lo carga ahora
@@ -270,7 +270,7 @@ auto Resource::getTextFile(const std::string& name) -> std::shared_ptr<Text::Fil
// Obtiene el objeto de texto a partir de un nombre (con carga perezosa) // Obtiene el objeto de texto a partir de un nombre (con carga perezosa)
auto Resource::getText(const std::string& name) -> std::shared_ptr<Text> { auto Resource::getText(const std::string& name) -> std::shared_ptr<Text> {
auto it = std::ranges::find_if(texts_, [&name](const auto& t) { return t.name == name; }); auto it = std::ranges::find_if(texts_, [&name](const auto& t) -> auto { return t.name == name; });
if (it != texts_.end()) { if (it != texts_.end()) {
// Si está en modo lazy y no se ha cargado aún, lo carga ahora // Si está en modo lazy y no se ha cargado aún, lo carga ahora
@@ -286,7 +286,7 @@ auto Resource::getText(const std::string& name) -> std::shared_ptr<Text> {
// Obtiene la animación a partir de un nombre (con carga perezosa) // Obtiene la animación a partir de un nombre (con carga perezosa)
auto Resource::getAnimation(const std::string& name) -> AnimationsFileBuffer& { auto Resource::getAnimation(const std::string& name) -> AnimationsFileBuffer& {
auto it = std::ranges::find_if(animations_, [&name](const auto& a) { return a.name == name; }); auto it = std::ranges::find_if(animations_, [&name](const auto& a) -> auto { return a.name == name; });
if (it != animations_.end()) { if (it != animations_.end()) {
// Si está en modo lazy y no se ha cargado aún (vector vacío), lo carga ahora // Si está en modo lazy y no se ha cargado aún (vector vacío), lo carga ahora
@@ -302,7 +302,7 @@ auto Resource::getAnimation(const std::string& name) -> AnimationsFileBuffer& {
// Obtiene el fichero con los datos para el modo demostración a partir de un índice // Obtiene el fichero con los datos para el modo demostración a partir de un índice
auto Resource::getDemoData(int index) -> DemoData& { auto Resource::getDemoData(int index) -> DemoData& {
if (index < 0 || index >= static_cast<int>(demos_.size())) { if (index < 0 || std::cmp_greater_equal(index, demos_.size())) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Index %d out of range for demo data (size: %d)", index, static_cast<int>(demos_.size())); SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Index %d out of range for demo data (size: %d)", index, static_cast<int>(demos_.size()));
static DemoData empty_demo_; static DemoData empty_demo_;
return empty_demo_; return empty_demo_;
@@ -613,9 +613,9 @@ void Resource::createPlayerTextures() {
texture = std::make_shared<Texture>(Screen::get()->getRenderer(), texture_file_path); texture = std::make_shared<Texture>(Screen::get()->getRenderer(), texture_file_path);
// Añadir todas las paletas // Añadir todas las paletas
texture->addPaletteFromPalFile(Asset::get()->get(player.palette_files[0])); texture->addPaletteFromPalFile(Asset::get()->getPath(player.palette_files[0]));
texture->addPaletteFromPalFile(Asset::get()->get(player.palette_files[1])); texture->addPaletteFromPalFile(Asset::get()->getPath(player.palette_files[1]));
texture->addPaletteFromPalFile(Asset::get()->get(player.palette_files[2])); texture->addPaletteFromPalFile(Asset::get()->getPath(player.palette_files[2]));
if (palette_idx == 1) { if (palette_idx == 1) {
// Textura 1 - modificar solo paleta 1 (one_coffee_shirt) // Textura 1 - modificar solo paleta 1 (one_coffee_shirt)

View File

@@ -103,15 +103,12 @@ class Resource {
// --- Estructura para el progreso de carga --- // --- Estructura para el progreso de carga ---
struct ResourceCount { struct ResourceCount {
size_t total; // Número total de recursos size_t total{0}; // Número total de recursos
size_t loaded; // Número de recursos cargados size_t loaded{0}; // Número de recursos cargados
ResourceCount() ResourceCount() = default;
: total(0),
loaded(0) {}
ResourceCount(size_t total) ResourceCount(size_t total)
: total(total), : total(total) {}
loaded(0) {}
void add(size_t amount) { loaded += amount; } void add(size_t amount) { loaded += amount; }
void increase() { loaded++; } void increase() { loaded++; }

View File

@@ -159,7 +159,7 @@ auto ResourcePack::addFile(const std::string& filename, const std::string& filep
auto ResourcePack::addDirectory(const std::string& directory) -> bool { auto ResourcePack::addDirectory(const std::string& directory) -> bool {
if (!std::filesystem::exists(directory)) { if (!std::filesystem::exists(directory)) {
std::cerr << "Error: Directory does not exist: " << directory << '\n'; std::cerr << "Error: Directory does not exist: " << directory << '\n';
return false; return false; // NOLINT(readability-simplify-boolean-expr)
} }
for (const auto& entry : std::filesystem::recursive_directory_iterator(directory)) { for (const auto& entry : std::filesystem::recursive_directory_iterator(directory)) {
@@ -203,7 +203,7 @@ auto ResourcePack::getResource(const std::string& filename) -> std::vector<uint8
} }
auto ResourcePack::hasResource(const std::string& filename) const -> bool { auto ResourcePack::hasResource(const std::string& filename) const -> bool {
return resources_.find(filename) != resources_.end(); return resources_.contains(filename);
} }
void ResourcePack::clear() { void ResourcePack::clear() {

View File

@@ -33,12 +33,12 @@ class ResourcePack {
auto addFile(const std::string& filename, const std::string& filepath) -> bool; auto addFile(const std::string& filename, const std::string& filepath) -> bool;
auto addDirectory(const std::string& directory) -> bool; auto addDirectory(const std::string& directory) -> bool;
auto getResource(const std::string& filename) -> std::vector<uint8_t>; [[nodiscard]] auto getResource(const std::string& filename) -> std::vector<uint8_t>;
auto hasResource(const std::string& filename) const -> bool; [[nodiscard]] auto hasResource(const std::string& filename) const -> bool;
void clear(); void clear();
auto getResourceCount() const -> size_t; [[nodiscard]] auto getResourceCount() const -> size_t;
auto getResourceList() const -> std::vector<std::string>; [[nodiscard]] auto getResourceList() const -> std::vector<std::string>;
static const std::string DEFAULT_ENCRYPT_KEY; static const std::string DEFAULT_ENCRYPT_KEY;
}; };

View File

@@ -63,10 +63,10 @@ Scoreboard::Scoreboard()
// Recalcula las anclas de los elementos // Recalcula las anclas de los elementos
recalculateAnchors(); recalculateAnchors();
power_meter_sprite_->setPosition(SDL_FRect{ power_meter_sprite_->setPosition(SDL_FRect{
static_cast<float>(slot4_2_.x - 20), .x = static_cast<float>(slot4_2_.x - 20),
slot4_2_.y, .y = slot4_2_.y,
40, .w = 40,
7}); .h = 7});
// Crea la textura de fondo // Crea la textura de fondo
background_ = nullptr; background_ = nullptr;
@@ -490,7 +490,7 @@ void Scoreboard::renderStageInfoMode() {
// POWERMETER // POWERMETER
power_meter_sprite_->setSpriteClip(0, 0, 40, 7); power_meter_sprite_->setSpriteClip(0, 0, 40, 7);
power_meter_sprite_->render(); power_meter_sprite_->render();
power_meter_sprite_->setSpriteClip(40, 0, int(power_ * 40.0F), 7); power_meter_sprite_->setSpriteClip(40, 0, static_cast<int>(power_ * 40.0F), 7);
power_meter_sprite_->render(); power_meter_sprite_->render();
// HI-SCORE // HI-SCORE
@@ -644,7 +644,7 @@ void Scoreboard::fillBackgroundTexture() {
// Recalcula las anclas de los elementos // Recalcula las anclas de los elementos
void Scoreboard::recalculateAnchors() { void Scoreboard::recalculateAnchors() {
// Recalcula la posición y el tamaño de los paneles // Recalcula la posición y el tamaño de los paneles
const float PANEL_WIDTH = rect_.w / (float)static_cast<int>(Id::SIZE); const float PANEL_WIDTH = rect_.w / static_cast<float>(static_cast<int>(Id::SIZE));
for (int i = 0; i < static_cast<int>(Id::SIZE); ++i) { for (int i = 0; i < static_cast<int>(Id::SIZE); ++i) {
panel_.at(i).pos.x = roundf(PANEL_WIDTH * i); panel_.at(i).pos.x = roundf(PANEL_WIDTH * i);
panel_.at(i).pos.y = 0; panel_.at(i).pos.y = 0;

View File

@@ -105,7 +105,7 @@ class Scoreboard {
Colors::Cycle name_color_cycle_; // Ciclo de colores para destacar el nombre una vez introducido Colors::Cycle name_color_cycle_; // Ciclo de colores para destacar el nombre una vez introducido
Color animated_color_; // Color actual animado (ciclo automático cada 100ms) Color animated_color_; // Color actual animado (ciclo automático cada 100ms)
std::string hi_score_name_; // Nombre del jugador con la máxima puntuación std::string hi_score_name_; // Nombre del jugador con la máxima puntuación
SDL_FRect rect_ = {0, 0, 320, 40}; // Posición y dimensiones del marcador SDL_FRect rect_ = {.x = 0, .y = 0, .w = 320, .h = 40}; // Posición y dimensiones del marcador
Color color_; // Color del marcador Color color_; // Color del marcador
std::array<size_t, static_cast<int>(Id::SIZE)> selector_pos_ = {}; // Posición del selector de letra para introducir el nombre std::array<size_t, static_cast<int>(Id::SIZE)> selector_pos_ = {}; // Posición del selector de letra para introducir el nombre
std::array<int, static_cast<int>(Id::SIZE)> score_ = {}; // Puntuación de los jugadores std::array<int, static_cast<int>(Id::SIZE)> score_ = {}; // Puntuación de los jugadores

View File

@@ -38,8 +38,8 @@ Screen::Screen()
game_canvas_(nullptr), game_canvas_(nullptr),
service_menu_(nullptr), service_menu_(nullptr),
notifier_(nullptr), notifier_(nullptr),
src_rect_(SDL_FRect{0, 0, param.game.width, param.game.height}), src_rect_(SDL_FRect{.x = 0, .y = 0, .w = param.game.width, .h = param.game.height}),
dst_rect_(SDL_FRect{0, 0, param.game.width, param.game.height}) { dst_rect_(SDL_FRect{.x = 0, .y = 0, .w = param.game.width, .h = param.game.height}) {
// Arranca SDL VIDEO, crea la ventana y el renderizador // Arranca SDL VIDEO, crea la ventana y el renderizador
initSDLVideo(); initSDLVideo();
@@ -215,7 +215,7 @@ void Screen::renderShake() {
} }
#ifdef _DEBUG #ifdef _DEBUG
// Muestra información por pantalla // Muestra información por pantalla
void Screen::renderInfo() { void Screen::renderInfo() const {
if (debug_info_.show) { if (debug_info_.show) {
// Resolution // Resolution
debug_info_.text->writeDX(Text::COLOR | Text::STROKE, param.game.width - debug_info_.text->length(Options::video.info) - 2, 1, Options::video.info, 1, param.debug.color, 1, param.debug.color.DARKEN(150)); debug_info_.text->writeDX(Text::COLOR | Text::STROKE, param.game.width - debug_info_.text->length(Options::video.info) - 2, 1, Options::video.info, 1, param.debug.color, 1, param.debug.color.DARKEN(150));
@@ -505,6 +505,6 @@ void Screen::applySettings() {
// Crea el objeto de texto // Crea el objeto de texto
void Screen::createText() { void Screen::createText() {
auto texture = std::make_shared<Texture>(getRenderer(), Asset::get()->get("aseprite.png")); auto texture = std::make_shared<Texture>(getRenderer(), Asset::get()->getPath("aseprite.png"));
text_ = std::make_shared<Text>(texture, Asset::get()->get("aseprite.txt")); text_ = std::make_shared<Text>(texture, Asset::get()->getPath("aseprite.txt"));
} }

View File

@@ -40,12 +40,12 @@ class Screen {
auto decWindowSize() -> bool; // Reduce 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 auto incWindowSize() -> bool; // Aumenta el tamaño de la ventana
void applySettings(); // Aplica los valores de las opciones void applySettings(); // Aplica los valores de las opciones
void initShaders(); // Inicializa los shaders static void initShaders(); // Inicializa los shaders
// --- Efectos visuales --- // --- Efectos visuales ---
void shake(int desp = 2, float delay_s = 0.05F, float duration_s = 0.133F) { shake_effect_.enable(src_rect_, dst_rect_, desp, delay_s, duration_s); } // Agita la pantalla (tiempo en segundos) void shake(int desp = 2, float delay_s = 0.05F, float duration_s = 0.133F) { shake_effect_.enable(src_rect_, dst_rect_, desp, delay_s, duration_s); } // Agita la pantalla (tiempo en segundos)
void flash(Color color, float duration_s = 0.167F, float delay_s = 0.0F) { flash_effect_ = FlashEffect(true, duration_s, delay_s, color); } // Pone la pantalla de color (tiempo en segundos) void flash(Color color, float duration_s = 0.167F, float delay_s = 0.0F) { flash_effect_ = FlashEffect(true, duration_s, delay_s, color); } // Pone la pantalla de color (tiempo en segundos)
void toggleShaders(); // Alterna entre activar y desactivar los shaders static void toggleShaders(); // Alterna entre activar y desactivar los shaders
void toggleIntegerScale(); // Alterna entre activar y desactivar el escalado entero void toggleIntegerScale(); // Alterna entre activar y desactivar el escalado entero
void toggleVSync(); // Alterna entre activar y desactivar el V-Sync void toggleVSync(); // Alterna entre activar y desactivar el V-Sync
void setVSync(bool enabled); // Establece el estado del V-Sync void setVSync(bool enabled); // Establece el estado del V-Sync
@@ -234,7 +234,7 @@ class Screen {
auto initSDLVideo() -> bool; // 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 renderFlash(); // Dibuja el efecto de flash en la pantalla
void renderShake(); // Aplica el efecto de agitar la pantalla void renderShake(); // Aplica el efecto de agitar la pantalla
void renderInfo(); // Muestra información por pantalla void renderInfo() const; // Muestra información por pantalla
void renderPresent(); // Selecciona y ejecuta el método de renderizado adecuado void renderPresent(); // Selecciona y ejecuta el método de renderizado adecuado
void loadShaders(); // Carga el contenido del archivo GLSL void loadShaders(); // Carga el contenido del archivo GLSL
void adjustWindowSize(); // Calcula el tamaño de la ventana void adjustWindowSize(); // Calcula el tamaño de la ventana

View File

@@ -223,7 +223,7 @@ void Credits::fillTextTexture() {
mini_logo_rect_dst_.h = mini_logo_rect_src_.h = mini_logo_sprite->getHeight() + 3 + text->getCharacterSize(); mini_logo_rect_dst_.h = mini_logo_rect_src_.h = mini_logo_sprite->getHeight() + 3 + text->getCharacterSize();
credits_rect_dst_.y = param.game.game_area.rect.h; credits_rect_dst_.y = param.game.game_area.rect.h;
mini_logo_rect_dst_.y = credits_rect_dst_.y + credits_rect_dst_.h + 30; mini_logo_rect_dst_.y = credits_rect_dst_.y + credits_rect_dst_.h + 30;
mini_logo_final_pos_ = param.game.game_area.center_y - mini_logo_rect_src_.h / 2; mini_logo_final_pos_ = param.game.game_area.center_y - (mini_logo_rect_src_.h / 2);
} }
// Dibuja todos los sprites en la textura // Dibuja todos los sprites en la textura

View File

@@ -107,32 +107,32 @@ class Credits {
// Definición del área de juego // Definición del área de juego
SDL_FRect play_area_ = { SDL_FRect play_area_ = {
param.game.game_area.rect.x, .x = param.game.game_area.rect.x,
param.game.game_area.rect.y + black_bars_size_, .y = param.game.game_area.rect.y + black_bars_size_,
param.game.game_area.rect.w, .w = param.game.game_area.rect.w,
PLAY_AREA_HEIGHT}; .h = PLAY_AREA_HEIGHT};
// Barras negras para efecto letterbox // Barras negras para efecto letterbox
SDL_FRect top_black_rect_ = { SDL_FRect top_black_rect_ = {
play_area_.x, .x = play_area_.x,
param.game.game_area.rect.y, .y = param.game.game_area.rect.y,
play_area_.w, .w = play_area_.w,
black_bars_size_}; .h = black_bars_size_};
SDL_FRect bottom_black_rect_ = { SDL_FRect bottom_black_rect_ = {
play_area_.x, .x = play_area_.x,
param.game.game_area.rect.h - black_bars_size_, .y = param.game.game_area.rect.h - black_bars_size_,
play_area_.w, .w = play_area_.w,
black_bars_size_}; .h = black_bars_size_};
SDL_FRect left_black_rect_ = { SDL_FRect left_black_rect_ = {
play_area_.x, .x = play_area_.x,
param.game.game_area.center_y - 1, .y = param.game.game_area.center_y - 1,
0, .w = 0,
2}; .h = 2};
SDL_FRect right_black_rect_ = { SDL_FRect right_black_rect_ = {
play_area_.x + play_area_.w, .x = play_area_.x + play_area_.w,
param.game.game_area.center_y - 1, .y = param.game.game_area.center_y - 1,
0, .w = 0,
2}; .h = 2};
// Borde para la ventana // Borde para la ventana
SDL_FRect border_rect_ = play_area_; // Delimitador de ventana SDL_FRect border_rect_ = play_area_; // Delimitador de ventana

View File

@@ -57,7 +57,7 @@ Game::Game(Player::Id player_id, int current_stage, bool demo_enabled)
screen_(Screen::get()), screen_(Screen::get()),
input_(Input::get()), input_(Input::get()),
canvas_(SDL_CreateTexture(renderer_, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, param.game.play_area.rect.w, param.game.play_area.rect.h)), canvas_(SDL_CreateTexture(renderer_, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, param.game.play_area.rect.w, param.game.play_area.rect.h)),
pause_manager_(std::make_unique<PauseManager>([this](bool is_paused) { onPauseStateChanged(is_paused); })), pause_manager_(std::make_unique<PauseManager>([this](bool is_paused) -> void { onPauseStateChanged(is_paused); })),
stage_manager_(std::make_unique<StageManager>()), stage_manager_(std::make_unique<StageManager>()),
balloon_manager_(std::make_unique<BalloonManager>(stage_manager_.get())), balloon_manager_(std::make_unique<BalloonManager>(stage_manager_.get())),
bullet_manager_(std::make_unique<BulletManager>()), bullet_manager_(std::make_unique<BulletManager>()),
@@ -71,8 +71,8 @@ Game::Game(Player::Id player_id, int current_stage, bool demo_enabled)
// Otras variables // Otras variables
Section::name = Section::Name::GAME; Section::name = Section::Name::GAME;
Section::options = Section::Options::NONE; Section::options = Section::Options::NONE;
stage_manager_->initialize(Asset::get()->get("stages.txt")); stage_manager_->initialize(Asset::get()->getPath("stages.txt"));
stage_manager_->setPowerChangeCallback([this](int amount) { background_->incrementProgress(amount); }); stage_manager_->setPowerChangeCallback([this](int amount) -> void { background_->incrementProgress(amount); });
stage_manager_->jumpToStage(current_stage); stage_manager_->jumpToStage(current_stage);
// Asigna texturas y animaciones // Asigna texturas y animaciones
@@ -109,7 +109,7 @@ Game::Game(Player::Id player_id, int current_stage, bool demo_enabled)
initPaths(); initPaths();
// Registra callbacks // Registra callbacks
ServiceMenu::get()->setStateChangeCallback([this](bool is_active) { ServiceMenu::get()->setStateChangeCallback([this](bool is_active) -> void {
// Solo aplicar pausa si NO estamos en modo demo // Solo aplicar pausa si NO estamos en modo demo
if (!demo_.enabled) { if (!demo_.enabled) {
pause_manager_->setServiceMenuPause(is_active); pause_manager_->setServiceMenuPause(is_active);
@@ -117,15 +117,15 @@ Game::Game(Player::Id player_id, int current_stage, bool demo_enabled)
}); });
// Configura callbacks del BulletManager // Configura callbacks del BulletManager
bullet_manager_->setTabeCollisionCallback([this](const std::shared_ptr<Bullet>& bullet) { bullet_manager_->setTabeCollisionCallback([this](const std::shared_ptr<Bullet>& bullet) -> bool {
return checkBulletTabeCollision(bullet); return checkBulletTabeCollision(bullet);
}); });
bullet_manager_->setBalloonCollisionCallback([this](const std::shared_ptr<Bullet>& bullet) { bullet_manager_->setBalloonCollisionCallback([this](const std::shared_ptr<Bullet>& bullet) -> bool {
return checkBulletBalloonCollision(bullet); return checkBulletBalloonCollision(bullet);
}); });
bullet_manager_->setOutOfBoundsCallback([this](const std::shared_ptr<Bullet>& bullet) { bullet_manager_->setOutOfBoundsCallback([this](const std::shared_ptr<Bullet>& bullet) -> void {
getPlayer(static_cast<Player::Id>(bullet->getOwner()))->decScoreMultiplier(); getPlayer(static_cast<Player::Id>(bullet->getOwner()))->decScoreMultiplier();
}); });
#ifdef RECORDING #ifdef RECORDING
@@ -137,7 +137,7 @@ Game::~Game() {
// [Modo JUEGO] Guarda puntuaciones y transita a modo título // [Modo JUEGO] Guarda puntuaciones y transita a modo título
if (!demo_.enabled) { if (!demo_.enabled) {
auto manager = std::make_unique<ManageHiScoreTable>(Options::settings.hi_score_table); auto manager = std::make_unique<ManageHiScoreTable>(Options::settings.hi_score_table);
manager->saveToFile(Asset::get()->get("score.bin")); manager->saveToFile(Asset::get()->getPath("score.bin"));
Section::attract_mode = Section::AttractMode::TITLE_TO_DEMO; Section::attract_mode = Section::AttractMode::TITLE_TO_DEMO;
if (Options::audio.enabled) { if (Options::audio.enabled) {
// Musica // Musica
@@ -151,7 +151,7 @@ Game::~Game() {
ServiceMenu::get()->setStateChangeCallback(nullptr); ServiceMenu::get()->setStateChangeCallback(nullptr);
#ifdef RECORDING #ifdef RECORDING
saveDemoFile(Asset::get()->get("demo1.bin"), demo_.data.at(0)); saveDemoFile(Asset::get()->getPath("demo1.bin"), demo_.data.at(0));
#endif #endif
Scoreboard::destroy(); Scoreboard::destroy();
@@ -551,7 +551,7 @@ void Game::handleTabeHitEffects() {
// Maneja la colisión entre bala y globos // Maneja la colisión entre bala y globos
auto Game::checkBulletBalloonCollision(const std::shared_ptr<Bullet>& bullet) -> bool { auto Game::checkBulletBalloonCollision(const std::shared_ptr<Bullet>& bullet) -> bool {
return std::ranges::any_of(balloon_manager_->getBalloons(), [this, &bullet](auto& balloon) { return std::ranges::any_of(balloon_manager_->getBalloons(), [this, &bullet](auto& balloon) -> auto {
if (!balloon->isEnabled() || balloon->isInvulnerable()) { if (!balloon->isEnabled() || balloon->isInvulnerable()) {
return false; return false;
} }
@@ -684,7 +684,7 @@ void Game::createItem(ItemType type, float x, float y) {
// Vacia el vector de items // Vacia el vector de items
void Game::freeItems() { void Game::freeItems() {
std::erase_if(items_, [&](const auto& item) { std::erase_if(items_, [&](const auto& item) -> auto {
if (!item->isEnabled()) { if (!item->isEnabled()) {
// Comprobamos si hay que realizar una acción extra // Comprobamos si hay que realizar una acción extra
if (item->getType() == ItemType::COFFEE_MACHINE) { if (item->getType() == ItemType::COFFEE_MACHINE) {
@@ -715,7 +715,7 @@ void Game::createItemText(int x, const std::shared_ptr<Texture>& texture) {
// Inicializa // Inicializa
path_sprites_.back()->setWidth(W); path_sprites_.back()->setWidth(W);
path_sprites_.back()->setHeight(H); path_sprites_.back()->setHeight(H);
path_sprites_.back()->setSpriteClip({0, 0, static_cast<float>(W), static_cast<float>(H)}); path_sprites_.back()->setSpriteClip({.x = 0, .y = 0, .w = static_cast<float>(W), .h = static_cast<float>(H)});
path_sprites_.back()->addPath(Y0, Y1, PathType::VERTICAL, x, 1.667F, easeOutQuint, 0); // 100 frames → 1.667s path_sprites_.back()->addPath(Y0, Y1, PathType::VERTICAL, x, 1.667F, easeOutQuint, 0); // 100 frames → 1.667s
path_sprites_.back()->addPath(Y1, Y2, PathType::VERTICAL, x, 1.333F, easeInQuint, 0); // 80 frames → 1.333s path_sprites_.back()->addPath(Y1, Y2, PathType::VERTICAL, x, 1.333F, easeInQuint, 0); // 80 frames → 1.333s
path_sprites_.back()->enable(); path_sprites_.back()->enable();
@@ -734,14 +734,14 @@ void Game::createMessage(const std::vector<Path>& paths, const std::shared_ptr<T
// Vacia la lista de smartsprites // Vacia la lista de smartsprites
void Game::freeSmartSprites() { void Game::freeSmartSprites() {
std::erase_if(smart_sprites_, [](const auto& sprite) { std::erase_if(smart_sprites_, [](const auto& sprite) -> auto {
return sprite->hasFinished(); return sprite->hasFinished();
}); });
} }
// Vacia la lista de pathsprites // Vacia la lista de pathsprites
void Game::freePathSprites() { void Game::freePathSprites() {
std::erase_if(path_sprites_, [](const auto& sprite) { std::erase_if(path_sprites_, [](const auto& sprite) -> auto {
return sprite->hasFinished(); return sprite->hasFinished();
}); });
} }
@@ -763,7 +763,7 @@ void Game::throwCoffee(int x, int y) {
smart_sprites_.back()->setEnabled(true); smart_sprites_.back()->setEnabled(true);
smart_sprites_.back()->setFinishedDelay(0.0F); smart_sprites_.back()->setFinishedDelay(0.0F);
smart_sprites_.back()->setSpriteClip(0, Item::HEIGHT, Item::WIDTH, Item::HEIGHT); smart_sprites_.back()->setSpriteClip(0, Item::HEIGHT, Item::WIDTH, Item::HEIGHT);
smart_sprites_.back()->setRotatingCenter({Item::WIDTH / 2, Item::HEIGHT / 2}); smart_sprites_.back()->setRotatingCenter({.x = Item::WIDTH / 2, .y = Item::HEIGHT / 2});
smart_sprites_.back()->setRotate(true); smart_sprites_.back()->setRotate(true);
smart_sprites_.back()->setRotateAmount(90.0); smart_sprites_.back()->setRotateAmount(90.0);
} }
@@ -1200,7 +1200,7 @@ void Game::checkPlayersStatusPlaying() {
// Obtiene un jugador a partir de su "id" // Obtiene un jugador a partir de su "id"
auto Game::getPlayer(Player::Id id) -> std::shared_ptr<Player> { auto Game::getPlayer(Player::Id id) -> std::shared_ptr<Player> {
auto it = std::ranges::find_if(players_, [id](const auto& player) { return player->getId() == id; }); auto it = std::ranges::find_if(players_, [id](const auto& player) -> auto { return player->getId() == id; });
if (it != players_.end()) { if (it != players_.end()) {
return *it; return *it;
@@ -1298,11 +1298,11 @@ void Game::demoHandlePlayerInput(const std::shared_ptr<Player>& player, int inde
// Maneja el disparo de un jugador, incluyendo la creación de balas y la gestión del tiempo de espera entre disparos. // Maneja el disparo de un jugador, incluyendo la creación de balas y la gestión del tiempo de espera entre disparos.
void Game::handleFireInput(const std::shared_ptr<Player>& player, Bullet::Type type) { void Game::handleFireInput(const std::shared_ptr<Player>& player, Bullet::Type type) {
if (player->canFire()) { if (player->canFire()) {
SDL_Point bullet = {0, 0}; SDL_Point bullet = {.x = 0, .y = 0};
switch (type) { switch (type) {
case Bullet::Type::UP: case Bullet::Type::UP:
player->setInput(Input::Action::FIRE_CENTER); player->setInput(Input::Action::FIRE_CENTER);
bullet.x = 2 + player->getPosX() + (Player::WIDTH - Bullet::WIDTH) / 2; bullet.x = 2 + player->getPosX() + ((Player::WIDTH - Bullet::WIDTH) / 2);
bullet.y = player->getPosY() - (Bullet::HEIGHT / 2); bullet.y = player->getPosY() - (Bullet::HEIGHT / 2);
break; break;
case Bullet::Type::LEFT: case Bullet::Type::LEFT:
@@ -1969,7 +1969,7 @@ void Game::buildPlayerDrawList(const Players& elements, Players& draw_list) {
for (const auto& e : elements) { for (const auto& e : elements) {
draw_list.push_back(e); // copia el shared_ptr draw_list.push_back(e); // copia el shared_ptr
} }
std::ranges::stable_sort(draw_list, [](const std::shared_ptr<Player>& a, const std::shared_ptr<Player>& b) { std::ranges::stable_sort(draw_list, [](const std::shared_ptr<Player>& a, const std::shared_ptr<Player>& b) -> bool {
return a->getZOrder() < b->getZOrder(); return a->getZOrder() < b->getZOrder();
}); });
} }
@@ -1983,7 +1983,7 @@ void Game::updatePlayerDrawList(const Players& elements, Players& draw_list) {
return; return;
} }
// Dado que apuntan a los mismos elementos, basta ordenar por los z_order actuales. // Dado que apuntan a los mismos elementos, basta ordenar por los z_order actuales.
std::ranges::stable_sort(draw_list, [](const std::shared_ptr<Player>& a, const std::shared_ptr<Player>& b) { std::ranges::stable_sort(draw_list, [](const std::shared_ptr<Player>& a, const std::shared_ptr<Player>& b) -> bool {
return a->getZOrder() < b->getZOrder(); return a->getZOrder() < b->getZOrder();
}); });
} }

View File

@@ -96,22 +96,13 @@ class Game {
bool need_coffee{false}; // Indica si se necesitan cafes bool need_coffee{false}; // Indica si se necesitan cafes
bool need_coffee_machine{false}; // Indica si se necesita PowerUp bool need_coffee_machine{false}; // Indica si se necesita PowerUp
bool need_power_ball{false}; // Indica si se necesita una PowerBall bool need_power_ball{false}; // Indica si se necesita una PowerBall
float counter; // Contador para no dar ayudas consecutivas float counter{HELP_COUNTER_S * 1000}; // Contador para no dar ayudas consecutivas
int item_disk_odds; // Probabilidad de aparición del objeto int item_disk_odds{ITEM_POINTS_1_DISK_ODDS}; // Probabilidad de aparición del objeto
int item_gavina_odds; // Probabilidad de aparición del objeto int item_gavina_odds{ITEM_POINTS_2_GAVINA_ODDS}; // Probabilidad de aparición del objeto
int item_pacmar_odds; // Probabilidad de aparición del objeto int item_pacmar_odds{ITEM_POINTS_3_PACMAR_ODDS}; // Probabilidad de aparición del objeto
int item_clock_odds; // Probabilidad de aparición del objeto int item_clock_odds{ITEM_CLOCK_ODDS}; // Probabilidad de aparición del objeto
int item_coffee_odds; // Probabilidad de aparición del objeto int item_coffee_odds{ITEM_COFFEE_ODDS}; // Probabilidad de aparición del objeto
int item_coffee_machine_odds; // Probabilidad de aparición del objeto int item_coffee_machine_odds{ITEM_COFFEE_MACHINE_ODDS}; // Probabilidad de aparición del objeto
Helper()
: counter(HELP_COUNTER_S * 1000), // Convertir a milisegundos para compatibilidad
item_disk_odds(ITEM_POINTS_1_DISK_ODDS),
item_gavina_odds(ITEM_POINTS_2_GAVINA_ODDS),
item_pacmar_odds(ITEM_POINTS_3_PACMAR_ODDS),
item_clock_odds(ITEM_CLOCK_ODDS),
item_coffee_odds(ITEM_COFFEE_ODDS),
item_coffee_machine_odds(ITEM_COFFEE_MACHINE_ODDS) {}
}; };
// --- Objetos y punteros --- // --- Objetos y punteros ---

View File

@@ -5,6 +5,7 @@
#include <algorithm> // Para max #include <algorithm> // Para max
#include <cstdlib> // Para rand, size_t #include <cstdlib> // Para rand, size_t
#include <functional> // Para function #include <functional> // Para function
#include <utility> // Para std::cmp_less
#include <vector> // Para vector #include <vector> // Para vector
#include "audio.hpp" // Para Audio #include "audio.hpp" // Para Audio
@@ -34,7 +35,7 @@ HiScoreTable::HiScoreTable()
fade_(std::make_unique<Fade>()), fade_(std::make_unique<Fade>()),
background_(std::make_unique<Background>()), background_(std::make_unique<Background>()),
view_area_(SDL_FRect{0, 0, param.game.width, param.game.height}), view_area_(SDL_FRect{.x = 0, .y = 0, .w = param.game.width, .h = param.game.height}),
fade_mode_(Fade::Mode::IN), fade_mode_(Fade::Mode::IN),
background_fade_color_(Color(0, 0, 0)) { background_fade_color_(Color(0, 0, 0)) {
// Inicializa el resto // Inicializa el resto
@@ -145,7 +146,7 @@ void HiScoreTable::updateFade(float delta_time) {
fade_->update(delta_time); fade_->update(delta_time);
if (fade_->hasEnded() && fade_mode_ == Fade::Mode::IN) { if (fade_->hasEnded() && fade_mode_ == Fade::Mode::IN) {
fade_->reset(); (*fade_).reset();
fade_mode_ = Fade::Mode::OUT; fade_mode_ = Fade::Mode::OUT;
fade_->setMode(fade_mode_); fade_->setMode(fade_mode_);
} }
@@ -163,7 +164,7 @@ auto HiScoreTable::format(int number) -> std::string {
const std::string SEPARATOR = "."; const std::string SEPARATOR = ".";
const std::string SCORE = std::to_string(number); const std::string SCORE = std::to_string(number);
auto index = (int)SCORE.size() - 1; auto index = static_cast<int>(SCORE.size()) - 1;
std::string result; std::string result;
auto i = 0; auto i = 0;
while (index >= 0) { while (index >= 0) {
@@ -211,7 +212,7 @@ void HiScoreTable::createSprites() {
const auto NUM_DOTS = ENTRY_LENGTH - Options::settings.hi_score_table.at(i).name.size() - SCORE.size(); const auto NUM_DOTS = ENTRY_LENGTH - Options::settings.hi_score_table.at(i).name.size() - SCORE.size();
const auto* const ONE_CC = Options::settings.hi_score_table.at(i).one_credit_complete ? " }" : ""; const auto* const ONE_CC = Options::settings.hi_score_table.at(i).one_credit_complete ? " }" : "";
std::string dots; std::string dots;
for (int j = 0; j < (int)NUM_DOTS; ++j) { for (int j = 0; std::cmp_less(j, NUM_DOTS); ++j) {
dots = dots + "."; dots = dots + ".";
} }
const auto LINE = TABLE_POSITION + Options::settings.hi_score_table.at(i).name + dots + SCORE + ONE_CC; const auto LINE = TABLE_POSITION + Options::settings.hi_score_table.at(i).name + dots + SCORE + ONE_CC;
@@ -264,7 +265,7 @@ void HiScoreTable::updateSprites(float delta_time) {
if (elapsed_time_ >= INIT_DELAY_S) { if (elapsed_time_ >= INIT_DELAY_S) {
const float ELAPSED_SINCE_INIT = elapsed_time_ - INIT_DELAY_S; const float ELAPSED_SINCE_INIT = elapsed_time_ - INIT_DELAY_S;
int index = static_cast<int>(ELAPSED_SINCE_INIT / ENTRY_DELAY_S); int index = static_cast<int>(ELAPSED_SINCE_INIT / ENTRY_DELAY_S);
if (index < static_cast<int>(entry_names_.size()) && index >= 0) { if (std::cmp_less(index, entry_names_.size()) && index >= 0) {
// Verificar si este índice debe activarse ahora // Verificar si este índice debe activarse ahora
float expected_time = index * ENTRY_DELAY_S; float expected_time = index * ENTRY_DELAY_S;
if (ELAPSED_SINCE_INIT >= expected_time && ELAPSED_SINCE_INIT < expected_time + delta_time) { if (ELAPSED_SINCE_INIT >= expected_time && ELAPSED_SINCE_INIT < expected_time + delta_time) {
@@ -340,7 +341,7 @@ auto HiScoreTable::getEntryColor(int counter) -> Color {
if (n < entry_colors_.size()) { if (n < entry_colors_.size()) {
index = n; // Avanza: 0,1,2,3 index = n; // Avanza: 0,1,2,3
} else { } else {
index = 2 * (entry_colors_.size() - 1) - n; // Retrocede: 2,1 index = (2 * (entry_colors_.size() - 1)) - n; // Retrocede: 2,1
} }
return entry_colors_[index]; return entry_colors_[index];

View File

@@ -78,16 +78,16 @@ void Instructions::iniSprites() {
item_textures_.emplace_back(Resource::get()->getTexture("item_coffee.png")); item_textures_.emplace_back(Resource::get()->getTexture("item_coffee.png"));
// Inicializa los sprites // Inicializa los sprites
for (int i = 0; i < (int)item_textures_.size(); ++i) { for (int i = 0; std::cmp_less(i, item_textures_.size()); ++i) {
auto sprite = std::make_unique<Sprite>(item_textures_[i], 0, 0, Item::WIDTH, Item::HEIGHT); auto sprite = std::make_unique<Sprite>(item_textures_[i], 0, 0, Item::WIDTH, Item::HEIGHT);
sprite->setPosition((SDL_FPoint){sprite_pos_.x, sprite_pos_.y + ((Item::HEIGHT + item_space_) * i)}); sprite->setPosition((SDL_FPoint){.x = sprite_pos_.x, .y = sprite_pos_.y + ((Item::HEIGHT + item_space_) * i)});
sprites_.push_back(std::move(sprite)); sprites_.push_back(std::move(sprite));
} }
} }
// Actualiza los sprites // Actualiza los sprites
void Instructions::updateSprites() { void Instructions::updateSprites() {
SDL_FRect src_rect = {0, 0, Item::WIDTH, Item::HEIGHT}; SDL_FRect src_rect = {.x = 0, .y = 0, .w = Item::WIDTH, .h = Item::HEIGHT};
// Disquito (desplazamiento 12/60 = 0.2s) // Disquito (desplazamiento 12/60 = 0.2s)
src_rect.y = Item::HEIGHT * (static_cast<int>((elapsed_time_ + 0.2F) / SPRITE_ANIMATION_CYCLE_S) % 2); src_rect.y = Item::HEIGHT * (static_cast<int>((elapsed_time_ + 0.2F) / SPRITE_ANIMATION_CYCLE_S) % 2);
@@ -134,7 +134,7 @@ void Instructions::fillTexture() {
const int SPACE_BETWEEN_ITEM_LINES = Item::HEIGHT + item_space_; const int SPACE_BETWEEN_ITEM_LINES = Item::HEIGHT + item_space_;
const int SPACE_NEW_PARAGRAPH = SPACE_BETWEEN_LINES * 0.5F; const int SPACE_NEW_PARAGRAPH = SPACE_BETWEEN_LINES * 0.5F;
const int SIZE = (NUM_LINES * SPACE_BETWEEN_LINES) + (NUM_ITEM_LINES * SPACE_BETWEEN_ITEM_LINES) + (NUM_POST_HEADERS * SPACE_POST_HEADER) + (NUM_PRE_HEADERS * SPACE_PRE_HEADER) + (SPACE_NEW_PARAGRAPH); const int SIZE = (NUM_LINES * SPACE_BETWEEN_LINES) + (NUM_ITEM_LINES * SPACE_BETWEEN_ITEM_LINES) + (NUM_POST_HEADERS * SPACE_POST_HEADER) + (NUM_PRE_HEADERS * SPACE_PRE_HEADER) + SPACE_NEW_PARAGRAPH;
const int FIRST_LINE = (param.game.height - SIZE) / 2; const int FIRST_LINE = (param.game.height - SIZE) / 2;
// Calcula cual es el texto más largo de las descripciones de los items // Calcula cual es el texto más largo de las descripciones de los items
@@ -333,8 +333,8 @@ auto Instructions::moveLines(std::vector<Line>& lines, int width, float duration
// Método para renderizar las líneas // Método para renderizar las líneas
void Instructions::renderLines(SDL_Renderer* renderer, SDL_Texture* texture, const std::vector<Line>& lines) { void Instructions::renderLines(SDL_Renderer* renderer, SDL_Texture* texture, const std::vector<Line>& lines) {
for (const auto& line : lines) { for (const auto& line : lines) {
SDL_FRect src_rect = {0, static_cast<float>(line.y), 320, 1}; SDL_FRect src_rect = {.x = 0, .y = static_cast<float>(line.y), .w = 320, .h = 1};
SDL_FRect dst_rect = {static_cast<float>(line.x), static_cast<float>(line.y), 320, 1}; SDL_FRect dst_rect = {.x = static_cast<float>(line.x), .y = static_cast<float>(line.y), .w = 320, .h = 1};
SDL_RenderTexture(renderer, texture, &src_rect, &dst_rect); SDL_RenderTexture(renderer, texture, &src_rect, &dst_rect);
} }
} }

View File

@@ -74,7 +74,7 @@ class Instructions {
float elapsed_time_ = 0.0F; // Tiempo transcurrido (segundos) float elapsed_time_ = 0.0F; // Tiempo transcurrido (segundos)
Uint64 last_time_ = 0; // Último timestamp para calcular delta-time Uint64 last_time_ = 0; // Último timestamp para calcular delta-time
SDL_FRect view_; // Vista del backbuffer que se va a mostrar por pantalla SDL_FRect view_; // Vista del backbuffer que se va a mostrar por pantalla
SDL_FPoint sprite_pos_ = {0, 0}; // Posición del primer sprite en la lista SDL_FPoint sprite_pos_ = {.x = 0, .y = 0}; // Posición del primer sprite en la lista
float item_space_ = 2.0; // Espacio entre los items en pantalla float item_space_ = 2.0; // Espacio entre los items en pantalla
std::vector<Line> lines_; // Vector que contiene las líneas animadas en la pantalla std::vector<Line> lines_; // Vector que contiene las líneas animadas en la pantalla
bool all_lines_off_screen_ = false; // Indica si todas las líneas han salido de la pantalla bool all_lines_off_screen_ = false; // Indica si todas las líneas han salido de la pantalla

View File

@@ -311,13 +311,13 @@ void Intro::initSprites() {
// Pone color en el marco de la textura // Pone color en el marco de la textura
auto color = param.intro.card_color; auto color = param.intro.card_color;
SDL_SetRenderDrawColor(Screen::get()->getRenderer(), color.r, color.g, color.b, color.a); SDL_SetRenderDrawColor(Screen::get()->getRenderer(), color.r, color.g, color.b, color.a);
SDL_FRect rect1 = {1, 0, CARD_WIDTH - 2, CARD_HEIGHT}; SDL_FRect rect1 = {.x = 1, .y = 0, .w = CARD_WIDTH - 2, .h = CARD_HEIGHT};
SDL_FRect rect2 = {0, 1, CARD_WIDTH, CARD_HEIGHT - 2}; SDL_FRect rect2 = {.x = 0, .y = 1, .w = CARD_WIDTH, .h = CARD_HEIGHT - 2};
SDL_RenderRect(Screen::get()->getRenderer(), &rect1); SDL_RenderRect(Screen::get()->getRenderer(), &rect1);
SDL_RenderRect(Screen::get()->getRenderer(), &rect2); SDL_RenderRect(Screen::get()->getRenderer(), &rect2);
// Copia la textura con la imagen dentro del marco // Copia la textura con la imagen dentro del marco
SDL_FRect dest = {BORDER, BORDER, CARD_WIDTH - (BORDER * 2), CARD_HEIGHT - (BORDER * 2)}; SDL_FRect dest = {.x = BORDER, .y = BORDER, .w = CARD_WIDTH - (BORDER * 2), .h = CARD_HEIGHT - (BORDER * 2)};
SDL_RenderTexture(Screen::get()->getRenderer(), Resource::get()->getTexture(TEXTURE_LIST.at(i))->getSDLTexture(), nullptr, &dest); SDL_RenderTexture(Screen::get()->getRenderer(), Resource::get()->getTexture(TEXTURE_LIST.at(i))->getSDLTexture(), nullptr, &dest);
// Deja el renderizador como estaba y añade la textura a la lista // Deja el renderizador como estaba y añade la textura a la lista
@@ -366,8 +366,8 @@ void Intro::initSprites() {
// Dibuja la sombra sobre la textura // Dibuja la sombra sobre la textura
auto shadow_color = param.intro.shadow_color; auto shadow_color = param.intro.shadow_color;
SDL_SetRenderDrawColor(Screen::get()->getRenderer(), shadow_color.r, shadow_color.g, shadow_color.b, Color::MAX_ALPHA_VALUE); SDL_SetRenderDrawColor(Screen::get()->getRenderer(), shadow_color.r, shadow_color.g, shadow_color.b, Color::MAX_ALPHA_VALUE);
SDL_FRect rect1 = {1, 0, SHADOW_SPRITE_WIDTH - 2, SHADOW_SPRITE_HEIGHT}; SDL_FRect rect1 = {.x = 1, .y = 0, .w = SHADOW_SPRITE_WIDTH - 2, .h = SHADOW_SPRITE_HEIGHT};
SDL_FRect rect2 = {0, 1, SHADOW_SPRITE_WIDTH, SHADOW_SPRITE_HEIGHT - 2}; SDL_FRect rect2 = {.x = 0, .y = 1, .w = SHADOW_SPRITE_WIDTH, .h = SHADOW_SPRITE_HEIGHT - 2};
SDL_RenderFillRect(Screen::get()->getRenderer(), &rect1); SDL_RenderFillRect(Screen::get()->getRenderer(), &rect1);
SDL_RenderFillRect(Screen::get()->getRenderer(), &rect2); SDL_RenderFillRect(Screen::get()->getRenderer(), &rect2);
@@ -522,7 +522,7 @@ void Intro::updatePostState() {
void Intro::renderTextRect() { void Intro::renderTextRect() {
static const float HEIGHT = Resource::get()->getText("04b_25_metal")->getCharacterSize(); static const float HEIGHT = Resource::get()->getText("04b_25_metal")->getCharacterSize();
static SDL_FRect rect_ = {0.0F, param.game.height - param.intro.text_distance_from_bottom - HEIGHT, param.game.width, HEIGHT * 3}; static SDL_FRect rect_ = {.x = 0.0F, .y = param.game.height - param.intro.text_distance_from_bottom - HEIGHT, .w = param.game.width, .h = HEIGHT * 3};
SDL_SetRenderDrawColor(Screen::get()->getRenderer(), param.intro.shadow_color.r, param.intro.shadow_color.g, param.intro.shadow_color.b, param.intro.shadow_color.a); SDL_SetRenderDrawColor(Screen::get()->getRenderer(), param.intro.shadow_color.r, param.intro.shadow_color.g, param.intro.shadow_color.b, param.intro.shadow_color.a);
SDL_RenderFillRect(Screen::get()->getRenderer(), &rect_); SDL_RenderFillRect(Screen::get()->getRenderer(), &rect_);
} }

View File

@@ -26,13 +26,13 @@ Logo::Logo()
jail_texture_(Resource::get()->getTexture("logo_jailgames.png")) { jail_texture_(Resource::get()->getTexture("logo_jailgames.png")) {
// Inicializa variables // Inicializa variables
Section::name = Section::Name::LOGO; Section::name = Section::Name::LOGO;
dest_.x = param.game.game_area.center_x - jail_texture_->getWidth() / 2; dest_.x = param.game.game_area.center_x - (jail_texture_->getWidth() / 2);
dest_.y = param.game.game_area.center_y - jail_texture_->getHeight() / 2; dest_.y = param.game.game_area.center_y - (jail_texture_->getHeight() / 2);
since_sprite_->setPosition(SDL_FRect{ since_sprite_->setPosition(SDL_FRect{
static_cast<float>((param.game.width - since_texture_->getWidth()) / 2), .x = static_cast<float>((param.game.width - since_texture_->getWidth()) / 2),
static_cast<float>(SINCE_SPRITE_Y_OFFSET + jail_texture_->getHeight() + LOGO_SPACING), .y = static_cast<float>(SINCE_SPRITE_Y_OFFSET + jail_texture_->getHeight() + LOGO_SPACING),
static_cast<float>(since_texture_->getWidth()), .w = static_cast<float>(since_texture_->getWidth()),
static_cast<float>(since_texture_->getHeight())}); .h = static_cast<float>(since_texture_->getHeight())});
since_sprite_->setY(dest_.y + jail_texture_->getHeight() + LOGO_SPACING); since_sprite_->setY(dest_.y + jail_texture_->getHeight() + LOGO_SPACING);
since_sprite_->setSpriteClip(0, 0, since_texture_->getWidth(), since_texture_->getHeight()); since_sprite_->setSpriteClip(0, 0, since_texture_->getWidth(), since_texture_->getHeight());
since_texture_->setColor(SPECTRUM_BLACK.r, SPECTRUM_BLACK.g, SPECTRUM_BLACK.b); since_texture_->setColor(SPECTRUM_BLACK.r, SPECTRUM_BLACK.g, SPECTRUM_BLACK.b);

View File

@@ -207,9 +207,9 @@ void Title::decrementAllComponents(Color& color) {
void Title::printColorValue(const Color& color) { void Title::printColorValue(const Color& color) {
std::cout << "#" std::cout << "#"
<< std::hex << std::setw(2) << std::setfill('0') << (int)color.r << std::hex << std::setw(2) << std::setfill('0') << static_cast<int>(color.r)
<< std::setw(2) << std::setfill('0') << (int)color.g << std::setw(2) << std::setfill('0') << static_cast<int>(color.g)
<< std::setw(2) << std::setfill('0') << (int)color.b << std::setw(2) << std::setfill('0') << static_cast<int>(color.b)
<< '\n'; << '\n';
} }
#endif #endif
@@ -586,7 +586,7 @@ void Title::renderPlayers() {
// Obtiene un jugador a partir de su "id" // Obtiene un jugador a partir de su "id"
auto Title::getPlayer(Player::Id id) -> std::shared_ptr<Player> { auto Title::getPlayer(Player::Id id) -> std::shared_ptr<Player> {
auto it = std::ranges::find_if(players_, [id](const auto& player) { return player->getId() == id; }); auto it = std::ranges::find_if(players_, [id](const auto& player) -> auto { return player->getId() == id; });
if (it != players_.end()) { if (it != players_.end()) {
return *it; return *it;

View File

@@ -20,10 +20,10 @@ class SmartSprite : public AnimatedSprite {
void render() override; // Dibuja el sprite void render() override; // Dibuja el sprite
// --- Getters --- // --- Getters ---
auto getDestX() const -> int { return dest_x_; } // Obtiene la posición de destino en X [[nodiscard]] 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 [[nodiscard]] 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 [[nodiscard]] auto isOnDestination() const -> bool { return on_destination_; } // Indica si está en el destino
auto hasFinished() const -> bool { return finished_; } // Indica si ya ha terminado [[nodiscard]] auto hasFinished() const -> bool { return finished_; } // Indica si ya ha terminado
// --- Setters --- // --- Setters ---
void setFinishedDelay(float value) { finished_delay_ms_ = value; } // Establece el retraso para deshabilitarlo (ms) void setFinishedDelay(float value) { finished_delay_ms_ = value; } // Establece el retraso para deshabilitarlo (ms)

View File

@@ -8,18 +8,18 @@
// Constructor // Constructor
Sprite::Sprite(std::shared_ptr<Texture> texture, float pos_x, float pos_y, float width, float height) Sprite::Sprite(std::shared_ptr<Texture> texture, float pos_x, float pos_y, float width, float height)
: textures_{std::move(texture)}, : textures_{std::move(texture)},
pos_((SDL_FRect){pos_x, pos_y, width, height}), pos_((SDL_FRect){.x = pos_x, .y = pos_y, .w = width, .h = height}),
sprite_clip_((SDL_FRect){0, 0, pos_.w, pos_.h}) {} sprite_clip_((SDL_FRect){.x = 0, .y = 0, .w = pos_.w, .h = pos_.h}) {}
Sprite::Sprite(std::shared_ptr<Texture> texture, SDL_FRect rect) Sprite::Sprite(std::shared_ptr<Texture> texture, SDL_FRect rect)
: textures_{std::move(texture)}, : textures_{std::move(texture)},
pos_(rect), pos_(rect),
sprite_clip_((SDL_FRect){0, 0, pos_.w, pos_.h}) {} sprite_clip_((SDL_FRect){.x = 0, .y = 0, .w = pos_.w, .h = pos_.h}) {}
Sprite::Sprite(std::shared_ptr<Texture> texture) Sprite::Sprite(std::shared_ptr<Texture> texture)
: textures_{std::move(texture)}, : textures_{std::move(texture)},
pos_(SDL_FRect{0, 0, static_cast<float>(textures_.at(texture_index_)->getWidth()), static_cast<float>(textures_.at(texture_index_)->getHeight())}), pos_(SDL_FRect{.x = 0, .y = 0, .w = static_cast<float>(textures_.at(texture_index_)->getWidth()), .h = static_cast<float>(textures_.at(texture_index_)->getHeight())}),
sprite_clip_(pos_) {} sprite_clip_(pos_) {}
// Muestra el sprite por pantalla // Muestra el sprite por pantalla
@@ -49,7 +49,6 @@ void Sprite::clear() {
auto Sprite::setActiveTexture(size_t index) -> bool { auto Sprite::setActiveTexture(size_t index) -> bool {
if (index < textures_.size()) { if (index < textures_.size()) {
texture_index_ = index; texture_index_ = index;
return true;
} }
return false; // Índice fuera de rango return index < textures_.size();
} }

View File

@@ -49,7 +49,7 @@ class Sprite {
// --- Sprite clip --- // --- Sprite clip ---
[[nodiscard]] auto getSpriteClip() const -> SDL_FRect { return sprite_clip_; } [[nodiscard]] auto getSpriteClip() const -> SDL_FRect { return sprite_clip_; }
void setSpriteClip(SDL_FRect rect) { sprite_clip_ = rect; } void setSpriteClip(SDL_FRect rect) { sprite_clip_ = rect; }
void setSpriteClip(float pos_x, float pos_y, float width, float height) { sprite_clip_ = SDL_FRect{pos_x, pos_y, width, height}; } void setSpriteClip(float pos_x, float pos_y, float width, float height) { sprite_clip_ = SDL_FRect{.x = pos_x, .y = pos_y, .w = width, .h = height}; }
// --- Textura --- // --- Textura ---
[[nodiscard]] auto getTexture() const -> std::shared_ptr<Texture> { return textures_.at(texture_index_); } [[nodiscard]] auto getTexture() const -> std::shared_ptr<Texture> { return textures_.at(texture_index_); }

View File

@@ -130,7 +130,7 @@ void Tabe::enable() {
void Tabe::setRandomFlyPath(Direction direction, int length) { void Tabe::setRandomFlyPath(Direction direction, int length) {
direction_ = direction; direction_ = direction;
fly_distance_ = length; fly_distance_ = length;
waiting_counter_ = 0.083F + (rand() % 15) * 0.0167F; // 5-20 frames converted to seconds (5/60 to 20/60) waiting_counter_ = 0.083F + ((rand() % 15) * 0.0167F); // 5-20 frames converted to seconds (5/60 to 20/60)
Audio::get()->playSound("tabe.wav"); Audio::get()->playSound("tabe.wav");
constexpr float SPEED = 120.0F; // 2 pixels/frame * 60fps = 120 pixels/second constexpr float SPEED = 120.0F; // 2 pixels/frame * 60fps = 120 pixels/second
@@ -138,14 +138,14 @@ void Tabe::setRandomFlyPath(Direction direction, int length) {
switch (direction) { switch (direction) {
case Direction::TO_THE_LEFT: { case Direction::TO_THE_LEFT: {
speed_ = -1.0F * SPEED; speed_ = -1.0F * SPEED;
accel_ = -1.0F * (1 + rand() % 10) * 2.0F; // Converted from frame-based to seconds accel_ = -1.0F * (1 + (rand() % 10)) * 2.0F; // Converted from frame-based to seconds
sprite_->setFlip(SDL_FLIP_NONE); sprite_->setFlip(SDL_FLIP_NONE);
break; break;
} }
case Direction::TO_THE_RIGHT: { case Direction::TO_THE_RIGHT: {
speed_ = SPEED; speed_ = SPEED;
accel_ = (1 + rand() % 10) * 2.0F; // Converted from frame-based to seconds accel_ = (1 + (rand() % 10)) * 2.0F; // Converted from frame-based to seconds
sprite_->setFlip(SDL_FLIP_HORIZONTAL); sprite_->setFlip(SDL_FLIP_HORIZONTAL);
break; break;
} }

View File

@@ -70,7 +70,7 @@ class Tabe {
// Restablece el temporizador con un nuevo tiempo hasta la próxima aparición // Restablece el temporizador con un nuevo tiempo hasta la próxima aparición
void reset() { void reset() {
Uint32 range = max_spawn_time - min_spawn_time; Uint32 range = max_spawn_time - min_spawn_time;
time_until_next_spawn = min_spawn_time + rand() % (range + 1); time_until_next_spawn = min_spawn_time + (rand() % (range + 1));
last_time = SDL_GetTicks(); last_time = SDL_GetTicks();
} }

View File

@@ -2,7 +2,8 @@
#include <SDL3/SDL.h> // Para SDL_FRect, Uint8, SDL_GetRenderTarget, SDL_RenderClear, SDL_SetRenderDrawColor, SDL_SetRenderTarget, SDL_BLENDMODE_BLEND, SDL_PixelFormat, SDL_TextureAccess, SDL_GetTextureAlphaMod #include <SDL3/SDL.h> // Para SDL_FRect, Uint8, SDL_GetRenderTarget, SDL_RenderClear, SDL_SetRenderDrawColor, SDL_SetRenderTarget, SDL_BLENDMODE_BLEND, SDL_PixelFormat, SDL_TextureAccess, SDL_GetTextureAlphaMod
#include <fstream> // Para basic_ifstream, basic_istream, basic_ostream, operator<<, istream, ifstream, istringstream #include <fstream> // Para basic_ifstream, basic_istream, basic_ostream, operator<<, istream, ifstream, istringstream
#include <utility> // Para std::cmp_less_equal
#include <iostream> // Para cerr #include <iostream> // Para cerr
#include <sstream> // Para basic_istringstream #include <sstream> // Para basic_istringstream
#include <stdexcept> // Para runtime_error #include <stdexcept> // Para runtime_error
@@ -32,7 +33,7 @@ Text::Text(const std::shared_ptr<Texture>& texture, const std::string& text_file
} }
// Crea los objetos // Crea los objetos
sprite_ = std::make_unique<Sprite>(texture, (SDL_FRect){0, 0, static_cast<float>(box_width_), static_cast<float>(box_height_)}); sprite_ = std::make_unique<Sprite>(texture, (SDL_FRect){.x = 0, .y = 0, .w = static_cast<float>(box_width_), .h = static_cast<float>(box_height_)});
// Inicializa variables // Inicializa variables
fixed_width_ = false; fixed_width_ = false;
@@ -50,7 +51,7 @@ Text::Text(const std::shared_ptr<Texture>& texture, const std::shared_ptr<Text::
} }
// Crea los objetos // Crea los objetos
sprite_ = std::make_unique<Sprite>(texture, (SDL_FRect){0, 0, static_cast<float>(box_width_), static_cast<float>(box_height_)}); sprite_ = std::make_unique<Sprite>(texture, (SDL_FRect){.x = 0, .y = 0, .w = static_cast<float>(box_width_), .h = static_cast<float>(box_height_)});
// Inicializa variables // Inicializa variables
fixed_width_ = false; fixed_width_ = false;
@@ -71,8 +72,8 @@ Text::Text(const std::shared_ptr<Texture>& texture, const std::shared_ptr<Textur
} }
// Crea los objetos // Crea los objetos
sprite_ = std::make_unique<Sprite>(texture, (SDL_FRect){0, 0, static_cast<float>(box_width_), static_cast<float>(box_height_)}); sprite_ = std::make_unique<Sprite>(texture, (SDL_FRect){.x = 0, .y = 0, .w = static_cast<float>(box_width_), .h = static_cast<float>(box_height_)});
white_sprite_ = std::make_unique<Sprite>(white_texture, (SDL_FRect){0, 0, static_cast<float>(box_width_), static_cast<float>(box_height_)}); white_sprite_ = std::make_unique<Sprite>(white_texture, (SDL_FRect){.x = 0, .y = 0, .w = static_cast<float>(box_width_), .h = static_cast<float>(box_height_)});
// Inicializa variables // Inicializa variables
fixed_width_ = false; fixed_width_ = false;
@@ -90,8 +91,8 @@ Text::Text(const std::shared_ptr<Texture>& texture, const std::shared_ptr<Textur
} }
// Crea los objetos // Crea los objetos
sprite_ = std::make_unique<Sprite>(texture, (SDL_FRect){0, 0, static_cast<float>(box_width_), static_cast<float>(box_height_)}); sprite_ = std::make_unique<Sprite>(texture, (SDL_FRect){.x = 0, .y = 0, .w = static_cast<float>(box_width_), .h = static_cast<float>(box_height_)});
white_sprite_ = std::make_unique<Sprite>(white_texture, (SDL_FRect){0, 0, static_cast<float>(box_width_), static_cast<float>(box_height_)}); white_sprite_ = std::make_unique<Sprite>(white_texture, (SDL_FRect){.x = 0, .y = 0, .w = static_cast<float>(box_width_), .h = static_cast<float>(box_height_)});
// Inicializa variables // Inicializa variables
fixed_width_ = false; fixed_width_ = false;
@@ -125,10 +126,10 @@ void Text::write2X(int x, int y, const std::string& text, int kerning, int lengt
if (INDEX < offset_.size()) { if (INDEX < offset_.size()) {
SDL_FRect rect = { SDL_FRect rect = {
static_cast<float>(offset_[INDEX].x), .x = static_cast<float>(offset_[INDEX].x),
static_cast<float>(offset_[INDEX].y), .y = static_cast<float>(offset_[INDEX].y),
static_cast<float>(box_width_), .w = static_cast<float>(box_width_),
static_cast<float>(box_height_)}; .h = static_cast<float>(box_height_)};
sprite_->getTexture()->render(x + shift, y, &rect, 2.0F, 2.0F); sprite_->getTexture()->render(x + shift, y, &rect, 2.0F, 2.0F);
shift += (offset_[INDEX].w + kerning) * 2; shift += (offset_[INDEX].w + kerning) * 2;
@@ -257,7 +258,7 @@ void Text::writeStrokeWithAlpha(int x, int y, const std::string& text, int kerni
// Renderiza stroke sin alpha (sólido) en textura temporal // Renderiza stroke sin alpha (sólido) en textura temporal
Color solid_color = Color(stroke_color.r, stroke_color.g, stroke_color.b, 255); Color solid_color = Color(stroke_color.r, stroke_color.g, stroke_color.b, 255);
for (int dist = 1; dist <= shadow_distance; ++dist) { for (int dist = 1; std::cmp_less_equal(dist, shadow_distance); ++dist) {
for (int dy = -dist; dy <= dist; ++dy) { for (int dy = -dist; dy <= dist; ++dy) {
for (int dx = -dist; dx <= dist; ++dx) { for (int dx = -dist; dx <= dist; ++dx) {
writeColoredWithSprite(stroke_sprite, shadow_distance + dx, shadow_distance + dy, text, solid_color, kerning, length); writeColoredWithSprite(stroke_sprite, shadow_distance + dx, shadow_distance + dy, text, solid_color, kerning, length);
@@ -296,7 +297,7 @@ void Text::renderShadow(int x, int y, const std::string& text, Color shadow_colo
// Renderiza stroke sólido (método tradicional para stroke sin alpha) // Renderiza stroke sólido (método tradicional para stroke sin alpha)
void Text::renderSolidStroke(int x, int y, const std::string& text, Color stroke_color, int kerning, int length, Uint8 shadow_distance) { void Text::renderSolidStroke(int x, int y, const std::string& text, Color stroke_color, int kerning, int length, Uint8 shadow_distance) {
for (int dist = 1; dist <= shadow_distance; ++dist) { for (int dist = 1; std::cmp_less_equal(dist, shadow_distance); ++dist) {
for (int dy = -dist; dy <= dist; ++dy) { for (int dy = -dist; dy <= dist; ++dy) {
for (int dx = -dist; dx <= dist; ++dx) { for (int dx = -dist; dx <= dist; ++dx) {
if (white_sprite_) { if (white_sprite_) {

View File

@@ -167,7 +167,7 @@ void Texture::setAlpha(Uint8 alpha) {
// Renderiza la textura en un punto específico // Renderiza la textura en un punto específico
void Texture::render(int x, int y, SDL_FRect* clip, float horizontal_zoom, float vertical_zoom, double angle, SDL_FPoint* center, SDL_FlipMode flip) { void Texture::render(int x, int y, SDL_FRect* clip, float horizontal_zoom, float vertical_zoom, double angle, SDL_FPoint* center, SDL_FlipMode flip) {
// Establece el destino de renderizado en la pantalla // Establece el destino de renderizado en la pantalla
SDL_FRect render_quad = {static_cast<float>(x), static_cast<float>(y), static_cast<float>(width_), static_cast<float>(height_)}; SDL_FRect render_quad = {.x = static_cast<float>(x), .y = static_cast<float>(y), .w = static_cast<float>(width_), .h = static_cast<float>(height_)};
// Obtiene las dimesiones del clip de renderizado // Obtiene las dimesiones del clip de renderizado
if (clip != nullptr) { if (clip != nullptr) {

View File

@@ -50,7 +50,7 @@ TiledBG::~TiledBG() {
// Rellena la textura con el contenido // Rellena la textura con el contenido
void TiledBG::fillTexture() { void TiledBG::fillTexture() {
// Crea los objetos para pintar en la textura de fondo // Crea los objetos para pintar en la textura de fondo
auto tile = std::make_unique<Sprite>(Resource::get()->getTexture("title_bg_tile.png"), (SDL_FRect){0, 0, TILE_WIDTH, TILE_HEIGHT}); auto tile = std::make_unique<Sprite>(Resource::get()->getTexture("title_bg_tile.png"), (SDL_FRect){.x = 0, .y = 0, .w = TILE_WIDTH, .h = TILE_HEIGHT});
// Prepara para dibujar sobre la textura // Prepara para dibujar sobre la textura
auto* temp = SDL_GetRenderTarget(renderer_); auto* temp = SDL_GetRenderTarget(renderer_);
@@ -160,6 +160,6 @@ void TiledBG::updateSpeedChange(float delta_time) {
} else { } else {
// Interpolación lineal entre velocidad inicial y objetivo // Interpolación lineal entre velocidad inicial y objetivo
float progress = change_timer_s_ / change_duration_s_; float progress = change_timer_s_ / change_duration_s_;
speed_ = initial_speed_ + (target_speed_ - initial_speed_) * progress; speed_ = initial_speed_ + ((target_speed_ - initial_speed_) * progress);
} }
} }

View File

@@ -135,8 +135,8 @@ class ListOption : public MenuOption {
return; return;
} }
size_t size = value_list_.size(); size_t size = value_list_.size();
list_index_ = (adjust_up) ? (list_index_ + 1) % size list_index_ = adjust_up ? (list_index_ + 1) % size
: (list_index_ + size - 1) % size; : (list_index_ + size - 1) % size;
setter_(value_list_[list_index_]); setter_(value_list_[list_index_]);
} }
auto getMaxValueWidth(Text* text_renderer) const -> int override { auto getMaxValueWidth(Text* text_renderer) const -> int override {

View File

@@ -57,7 +57,7 @@ void MenuRenderer::render(const ServiceMenu* menu_state) {
// Dibuja la sombra // Dibuja la sombra
if (param.service_menu.drop_shadow) { if (param.service_menu.drop_shadow) {
SDL_FRect shadow_rect = {rect_.x + 5, rect_.y + 5, rect_.w, rect_.h}; SDL_FRect shadow_rect = {.x = rect_.x + 5, .y = rect_.y + 5, .w = rect_.w, .h = rect_.h};
SDL_SetRenderDrawColor(Screen::get()->getRenderer(), 0, 0, 0, 64); SDL_SetRenderDrawColor(Screen::get()->getRenderer(), 0, 0, 0, 64);
SDL_RenderFillRect(Screen::get()->getRenderer(), &shadow_rect); SDL_RenderFillRect(Screen::get()->getRenderer(), &shadow_rect);
} }
@@ -203,7 +203,7 @@ auto MenuRenderer::calculateNewRect(const ServiceMenu* menu_state) -> SDL_FRect
lower_height_ = ((!display_options.empty() ? display_options.size() - 1 : 0) * (options_height_ + options_padding_)) + options_height_ + (lower_padding_ * 2); lower_height_ = ((!display_options.empty() ? display_options.size() - 1 : 0) * (options_height_ + options_padding_)) + options_height_ + (lower_padding_ * 2);
height_ = std::min(upper_height_ + lower_height_, max_menu_height_); height_ = std::min(upper_height_ + lower_height_, max_menu_height_);
SDL_FRect new_rect = {0, 0, (float)width_, (float)height_}; SDL_FRect new_rect = {.x = 0, .y = 0, .w = static_cast<float>(width_), .h = static_cast<float>(height_)};
// La posición x, y se establecerá en `updatePosition` // La posición x, y se establecerá en `updatePosition`
return new_rect; return new_rect;
@@ -286,8 +286,8 @@ void MenuRenderer::updateResizeAnimation(float delta_time) {
updatePosition(); updatePosition();
} else { } else {
float progress = easeOut(resize_animation_.elapsed / duration); float progress = easeOut(resize_animation_.elapsed / duration);
rect_.w = resize_animation_.start_width + (resize_animation_.target_width - resize_animation_.start_width) * progress; rect_.w = resize_animation_.start_width + ((resize_animation_.target_width - resize_animation_.start_width) * progress);
rect_.h = resize_animation_.start_height + (resize_animation_.target_height - resize_animation_.start_height) * progress; rect_.h = resize_animation_.start_height + ((resize_animation_.target_height - resize_animation_.start_height) * progress);
updatePosition(); updatePosition();
} }
options_y_ = rect_.y + upper_height_ + lower_padding_; options_y_ = rect_.y + upper_height_ + lower_padding_;
@@ -296,8 +296,8 @@ void MenuRenderer::updateResizeAnimation(float delta_time) {
void MenuRenderer::updatePosition() { void MenuRenderer::updatePosition() {
switch (position_mode_) { switch (position_mode_) {
case PositionMode::CENTERED: case PositionMode::CENTERED:
rect_.x = anchor_x_ - rect_.w / 2.0F; rect_.x = anchor_x_ - (rect_.w / 2.0F);
rect_.y = anchor_y_ - rect_.h / 2.0F; rect_.y = anchor_y_ - (rect_.h / 2.0F);
break; break;
case PositionMode::FIXED: case PositionMode::FIXED:
rect_.x = anchor_x_; rect_.x = anchor_x_;
@@ -310,7 +310,7 @@ void MenuRenderer::updatePosition() {
// Resto de métodos (sin cambios significativos) // Resto de métodos (sin cambios significativos)
void MenuRenderer::precalculateMenuWidths(const std::vector<std::unique_ptr<MenuOption>>& all_options, const ServiceMenu* menu_state) { void MenuRenderer::precalculateMenuWidths(const std::vector<std::unique_ptr<MenuOption>>& all_options, const ServiceMenu* menu_state) { // NOLINT(readability-named-parameter)
for (int& w : group_menu_widths_) { for (int& w : group_menu_widths_) {
w = ServiceMenu::MIN_WIDTH; w = ServiceMenu::MIN_WIDTH;
} }
@@ -341,7 +341,7 @@ void MenuRenderer::precalculateMenuWidths(const std::vector<std::unique_ptr<Menu
if (menu_state->getCurrentGroupAlignment() == ServiceMenu::GroupAlignment::LEFT) { if (menu_state->getCurrentGroupAlignment() == ServiceMenu::GroupAlignment::LEFT) {
total_width += ServiceMenu::MIN_GAP_OPTION_VALUE + max_value_width; total_width += ServiceMenu::MIN_GAP_OPTION_VALUE + max_value_width;
} }
group_menu_widths_[group] = std::min(std::max((int)ServiceMenu::MIN_WIDTH, (int)total_width), static_cast<int>(max_menu_width_)); group_menu_widths_[group] = std::min(std::max(static_cast<int>(ServiceMenu::MIN_WIDTH), static_cast<int>(total_width)), static_cast<int>(max_menu_width_));
} }
} }

View File

@@ -117,7 +117,7 @@ class MenuRenderer {
void updateShowHideAnimation(float delta_time); void updateShowHideAnimation(float delta_time);
void updatePosition(); void updatePosition();
void precalculateMenuWidths(const std::vector<std::unique_ptr<MenuOption>>& all_options, const ServiceMenu* menu_state); void precalculateMenuWidths(const std::vector<std::unique_ptr<MenuOption>>& all_options, const ServiceMenu* menu_state); // NOLINT(readability-avoid-const-params-in-decls)
[[nodiscard]] auto getMenuWidthForGroup(ServiceMenu::SettingsGroup group) const -> int; [[nodiscard]] auto getMenuWidthForGroup(ServiceMenu::SettingsGroup group) const -> int;
[[nodiscard]] auto getAnimatedSelectedColor() const -> Color; [[nodiscard]] auto getAnimatedSelectedColor() const -> Color;
void updateColorCounter(); void updateColorCounter();

View File

@@ -37,14 +37,14 @@ Notifier::Notifier(const std::string& icon_file, std::shared_ptr<Text> text)
// Dibuja las notificaciones por pantalla // Dibuja las notificaciones por pantalla
void Notifier::render() { void Notifier::render() {
for (int i = (int)notifications_.size() - 1; i >= 0; --i) { for (int i = static_cast<int>(notifications_.size()) - 1; i >= 0; --i) {
notifications_[i].sprite->render(); notifications_[i].sprite->render();
} }
} }
// Actualiza el estado de las notificaciones // Actualiza el estado de las notificaciones
void Notifier::update(float delta_time) { void Notifier::update(float delta_time) {
for (int i = 0; i < (int)notifications_.size(); ++i) { for (int i = 0; std::cmp_less(i, notifications_.size()); ++i) {
if (!shouldProcessNotification(i)) { if (!shouldProcessNotification(i)) {
break; break;
} }
@@ -148,7 +148,7 @@ void Notifier::transitionToStayState(int index) {
// Elimina las notificaciones finalizadas // Elimina las notificaciones finalizadas
void Notifier::clearFinishedNotifications() { void Notifier::clearFinishedNotifications() {
for (int i = (int)notifications_.size() - 1; i >= 0; --i) { for (int i = static_cast<int>(notifications_.size()) - 1; i >= 0; --i) {
if (notifications_[i].state == State::FINISHED) { if (notifications_[i].state == State::FINISHED) {
notifications_.erase(notifications_.begin() + i); notifications_.erase(notifications_.begin() + i);
} }
@@ -167,7 +167,7 @@ void Notifier::show(std::vector<std::string> texts, int icon, const std::string&
} }
// Elimina las cadenas vacías // Elimina las cadenas vacías
texts.erase(std::ranges::remove_if(texts, [](const std::string& s) { return s.empty(); }).begin(), texts.end()); texts.erase(std::ranges::remove_if(texts, [](const std::string& s) -> bool { return s.empty(); }).begin(), texts.end());
// Encuentra la cadena más larga // Encuentra la cadena más larga
std::string longest; std::string longest;
@@ -259,13 +259,13 @@ void Notifier::show(std::vector<std::string> texts, int icon, const std::string&
// Dibuja el icono de la notificación // Dibuja el icono de la notificación
if (has_icons_ && icon >= 0 && texts.size() >= 2) { if (has_icons_ && icon >= 0 && texts.size() >= 2) {
auto sp = std::make_unique<Sprite>(icon_texture_, (SDL_FRect){0, 0, ICON_SIZE, ICON_SIZE}); auto sp = std::make_unique<Sprite>(icon_texture_, (SDL_FRect){.x = 0, .y = 0, .w = ICON_SIZE, .h = ICON_SIZE});
sp->setPosition({PADDING_IN_H, PADDING_IN_V, ICON_SIZE, ICON_SIZE}); sp->setPosition({.x = PADDING_IN_H, .y = PADDING_IN_V, .w = ICON_SIZE, .h = ICON_SIZE});
sp->setSpriteClip(SDL_FRect{ sp->setSpriteClip(SDL_FRect{
static_cast<float>(ICON_SIZE * (icon % 10)), .x = static_cast<float>(ICON_SIZE * (icon % 10)),
static_cast<float>(ICON_SIZE * (icon / 10)), .y = static_cast<float>(ICON_SIZE * (icon / 10)),
ICON_SIZE, .w = ICON_SIZE,
ICON_SIZE}); .h = ICON_SIZE});
sp->render(); sp->render();
} }

View File

@@ -75,7 +75,7 @@ class Notifier {
explicit Notification() explicit Notification()
: texture(nullptr), : texture(nullptr),
sprite(nullptr), sprite(nullptr),
rect{0, 0, 0, 0} {} rect{.x = 0, .y = 0, .w = 0, .h = 0} {}
}; };
// --- Objetos y punteros --- // --- Objetos y punteros ---

View File

@@ -291,13 +291,13 @@ void ServiceMenu::initializeOptions() {
Lang::getText("[SERVICE_MENU] CONTROLLER1"), Lang::getText("[SERVICE_MENU] CONTROLLER1"),
SettingsGroup::CONTROLS, SettingsGroup::CONTROLS,
Input::get()->getControllerNames(), Input::get()->getControllerNames(),
[]() { []() -> std::string {
return Options::gamepad_manager.getGamepad(Player::Id::PLAYER1).name; return Options::gamepad_manager.getGamepad(Player::Id::PLAYER1).name;
}, },
[](const std::string& val) { [](const std::string& val) -> void {
Options::gamepad_manager.assignGamepadToPlayer(Player::Id::PLAYER1, Input::get()->getGamepadByName(val), val); Options::gamepad_manager.assignGamepadToPlayer(Player::Id::PLAYER1, Input::get()->getGamepadByName(val), val);
}, },
[this]() { [this]() -> void {
// Acción: configurar botones del mando del jugador 1 // Acción: configurar botones del mando del jugador 1
auto* gamepad = &Options::gamepad_manager.getGamepad(Player::Id::PLAYER1); auto* gamepad = &Options::gamepad_manager.getGamepad(Player::Id::PLAYER1);
if ((gamepad != nullptr) && gamepad->instance) { if ((gamepad != nullptr) && gamepad->instance) {
@@ -309,13 +309,13 @@ void ServiceMenu::initializeOptions() {
Lang::getText("[SERVICE_MENU] CONTROLLER2"), Lang::getText("[SERVICE_MENU] CONTROLLER2"),
SettingsGroup::CONTROLS, SettingsGroup::CONTROLS,
Input::get()->getControllerNames(), Input::get()->getControllerNames(),
[]() { []() -> std::string {
return Options::gamepad_manager.getGamepad(Player::Id::PLAYER2).name; return Options::gamepad_manager.getGamepad(Player::Id::PLAYER2).name;
}, },
[](const std::string& val) { [](const std::string& val) -> void {
Options::gamepad_manager.assignGamepadToPlayer(Player::Id::PLAYER2, Input::get()->getGamepadByName(val), val); Options::gamepad_manager.assignGamepadToPlayer(Player::Id::PLAYER2, Input::get()->getGamepadByName(val), val);
}, },
[this]() { [this]() -> void {
// Acción: configurar botones del mando del jugador 2 // Acción: configurar botones del mando del jugador 2
auto* gamepad = &Options::gamepad_manager.getGamepad(Player::Id::PLAYER2); auto* gamepad = &Options::gamepad_manager.getGamepad(Player::Id::PLAYER2);
if ((gamepad != nullptr) && gamepad->instance) { if ((gamepad != nullptr) && gamepad->instance) {
@@ -330,11 +330,11 @@ void ServiceMenu::initializeOptions() {
std::vector<std::string>{ std::vector<std::string>{
Lang::getText("[SERVICE_MENU] PLAYER1"), Lang::getText("[SERVICE_MENU] PLAYER1"),
Lang::getText("[SERVICE_MENU] PLAYER2")}, Lang::getText("[SERVICE_MENU] PLAYER2")},
[]() { []() -> std::string {
// Devolver el jugador actual asignado al teclado // Devolver el jugador actual asignado al teclado
return Options::playerIdToString(Options::getPlayerWhoUsesKeyboard()); return Options::playerIdToString(Options::getPlayerWhoUsesKeyboard());
}, },
[](const std::string& val) { [](const std::string& val) -> void {
// Asignar el teclado al jugador seleccionado // Asignar el teclado al jugador seleccionado
Options::keyboard.assignTo(Options::stringToPlayerId(val)); Options::keyboard.assignTo(Options::stringToPlayerId(val));
})); }));
@@ -343,7 +343,7 @@ void ServiceMenu::initializeOptions() {
options_.push_back(std::make_unique<ActionOption>( options_.push_back(std::make_unique<ActionOption>(
Lang::getText("[SERVICE_MENU] SWAP_CONTROLLERS"), Lang::getText("[SERVICE_MENU] SWAP_CONTROLLERS"),
SettingsGroup::CONTROLS, SettingsGroup::CONTROLS,
[this]() { [this]() -> void {
Options::gamepad_manager.swapPlayers(); Options::gamepad_manager.swapPlayers();
adjustListValues(); // Sincroniza el valor de las opciones de lista (como MANDO1) con los datos reales adjustListValues(); // Sincroniza el valor de las opciones de lista (como MANDO1) con los datos reales
updateOptionPairs(); // Actualiza los pares de texto <opción, valor> que se van a dibujar updateOptionPairs(); // Actualiza los pares de texto <opción, valor> que se van a dibujar
@@ -421,10 +421,10 @@ void ServiceMenu::initializeOptions() {
Lang::getText("[SERVICE_MENU] LANG_ES"), Lang::getText("[SERVICE_MENU] LANG_ES"),
Lang::getText("[SERVICE_MENU] LANG_BA"), Lang::getText("[SERVICE_MENU] LANG_BA"),
Lang::getText("[SERVICE_MENU] LANG_EN")}, Lang::getText("[SERVICE_MENU] LANG_EN")},
[]() { []() -> std::string {
return Lang::getNameFromCode(Options::pending_changes.new_language); return Lang::getNameFromCode(Options::pending_changes.new_language);
}, },
[](const std::string& val) { [](const std::string& val) -> void {
Options::pending_changes.new_language = Lang::getCodeFromName(val); Options::pending_changes.new_language = Lang::getCodeFromName(val);
Options::checkPendingChanges(); Options::checkPendingChanges();
})); }));
@@ -436,10 +436,10 @@ void ServiceMenu::initializeOptions() {
Lang::getText("[SERVICE_MENU] EASY"), Lang::getText("[SERVICE_MENU] EASY"),
Lang::getText("[SERVICE_MENU] NORMAL"), Lang::getText("[SERVICE_MENU] NORMAL"),
Lang::getText("[SERVICE_MENU] HARD")}, Lang::getText("[SERVICE_MENU] HARD")},
[]() { []() -> std::string {
return Difficulty::getNameFromCode(Options::pending_changes.new_difficulty); return Difficulty::getNameFromCode(Options::pending_changes.new_difficulty);
}, },
[](const std::string& val) { [](const std::string& val) -> void {
Options::pending_changes.new_difficulty = Difficulty::getCodeFromName(val); Options::pending_changes.new_difficulty = Difficulty::getCodeFromName(val);
Options::checkPendingChanges(); Options::checkPendingChanges();
})); }));
@@ -453,7 +453,7 @@ void ServiceMenu::initializeOptions() {
options_.push_back(std::make_unique<ActionOption>( options_.push_back(std::make_unique<ActionOption>(
Lang::getText("[SERVICE_MENU] RESET"), Lang::getText("[SERVICE_MENU] RESET"),
SettingsGroup::SYSTEM, SettingsGroup::SYSTEM,
[this]() { [this]() -> void {
Section::name = Section::Name::RESET; Section::name = Section::Name::RESET;
toggle(); toggle();
})); }));
@@ -461,7 +461,7 @@ void ServiceMenu::initializeOptions() {
options_.push_back(std::make_unique<ActionOption>( options_.push_back(std::make_unique<ActionOption>(
Lang::getText("[SERVICE_MENU] QUIT"), Lang::getText("[SERVICE_MENU] QUIT"),
SettingsGroup::SYSTEM, SettingsGroup::SYSTEM,
[]() { []() -> void {
Section::name = Section::Name::QUIT; Section::name = Section::Name::QUIT;
Section::options = Section::Options::NONE; Section::options = Section::Options::NONE;
})); }));
@@ -469,7 +469,7 @@ void ServiceMenu::initializeOptions() {
options_.push_back(std::make_unique<ActionOption>( options_.push_back(std::make_unique<ActionOption>(
Lang::getText("[SERVICE_MENU] SHUTDOWN"), Lang::getText("[SERVICE_MENU] SHUTDOWN"),
SettingsGroup::SYSTEM, SettingsGroup::SYSTEM,
[]() { []() -> void {
Section::name = Section::Name::QUIT; Section::name = Section::Name::QUIT;
Section::options = Section::Options::SHUTDOWN; Section::options = Section::Options::SHUTDOWN;
}, },
@@ -581,12 +581,12 @@ auto ServiceMenu::checkInput() -> bool {
using Action = Input::Action; using Action = Input::Action;
const std::vector<std::pair<Action, std::function<void()>>> ACTIONS = { const std::vector<std::pair<Action, std::function<void()>>> ACTIONS = {
{Action::UP, [this]() { setSelectorUp(); }}, {Action::UP, [this]() -> void { setSelectorUp(); }},
{Action::DOWN, [this]() { setSelectorDown(); }}, {Action::DOWN, [this]() -> void { setSelectorDown(); }},
{Action::RIGHT, [this]() { adjustOption(true); }}, {Action::RIGHT, [this]() -> void { adjustOption(true); }},
{Action::LEFT, [this]() { adjustOption(false); }}, {Action::LEFT, [this]() -> void { adjustOption(false); }},
{Action::SM_SELECT, [this]() { selectOption(); }}, {Action::SM_SELECT, [this]() -> void { selectOption(); }},
{Action::SM_BACK, [this]() { moveBack(); }}, {Action::SM_BACK, [this]() -> void { moveBack(); }},
}; };
// Teclado // Teclado

View File

@@ -61,7 +61,7 @@ void UIMessage::updateAnimation(float delta_time) {
t = pow(t, 3); t = pow(t, 3);
} }
y_offset_ = start_y_ + (target_y_ - start_y_) * t; y_offset_ = start_y_ + ((target_y_ - start_y_) * t);
if (animation_timer_ >= ANIMATION_DURATION_S) { if (animation_timer_ >= ANIMATION_DURATION_S) {
y_offset_ = target_y_; y_offset_ = target_y_;

View File

@@ -192,8 +192,8 @@ void WindowMessage::updateStyles() {
void WindowMessage::updatePosition() { void WindowMessage::updatePosition() {
switch (position_mode_) { switch (position_mode_) {
case PositionMode::CENTERED: case PositionMode::CENTERED:
rect_.x = anchor_.x - rect_.w / 2.0F; rect_.x = anchor_.x - (rect_.w / 2.0F);
rect_.y = anchor_.y - rect_.h / 2.0F; rect_.y = anchor_.y - (rect_.h / 2.0F);
break; break;
case PositionMode::FIXED: case PositionMode::FIXED:
rect_.x = anchor_.x; rect_.x = anchor_.x;
@@ -355,9 +355,9 @@ void WindowMessage::updateResizeAnimation(float delta_time) {
float progress = easeOut(resize_animation_.getProgress(config_.animation_duration)); float progress = easeOut(resize_animation_.getProgress(config_.animation_duration));
rect_.w = resize_animation_.start_width + rect_.w = resize_animation_.start_width +
(resize_animation_.target_width - resize_animation_.start_width) * progress; ((resize_animation_.target_width - resize_animation_.start_width) * progress);
rect_.h = resize_animation_.start_height + rect_.h = resize_animation_.start_height +
(resize_animation_.target_height - resize_animation_.start_height) * progress; ((resize_animation_.target_height - resize_animation_.start_height) * progress);
updatePosition(); // Mantener la posición centrada durante la animación updatePosition(); // Mantener la posición centrada durante la animación
} }

View File

@@ -140,9 +140,9 @@ class WindowMessage {
std::vector<std::string> texts_; std::vector<std::string> texts_;
// Posición y tamaño // Posición y tamaño
SDL_FRect rect_{0, 0, 300, 200}; SDL_FRect rect_{.x = 0, .y = 0, .w = 300, .h = 200};
PositionMode position_mode_ = PositionMode::CENTERED; PositionMode position_mode_ = PositionMode::CENTERED;
SDL_FPoint anchor_{0.0F, 0.0F}; SDL_FPoint anchor_{.x = 0.0F, .y = 0.0F};
// Animación de redimensionado // Animación de redimensionado
struct ResizeAnimation { struct ResizeAnimation {

View File

@@ -35,8 +35,8 @@ auto getCollisionPoint(const Circle& a, const Circle& b) -> SDL_FPoint {
// Punto en el borde del círculo A hacia B // Punto en el borde del círculo A hacia B
SDL_FPoint contact; SDL_FPoint contact;
contact.x = a.x + nx * a.r; contact.x = a.x + (nx * a.r);
contact.y = a.y + ny * a.r; contact.y = a.y + (ny * a.r);
return contact; return contact;
} }
@@ -117,7 +117,7 @@ auto boolToOnOff(bool value) -> std::string {
// Convierte una cadena a minusculas // Convierte una cadena a minusculas
auto toLower(const std::string& str) -> std::string { auto toLower(const std::string& str) -> std::string {
std::string result = str; std::string result = str;
std::ranges::transform(result, result.begin(), [](unsigned char c) { return std::tolower(c); }); std::ranges::transform(result, result.begin(), [](unsigned char c) -> int { return std::tolower(c); });
return result; return result;
} }
@@ -195,7 +195,7 @@ auto easeInOutSine(double time) -> double {
// Función de suavizado // Función de suavizado
auto easeInOut(double time) -> double { auto easeInOut(double time) -> double {
return time < 0.5 ? 2 * time * time : -1 + ((4 - 2 * time) * time); return time < 0.5 ? 2 * time * time : -1 + ((4 - (2 * time)) * time);
} }
// Función de suavizado (easeInOutExpo) // Función de suavizado (easeInOutExpo)
@@ -226,7 +226,7 @@ auto easeInElastic(double time) -> double {
} }
const double C4 = (2 * M_PI) / 3; const double C4 = (2 * M_PI) / 3;
return -pow(2, (10 * time) - 10) * sin((time * 10 - 10.75) * C4); return -pow(2, (10 * time) - 10) * sin(((time * 10) - 10.75) * C4);
} }
// Función de suavizado // Función de suavizado
@@ -257,7 +257,7 @@ auto easeOutElastic(double time) -> double {
} }
const double C4 = (2 * M_PI) / 3; // Constante para controlar la elasticidad const double C4 = (2 * M_PI) / 3; // Constante para controlar la elasticidad
return (pow(2, -10 * time) * sin((time * 10 - 0.75) * C4)) + 1; return (pow(2, -10 * time) * sin(((time * 10) - 0.75) * C4)) + 1;
} }
// Ease Out Expo - Muy suave al final (más dramático) // Ease Out Expo - Muy suave al final (más dramático)