neteja cppcheck (105 → 0)

This commit is contained in:
2026-05-16 19:35:23 +02:00
parent c9d16959d0
commit fcd2718794
48 changed files with 293 additions and 486 deletions
+1 -1
View File
@@ -85,7 +85,7 @@ class Balloon {
};
// --- Constructores y destructor ---
Balloon(const Config& config);
explicit Balloon(const Config& config);
~Balloon() = default;
// --- Métodos principales ---
+1 -1
View File
@@ -977,7 +977,7 @@ void Player::playSound(const std::string& name) const {
return;
}
static auto* audio_ = Audio::get();
static const auto* audio_ = Audio::get();
audio_->playSound(name);
}
+7 -7
View File
@@ -114,7 +114,7 @@ class Player {
};
// --- Constructor y destructor ---
Player(const Config& config);
explicit Player(const Config& config);
~Player() = default;
// --- Inicialización y ciclo de vida ---
@@ -201,16 +201,16 @@ class Player {
[[nodiscard]] auto getCoffees() const -> int { return coffees_; }
[[nodiscard]] auto getPowerUpCounter() const -> int { return power_up_counter_; }
[[nodiscard]] auto getInvulnerableCounter() const -> int { return invulnerable_counter_; }
[[nodiscard]] auto getBulletColor() const -> Bullet::Color; // Devuelve el color actual de bala según el estado
auto getNextBulletColor() -> Bullet::Color; // Devuelve el color para la próxima bala (alterna si está en modo toggle)
void setBulletColors(Bullet::Color normal, Bullet::Color powered); // Establece los colores de bala para este jugador
[[nodiscard]] auto getBulletSoundFile() const -> std::string { return bullet_sound_file_; } // Devuelve el archivo de sonido de bala
void setBulletSoundFile(const std::string& filename); // Establece el archivo de sonido de bala para este jugador
[[nodiscard]] auto getBulletColor() const -> Bullet::Color; // Devuelve el color actual de bala según el estado
auto getNextBulletColor() -> Bullet::Color; // Devuelve el color para la próxima bala (alterna si está en modo toggle)
void setBulletColors(Bullet::Color normal, Bullet::Color powered); // Establece los colores de bala para este jugador
[[nodiscard]] auto getBulletSoundFile() const -> const std::string& { return bullet_sound_file_; } // Devuelve el archivo de sonido de bala
void setBulletSoundFile(const std::string& filename); // Establece el archivo de sonido de bala para este jugador
// Contadores y timers
[[nodiscard]] auto getContinueCounter() const -> int { return continue_counter_; }
[[nodiscard]] auto getRecordName() const -> std::string { return enter_name_ ? enter_name_->getFinalName() : "xxx"; }
[[nodiscard]] auto getLastEnterName() const -> std::string { return last_enter_name_; }
[[nodiscard]] auto getLastEnterName() const -> const std::string& { return last_enter_name_; }
// --- Configuración e interfaz externa ---
void setName(const std::string& name) { name_ = name; }
+9 -12
View File
@@ -222,13 +222,13 @@ void BalloonFormations::createFloaterVariants() {
formations_.resize(100);
// Crear variantes flotantes de las primeras 50 formaciones
for (size_t k = 0; k < 50 && k < formations_.size(); k++) {
for (size_t k = 0; k < 50; k++) {
const auto& source = formations_.at(k).balloons;
std::vector<SpawnParams> floater_params;
floater_params.reserve(formations_.at(k).balloons.size());
for (const auto& original : formations_.at(k).balloons) {
floater_params.emplace_back(original.x, original.y, original.vel_x, Balloon::Type::FLOATER, original.size, original.creation_counter);
}
floater_params.reserve(source.size());
std::ranges::transform(source, std::back_inserter(floater_params), [](const auto& original) {
return SpawnParams{original.x, original.y, original.vel_x, Balloon::Type::FLOATER, original.size, original.creation_counter};
});
formations_.at(k + 50) = Formation(floater_params);
}
@@ -395,24 +395,21 @@ void BalloonFormations::loadDefaultPools() {
}
}
// Pool 2: Mix de formaciones normales y floaters (50+)
// Pools 2 i 3: requereixen formacions de floaters (>50)
if (total_formations > 50) {
// Pool 2: Mix de formacions normals i floaters
Pool pool2;
// Agregar algunas formaciones básicas
for (size_t i = 0; i < std::min(static_cast<size_t>(5), total_formations); ++i) {
pool2.push_back(static_cast<int>(i));
}
// Agregar algunas floaters si existen
for (size_t i = 50; i < std::min(static_cast<size_t>(55), total_formations); ++i) {
pool2.push_back(static_cast<int>(i));
}
if (!pool2.empty()) {
pools_.push_back(pool2);
}
}
// Pool 3: Solo floaters (si existen formaciones 50+)
if (total_formations > 50) {
// Pool 3: Només floaters
Pool pool3;
for (size_t i = 50; i < std::min(static_cast<size_t>(70), total_formations); ++i) {
pool3.push_back(static_cast<int>(i));
+1 -1
View File
@@ -39,7 +39,7 @@ class BalloonFormations {
std::vector<SpawnParams> balloons; // Vector con todas las inicializaciones de los globos de la formación
// Constructor con parámetros
Formation(const std::vector<SpawnParams>& spawn_params)
explicit Formation(const std::vector<SpawnParams>& spawn_params)
: balloons(spawn_params) {}
// Constructor por defecto
+3 -3
View File
@@ -106,7 +106,7 @@ void BalloonManager::deployRandomFormation(int stage) {
// Crea los globos de la formación
const auto BALLOONS = balloon_formations_->getFormationFromPool(stage, formation_id).balloons;
for (auto balloon : BALLOONS) {
for (const auto& balloon : BALLOONS) {
Balloon::Config config = {
.x = balloon.x,
.y = balloon.y,
@@ -127,7 +127,7 @@ void BalloonManager::deployRandomFormation(int stage) {
// Crea una formación de globos específica
void BalloonManager::deployFormation(int formation_id) {
const auto BALLOONS = balloon_formations_->getFormation(formation_id).balloons;
for (auto balloon : BALLOONS) {
for (const auto& balloon : BALLOONS) {
Balloon::Config config = {
.x = balloon.x,
.y = balloon.y,
@@ -143,7 +143,7 @@ void BalloonManager::deployFormation(int formation_id) {
// Crea una formación de globos específica a una altura determinada
void BalloonManager::deployFormation(int formation_id, float y) {
const auto BALLOONS = balloon_formations_->getFormation(formation_id).balloons;
for (auto balloon : BALLOONS) {
for (const auto& balloon : BALLOONS) {
Balloon::Config config = {
.x = balloon.x,
.y = y,
+1 -1
View File
@@ -24,7 +24,7 @@ using Balloons = std::list<std::shared_ptr<Balloon>>;
class BalloonManager {
public:
// --- Constructor y destructor ---
BalloonManager(IStageInfo* stage_info);
explicit BalloonManager(IStageInfo* stage_info);
~BalloonManager() = default;
// --- Métodos principales ---
+2 -2
View File
@@ -14,7 +14,7 @@ BulletManager::BulletManager()
// Actualiza el estado de todas las balas
void BulletManager::update(float delta_time) {
for (auto& bullet : bullets_) {
for (const auto& bullet : bullets_) {
if (bullet->isEnabled()) {
processBulletUpdate(bullet, delta_time);
}
@@ -23,7 +23,7 @@ void BulletManager::update(float delta_time) {
// Renderiza todas las balas activas
void BulletManager::render() {
for (auto& bullet : bullets_) {
for (const auto& bullet : bullets_) {
if (bullet->isEnabled()) {
bullet->render();
}
+1 -1
View File
@@ -4,7 +4,7 @@
class Cooldown {
public:
Cooldown(float first_delay_s = 0.0F, float repeat_delay_s = 0.0F)
explicit Cooldown(float first_delay_s = 0.0F, float repeat_delay_s = 0.0F)
: first_delay_s_(first_delay_s),
repeat_delay_s_(repeat_delay_s) {}
+10 -9
View File
@@ -1,6 +1,7 @@
#include "game/gameplay/difficulty.hpp"
#include <vector> // Para vector
#include <algorithm> // Para ranges::find_if
#include <vector> // Para vector
namespace Difficulty {
@@ -18,19 +19,19 @@ namespace Difficulty {
}
auto getNameFromCode(Code code) -> std::string {
for (const auto& difficulty : difficulties_list) {
if (difficulty.code == code) {
return difficulty.name;
}
const auto it = std::ranges::find_if(difficulties_list,
[code](const auto& difficulty) { return difficulty.code == code; });
if (it != difficulties_list.end()) {
return it->name;
}
return !difficulties_list.empty() ? difficulties_list.front().name : "Unknown";
}
auto getCodeFromName(const std::string& name) -> Code {
for (const auto& difficulty : difficulties_list) {
if (difficulty.name == name) {
return difficulty.code;
}
const auto it = std::ranges::find_if(difficulties_list,
[&name](const auto& difficulty) { return difficulty.name == name; });
if (it != difficulties_list.end()) {
return it->code;
}
return !difficulties_list.empty() ? difficulties_list.front().code : Code::NORMAL;
}
+1 -1
View File
@@ -21,7 +21,7 @@ class EnterName {
void removeLastCharacter(); // Elimina el último carácter del nombre
auto getFinalName() -> std::string; // Obtiene el nombre final (o aleatorio si vacío)
[[nodiscard]] auto getCurrentName() const -> std::string { return name_; } // Obtiene el nombre actual en proceso
[[nodiscard]] auto getCurrentName() const -> const std::string& { return name_; } // Obtiene el nombre actual en proceso
[[nodiscard]] auto getSelectedCharacter(int offset = 0) const -> std::string; // Devuelve el carácter seleccionado con offset relativo
[[nodiscard]] auto getCarousel(int size) const -> std::string; // Devuelve el carrusel de caracteres (size debe ser impar)
[[nodiscard]] auto getSelectedIndex() const -> int { return selected_index_; } // Obtiene el índice del carácter seleccionado
+5 -15
View File
@@ -8,6 +8,7 @@
#include <iomanip> // Para std::setw, std::setfill
#include <iostream> // Para std::cout
#include <iterator> // Para distance
#include <numeric> // Para accumulate
#include <ranges> // Para __find_if_fn, find_if
#include <utility> // Para move
@@ -260,22 +261,11 @@ auto ManageHiScoreTable::verifyChecksum(SDL_IOStream* file, const std::string& f
// Calcula checksum de la tabla
auto ManageHiScoreTable::calculateChecksum(const Table& table) -> unsigned int {
unsigned int checksum = 0x12345678; // Magic seed
for (const auto& entry : table) {
// Checksum del score
return std::accumulate(table.begin(), table.end(), 0x12345678U, [](unsigned int checksum, const auto& entry) {
checksum = ((checksum << 5) + checksum) + static_cast<unsigned int>(entry.score);
// Checksum del nombre
for (char c : entry.name) {
checksum = ((checksum << 5) + checksum) + static_cast<unsigned int>(c);
}
// Checksum de one_credit_complete
checksum = ((checksum << 5) + checksum) + (entry.one_credit_complete ? 1U : 0U);
}
return checksum;
checksum = std::accumulate(entry.name.begin(), entry.name.end(), checksum, [](unsigned int acc, char c) { return ((acc << 5) + acc) + static_cast<unsigned int>(c); });
return ((checksum << 5) + checksum) + (entry.one_credit_complete ? 1U : 0U);
});
}
// Guarda la tabla en un fichero
+1 -1
View File
@@ -724,7 +724,7 @@ void Scoreboard::renderSeparator() {
// Pinta el carrusel de caracteres con efecto de color LERP y animación suave
void Scoreboard::renderCarousel(size_t panel_index, int center_x, int y) {
// Obtener referencia a EnterName
EnterName* enter_name = enter_name_ref_.at(panel_index);
const EnterName* enter_name = enter_name_ref_.at(panel_index);
if (enter_name == nullptr) {
return;
}
+2 -5
View File
@@ -3,6 +3,7 @@
#include <algorithm> // Para max, min
#include <exception> // Para exception
#include <fstream> // Para basic_istream, basic_ifstream, ifstream, stringstream
#include <numeric> // Para accumulate
#include <sstream> // Para basic_stringstream
#include <utility> // Para move
@@ -282,11 +283,7 @@ auto StageManager::getPowerNeededForCurrentStage() const -> int {
}
auto StageManager::getTotalPowerNeededToCompleteGame() const -> int {
int total_power_needed = 0;
for (const auto& stage : stages_) {
total_power_needed += stage.getPowerToComplete();
}
return total_power_needed;
return std::accumulate(stages_.begin(), stages_.end(), 0, [](int total, const auto& stage) { return total + stage.getPowerToComplete(); });
}
auto StageManager::getPowerNeededToReachStage(size_t target_stage_index) const -> int {
+27 -27
View File
@@ -2,7 +2,7 @@
#include <SDL3/SDL.h> // Para SDL_ScaleMode, SDL_LogCategory, SDL_LogError, SDL_LogInfo, SDL_LogWarn
#include <algorithm> // Para clamp
#include <algorithm> // Para clamp, ranges::find_if
#include <cstddef> // Para size_t
#include <fstream> // Para ifstream, ofstream
#include <iostream> // Para std::cout
@@ -820,14 +820,14 @@ namespace Options {
continue;
}
for (const auto& physical_gamepad : physical_gamepads) {
if (physical_gamepad->path == desired_path && !isGamepadAssigned(physical_gamepad, assigned_instances)) {
gamepads_[i].instance = physical_gamepad;
gamepads_[i].name = physical_gamepad->name;
assigned_instances.push_back(physical_gamepad);
break;
}
const auto it = std::ranges::find_if(physical_gamepads,
[this, &desired_path, &assigned_instances](const auto& pg) {
return pg->path == desired_path && !isGamepadAssigned(pg, assigned_instances);
});
if (it != physical_gamepads.end()) {
gamepads_[i].instance = *it;
gamepads_[i].name = (*it)->name;
assigned_instances.push_back(*it);
}
}
}
@@ -849,15 +849,15 @@ namespace Options {
continue;
}
for (const auto& physical_gamepad : physical_gamepads) {
if (physical_gamepad->name == desired_name && !isGamepadAssigned(physical_gamepad, assigned_instances)) {
gamepads_[i].instance = physical_gamepad;
gamepads_[i].name = physical_gamepad->name;
gamepads_[i].path = physical_gamepad->path;
assigned_instances.push_back(physical_gamepad);
break;
}
const auto it = std::ranges::find_if(physical_gamepads,
[this, &desired_name, &assigned_instances](const auto& pg) {
return pg->name == desired_name && !isGamepadAssigned(pg, assigned_instances);
});
if (it != physical_gamepads.end()) {
gamepads_[i].instance = *it;
gamepads_[i].name = (*it)->name;
gamepads_[i].path = (*it)->path;
assigned_instances.push_back(*it);
}
}
}
@@ -871,15 +871,15 @@ namespace Options {
continue;
}
for (const auto& physical_gamepad : physical_gamepads) {
if (!isGamepadAssigned(physical_gamepad, assigned_instances)) {
gamepads_[i].instance = physical_gamepad;
gamepads_[i].name = physical_gamepad->name;
gamepads_[i].path = physical_gamepad->path;
assigned_instances.push_back(physical_gamepad);
break;
}
const auto it = std::ranges::find_if(physical_gamepads,
[this, &assigned_instances](const auto& pg) {
return !isGamepadAssigned(pg, assigned_instances);
});
if (it != physical_gamepads.end()) {
gamepads_[i].instance = *it;
gamepads_[i].name = (*it)->name;
gamepads_[i].path = (*it)->path;
assigned_instances.push_back(*it);
}
}
}
+1 -1
View File
@@ -141,7 +141,7 @@ namespace Options {
std::string path; // Ruta física del dispositivo
Player::Id player_id; // Jugador asociado al mando
Gamepad(Player::Id custom_player_id = Player::Id::NO_PLAYER)
explicit Gamepad(Player::Id custom_player_id = Player::Id::NO_PLAYER)
: player_id(custom_player_id) {}
};
+3 -2
View File
@@ -683,10 +683,11 @@ void Credits::startCredits() {
init_right_x_ = static_cast<int>(right_black_rect_.x);
// Objetivos
const int CENTER_X = param.game.game_area.center_x;
int top_target_h = param.game.game_area.center_y - 1;
int bottom_target_y = param.game.game_area.center_y + 1;
int left_target_w = param.game.game_area.center_x;
int right_target_x = param.game.game_area.center_x;
int left_target_w = CENTER_X;
int right_target_x = CENTER_X;
// Pasos verticales
int pasos_top = std::max(0, top_target_h - init_top_h_);
+15 -29
View File
@@ -801,7 +801,7 @@ void Game::renderPathSprites() {
}
// Acciones a realizar cuando el jugador colisiona con un globo
void Game::handlePlayerCollision(std::shared_ptr<Player>& player, std::shared_ptr<Balloon>& balloon) {
void Game::handlePlayerCollision(std::shared_ptr<Player>& player, const std::shared_ptr<Balloon>& balloon) {
if (!player->isPlaying() || player->isInvulnerable()) {
return; // Si no está jugando o tiene inmunidad, no hace nada
}
@@ -1243,18 +1243,6 @@ auto Game::getPlayer(Player::Id id) -> std::shared_ptr<Player> {
return nullptr;
}
// Obtiene un controlador a partir del "id" del jugador
auto Game::getController(Player::Id player_id) -> int {
switch (player_id) {
case Player::Id::PLAYER1:
return 0;
case Player::Id::PLAYER2:
return 1;
default:
return -1;
}
}
// Gestiona la entrada durante el juego
void Game::checkInput() {
Input::get()->update();
@@ -1293,11 +1281,12 @@ void Game::checkInput() {
// Verifica si alguno de los controladores ha solicitado una pausa y actualiza el estado de pausa del juego.
void Game::checkPauseInput() {
// Comprueba los mandos
for (const auto& gamepad : input_->getGamepads()) {
if (input_->checkAction(Input::Action::PAUSE, Input::DO_NOT_ALLOW_REPEAT, Input::DO_NOT_CHECK_KEYBOARD, gamepad)) {
pause_manager_->togglePlayerPause();
return;
}
const auto& gamepads = input_->getGamepads();
if (std::ranges::any_of(gamepads, [this](const auto& gamepad) {
return input_->checkAction(Input::Action::PAUSE, Input::DO_NOT_ALLOW_REPEAT, Input::DO_NOT_CHECK_KEYBOARD, gamepad);
})) {
pause_manager_->togglePlayerPause();
return;
}
// Comprueba el teclado
@@ -1973,7 +1962,7 @@ void Game::playSound(const std::string& name) const {
return;
}
static auto* audio_ = Audio::get();
static const auto* audio_ = Audio::get();
audio_->playSound(name);
}
@@ -2048,9 +2037,7 @@ void Game::handleGameOverEvents() {
void Game::buildPlayerDrawList(const Players& elements, Players& draw_list) {
draw_list.clear();
draw_list.reserve(elements.size());
for (const auto& e : elements) {
draw_list.push_back(e); // copia el shared_ptr
}
std::ranges::copy(elements, std::back_inserter(draw_list));
std::ranges::stable_sort(draw_list, [](const std::shared_ptr<Player>& a, const std::shared_ptr<Player>& b) -> bool {
return a->getZOrder() < b->getZOrder();
});
@@ -2154,8 +2141,8 @@ void Game::autoplayHandleInput() {
// Comprueba los eventos en el modo DEBUG
void Game::handleDebugEvents(const SDL_Event& event) {
static int formation_id_ = 0;
if (event.type == SDL_EVENT_KEY_DOWN && static_cast<int>(event.key.repeat) == 0) {
static int formation_id_ = 0;
switch (event.key.key) {
case SDLK_1: { // Crea una powerball
balloon_manager_->createPowerBall();
@@ -2196,12 +2183,11 @@ void Game::handleDebugEvents(const SDL_Event& event) {
break;
}
case SDLK_8: {
for (const auto& player : players_) {
if (player->isPlaying()) {
createItem(ItemType::COFFEE_MACHINE, player->getPosX(), param.game.game_area.rect.y - Item::COFFEE_MACHINE_HEIGHT);
coffee_machine_enabled_ = true;
break;
}
const auto it = std::ranges::find_if(players_,
[](const auto& player) { return player->isPlaying(); });
if (it != players_.end()) {
createItem(ItemType::COFFEE_MACHINE, (*it)->getPosX(), param.game.game_area.rect.y - Item::COFFEE_MACHINE_HEIGHT);
coffee_machine_enabled_ = true;
}
break;
}
+3 -4
View File
@@ -227,7 +227,6 @@ class Game {
void updatePlayers(float delta_time); // Actualiza las variables y estados de los jugadores
void renderPlayers(); // Renderiza todos los jugadores en pantalla
auto getPlayer(Player::Id id) -> std::shared_ptr<Player>; // Obtiene un jugador por su identificador
static auto getController(Player::Id player_id) -> int; // Obtiene el controlador asignado a un jugador
// --- Estado de jugadores ---
void checkAndUpdatePlayerStatus(int active_player_index, int inactive_player_index); // Actualiza estado entre jugadores
@@ -237,9 +236,9 @@ class Game {
auto allPlayersAreNotPlaying() -> bool; // Verifica si ningún jugador está activo
// --- Colisiones de jugadores ---
void handlePlayerCollision(std::shared_ptr<Player>& player, std::shared_ptr<Balloon>& balloon); // Procesa colisión de jugador con globo
auto checkPlayerBalloonCollision(std::shared_ptr<Player>& player) -> std::shared_ptr<Balloon>; // Detecta colisión jugador-globo
void checkPlayerItemCollision(std::shared_ptr<Player>& player); // Detecta colisión jugador-ítem
void handlePlayerCollision(std::shared_ptr<Player>& player, const std::shared_ptr<Balloon>& balloon); // Procesa colisión de jugador con globo
auto checkPlayerBalloonCollision(std::shared_ptr<Player>& player) -> std::shared_ptr<Balloon>; // Detecta colisión jugador-globo
void checkPlayerItemCollision(std::shared_ptr<Player>& player); // Detecta colisión jugador-ítem
// --- Sistema de entrada (input) ---
void checkInput(); // Gestiona toda la entrada durante el juego
-3
View File
@@ -245,9 +245,6 @@ void Title::run() {
}
}
// Reinicia el contador interno
void Title::resetCounter() { counter_time_ = 0.0F; }
// Intercambia la asignación de mandos a los jugadores
void Title::swapControllers() {
if (Input::get()->getNumGamepads() == 0) {
-1
View File
@@ -107,7 +107,6 @@ class Title {
auto calculateDeltaTime() -> float; // Calcula el tiempo transcurrido desde el último frame
void updateState(float delta_time); // Actualiza el estado actual del título
void setState(State state); // Cambia el estado del título
void resetCounter(); // Reinicia el contador interno
// --- Entrada de usuario ---
void checkEvents(); // Comprueba los eventos
+2 -5
View File
@@ -3,6 +3,7 @@
#include <algorithm> // Para max, clamp
#include <cstddef> // Para size_t
#include <functional> // Para function
#include <numeric> // Para accumulate
#include <string> // Para allocator, string, basic_string, to_string, operator==, char_traits
#include <utility> // Para move
#include <vector> // Para vector
@@ -174,11 +175,7 @@ class ListOption : public MenuOption {
setter_(value_list_[list_index_]);
}
auto getMaxValueWidth(Text* text_renderer) const -> int override {
int max_w = 0;
for (const auto& val : value_list_) {
max_w = std::max(max_w, text_renderer->length(val, -2));
}
return max_w;
return std::accumulate(value_list_.begin(), value_list_.end(), 0, [text_renderer](int max_w, const auto& val) { return std::max(max_w, text_renderer->length(val, -2)); });
}
private:
+1 -30
View File
@@ -381,9 +381,7 @@ void MenuRenderer::updatePosition() {
// Resto de métodos (sin cambios significativos)
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_) {
w = ServiceMenu::MIN_WIDTH;
}
std::ranges::fill(group_menu_widths_, ServiceMenu::MIN_WIDTH);
for (int group = 0; group < 5; ++group) {
auto sg = static_cast<ServiceMenu::SettingsGroup>(group);
int max_option_width = 0;
@@ -433,33 +431,6 @@ auto MenuRenderer::getAnimatedSelectedColor() const -> Color {
static auto color_cycle_ = Colors::generateMirroredCycle(param.service_menu.selected_color, ColorCycleStyle::HUE_WAVE);
return color_cycle_.at(color_counter_ % color_cycle_.size());
}
auto MenuRenderer::setRect(SDL_FRect rect) -> SDL_FRect {
border_rect_ = {.x = rect.x - 1, .y = rect.y + 1, .w = rect.w + 2, .h = rect.h - 2};
return rect;
}
auto MenuRenderer::getTruncatedValueWidth(const std::string& value, int available_width) const -> int {
int value_width = element_text_->length(value, -2);
if (value_width <= available_width) {
return value_width;
}
// Calculamos cuántos caracteres podemos mostrar más los puntos suspensivos
// Estimamos el ancho de los puntos suspensivos como 3 caracteres promedio
int ellipsis_width = element_text_->length("...", -2);
int available_for_text = available_width - ellipsis_width;
if (available_for_text <= 0) {
return ellipsis_width; // Solo mostramos los puntos suspensivos
}
// Calculamos aproximadamente cuántos caracteres caben
float char_width = static_cast<float>(value_width) / value.length();
auto max_chars = static_cast<size_t>(available_for_text / char_width);
// Verificamos el ancho real del texto truncado
std::string truncated = truncateWithEllipsis(value, max_chars);
return element_text_->length(truncated, -2);
}
auto MenuRenderer::getTruncatedValue(const std::string& value, int available_width) const -> std::string {
int value_width = element_text_->length(value, -2);
+6 -5
View File
@@ -82,8 +82,10 @@ class MenuRenderer {
// --- Estructuras de Animación ---
struct ResizeAnimation {
bool active = false;
float start_width, start_height;
float target_width, target_height;
float start_width = 0.0F;
float start_height = 0.0F;
float target_width = 0.0F;
float target_height = 0.0F;
float elapsed = 0.0F;
float duration = 0.2F;
@@ -97,7 +99,8 @@ class MenuRenderer {
HIDING };
Type type = Type::NONE;
bool active = false;
float target_width, target_height;
float target_width = 0.0F;
float target_height = 0.0F;
float elapsed = 0.0F;
float duration = 0.25F;
@@ -140,8 +143,6 @@ class MenuRenderer {
[[nodiscard]] auto getMenuWidthForGroup(ServiceMenu::SettingsGroup group) const -> int;
[[nodiscard]] auto getAnimatedSelectedColor() const -> Color;
void updateColorCounter();
auto setRect(SDL_FRect rect) -> SDL_FRect;
[[nodiscard]] auto getTruncatedValueWidth(const std::string& value, int available_width) const -> int;
[[nodiscard]] auto getTruncatedValue(const std::string& value, int available_width) const -> std::string;
[[nodiscard]] static auto easeOut(float t) -> float;
[[nodiscard]] auto shouldShowContent() const -> bool;
+6 -7
View File
@@ -2,8 +2,9 @@
#include <SDL3/SDL.h> // Para SDL_RenderFillRect, SDL_FRect, SDL_RenderClear
#include <algorithm> // Para remove_if, min
#include <string> // Para basic_string, string
#include <algorithm> // Para ranges::transform, min
#include <iterator> // Para back_inserter
#include <string> // Para basic_string, string, erase_if
#include <utility>
#include <vector> // Para vector
@@ -77,7 +78,7 @@ void Notifier::playNotificationSoundIfNeeded(const Notification& notification) {
}
void Notifier::updateNotificationState(int index, float delta_time) {
auto& notification = notifications_[index];
const auto& notification = notifications_[index];
switch (notification.state) {
case State::RISING:
@@ -167,7 +168,7 @@ void Notifier::show(std::vector<std::string> texts, int icon, const std::string&
}
// Elimina las cadenas vacías
texts.erase(std::ranges::remove_if(texts, [](const std::string& s) -> bool { return s.empty(); }).begin(), texts.end());
std::erase_if(texts, [](const std::string& s) -> bool { return s.empty(); });
// Encuentra la cadena más larga
std::string longest;
@@ -303,8 +304,6 @@ void Notifier::clearAllNotifications() {
auto Notifier::getCodes() -> std::vector<std::string> {
std::vector<std::string> codes;
codes.reserve(notifications_.size());
for (const auto& notification : notifications_) {
codes.emplace_back(notification.code);
}
std::ranges::transform(notifications_, std::back_inserter(codes), [](const auto& notification) { return notification.code; });
return codes;
}
+17 -24
View File
@@ -1,5 +1,8 @@
#include "game/ui/service_menu.hpp"
#include <algorithm>
#include <iterator>
#include <numeric>
#include <utility>
#include "core/audio/audio.hpp" // Para Audio
@@ -175,7 +178,7 @@ void ServiceMenu::selectOption() {
return;
}
if (auto* folder = dynamic_cast<FolderOption*>(selected_option)) {
if (const auto* folder = dynamic_cast<const FolderOption*>(selected_option)) {
previous_settings_group_ = current_settings_group_;
current_settings_group_ = folder->getTargetGroup();
selected_ = 0;
@@ -200,9 +203,8 @@ void ServiceMenu::updateDisplayOptions() {
void ServiceMenu::updateOptionPairs() {
option_pairs_.clear();
for (const auto& option : display_options_) {
option_pairs_.emplace_back(option->getCaption(), option->getValueAsString());
}
option_pairs_.reserve(display_options_.size());
std::ranges::transform(display_options_, std::back_inserter(option_pairs_), [](const auto* option) { return std::pair{option->getCaption(), option->getValueAsString()}; });
}
void ServiceMenu::updateMenu() {
@@ -250,12 +252,9 @@ void ServiceMenu::applySettingsSettings() {
}
auto ServiceMenu::getOptionByCaption(const std::string& caption) const -> MenuOption* {
for (const auto& option : options_) {
if (option->getCaption() == caption) {
return option.get();
}
}
return nullptr;
const auto it = std::ranges::find_if(options_,
[&caption](const auto& option) { return option->getCaption() == caption; });
return it != options_.end() ? it->get() : nullptr;
}
// --- Getters y otros ---
@@ -273,13 +272,8 @@ auto ServiceMenu::getCurrentGroupAlignment() const -> ServiceMenu::GroupAlignmen
}
auto ServiceMenu::countOptionsInGroup(SettingsGroup group) const -> size_t {
size_t count = 0;
for (const auto& option : options_) {
if (option->getGroup() == group && !option->isHidden()) {
count++;
}
}
return count;
return std::ranges::count_if(options_,
[group](const auto& option) { return option->getGroup() == group && !option->isHidden(); });
}
// Inicializa todas las opciones del menú
@@ -300,7 +294,7 @@ void ServiceMenu::initializeOptions() {
[this]() -> void {
// Acción: configurar botones del mando del jugador 1
auto* gamepad = &Options::gamepad_manager.getGamepad(Player::Id::PLAYER1);
if ((gamepad != nullptr) && gamepad->instance) {
if (gamepad->instance != nullptr) {
define_buttons_->enable(gamepad);
}
}));
@@ -318,7 +312,7 @@ void ServiceMenu::initializeOptions() {
[this]() -> void {
// Acción: configurar botones del mando del jugador 2
auto* gamepad = &Options::gamepad_manager.getGamepad(Player::Id::PLAYER2);
if ((gamepad != nullptr) && gamepad->instance) {
if (gamepad->instance != nullptr) {
define_buttons_->enable(gamepad);
}
}));
@@ -436,11 +430,10 @@ void ServiceMenu::initializeOptions() {
}
Screen::initShaders();
};
auto preset_max_width = [](Text* text) -> int {
int max_w = 0;
for (const auto& p : Options::postfx_presets) { max_w = std::max(max_w, text->length(p.name, -2)); }
for (const auto& p : Options::crtpi_presets) { max_w = std::max(max_w, text->length(p.name, -2)); }
return max_w;
auto preset_max_width = [](const Text* text) -> int {
const auto presets_length = [text](int max_w, const auto& p) { return std::max(max_w, text->length(p.name, -2)); };
int max_w = std::accumulate(Options::postfx_presets.begin(), Options::postfx_presets.end(), 0, presets_length);
return std::accumulate(Options::crtpi_presets.begin(), Options::crtpi_presets.end(), max_w, presets_length);
};
options_.push_back(std::make_unique<CallbackOption>(
+8 -5
View File
@@ -51,7 +51,7 @@ class WindowMessage {
text_color{200, 200, 200, 255} {}
// Constructor que convierte desde ParamServiceMenu::WindowMessage
Config(const ParamServiceMenu::WindowMessage& param_config)
explicit Config(const ParamServiceMenu::WindowMessage& param_config)
: bg_color(param_config.bg_color),
border_color(param_config.border_color),
title_color(param_config.title_color),
@@ -67,7 +67,7 @@ class WindowMessage {
animation_duration(param_config.animation_duration) {}
};
WindowMessage(
explicit WindowMessage(
std::shared_ptr<Text> text_renderer,
std::string title = "",
const Config& config = Config{});
@@ -148,8 +148,10 @@ class WindowMessage {
// Animación de redimensionado
struct ResizeAnimation {
bool active = false;
float start_width, start_height;
float target_width, target_height;
float start_width = 0.0F;
float start_height = 0.0F;
float target_width = 0.0F;
float target_height = 0.0F;
float elapsed = 0.0F;
void start(float from_w, float from_h, float to_w, float to_h) {
@@ -183,7 +185,8 @@ class WindowMessage {
Type type = Type::NONE;
bool active = false;
float target_width, target_height; // Tamaño final al mostrar
float target_width = 0.0F;
float target_height = 0.0F;
float elapsed = 0.0F;
void startShow(float to_w, float to_h) {