passant linters a vore si trobe variables sense inicialitzar

This commit is contained in:
2025-08-17 00:23:59 +02:00
parent ada5025c65
commit 327987447d
55 changed files with 516 additions and 474 deletions

View File

@@ -1,10 +1,21 @@
Checks: > Checks: >
readability-*, readability-*,
modernize-*, modernize-*,
bugprone-*,
performance-*, performance-*,
bugprone-unchecked-optional-access,
bugprone-sizeof-expression,
bugprone-suspicious-missing-comma,
bugprone-suspicious-index,
bugprone-undefined-memory-manipulation,
bugprone-use-after-move,
bugprone-out-of-bound-access,
-readability-identifier-length, -readability-identifier-length,
-readability-magic-numbers -readability-magic-numbers,
-bugprone-narrowing-conversions,
-performance-enum-size,
-performance-inefficient-string-concatenation,
-bugprone-integer-division,
-bugprone-easily-swappable-parameters
WarningsAsErrors: '*' WarningsAsErrors: '*'
# Solo incluir archivos de tu código fuente # Solo incluir archivos de tu código fuente

View File

@@ -0,0 +1,15 @@
#!/bin/bash
# 🏁 Ruta base del proyecto
BASE_DIR="/home/sergio/gitea/coffee_crisis_arcade_edition"
# 📁 Ruta al build
BUILD_DIR="$BASE_DIR/build"
# 📄 Archivo de mapping personalizado
MAPPING_FILE="$BASE_DIR/linux_utils/sdl3_mapping.imp"
# 📦 Generar compile_commands.json
echo "🔧 Generando compile_commands.json..."
cmake -DCMAKE_EXPORT_COMPILE_COMMANDS=ON -S "$BASE_DIR" -B "$BUILD_DIR"

View File

@@ -35,7 +35,7 @@ auto loadAnimationsFromFile(const std::string& file_path) -> AnimationsFileBuffe
// Constructor // Constructor
AnimatedSprite::AnimatedSprite(std::shared_ptr<Texture> texture, const std::string& file_path) AnimatedSprite::AnimatedSprite(std::shared_ptr<Texture> texture, const std::string& file_path)
: MovingSprite(texture) { : MovingSprite(std::move(texture)) {
// Carga las animaciones // Carga las animaciones
if (!file_path.empty()) { if (!file_path.empty()) {
auto buffer = loadAnimationsFromFile(file_path); auto buffer = loadAnimationsFromFile(file_path);
@@ -45,7 +45,7 @@ AnimatedSprite::AnimatedSprite(std::shared_ptr<Texture> texture, const std::stri
// Constructor // Constructor
AnimatedSprite::AnimatedSprite(std::shared_ptr<Texture> texture, const AnimationsFileBuffer& animations) AnimatedSprite::AnimatedSprite(std::shared_ptr<Texture> texture, const AnimationsFileBuffer& animations)
: MovingSprite(texture) { : MovingSprite(std::move(texture)) {
if (!animations.empty()) { if (!animations.empty()) {
loadFromAnimationsFileBuffer(animations); loadFromAnimationsFileBuffer(animations);
} }
@@ -176,7 +176,7 @@ void AnimatedSprite::loadFromAnimationsFileBuffer(const AnimationsFileBuffer& so
// Procesa una línea de configuración // Procesa una línea de configuración
void AnimatedSprite::processConfigLine(const std::string& line, AnimationConfig& config) { void AnimatedSprite::processConfigLine(const std::string& line, AnimationConfig& config) {
size_t pos = line.find("="); size_t pos = line.find('=');
if (pos == std::string::npos) { if (pos == std::string::npos) {
return; return;
} }
@@ -230,7 +230,7 @@ auto AnimatedSprite::processAnimationBlock(const AnimationsFileBuffer& source, s
// Procesa un parámetro individual de animación // Procesa un parámetro individual de animación
void AnimatedSprite::processAnimationParameter(const std::string& line, Animation& animation, const AnimationConfig& config) { void AnimatedSprite::processAnimationParameter(const std::string& line, Animation& animation, const AnimationConfig& config) {
size_t pos = line.find("="); size_t pos = line.find('=');
if (pos == std::string::npos) { if (pos == std::string::npos) {
return; return;
} }

View File

@@ -7,7 +7,8 @@
#include <memory> // Para allocator, shared_ptr #include <memory> // Para allocator, shared_ptr
#include <string> // Para string, hash #include <string> // Para string, hash
#include <unordered_map> // Para unordered_map #include <unordered_map> // Para unordered_map
#include <vector> // Para vector #include <utility>
#include <vector> // Para vector
#include "moving_sprite.h" // Para MovingSprite #include "moving_sprite.h" // Para MovingSprite
@@ -49,7 +50,7 @@ class AnimatedSprite : public MovingSprite {
// --- Constructores y destructor --- // --- Constructores y destructor ---
AnimatedSprite(std::shared_ptr<Texture> texture, const std::string& file_path); AnimatedSprite(std::shared_ptr<Texture> texture, const std::string& file_path);
AnimatedSprite(std::shared_ptr<Texture> texture, const AnimationsFileBuffer& animations); AnimatedSprite(std::shared_ptr<Texture> texture, const AnimationsFileBuffer& animations);
explicit AnimatedSprite(std::shared_ptr<Texture> texture) : MovingSprite(texture) {} explicit AnimatedSprite(std::shared_ptr<Texture> texture) : MovingSprite(std::move(texture)) {}
~AnimatedSprite() override = default; ~AnimatedSprite() override = default;
// --- Métodos principales --- // --- Métodos principales ---

View File

@@ -5,6 +5,7 @@
#include <algorithm> // Para clamp, max #include <algorithm> // Para clamp, max
#include <cmath> // Para M_PI, cos, sin #include <cmath> // Para M_PI, cos, sin
#include <utility>
#include "moving_sprite.h" // Para MovingSprite #include "moving_sprite.h" // Para MovingSprite
#include "param.h" // Para Param, ParamBackground, param #include "param.h" // Para Param, ParamBackground, param
@@ -171,7 +172,7 @@ void Background::incrementProgress(float amount) {
// Establece la progresión absoluta // Establece la progresión absoluta
void Background::setProgress(float absolute_progress) { void Background::setProgress(float absolute_progress) {
float old_progress = progress_; float old_progress = progress_;
progress_ = std::clamp(absolute_progress, 0.0f, total_progress_to_complete_); progress_ = std::clamp(absolute_progress, 0.0F, total_progress_to_complete_);
// Notifica el cambio si hay callback y el progreso cambió // Notifica el cambio si hay callback y el progreso cambió
if (progress_callback_ && progress_ != old_progress) { if (progress_callback_ && progress_ != old_progress) {
@@ -187,11 +188,11 @@ void Background::setState(State new_state) {
// Reinicia la progresión // Reinicia la progresión
void Background::reset() { void Background::reset() {
float old_progress = progress_; float old_progress = progress_;
progress_ = 0.0f; progress_ = 0.0F;
state_ = State::NORMAL; state_ = State::NORMAL;
manual_mode_ = false; manual_mode_ = false;
gradient_number_ = 0; gradient_number_ = 0;
transition_ = 0.0f; transition_ = 0.0F;
sun_index_ = 0; sun_index_ = 0;
moon_index_ = 0; moon_index_ = 0;
@@ -208,7 +209,7 @@ void Background::setManualMode(bool manual) {
// Establece callback para sincronización automática // Establece callback para sincronización automática
void Background::setProgressCallback(ProgressCallback callback) { void Background::setProgressCallback(ProgressCallback callback) {
progress_callback_ = callback; progress_callback_ = std::move(callback);
} }
// Elimina el callback // Elimina el callback
@@ -224,8 +225,8 @@ void Background::setCloudsSpeed(float value) {
// Las nubes inferiores van a la mitad de velocidad que las superiores // Las nubes inferiores van a la mitad de velocidad que las superiores
top_clouds_sprite_a_->setVelX(value); top_clouds_sprite_a_->setVelX(value);
top_clouds_sprite_b_->setVelX(value); top_clouds_sprite_b_->setVelX(value);
bottom_clouds_sprite_a_->setVelX(value / 2.0f); bottom_clouds_sprite_a_->setVelX(value / 2.0F);
bottom_clouds_sprite_b_->setVelX(value / 2.0f); bottom_clouds_sprite_b_->setVelX(value / 2.0F);
} }
// Establece el degradado de fondo // Establece el degradado de fondo
@@ -262,19 +263,19 @@ void Background::updateProgression() {
} }
// Calcula la transición de los diferentes fondos // Calcula la transición de los diferentes fondos
const float gradient_number_float = std::min(progress_ / progress_per_stage_, 3.0F); const float GRADIENT_NUMBER_FLOAT = std::min(progress_ / progress_per_stage_, 3.0F);
const float percent = gradient_number_float - static_cast<int>(gradient_number_float); const float PERCENT = GRADIENT_NUMBER_FLOAT - static_cast<int>(GRADIENT_NUMBER_FLOAT);
gradient_number_ = static_cast<size_t>(gradient_number_float); gradient_number_ = static_cast<size_t>(GRADIENT_NUMBER_FLOAT);
transition_ = percent; transition_ = PERCENT;
// Calcula la posición del sol // Calcula la posición del sol
const float sun_progression = std::min(progress_ / sun_completion_progress_, 1.0f); const float SUN_PROGRESSION = std::min(progress_ / sun_completion_progress_, 1.0F);
sun_index_ = static_cast<size_t>(sun_progression * (sun_path_.size() - 1)); sun_index_ = static_cast<size_t>(SUN_PROGRESSION * (sun_path_.size() - 1));
// Calcula la posición de la luna // Calcula la posición de la luna
const float moon_progression = std::min(progress_ / total_progress_to_complete_, 1.0f); const float MOON_PROGRESSION = std::min(progress_ / total_progress_to_complete_, 1.0F);
moon_index_ = static_cast<size_t>(moon_progression * (moon_path_.size() - 1)); moon_index_ = static_cast<size_t>(MOON_PROGRESSION * (moon_path_.size() - 1));
// Actualiza la velocidad de las nubes // Actualiza la velocidad de las nubes
updateCloudsSpeed(); updateCloudsSpeed();
@@ -294,22 +295,22 @@ void Background::updateCloudsSpeed() {
if (state_ == State::COMPLETED) { if (state_ == State::COMPLETED) {
float completion_factor = (progress_ - MINIMUM_COMPLETED_PROGRESS) / float completion_factor = (progress_ - MINIMUM_COMPLETED_PROGRESS) /
(total_progress_to_complete_ - MINIMUM_COMPLETED_PROGRESS); (total_progress_to_complete_ - MINIMUM_COMPLETED_PROGRESS);
completion_factor = std::max(0.1f, completion_factor); completion_factor = std::max(0.1F, completion_factor);
base_clouds_speed *= completion_factor; base_clouds_speed *= completion_factor;
} }
// Aplicar velocidades diferentes para nubes superiores e inferiores // Aplicar velocidades diferentes para nubes superiores e inferiores
const float top_clouds_speed = base_clouds_speed; const float TOP_CLOUDS_SPEED = base_clouds_speed;
const float bottom_clouds_speed = base_clouds_speed / 2.0f; const float BOTTOM_CLOUDS_SPEED = base_clouds_speed / 2.0F;
// Aplicar las velocidades a los sprites correspondientes // Aplicar las velocidades a los sprites correspondientes
top_clouds_sprite_a_->setVelX(top_clouds_speed); top_clouds_sprite_a_->setVelX(TOP_CLOUDS_SPEED);
top_clouds_sprite_b_->setVelX(top_clouds_speed); top_clouds_sprite_b_->setVelX(TOP_CLOUDS_SPEED);
bottom_clouds_sprite_a_->setVelX(bottom_clouds_speed); bottom_clouds_sprite_a_->setVelX(BOTTOM_CLOUDS_SPEED);
bottom_clouds_sprite_b_->setVelX(bottom_clouds_speed); bottom_clouds_sprite_b_->setVelX(BOTTOM_CLOUDS_SPEED);
// Guardar la velocidad principal // Guardar la velocidad principal
clouds_speed_ = top_clouds_speed; clouds_speed_ = TOP_CLOUDS_SPEED;
} }
// Actualiza las nubes // Actualiza las nubes
@@ -501,9 +502,9 @@ void Background::createMoonPath() {
constexpr double STEP = 0.01; constexpr double STEP = 0.01;
const int NUM_STEPS = static_cast<int>((M_PI / 2) / STEP) + 1; const int NUM_STEPS = static_cast<int>((M_PI / 2) / STEP) + 1;
constexpr float FREEZE_PERCENTAGE = 0.2f; // Porcentaje final del recorrido que se mantiene fijo constexpr float FREEZE_PERCENTAGE = 0.2F; // Porcentaje final del recorrido que se mantiene fijo
const int FREEZE_START_INDEX = static_cast<int>(NUM_STEPS * (1.0f - FREEZE_PERCENTAGE)); const int FREEZE_START_INDEX = static_cast<int>(NUM_STEPS * (1.0F - FREEZE_PERCENTAGE));
for (int i = 0; i < NUM_STEPS; ++i) { for (int i = 0; i < NUM_STEPS; ++i) {
double theta = i * STEP; double theta = i * STEP;

View File

@@ -27,7 +27,7 @@ class Background {
using ProgressCallback = std::function<void(float)>; // Callback para sincronización using ProgressCallback = std::function<void(float)>; // Callback para sincronización
// --- Constructor y destructor --- // --- Constructor y destructor ---
Background(float total_progress_to_complete = 6100.0f); // Constructor principal Background(float total_progress_to_complete = 6100.0F); // Constructor principal
~Background(); // Destructor ~Background(); // Destructor
// --- Métodos principales --- // --- Métodos principales ---
@@ -50,7 +50,7 @@ class Background {
void setAlpha(int alpha); // Ajusta la transparencia del fondo void setAlpha(int alpha); // Ajusta la transparencia del fondo
// --- Control de progresión --- // --- Control de progresión ---
void incrementProgress(float amount = 1.0f); // Incrementa la progresión interna void incrementProgress(float amount = 1.0F); // Incrementa la progresión interna
void setProgress(float absolute_progress); // Establece la progresión absoluta void setProgress(float absolute_progress); // Establece la progresión absoluta
// --- Getters --- // --- Getters ---
@@ -61,9 +61,9 @@ class Background {
private: private:
// --- Constantes --- // --- Constantes ---
static constexpr size_t STAGES = 4; // Número de etapas static constexpr size_t STAGES = 4; // Número de etapas
static constexpr float COMPLETED_REDUCTION_RATE = 25.0f; // Tasa de reducción completada static constexpr float COMPLETED_REDUCTION_RATE = 25.0F; // Tasa de reducción completada
static constexpr float MINIMUM_COMPLETED_PROGRESS = 200.0f; // Progreso mínimo completado static constexpr float MINIMUM_COMPLETED_PROGRESS = 200.0F; // Progreso mínimo completado
static constexpr float SUN_COMPLETION_FACTOR = 0.5f; // Factor de completado del sol static constexpr float SUN_COMPLETION_FACTOR = 0.5F; // Factor de completado del sol
// --- Objetos y punteros --- // --- Objetos y punteros ---
SDL_Renderer *renderer_; // Renderizador de la ventana SDL_Renderer *renderer_; // Renderizador de la ventana
@@ -103,7 +103,7 @@ class Background {
SDL_FRect dst_rect_; // Posición en pantalla donde se copia el objeto SDL_FRect dst_rect_; // Posición en pantalla donde se copia el objeto
Color attenuate_color_; // Color de atenuación Color attenuate_color_; // Color de atenuación
State state_ = State::NORMAL; // Estado actual State state_ = State::NORMAL; // Estado actual
float progress_ = 0.0f; // Progresión interna float progress_ = 0.0F; // Progresión interna
float clouds_speed_ = 0; // Velocidad de las nubes float clouds_speed_ = 0; // Velocidad de las nubes
float transition_ = 0; // Porcentaje de transición float transition_ = 0; // Porcentaje de transición
size_t gradient_number_ = 0; // Índice de fondo degradado size_t gradient_number_ = 0; // Índice de fondo degradado

View File

@@ -11,7 +11,7 @@
#include "texture.h" // Para Texture #include "texture.h" // Para Texture
// Constructor // Constructor
Balloon::Balloon(float x, float y, Type type, Size size, float vel_x, float speed, Uint16 creation_timer, SDL_FRect play_area, std::shared_ptr<Texture> texture, const std::vector<std::string> &animation) Balloon::Balloon(float x, float y, Type type, Size size, float vel_x, float speed, Uint16 creation_timer, SDL_FRect play_area, const std::shared_ptr<Texture> &texture, const std::vector<std::string> &animation)
: sprite_(std::make_unique<AnimatedSprite>(texture, animation)), : sprite_(std::make_unique<AnimatedSprite>(texture, animation)),
x_(x), x_(x),
y_(y), y_(y),
@@ -44,7 +44,7 @@ Balloon::Balloon(float x, float y, Type type, Size size, float vel_x, float spee
} }
case Type::FLOATER: { case Type::FLOATER: {
default_vy_ = max_vy_ = vy_ = fabs(vx_ * 2.0F); default_vy_ = max_vy_ = vy_ = std::fabs(vx_ * 2.0F);
gravity_ = 0.00F; gravity_ = 0.00F;
const int INDEX = static_cast<int>(size_); const int INDEX = static_cast<int>(size_);

View File

@@ -62,7 +62,7 @@ class Balloon {
float speed, float speed,
Uint16 creation_timer, Uint16 creation_timer,
SDL_FRect play_area, SDL_FRect play_area,
std::shared_ptr<Texture> texture, const std::shared_ptr<Texture>& texture,
const std::vector<std::string>& animation); const std::vector<std::string>& animation);
~Balloon() = default; ~Balloon() = default;

View File

@@ -64,7 +64,7 @@ void BalloonManager::init() {
// Actualiza // Actualiza
void BalloonManager::update() { void BalloonManager::update() {
for (auto balloon : balloons_) { for (const auto &balloon : balloons_) {
balloon->update(); balloon->update();
} }
updateBalloonDeployCounter(); updateBalloonDeployCounter();
@@ -226,7 +226,7 @@ void BalloonManager::setBalloonSpeed(float speed) {
} }
// Explosiona un globo. Lo destruye y crea otros dos si es el caso // Explosiona un globo. Lo destruye y crea otros dos si es el caso
auto BalloonManager::popBalloon(std::shared_ptr<Balloon> balloon) -> int { auto BalloonManager::popBalloon(const std::shared_ptr<Balloon> &balloon) -> int {
stage_info_->addPower(1); stage_info_->addPower(1);
int score = 0; int score = 0;

View File

@@ -55,7 +55,7 @@ class BalloonManager {
auto calculateScreenPower() -> int; // Calcula el poder de los globos en pantalla auto calculateScreenPower() -> int; // Calcula el poder de los globos en pantalla
// --- Manipulación de globos existentes --- // --- Manipulación de globos existentes ---
auto popBalloon(std::shared_ptr<Balloon> balloon) -> int; // Explosiona un globo, creando otros si aplica auto popBalloon(const std::shared_ptr<Balloon> &balloon) -> int; // Explosiona un globo, creando otros si aplica
auto destroyBalloon(std::shared_ptr<Balloon> &balloon) -> int; // Explosiona un globo sin crear otros auto destroyBalloon(std::shared_ptr<Balloon> &balloon) -> int; // Explosiona un globo sin crear otros
auto destroyAllBalloons() -> int; // Destruye todos los globos auto destroyAllBalloons() -> int; // Destruye todos los globos
void stopAllBalloons(); // Detiene el movimiento de los globos void stopAllBalloons(); // Detiene el movimiento de los globos

View File

@@ -81,7 +81,7 @@ struct Color {
} }
// Convierte el color a un entero de 32 bits en formato RGBA // Convierte el color a un entero de 32 bits en formato RGBA
[[nodiscard]] constexpr auto toUint32() const -> Uint32 { [[nodiscard]] constexpr auto TO_UINT32() const -> Uint32 {
return (static_cast<Uint32>(r) << 24) | return (static_cast<Uint32>(r) << 24) |
(static_cast<Uint32>(g) << 16) | (static_cast<Uint32>(g) << 16) |
(static_cast<Uint32>(b) << 8) | (static_cast<Uint32>(b) << 8) |

View File

@@ -10,38 +10,38 @@ namespace GameDefaults {
// --- GAME --- // --- GAME ---
namespace Game { namespace Game {
constexpr float WIDTH = 320.0f; constexpr float WIDTH = 320.0F;
constexpr float HEIGHT = 256.0f; constexpr float HEIGHT = 256.0F;
constexpr float ITEM_SIZE = 20.0f; constexpr float ITEM_SIZE = 20.0F;
constexpr int NAME_ENTRY_IDLE_TIME = 10; constexpr int NAME_ENTRY_IDLE_TIME = 10;
constexpr int NAME_ENTRY_TOTAL_TIME = 60; constexpr int NAME_ENTRY_TOTAL_TIME = 60;
constexpr bool HIT_STOP = false; constexpr bool HIT_STOP = false;
constexpr int HIT_STOP_MS = 500; constexpr int HIT_STOP_MS = 500;
// Play area por defecto // Play area por defecto
constexpr float PLAY_AREA_X = 0.0f; constexpr float PLAY_AREA_X = 0.0F;
constexpr float PLAY_AREA_Y = 0.0f; constexpr float PLAY_AREA_Y = 0.0F;
constexpr float PLAY_AREA_W = 320.0f; constexpr float PLAY_AREA_W = 320.0F;
constexpr float PLAY_AREA_H = 216.0f; constexpr float PLAY_AREA_H = 216.0F;
} // namespace Game } // namespace Game
// --- FADE --- // --- FADE ---
namespace Fade { namespace Fade {
constexpr const char* COLOR = "1F2B30"; constexpr const char* COLOR = "1F2B30";
constexpr float NUM_SQUARES_WIDTH = 160.0f; constexpr float NUM_SQUARES_WIDTH = 160.0F;
constexpr float NUM_SQUARES_HEIGHT = 128.0f; constexpr float NUM_SQUARES_HEIGHT = 128.0F;
constexpr int RANDOM_SQUARES_DELAY = 1; constexpr int RANDOM_SQUARES_DELAY = 1;
constexpr int RANDOM_SQUARES_MULT = 500; constexpr int RANDOM_SQUARES_MULT = 500;
constexpr int POST_DURATION = 80; constexpr int POST_DURATION = 80;
constexpr float VENETIAN_SIZE = 12.0f; constexpr float VENETIAN_SIZE = 12.0F;
} // namespace Fade } // namespace Fade
// --- SCOREBOARD --- // --- SCOREBOARD ---
namespace Scoreboard { namespace Scoreboard {
constexpr float RECT_X = 0.0f; constexpr float RECT_X = 0.0F;
constexpr float RECT_Y = 216.0f; constexpr float RECT_Y = 216.0F;
constexpr float RECT_W = 320.0f; constexpr float RECT_W = 320.0F;
constexpr float RECT_H = 40.0f; constexpr float RECT_H = 40.0F;
constexpr bool SEPARATOR_AUTOCOLOR = true; constexpr bool SEPARATOR_AUTOCOLOR = true;
constexpr const char* SEPARATOR_COLOR = "0D1A2B"; constexpr const char* SEPARATOR_COLOR = "0D1A2B";
constexpr const char* EASY_COLOR = "4B692F"; constexpr const char* EASY_COLOR = "4B692F";
@@ -77,10 +77,10 @@ struct BalloonSettings {
}; };
constexpr std::array<BalloonSettings, 4> SETTINGS = {{ constexpr std::array<BalloonSettings, 4> SETTINGS = {{
BalloonSettings(2.75f, 0.09f), // Globo 0 BalloonSettings(2.75F, 0.09F), // Globo 0
BalloonSettings(3.70f, 0.10f), // Globo 1 BalloonSettings(3.70F, 0.10F), // Globo 1
BalloonSettings(4.70f, 0.10f), // Globo 2 BalloonSettings(4.70F, 0.10F), // Globo 2
BalloonSettings(5.45f, 0.10f) // Globo 3 BalloonSettings(5.45F, 0.10F) // Globo 3
}}; }};
constexpr std::array<const char*, 4> COLORS = { constexpr std::array<const char*, 4> COLORS = {
@@ -111,15 +111,15 @@ constexpr const char* BG_COLOR = "141E32F0"; // Color(20, 30, 50, 240)
constexpr const char* BORDER_COLOR = "6496C8FF"; // Color(100, 150, 200, 255) constexpr const char* BORDER_COLOR = "6496C8FF"; // Color(100, 150, 200, 255)
constexpr const char* TITLE_COLOR = "6496C8FF"; // Color(100, 150, 200, 255) constexpr const char* TITLE_COLOR = "6496C8FF"; // Color(100, 150, 200, 255)
constexpr const char* TEXT_COLOR = "DCDCDCFF"; // Color(220, 220, 220, 255) constexpr const char* TEXT_COLOR = "DCDCDCFF"; // Color(220, 220, 220, 255)
constexpr float PADDING = 15.0f; constexpr float PADDING = 15.0F;
constexpr float LINE_SPACING = 5.0f; constexpr float LINE_SPACING = 5.0F;
constexpr float TITLE_SEPARATOR_SPACING = 10.0f; // Cambiado a float constexpr float TITLE_SEPARATOR_SPACING = 10.0F; // Cambiado a float
constexpr float MIN_WIDTH = 250.0f; constexpr float MIN_WIDTH = 250.0F;
constexpr float MIN_HEIGHT = 32.0f; // Cambiado a float constexpr float MIN_HEIGHT = 32.0F; // Cambiado a float
constexpr float MAX_WIDTH_RATIO = 0.8f; // Nuevo constexpr float MAX_WIDTH_RATIO = 0.8F; // Nuevo
constexpr float MAX_HEIGHT_RATIO = 0.8f; // Nuevo constexpr float MAX_HEIGHT_RATIO = 0.8F; // Nuevo
constexpr float TEXT_SAFETY_MARGIN = 15.0f; constexpr float TEXT_SAFETY_MARGIN = 15.0F;
constexpr float ANIMATION_DURATION = 0.3f; constexpr float ANIMATION_DURATION = 0.3F;
} // namespace WindowMessage } // namespace WindowMessage
} // namespace ServiceMenu } // namespace ServiceMenu
@@ -143,8 +143,8 @@ constexpr const char* COLOR = "FFFFFF";
// --- TABE --- // --- TABE ---
namespace Tabe { namespace Tabe {
constexpr float MIN_SPAWN_TIME = 2.0f; constexpr float MIN_SPAWN_TIME = 2.0F;
constexpr float MAX_SPAWN_TIME = 3.0f; constexpr float MAX_SPAWN_TIME = 3.0F;
} // namespace Tabe } // namespace Tabe
// --- PLAYER --- // --- PLAYER ---

View File

@@ -188,7 +188,7 @@ void Director::createSystemFolder(const std::string &folder) {
if (result != SystemUtils::Result::SUCCESS) { if (result != SystemUtils::Result::SUCCESS) {
std::cerr << "Error creando carpeta del sistema: " std::cerr << "Error creando carpeta del sistema: "
<< SystemUtils::resultToString(result) << std::endl; << SystemUtils::resultToString(result) << '\n';
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
} }
} }
@@ -321,7 +321,7 @@ void Director::shutdownSystem(bool should_shutdown) {
auto result = SystemShutdown::shutdownSystem(5, true); // 5 segundos, forzar apps auto result = SystemShutdown::shutdownSystem(5, true); // 5 segundos, forzar apps
if (result != SystemShutdown::ShutdownResult::SUCCESS) { if (result != SystemShutdown::ShutdownResult::SUCCESS) {
std::cerr << SystemShutdown::resultToString(result) << std::endl; std::cerr << SystemShutdown::resultToString(result) << '\n';
} }
} }
} }

View File

@@ -24,7 +24,7 @@ void Explosions::render() {
} }
// Añade texturas al objeto // Añade texturas al objeto
void Explosions::addTexture(int size, std::shared_ptr<Texture> texture, const std::vector<std::string> &animation) { void Explosions::addTexture(int size, const std::shared_ptr<Texture> &texture, const std::vector<std::string> &animation) {
textures_.emplace_back(size, texture, animation); textures_.emplace_back(size, texture, animation);
} }

View File

@@ -31,7 +31,7 @@ class Explosions {
void render(); // Dibuja el objeto en pantalla void render(); // Dibuja el objeto en pantalla
// --- Configuración --- // --- Configuración ---
void addTexture(int size, std::shared_ptr<Texture> texture, const std::vector<std::string> &animation); // Añade texturas al objeto void addTexture(int size, const std::shared_ptr<Texture> &texture, const std::vector<std::string> &animation); // Añade texturas al objeto
void add(int x, int y, int size); // Añade una explosión void add(int x, int y, int size); // Añade una explosión
private: private:

View File

@@ -27,8 +27,8 @@ Fade::~Fade() {
// Inicializa las variables // Inicializa las variables
void Fade::init() { void Fade::init() {
type_ = FadeType::CENTER; type_ = Type::CENTER;
mode_ = FadeMode::OUT; mode_ = Mode::OUT;
counter_ = 0; counter_ = 0;
r_ = 0; r_ = 0;
g_ = 0; g_ = 0;
@@ -46,13 +46,13 @@ void Fade::init() {
// Resetea algunas variables para volver a hacer el fade sin perder ciertos parametros // Resetea algunas variables para volver a hacer el fade sin perder ciertos parametros
void Fade::reset() { void Fade::reset() {
state_ = FadeState::NOT_ENABLED; state_ = State::NOT_ENABLED;
counter_ = 0; counter_ = 0;
} }
// Pinta una transición en pantalla // Pinta una transición en pantalla
void Fade::render() { void Fade::render() {
if (state_ != FadeState::NOT_ENABLED) { if (state_ != State::NOT_ENABLED) {
SDL_RenderTexture(renderer_, backbuffer_, nullptr, nullptr); SDL_RenderTexture(renderer_, backbuffer_, nullptr, nullptr);
} }
} }
@@ -60,13 +60,13 @@ void Fade::render() {
// Actualiza las variables internas // Actualiza las variables internas
void Fade::update() { void Fade::update() {
switch (state_) { switch (state_) {
case FadeState::PRE: case State::PRE:
updatePreState(); updatePreState();
break; break;
case FadeState::FADING: case State::FADING:
updateFadingState(); updateFadingState();
break; break;
case FadeState::POST: case State::POST:
updatePostState(); updatePostState();
break; break;
default: default:
@@ -76,7 +76,7 @@ void Fade::update() {
void Fade::updatePreState() { void Fade::updatePreState() {
if (pre_counter_ == pre_duration_) { if (pre_counter_ == pre_duration_) {
state_ = FadeState::FADING; state_ = State::FADING;
} else { } else {
pre_counter_++; pre_counter_++;
} }
@@ -84,16 +84,16 @@ void Fade::updatePreState() {
void Fade::updateFadingState() { void Fade::updateFadingState() {
switch (type_) { switch (type_) {
case FadeType::FULLSCREEN: case Type::FULLSCREEN:
updateFullscreenFade(); updateFullscreenFade();
break; break;
case FadeType::CENTER: case Type::CENTER:
updateCenterFade(); updateCenterFade();
break; break;
case FadeType::RANDOM_SQUARE: case Type::RANDOM_SQUARE:
updateRandomSquareFade(); updateRandomSquareFade();
break; break;
case FadeType::VENETIAN: case Type::VENETIAN:
updateVenetianFade(); updateVenetianFade();
break; break;
default: default:
@@ -104,7 +104,7 @@ void Fade::updateFadingState() {
void Fade::updatePostState() { void Fade::updatePostState() {
if (post_counter_ == post_duration_) { if (post_counter_ == post_duration_) {
state_ = FadeState::FINISHED; state_ = State::FINISHED;
} else { } else {
post_counter_++; post_counter_++;
} }
@@ -113,12 +113,12 @@ void Fade::updatePostState() {
void Fade::updateFullscreenFade() { void Fade::updateFullscreenFade() {
// Modifica la transparencia // Modifica la transparencia
a_ = mode_ == FadeMode::OUT ? std::min(counter_ * 4, 255) : 255 - std::min(counter_ * 4, 255); a_ = mode_ == Mode::OUT ? std::min(counter_ * 4, 255) : 255 - std::min(counter_ * 4, 255);
SDL_SetTextureAlphaMod(backbuffer_, a_); SDL_SetTextureAlphaMod(backbuffer_, a_);
// Comprueba si ha terminado // Comprueba si ha terminado
if (counter_ >= 255 / 4) { if (counter_ >= 255 / 4) {
state_ = FadeState::POST; state_ = State::POST;
} }
} }
@@ -127,7 +127,7 @@ void Fade::updateCenterFade() {
// Comprueba si ha terminado // Comprueba si ha terminado
if ((counter_ * 4) > param.game.height) { if ((counter_ * 4) > param.game.height) {
state_ = FadeState::POST; state_ = State::POST;
a_ = 255; a_ = 255;
} }
} }
@@ -160,7 +160,7 @@ void Fade::updateRandomSquareFade() {
// Comprueba si ha terminado // Comprueba si ha terminado
if (counter_ * fade_random_squares_mult_ / fade_random_squares_delay_ >= if (counter_ * fade_random_squares_mult_ / fade_random_squares_delay_ >=
num_squares_width_ * num_squares_height_) { num_squares_width_ * num_squares_height_) {
state_ = FadeState::POST; state_ = State::POST;
} }
} }
@@ -192,7 +192,7 @@ void Fade::updateVenetianFade() {
updateVenetianRectangles(); updateVenetianRectangles();
calculateVenetianProgress(); calculateVenetianProgress();
} else { } else {
state_ = FadeState::POST; state_ = State::POST;
} }
} }
@@ -233,30 +233,30 @@ void Fade::calculateVenetianProgress() {
// Activa el fade // Activa el fade
void Fade::activate() { void Fade::activate() {
// Si ya está habilitado, no hay que volverlo a activar // Si ya está habilitado, no hay que volverlo a activar
if (state_ != FadeState::NOT_ENABLED) { if (state_ != State::NOT_ENABLED) {
return; return;
} }
state_ = FadeState::PRE; state_ = State::PRE;
counter_ = 0; counter_ = 0;
post_counter_ = 0; post_counter_ = 0;
pre_counter_ = 0; pre_counter_ = 0;
switch (type_) { switch (type_) {
case FadeType::FULLSCREEN: { case Type::FULLSCREEN: {
// Pinta el backbuffer_ de color sólido // Pinta el backbuffer_ de color sólido
cleanBackbuffer(r_, g_, b_, 255); cleanBackbuffer(r_, g_, b_, 255);
break; break;
} }
case FadeType::CENTER: { case Type::CENTER: {
rect1_ = {0, 0, param.game.width, 0}; rect1_ = {0, 0, param.game.width, 0};
rect2_ = {0, 0, param.game.width, 0}; rect2_ = {0, 0, param.game.width, 0};
a_ = 64; a_ = 64;
break; break;
} }
case FadeType::RANDOM_SQUARE: { case Type::RANDOM_SQUARE: {
rect1_ = {0, 0, static_cast<float>(param.game.width / num_squares_width_), static_cast<float>(param.game.height / num_squares_height_)}; rect1_ = {0, 0, static_cast<float>(param.game.width / num_squares_width_), static_cast<float>(param.game.height / num_squares_height_)};
square_.clear(); square_.clear();
@@ -278,22 +278,22 @@ void Fade::activate() {
} }
// Limpia la textura // Limpia la textura
a_ = mode_ == FadeMode::OUT ? 0 : 255; a_ = mode_ == Mode::OUT ? 0 : 255;
cleanBackbuffer(r_, g_, b_, a_); cleanBackbuffer(r_, g_, b_, a_);
// Deja el color listo para usar // Deja el color listo para usar
a_ = mode_ == FadeMode::OUT ? 255 : 0; a_ = mode_ == Mode::OUT ? 255 : 0;
break; break;
} }
case FadeType::VENETIAN: { case Type::VENETIAN: {
// Limpia la textura // Limpia la textura
a_ = mode_ == FadeMode::OUT ? 0 : 255; a_ = mode_ == Mode::OUT ? 0 : 255;
cleanBackbuffer(r_, g_, b_, a_); cleanBackbuffer(r_, g_, b_, a_);
// Deja el color listo para usar // Deja el color listo para usar
a_ = mode_ == FadeMode::OUT ? 255 : 0; a_ = mode_ == Mode::OUT ? 255 : 0;
// Añade los cuadrados al vector // Añade los cuadrados al vector
square_.clear(); square_.clear();

View File

@@ -6,30 +6,30 @@
struct Color; struct Color;
// --- Enums ---
enum class FadeType : Uint8 {
FULLSCREEN = 0, // Fundido de pantalla completa
CENTER = 1, // Fundido desde el centro
RANDOM_SQUARE = 2, // Fundido con cuadrados aleatorios
VENETIAN = 3, // Fundido tipo persiana veneciana
};
enum class FadeMode : Uint8 {
IN = 0, // Fundido de entrada
OUT = 1, // Fundido de salida
};
enum class FadeState : Uint8 {
NOT_ENABLED = 0, // No activado
PRE = 1, // Estado previo
FADING = 2, // Fundiendo
POST = 3, // Estado posterior
FINISHED = 4, // Finalizado
};
// --- Clase Fade: gestor de transiciones de fundido --- // --- Clase Fade: gestor de transiciones de fundido ---
class Fade { class Fade {
public: public:
// --- Enums ---
enum class Type : Uint8 {
FULLSCREEN = 0, // Fundido de pantalla completa
CENTER = 1, // Fundido desde el centro
RANDOM_SQUARE = 2, // Fundido con cuadrados aleatorios
VENETIAN = 3, // Fundido tipo persiana veneciana
};
enum class Mode : Uint8 {
IN = 0, // Fundido de entrada
OUT = 1, // Fundido de salida
};
enum class State : Uint8 {
NOT_ENABLED = 0, // No activado
PRE = 1, // Estado previo
FADING = 2, // Fundiendo
POST = 3, // Estado posterior
FINISHED = 4, // Finalizado
};
// --- Constructores y destructor --- // --- Constructores y destructor ---
Fade(); Fade();
~Fade(); ~Fade();
@@ -41,17 +41,17 @@ class Fade {
void activate(); // Activa el fade void activate(); // Activa el fade
// --- Configuración --- // --- Configuración ---
void setColor(Uint8 r, Uint8 g, Uint8 b); // Establece el color RGB del fade void setColor(Uint8 r, Uint8 g, Uint8 b); // Establece el color RGB del fade
void setColor(Color color); // Establece el color del fade void setColor(Color color); // Establece el color del fade
void setType(FadeType type) { type_ = type; } // Establece el tipo de fade void setType(Type type) { type_ = type; } // Establece el tipo de fade
void setMode(FadeMode mode) { mode_ = mode; } // Establece el modo de fade void setMode(Mode mode) { mode_ = mode; } // Establece el modo de fade
void setPostDuration(int value) { post_duration_ = value; } // Duración posterior al fade void setPostDuration(int value) { post_duration_ = value; } // Duración posterior al fade
void setPreDuration(int value) { pre_duration_ = value; } // Duración previa al fade void setPreDuration(int value) { pre_duration_ = value; } // Duración previa al fade
// --- Getters --- // --- Getters ---
[[nodiscard]] auto getValue() const -> int { return value_; } [[nodiscard]] auto getValue() const -> int { return value_; }
[[nodiscard]] auto isEnabled() const -> bool { return state_ != FadeState::NOT_ENABLED; } [[nodiscard]] auto isEnabled() const -> bool { return state_ != State::NOT_ENABLED; }
[[nodiscard]] auto hasEnded() const -> bool { return state_ == FadeState::FINISHED; } [[nodiscard]] auto hasEnded() const -> bool { return state_ == State::FINISHED; }
private: private:
// --- Objetos y punteros --- // --- Objetos y punteros ---
@@ -59,22 +59,22 @@ class Fade {
SDL_Texture *backbuffer_; // Backbuffer para efectos SDL_Texture *backbuffer_; // Backbuffer para efectos
// --- Variables de estado --- // --- Variables de estado ---
std::vector<SDL_FRect> square_; // Vector de cuadrados std::vector<SDL_FRect> square_; // Vector de cuadrados
SDL_FRect rect1_, rect2_; // Rectángulos para efectos SDL_FRect rect1_, rect2_; // Rectángulos para efectos
FadeType type_; // Tipo de fade Type type_; // Tipo de fade
FadeMode mode_; // Modo de fade Mode mode_; // Modo de fade
FadeState state_ = FadeState::NOT_ENABLED; // Estado actual State state_ = State::NOT_ENABLED; // Estado actual
Uint16 counter_; // Contador interno Uint16 counter_; // Contador interno
Uint8 r_, g_, b_, a_; // Color del fade (RGBA) Uint8 r_, g_, b_, a_; // Color del fade (RGBA)
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 fade_random_squares_delay_; // Delay entre cuadrados int fade_random_squares_delay_; // Delay entre cuadrados
int fade_random_squares_mult_; // Cuadrados por paso int fade_random_squares_mult_; // Cuadrados por paso
int post_duration_ = 0; // Duración posterior int post_duration_ = 0; // Duración posterior
int post_counter_ = 0; // Contador posterior int post_counter_ = 0; // Contador posterior
int pre_duration_ = 0; // Duración previa int pre_duration_ = 0; // Duración previa
int pre_counter_ = 0; // Contador previo int pre_counter_ = 0; // Contador previo
int value_ = 0; // Estado del fade (0-100) int value_ = 0; // Estado del fade (0-100)
// --- Inicialización y limpieza --- // --- Inicialización y limpieza ---
void init(); // Inicializa variables void init(); // Inicializa variables

View File

@@ -145,7 +145,7 @@ auto checkServiceButton() -> bool {
} }
// Mandos // Mandos
for (auto gamepad : Input::get()->getGamepads()) { for (const auto& gamepad : Input::get()->getGamepads()) {
if (Input::get()->checkAction(Input::Action::SERVICE, Input::DO_NOT_ALLOW_REPEAT, Input::DO_NOT_CHECK_KEYBOARD, gamepad)) { if (Input::get()->checkAction(Input::Action::SERVICE, Input::DO_NOT_ALLOW_REPEAT, Input::DO_NOT_CHECK_KEYBOARD, gamepad)) {
toggleServiceMenu(); toggleServiceMenu();
return true; return true;

View File

@@ -12,7 +12,7 @@ struct Hit {
public: public:
// --- Constructor --- // --- Constructor ---
Hit() = delete; // Elimina el constructor por defecto para obligar a pasar una textura Hit() = delete; // Elimina el constructor por defecto para obligar a pasar una textura
explicit Hit(std::shared_ptr<Texture> texture) // Constructor con textura obligatoria explicit Hit(const std::shared_ptr<Texture>& texture) // Constructor con textura obligatoria
: sprite_(std::make_unique<Sprite>(texture)) {} : sprite_(std::make_unique<Sprite>(texture)) {}
// --- Métodos principales --- // --- Métodos principales ---

View File

@@ -36,21 +36,21 @@ void Input::bindKey(Action action, SDL_Scancode code) {
} }
// Asigna inputs a botones del mando // Asigna inputs a botones del mando
void Input::bindGameControllerButton(std::shared_ptr<Gamepad> gamepad, Action action, SDL_GamepadButton button) { void Input::bindGameControllerButton(const std::shared_ptr<Gamepad> &gamepad, Action action, SDL_GamepadButton button) {
if (gamepad != nullptr) { if (gamepad != nullptr) {
gamepad->bindings[action].button = button; gamepad->bindings[action].button = button;
} }
} }
// Asigna inputs a botones del mando // Asigna inputs a botones del mando
void Input::bindGameControllerButton(std::shared_ptr<Gamepad> gamepad, Action action_target, Action action_source) { void Input::bindGameControllerButton(const std::shared_ptr<Gamepad> &gamepad, Action action_target, Action action_source) {
if (gamepad != nullptr) { if (gamepad != nullptr) {
gamepad->bindings[action_target].button = gamepad->bindings[action_source].button; gamepad->bindings[action_target].button = gamepad->bindings[action_source].button;
} }
} }
// Comprueba si alguna acción está activa // Comprueba si alguna acción está activa
auto Input::checkAction(Action action, bool repeat, bool check_keyboard, std::shared_ptr<Gamepad> gamepad) -> bool { auto Input::checkAction(Action action, bool repeat, bool check_keyboard, const std::shared_ptr<Gamepad> &gamepad) -> bool {
bool success_keyboard = false; bool success_keyboard = false;
bool success_controller = false; bool success_controller = false;
@@ -82,7 +82,7 @@ auto Input::checkAction(Action action, bool repeat, bool check_keyboard, std::sh
} }
// Comprueba si hay almenos una acción activa // Comprueba si hay almenos una acción activa
auto Input::checkAnyInput(bool check_keyboard, std::shared_ptr<Gamepad> gamepad) -> bool { auto Input::checkAnyInput(bool check_keyboard, const std::shared_ptr<Gamepad> &gamepad) -> bool {
// Obtenemos el número total de acciones posibles para iterar sobre ellas. // Obtenemos el número total de acciones posibles para iterar sobre ellas.
// --- Comprobación del Teclado --- // --- Comprobación del Teclado ---
@@ -122,7 +122,7 @@ auto Input::checkAnyButton(bool repeat) -> bool {
} }
// Comprueba los mandos // Comprueba los mandos
for (auto gamepad : gamepads_) { for (const auto &gamepad : gamepads_) {
if (checkAction(bi, repeat, DO_NOT_CHECK_KEYBOARD, gamepad)) { if (checkAction(bi, repeat, DO_NOT_CHECK_KEYBOARD, gamepad)) {
return true; return true;
} }
@@ -136,7 +136,8 @@ auto Input::checkAnyButton(bool repeat) -> bool {
auto Input::gameControllerFound() const -> bool { return !gamepads_.empty(); } auto Input::gameControllerFound() const -> bool { return !gamepads_.empty(); }
// Obten el nombre de un mando de juego // Obten el nombre de un mando de juego
auto Input::getControllerName(std::shared_ptr<Gamepad> gamepad) -> std::string { return gamepad == nullptr ? std::string() : gamepad->name; } auto Input::getControllerName(const std::shared_ptr<Gamepad> &gamepad) -> std::string {
return gamepad == nullptr ? std::string() : gamepad->name; }
// Obtiene la lista de nombres de mandos // Obtiene la lista de nombres de mandos
auto Input::getControllerNames() const -> std::vector<std::string> { auto Input::getControllerNames() const -> std::vector<std::string> {
@@ -170,7 +171,7 @@ auto Input::getGamepadByName(const std::string &name) const -> std::shared_ptr<I
} }
// Obtiene el SDL_GamepadButton asignado a un action // Obtiene el SDL_GamepadButton asignado a un action
auto Input::getControllerBinding(std::shared_ptr<Gamepad> gamepad, Action action) -> SDL_GamepadButton { auto Input::getControllerBinding(const std::shared_ptr<Gamepad> &gamepad, Action action) -> SDL_GamepadButton {
return gamepad->bindings[action].button; return gamepad->bindings[action].button;
} }
@@ -206,7 +207,7 @@ auto Input::stringToInput(const std::string &name) -> Action {
} }
// Comprueba el eje del mando // Comprueba el eje del mando
auto Input::checkAxisInput(Action action, std::shared_ptr<Gamepad> gamepad, bool repeat) -> bool { auto Input::checkAxisInput(Action action, const std::shared_ptr<Gamepad> &gamepad, bool repeat) -> bool {
// Umbral para considerar el eje como activo // Umbral para considerar el eje como activo
bool axis_active_now = false; bool axis_active_now = false;
@@ -248,7 +249,7 @@ auto Input::checkAxisInput(Action action, std::shared_ptr<Gamepad> gamepad, bool
} }
// Comprueba los triggers del mando como botones digitales // Comprueba los triggers del mando como botones digitales
auto Input::checkTriggerInput(Action action, std::shared_ptr<Gamepad> gamepad, bool repeat) -> bool { auto Input::checkTriggerInput(Action action, const std::shared_ptr<Gamepad> &gamepad, bool repeat) -> bool {
// Solo manejamos botones específicos que pueden ser triggers // Solo manejamos botones específicos que pueden ser triggers
if (gamepad->bindings[action].button != SDL_GAMEPAD_BUTTON_INVALID) { if (gamepad->bindings[action].button != SDL_GAMEPAD_BUTTON_INVALID) {
// Solo procesamos L2 y R2 como triggers // Solo procesamos L2 y R2 como triggers
@@ -297,7 +298,7 @@ auto Input::checkTriggerInput(Action action, std::shared_ptr<Gamepad> gamepad, b
void Input::addGamepadMappingsFromFile() { void Input::addGamepadMappingsFromFile() {
if (SDL_AddGamepadMappingsFromFile(gamepad_mappings_file_.c_str()) < 0) { if (SDL_AddGamepadMappingsFromFile(gamepad_mappings_file_.c_str()) < 0) {
std::cout << "Error, could not load " << gamepad_mappings_file_.c_str() << " file: " << SDL_GetError() << std::endl; std::cout << "Error, could not load " << gamepad_mappings_file_.c_str() << " file: " << SDL_GetError() << '\n';
} }
} }
@@ -350,7 +351,7 @@ void Input::update() {
} }
// --- MANDOS --- // --- MANDOS ---
for (auto gamepad : gamepads_) { for (const auto &gamepad : gamepads_) {
for (auto &binding : gamepad->bindings) { for (auto &binding : gamepad->bindings) {
bool button_is_down_now = static_cast<int>(SDL_GetGamepadButton(gamepad->pad, binding.second.button)) != 0; bool button_is_down_now = static_cast<int>(SDL_GetGamepadButton(gamepad->pad, binding.second.button)) != 0;
@@ -374,13 +375,13 @@ auto Input::handleEvent(const SDL_Event &event) -> std::string {
auto Input::addGamepad(int device_index) -> std::string { auto Input::addGamepad(int device_index) -> std::string {
SDL_Gamepad *pad = SDL_OpenGamepad(device_index); SDL_Gamepad *pad = SDL_OpenGamepad(device_index);
if (pad == nullptr) { if (pad == nullptr) {
std::cerr << "Error al abrir el gamepad: " << SDL_GetError() << std::endl; std::cerr << "Error al abrir el gamepad: " << SDL_GetError() << '\n';
return {}; return {};
} }
auto gamepad = std::make_shared<Gamepad>(pad); auto gamepad = std::make_shared<Gamepad>(pad);
auto name = gamepad->name; auto name = gamepad->name;
std::cout << "Gamepad connected (" << name << ")" << std::endl; std::cout << "Gamepad connected (" << name << ")" << '\n';
applyGamepadConfig(gamepad); applyGamepadConfig(gamepad);
saveGamepadConfigFromGamepad(gamepad); saveGamepadConfigFromGamepad(gamepad);
gamepads_.push_back(std::move(gamepad)); gamepads_.push_back(std::move(gamepad));
@@ -394,17 +395,17 @@ auto Input::removeGamepad(SDL_JoystickID id) -> std::string {
if (it != gamepads_.end()) { if (it != gamepads_.end()) {
std::string name = (*it)->name; std::string name = (*it)->name;
std::cout << "Gamepad disconnected (" << name << ")" << std::endl; std::cout << "Gamepad disconnected (" << name << ")" << '\n';
gamepads_.erase(it); gamepads_.erase(it);
return name + " DISCONNECTED"; return name + " DISCONNECTED";
} }
std::cerr << "No se encontró el gamepad con ID " << id << std::endl; std::cerr << "No se encontró el gamepad con ID " << id << '\n';
return {}; return {};
} }
void Input::printConnectedGamepads() const { void Input::printConnectedGamepads() const {
if (gamepads_.empty()) { if (gamepads_.empty()) {
std::cout << "No hay gamepads conectados." << std::endl; std::cout << "No hay gamepads conectados." << '\n';
return; return;
} }
@@ -412,7 +413,7 @@ void Input::printConnectedGamepads() const {
for (const auto &gamepad : gamepads_) { for (const auto &gamepad : gamepads_) {
std::string name = gamepad->name.empty() ? "Desconocido" : gamepad->name; std::string name = gamepad->name.empty() ? "Desconocido" : gamepad->name;
std::cout << " - ID: " << gamepad->instance_id std::cout << " - ID: " << gamepad->instance_id
<< ", Nombre: " << name << ")" << std::endl; << ", Nombre: " << name << ")" << '\n';
} }
} }
@@ -438,7 +439,7 @@ void Input::applyGamepadConfig(std::shared_ptr<Gamepad> gamepad) {
if (config_it != gamepad_configs_.end()) { if (config_it != gamepad_configs_.end()) {
// 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 << std::endl; 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.find(action) != gamepad->bindings.end()) {
gamepad->bindings[action].button = button; gamepad->bindings[action].button = button;

View File

@@ -144,18 +144,18 @@ class Input {
// --- Métodos de configuración de controles --- // --- Métodos de configuración de controles ---
void bindKey(Action action, SDL_Scancode code); void bindKey(Action action, SDL_Scancode code);
static void bindGameControllerButton(std::shared_ptr<Gamepad> gamepad, Action action, SDL_GamepadButton button); static void bindGameControllerButton(const std::shared_ptr<Gamepad> &gamepad, Action action, SDL_GamepadButton button);
static void bindGameControllerButton(std::shared_ptr<Gamepad> gamepad, Action action_target, Action action_source); static void bindGameControllerButton(const std::shared_ptr<Gamepad> &gamepad, Action action_target, Action action_source);
// --- Métodos de consulta de entrada --- // --- Métodos de consulta de entrada ---
void update(); void update();
auto checkAction(Action action, bool repeat = true, bool check_keyboard = true, std::shared_ptr<Gamepad> gamepad = nullptr) -> bool; auto checkAction(Action action, bool repeat = true, bool check_keyboard = true, const std::shared_ptr<Gamepad> &gamepad = nullptr) -> bool;
auto checkAnyInput(bool check_keyboard = true, std::shared_ptr<Gamepad> gamepad = nullptr) -> bool; auto checkAnyInput(bool check_keyboard = true, const std::shared_ptr<Gamepad> &gamepad = nullptr) -> bool;
auto checkAnyButton(bool repeat = DO_NOT_ALLOW_REPEAT) -> bool; auto checkAnyButton(bool repeat = DO_NOT_ALLOW_REPEAT) -> bool;
// --- 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(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>; 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>; auto getGamepad(SDL_JoystickID id) const -> std::shared_ptr<Gamepad>;
@@ -163,7 +163,7 @@ class Input {
auto getGamepads() const -> const Gamepads & { return gamepads_; } auto getGamepads() const -> const Gamepads & { return gamepads_; }
// --- Métodos de consulta y utilidades --- // --- Métodos de consulta y utilidades ---
[[nodiscard]] static auto getControllerBinding(std::shared_ptr<Gamepad> gamepad, Action action) -> SDL_GamepadButton; [[nodiscard]] static auto getControllerBinding(const std::shared_ptr<Gamepad> &gamepad, Action action) -> SDL_GamepadButton;
[[nodiscard]] static auto inputToString(Action action) -> std::string; [[nodiscard]] static auto inputToString(Action action) -> std::string;
[[nodiscard]] static auto stringToInput(const std::string &name) -> Action; [[nodiscard]] static auto stringToInput(const std::string &name) -> Action;
@@ -193,8 +193,8 @@ class Input {
// --- Métodos internos --- // --- Métodos internos ---
void initSDLGamePad(); void initSDLGamePad();
static auto checkAxisInput(Action action, std::shared_ptr<Gamepad> gamepad, bool repeat) -> bool; static auto checkAxisInput(Action action, const std::shared_ptr<Gamepad> &gamepad, bool repeat) -> bool;
static auto checkTriggerInput(Action action, std::shared_ptr<Gamepad> gamepad, bool repeat) -> bool; static auto checkTriggerInput(Action action, const std::shared_ptr<Gamepad> &gamepad, bool repeat) -> bool;
auto addGamepad(int device_index) -> std::string; auto addGamepad(int device_index) -> std::string;
auto removeGamepad(SDL_JoystickID id) -> std::string; auto removeGamepad(SDL_JoystickID id) -> std::string;
void addGamepadMappingsFromFile(); void addGamepadMappingsFromFile();

View File

@@ -8,7 +8,7 @@
class Texture; // lines 6-6 class Texture; // lines 6-6
Item::Item(ItemType type, float x, float y, SDL_FRect &play_area, std::shared_ptr<Texture> texture, const std::vector<std::string> &animation) Item::Item(ItemType type, float x, float y, SDL_FRect &play_area, const std::shared_ptr<Texture> &texture, const std::vector<std::string> &animation)
: sprite_(std::make_unique<AnimatedSprite>(texture, animation)), : sprite_(std::make_unique<AnimatedSprite>(texture, animation)),
play_area_(play_area), play_area_(play_area),
type_(type) { type_(type) {

View File

@@ -31,7 +31,7 @@ class Item {
static constexpr int COFFEE_MACHINE_HEIGHT = 39; // Altura de la máquina de café static constexpr int COFFEE_MACHINE_HEIGHT = 39; // Altura de la máquina de café
// --- Constructor y destructor --- // --- Constructor y destructor ---
Item(ItemType type, float x, float y, SDL_FRect &play_area, std::shared_ptr<Texture> texture, const std::vector<std::string> &animation); // Constructor principal Item(ItemType type, float x, float y, SDL_FRect &play_area, const std::shared_ptr<Texture> &texture, const std::vector<std::string> &animation); // Constructor principal
~Item() = default; // Destructor ~Item() = default; // Destructor
// --- Métodos principales --- // --- Métodos principales ---

View File

@@ -1,10 +1,12 @@
#include "moving_sprite.h" #include "moving_sprite.h"
#include <utility>
#include "texture.h" // Para Texture #include "texture.h" // Para Texture
// Constructor // Constructor
MovingSprite::MovingSprite(std::shared_ptr<Texture> texture, SDL_FRect pos, Rotate rotate, float horizontal_zoom, float vertical_zoom, SDL_FlipMode flip) MovingSprite::MovingSprite(std::shared_ptr<Texture> texture, SDL_FRect pos, Rotate rotate, float horizontal_zoom, float vertical_zoom, SDL_FlipMode flip)
: Sprite(texture, pos), : Sprite(std::move(texture), pos),
rotate_(rotate), rotate_(rotate),
flip_(flip), flip_(flip),
x_(pos.x), x_(pos.x),
@@ -13,7 +15,7 @@ MovingSprite::MovingSprite(std::shared_ptr<Texture> texture, SDL_FRect pos, Rota
vertical_zoom_(vertical_zoom) {} vertical_zoom_(vertical_zoom) {}
MovingSprite::MovingSprite(std::shared_ptr<Texture> texture, SDL_FRect pos) MovingSprite::MovingSprite(std::shared_ptr<Texture> texture, SDL_FRect pos)
: Sprite(texture, pos), : Sprite(std::move(texture), pos),
flip_(SDL_FLIP_NONE), flip_(SDL_FLIP_NONE),
x_(pos.x), x_(pos.x),
y_(pos.y), y_(pos.y),
@@ -21,7 +23,7 @@ MovingSprite::MovingSprite(std::shared_ptr<Texture> texture, SDL_FRect pos)
vertical_zoom_(1.0F) {} vertical_zoom_(1.0F) {}
MovingSprite::MovingSprite(std::shared_ptr<Texture> texture) MovingSprite::MovingSprite(std::shared_ptr<Texture> texture)
: Sprite(texture), : Sprite(std::move(texture)),
flip_(SDL_FLIP_NONE), flip_(SDL_FLIP_NONE),
horizontal_zoom_(1.0F), horizontal_zoom_(1.0F),
vertical_zoom_(1.0F) { Sprite::clear(); } vertical_zoom_(1.0F) { Sprite::clear(); }

View File

@@ -65,7 +65,7 @@ auto loadFromFile() -> bool {
std::string line; std::string line;
while (std::getline(file, line)) { while (std::getline(file, line)) {
if (line.substr(0, 1) != "#") { if (line.substr(0, 1) != "#") {
int pos = line.find("="); int pos = line.find('=');
if (!set(line.substr(0, pos), line.substr(pos + 1, line.length()))) { if (!set(line.substr(0, pos), line.substr(pos + 1, line.length()))) {
SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION, "Unknown parameter: %s", line.substr(0, pos).c_str()); SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION, "Unknown parameter: %s", line.substr(0, pos).c_str());
} }
@@ -413,7 +413,7 @@ auto playerIdToString(Player::Id player_id) -> std::string {
} }
// Convierte un texto a player id segun Lang // Convierte un texto a player id segun Lang
auto stringToPlayerId(std::string name) -> Player::Id { auto stringToPlayerId(const std::string& name) -> Player::Id {
if (name == Lang::getText("[SERVICE_MENU] PLAYER1")) { if (name == Lang::getText("[SERVICE_MENU] PLAYER1")) {
return Player::Id::PLAYER1; return Player::Id::PLAYER1;
} }

View File

@@ -11,7 +11,8 @@
#include <stdexcept> // Para out_of_range, invalid_argument #include <stdexcept> // Para out_of_range, invalid_argument
#include <string> // Para char_traits, string, allocator, operator==, swap, operator<<, basic_string, stoi #include <string> // Para char_traits, string, allocator, operator==, swap, operator<<, basic_string, stoi
#include <string_view> // Para string_view #include <string_view> // Para string_view
#include <vector> // Para vector #include <utility>
#include <vector> // Para vector
#include "difficulty.h" // Para Code #include "difficulty.h" // Para Code
#include "input.h" // Para Input #include "input.h" // Para Input
@@ -139,7 +140,7 @@ class GamepadManager {
const std::string& name) -> bool { const std::string& name) -> bool {
try { try {
auto& gamepad = getGamepad(player_id); auto& gamepad = getGamepad(player_id);
gamepad.instance = instance; gamepad.instance = std::move(instance);
gamepad.name = name; gamepad.name = name;
return true; return true;
} catch (const std::exception&) { } catch (const std::exception&) {
@@ -156,7 +157,7 @@ class GamepadManager {
} }
void resyncGamepadsWithPlayers() { void resyncGamepadsWithPlayers() {
for (auto player : players_) { for (const auto& player : players_) {
switch (player->getId()) { switch (player->getId()) {
case Player::Id::PLAYER1: case Player::Id::PLAYER1:
player->setGamepad(gamepads_[0].instance); player->setGamepad(gamepads_[0].instance);
@@ -221,11 +222,11 @@ class GamepadManager {
return false; return false;
} }
void addPlayer(std::shared_ptr<Player> player) { players_.push_back(player); } // Añade un jugador a la lista void addPlayer(const std::shared_ptr<Player>& player) { players_.push_back(player); } // Añade un jugador a la lista
void clearPlayers() { players_.clear(); } // Limpia la lista de jugadores void clearPlayers() { players_.clear(); } // Limpia la lista de jugadores
// Asigna el mando a un jugador // Asigna el mando a un jugador
void assignTo(Input::Gamepad gamepad, Player::Id player_id) { void assignTo(const Input::Gamepad& gamepad, Player::Id player_id) {
} }
// Asigna los mandos físicos basándose en la configuración actual de nombres. // Asigna los mandos físicos basándose en la configuración actual de nombres.
@@ -274,7 +275,7 @@ struct Keyboard {
Player::Id player_id = Player::Id::PLAYER1; // Jugador asociado al teclado Player::Id player_id = Player::Id::PLAYER1; // Jugador asociado al teclado
std::vector<std::shared_ptr<Player>> players; // Punteros a los jugadores std::vector<std::shared_ptr<Player>> players; // Punteros a los jugadores
void addPlayer(std::shared_ptr<Player> player) { players.push_back(player); } // Añade un jugador a la lista void addPlayer(const std::shared_ptr<Player>& player) { players.push_back(player); } // Añade un jugador a la lista
void clearPlayers() { players.clear(); } // Limpia la lista de jugadores void clearPlayers() { players.clear(); } // Limpia la lista de jugadores
// Asigna el teclado a un jugador // Asigna el teclado a un jugador
@@ -315,7 +316,7 @@ void swapKeyboard();
void swapControllers(); // Intercambia los jugadores asignados a los dos primeros mandos void swapControllers(); // Intercambia los jugadores asignados a los dos primeros mandos
auto getPlayerWhoUsesKeyboard() -> Player::Id; // Averigua quién está usando el teclado auto getPlayerWhoUsesKeyboard() -> Player::Id; // Averigua quién está usando el teclado
auto playerIdToString(Player::Id player_id) -> std::string; // Convierte un player id a texto segun Lang auto playerIdToString(Player::Id player_id) -> std::string; // Convierte un player id a texto segun Lang
auto stringToPlayerId(std::string name) -> Player::Id; // Convierte un texto a player id segun Lang auto stringToPlayerId(const std::string& name) -> Player::Id; // Convierte un texto a player id segun Lang
void applyPendingChanges(); // Aplica los cambios pendientes copiando los valores a sus variables void applyPendingChanges(); // Aplica los cambios pendientes copiando los valores a sus variables
void checkPendingChanges(); // Verifica si hay cambios pendientes void checkPendingChanges(); // Verifica si hay cambios pendientes
auto assignGamepadByName(const std::string& gamepad_name, Player::Id player_id) -> bool; // Buscar y asignar un mando disponible por nombre auto assignGamepadByName(const std::string& gamepad_name, Player::Id player_id) -> bool; // Buscar y asignar un mando disponible por nombre

View File

@@ -56,7 +56,7 @@ struct ParamBalloon {
float vel; float vel;
// Constructor por defecto // Constructor por defecto
constexpr Settings(float grav_val = 0.0f, float vel_val = 0.0f) constexpr Settings(float grav_val = 0.0F, float vel_val = 0.0F)
: grav(grav_val), vel(vel_val) {} : grav(grav_val), vel(vel_val) {}
}; };

View File

@@ -83,7 +83,7 @@ void PathSprite::addPath(int start, int end, PathType type, int fixed_pos, int s
} }
// Añade un recorrido // Añade un recorrido
void PathSprite::addPath(std::vector<SDL_FPoint> spots, int waiting_counter) { void PathSprite::addPath(const std::vector<SDL_FPoint> &spots, int waiting_counter) {
paths_.emplace_back(std::move(spots), waiting_counter); paths_.emplace_back(std::move(spots), waiting_counter);
} }

View File

@@ -4,7 +4,8 @@
#include <functional> // Para std::function #include <functional> // Para std::function
#include <memory> // Para shared_ptr #include <memory> // Para shared_ptr
#include <vector> // Para vector #include <utility>
#include <vector> // Para vector
#include "sprite.h" // Para Sprite #include "sprite.h" // Para Sprite
@@ -43,7 +44,7 @@ class PathSprite : public Sprite {
public: public:
// --- Constructor y destructor --- // --- Constructor y destructor ---
explicit PathSprite(std::shared_ptr<Texture> texture) explicit PathSprite(std::shared_ptr<Texture> texture)
: Sprite(texture) {} : Sprite(std::move(texture)) {}
~PathSprite() override = default; ~PathSprite() override = default;
// --- Métodos principales --- // --- Métodos principales ---
@@ -52,7 +53,7 @@ class PathSprite : public Sprite {
// --- Gestión de recorridos --- // --- Gestión de recorridos ---
void addPath(Path path, bool centered = false); // Añade un recorrido (Path) void addPath(Path path, bool centered = false); // Añade un recorrido (Path)
void addPath(std::vector<SDL_FPoint> spots, int waiting_counter = 0); // Añade un recorrido a partir de puntos void addPath(const std::vector<SDL_FPoint> &spots, int waiting_counter = 0); // Añade un recorrido a partir de puntos
void addPath(int start, int end, PathType type, int fixed_pos, int steps, const std::function<double(double)> &easing_function, int waiting_counter = 0); // Añade un recorrido generado void addPath(int start, int end, PathType type, int fixed_pos, int steps, const std::function<double(double)> &easing_function, int waiting_counter = 0); // Añade un recorrido generado
// --- Estado y control --- // --- Estado y control ---

View File

@@ -115,7 +115,7 @@ class PauseManager {
return result; return result;
} }
void setCallback(std::function<void(bool)> callback) { // Permite cambiar el callback en runtime void setCallback(std::function<void(bool)> callback) { // Permite cambiar el callback en runtime
on_pause_changed_callback_ = callback; on_pause_changed_callback_ = std::move(callback);
} }
private: private:

View File

@@ -186,7 +186,7 @@ class Player {
void setWalkingState(State state) { walking_state_ = state; } void setWalkingState(State state) { walking_state_ = state; }
void addCredit(); void addCredit();
void setGamepad(std::shared_ptr<Input::Gamepad> gamepad) { gamepad_ = gamepad; } void setGamepad(std::shared_ptr<Input::Gamepad> gamepad) { gamepad_ = std::move(gamepad); }
[[nodiscard]] auto getGamepad() const -> std::shared_ptr<Input::Gamepad> { return gamepad_; } [[nodiscard]] auto getGamepad() const -> std::shared_ptr<Input::Gamepad> { return gamepad_; }
void setUsesKeyboard(bool value) { uses_keyboard_ = value; } void setUsesKeyboard(bool value) { uses_keyboard_ = value; }
[[nodiscard]] auto getUsesKeyboard() const -> bool { return uses_keyboard_; } [[nodiscard]] auto getUsesKeyboard() const -> bool { return uses_keyboard_; }

View File

@@ -571,15 +571,15 @@ void Resource::createPlayerTextures() {
texture_copy->addPaletteFromPalFile(Asset::get()->get(player.palette_files[2])); texture_copy->addPaletteFromPalFile(Asset::get()->get(player.palette_files[2]));
// Añade los colores establecidos en param.player usando el índice del jugador (player_idx) // Añade los colores establecidos en param.player usando el índice del jugador (player_idx)
texture_copy->setPaletteColor(1, 16, param.player.one_coffee_shirt[player_idx].darkest.toUint32()); texture_copy->setPaletteColor(1, 16, param.player.one_coffee_shirt[player_idx].darkest.TO_UINT32());
texture_copy->setPaletteColor(1, 17, param.player.one_coffee_shirt[player_idx].dark.toUint32()); texture_copy->setPaletteColor(1, 17, param.player.one_coffee_shirt[player_idx].dark.TO_UINT32());
texture_copy->setPaletteColor(1, 18, param.player.one_coffee_shirt[player_idx].base.toUint32()); texture_copy->setPaletteColor(1, 18, param.player.one_coffee_shirt[player_idx].base.TO_UINT32());
texture_copy->setPaletteColor(1, 19, param.player.one_coffee_shirt[player_idx].light.toUint32()); texture_copy->setPaletteColor(1, 19, param.player.one_coffee_shirt[player_idx].light.TO_UINT32());
texture_copy->setPaletteColor(2, 16, param.player.two_coffee_shirt[player_idx].darkest.toUint32()); texture_copy->setPaletteColor(2, 16, param.player.two_coffee_shirt[player_idx].darkest.TO_UINT32());
texture_copy->setPaletteColor(2, 17, param.player.two_coffee_shirt[player_idx].dark.toUint32()); texture_copy->setPaletteColor(2, 17, param.player.two_coffee_shirt[player_idx].dark.TO_UINT32());
texture_copy->setPaletteColor(2, 18, param.player.two_coffee_shirt[player_idx].base.toUint32()); texture_copy->setPaletteColor(2, 18, param.player.two_coffee_shirt[player_idx].base.TO_UINT32());
texture_copy->setPaletteColor(2, 19, param.player.two_coffee_shirt[player_idx].light.toUint32()); texture_copy->setPaletteColor(2, 19, param.player.two_coffee_shirt[player_idx].light.TO_UINT32());
// Cambiar a la paleta específica (índice i+1 porque 0 es la original) // Cambiar a la paleta específica (índice i+1 porque 0 es la original)
texture_copy->setPalette(i + 1); texture_copy->setPalette(i + 1);

View File

@@ -39,8 +39,8 @@ Credits::Credits()
tiled_bg_(std::make_unique<TiledBG>(param.game.game_area.rect, TiledBGMode::DIAGONAL)), tiled_bg_(std::make_unique<TiledBG>(param.game.game_area.rect, TiledBGMode::DIAGONAL)),
fade_in_(std::make_unique<Fade>()), fade_in_(std::make_unique<Fade>()),
fade_out_(std::make_unique<Fade>()), fade_out_(std::make_unique<Fade>()),
text_texture_(SDL_CreateTexture(Screen::get()->getRenderer(), SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, param.game.width, param.game.height)), text_texture_(SDL_CreateTexture(Screen::get()->getRenderer(), SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, static_cast<int>(param.game.width), static_cast<int>(param.game.height))),
canvas_(SDL_CreateTexture(Screen::get()->getRenderer(), SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, param.game.width, param.game.height)) { canvas_(SDL_CreateTexture(Screen::get()->getRenderer(), SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, static_cast<int>(param.game.width), static_cast<int>(param.game.height))) {
if (text_texture_ == nullptr) { if (text_texture_ == nullptr) {
throw std::runtime_error("Failed to create SDL texture for text."); throw std::runtime_error("Failed to create SDL texture for text.");
} }
@@ -48,13 +48,13 @@ Credits::Credits()
balloon_manager_->setPlayArea(play_area_); balloon_manager_->setPlayArea(play_area_);
fade_in_->setColor(param.fade.color); fade_in_->setColor(param.fade.color);
fade_in_->setType(FadeType::FULLSCREEN); fade_in_->setType(Fade::Type::FULLSCREEN);
fade_in_->setPostDuration(50); fade_in_->setPostDuration(50);
fade_in_->setMode(FadeMode::IN); fade_in_->setMode(Fade::Mode::IN);
fade_in_->activate(); fade_in_->activate();
fade_out_->setColor(0, 0, 0); fade_out_->setColor(0, 0, 0);
fade_out_->setType(FadeType::FULLSCREEN); fade_out_->setType(Fade::Type::FULLSCREEN);
fade_out_->setPostDuration(400); fade_out_->setPostDuration(400);
updateRedRect(); updateRedRect();
@@ -63,7 +63,7 @@ Credits::Credits()
initPlayers(); initPlayers();
SDL_SetTextureBlendMode(text_texture_, SDL_BLENDMODE_BLEND); SDL_SetTextureBlendMode(text_texture_, SDL_BLENDMODE_BLEND);
fillTextTexture(); fillTextTexture();
steps_ = std::abs((top_black_rect_.h - param.game.game_area.center_y - 1) + ((left_black_rect_.w - param.game.game_area.center_x) / 4)); steps_ = static_cast<int>(std::abs((top_black_rect_.h - param.game.game_area.center_y - 1) + ((left_black_rect_.w - param.game.game_area.center_x) / 4)));
} }
// Destructor // Destructor
@@ -171,57 +171,59 @@ void Credits::fillTextTexture() {
const int SPACE_POST_TITLE = 3 + text->getCharacterSize(); const int SPACE_POST_TITLE = 3 + text->getCharacterSize();
const int SPACE_PRE_TITLE = text->getCharacterSize() * 4; const int SPACE_PRE_TITLE = text->getCharacterSize() * 4;
const int TEXTS_HEIGHT = 1 * text->getCharacterSize() + 8 * SPACE_POST_TITLE + 3 * SPACE_PRE_TITLE; const int TEXTS_HEIGHT = 1 * text->getCharacterSize() + 8 * SPACE_POST_TITLE + 3 * SPACE_PRE_TITLE;
credits_rect_dst_.h = credits_rect_src_.h = TEXTS_HEIGHT; const int POS_X = static_cast<int>(param.game.game_area.center_x);
credits_rect_dst_.h = credits_rect_src_.h = static_cast<float>(TEXTS_HEIGHT);
auto text_style = Text::Style(Text::CENTER | Text::SHADOW, NO_TEXT_COLOR, SHADOW_TEXT_COLOR);
// PROGRAMMED_AND_DESIGNED_BY // PROGRAMMED_AND_DESIGNED_BY
int y = 0; int y = 0;
text_grad->writeDX(Text::CENTER | Text::SHADOW, param.game.game_area.center_x, y, TEXTS.at(0), 1, NO_TEXT_COLOR, 1, SHADOW_TEXT_COLOR); text_grad->writeStyle(POS_X, y, TEXTS.at(0), text_style);
y += SPACE_POST_TITLE; y += SPACE_POST_TITLE;
text->writeDX(Text::CENTER | Text::SHADOW, param.game.game_area.center_x, y, TEXTS.at(4), 1, NO_TEXT_COLOR, 1, SHADOW_TEXT_COLOR); text->writeStyle(POS_X, y, TEXTS.at(4), text_style);
// PIXELART_DRAWN_BY // PIXELART_DRAWN_BY
y += SPACE_PRE_TITLE; y += SPACE_PRE_TITLE;
text_grad->writeDX(Text::CENTER | Text::SHADOW, param.game.game_area.center_x, y, TEXTS.at(1), 1, NO_TEXT_COLOR, 1, SHADOW_TEXT_COLOR); text_grad->writeStyle(POS_X, y, TEXTS.at(1), text_style);
y += SPACE_POST_TITLE; y += SPACE_POST_TITLE;
text->writeDX(Text::CENTER | Text::SHADOW, param.game.game_area.center_x, y, TEXTS.at(4), 1, NO_TEXT_COLOR, 1, SHADOW_TEXT_COLOR); text->writeStyle(POS_X, y, TEXTS.at(4), text_style);
// MUSIC_COMPOSED_BY // MUSIC_COMPOSED_BY
y += SPACE_PRE_TITLE; y += SPACE_PRE_TITLE;
text_grad->writeDX(Text::CENTER | Text::SHADOW, param.game.game_area.center_x, y, TEXTS.at(2), 1, NO_TEXT_COLOR, 1, SHADOW_TEXT_COLOR); text_grad->writeStyle(POS_X, y, TEXTS.at(2), text_style);
y += SPACE_POST_TITLE; y += SPACE_POST_TITLE;
text->writeDX(Text::CENTER | Text::SHADOW, param.game.game_area.center_x, y, TEXTS.at(5), 1, NO_TEXT_COLOR, 1, SHADOW_TEXT_COLOR); text->writeStyle(POS_X, y, TEXTS.at(5), text_style);
y += SPACE_POST_TITLE; y += SPACE_POST_TITLE;
text->writeDX(Text::CENTER | Text::SHADOW, param.game.game_area.center_x, y, TEXTS.at(6), 1, NO_TEXT_COLOR, 1, SHADOW_TEXT_COLOR); text->writeStyle(POS_X, y, TEXTS.at(6), text_style);
// SOUND_EFFECTS // SOUND_EFFECTS
y += SPACE_PRE_TITLE; y += SPACE_PRE_TITLE;
text_grad->writeDX(Text::CENTER | Text::SHADOW, param.game.game_area.center_x, y, TEXTS.at(3), 1, NO_TEXT_COLOR, 1, SHADOW_TEXT_COLOR); text_grad->writeStyle(POS_X, y, TEXTS.at(3), text_style);
y += SPACE_POST_TITLE; y += SPACE_POST_TITLE;
text->writeDX(Text::CENTER | Text::SHADOW, param.game.game_area.center_x, y, TEXTS.at(7), 1, NO_TEXT_COLOR, 1, SHADOW_TEXT_COLOR); text->writeStyle(POS_X, y, TEXTS.at(7), text_style);
y += SPACE_POST_TITLE; y += SPACE_POST_TITLE;
text->writeDX(Text::CENTER | Text::SHADOW, param.game.game_area.center_x, y, TEXTS.at(8), 1, NO_TEXT_COLOR, 1, SHADOW_TEXT_COLOR); text->writeStyle(POS_X, y, TEXTS.at(8), text_style);
y += SPACE_POST_TITLE; y += SPACE_POST_TITLE;
text->writeDX(Text::CENTER | Text::SHADOW, param.game.game_area.center_x, y, TEXTS.at(9), 1, NO_TEXT_COLOR, 1, SHADOW_TEXT_COLOR); text->writeStyle(POS_X, y, TEXTS.at(9), text_style);
y += SPACE_POST_TITLE; y += SPACE_POST_TITLE;
text->writeDX(Text::CENTER | Text::SHADOW, param.game.game_area.center_x, y, TEXTS.at(10), 1, NO_TEXT_COLOR, 1, SHADOW_TEXT_COLOR); text->writeStyle(POS_X, y, TEXTS.at(10), text_style);
// Mini logo // Mini logo
y += SPACE_PRE_TITLE; y += SPACE_PRE_TITLE;
mini_logo_rect_src_.y = y; mini_logo_rect_src_.y = static_cast<float>(y);
auto mini_logo_sprite = std::make_unique<Sprite>(Resource::get()->getTexture("logo_jailgames_mini.png")); auto mini_logo_sprite = std::make_unique<Sprite>(Resource::get()->getTexture("logo_jailgames_mini.png"));
mini_logo_sprite->setPosition(1 + param.game.game_area.center_x - mini_logo_sprite->getWidth() / 2, 1 + y); mini_logo_sprite->setPosition(1 + POS_X - mini_logo_sprite->getWidth() / 2, 1 + y);
Resource::get()->getTexture("logo_jailgames_mini.png")->setColor(SHADOW_TEXT_COLOR.r, SHADOW_TEXT_COLOR.g, SHADOW_TEXT_COLOR.b); Resource::get()->getTexture("logo_jailgames_mini.png")->setColor(SHADOW_TEXT_COLOR.r, SHADOW_TEXT_COLOR.g, SHADOW_TEXT_COLOR.b);
mini_logo_sprite->render(); mini_logo_sprite->render();
mini_logo_sprite->setPosition(param.game.game_area.center_x - mini_logo_sprite->getWidth() / 2, y); mini_logo_sprite->setPosition(POS_X - mini_logo_sprite->getWidth() / 2, y);
Resource::get()->getTexture("logo_jailgames_mini.png")->setColor(255, 255, 255); Resource::get()->getTexture("logo_jailgames_mini.png")->setColor(255, 255, 255);
mini_logo_sprite->render(); mini_logo_sprite->render();
// Texto con el copyright // Texto con el copyright
y += mini_logo_sprite->getHeight() + 3; y += mini_logo_sprite->getHeight() + 3;
text->writeDX(Text::CENTER | Text::SHADOW, param.game.game_area.center_x, y, std::string(TEXT_COPYRIGHT), 1, NO_TEXT_COLOR, 1, SHADOW_TEXT_COLOR); text->writeDX(Text::CENTER | Text::SHADOW, POS_X, y, std::string(TEXT_COPYRIGHT), 1, NO_TEXT_COLOR, 1, SHADOW_TEXT_COLOR);
// Resetea el renderizador // Resetea el renderizador
SDL_SetRenderTarget(Screen::get()->getRenderer(), nullptr); SDL_SetRenderTarget(Screen::get()->getRenderer(), nullptr);
@@ -384,7 +386,7 @@ void Credits::initPlayers() {
players_.back()->setPlayingState(Player::State::CREDITS); players_.back()->setPlayingState(Player::State::CREDITS);
// Registra los jugadores en Options // Registra los jugadores en Options
for (auto player : players_) { for (const auto &player : players_) {
Options::keyboard.addPlayer(player); Options::keyboard.addPlayer(player);
Options::gamepad_manager.addPlayer(player); Options::gamepad_manager.addPlayer(player);
} }

View File

@@ -81,13 +81,13 @@ Game::Game(Player::Id player_id, int current_stage, bool demo)
fade_in_->setColor(param.fade.color); fade_in_->setColor(param.fade.color);
fade_in_->setPreDuration(demo_.enabled ? 80 : 0); fade_in_->setPreDuration(demo_.enabled ? 80 : 0);
fade_in_->setPostDuration(0); fade_in_->setPostDuration(0);
fade_in_->setType(FadeType::RANDOM_SQUARE); fade_in_->setType(Fade::Type::RANDOM_SQUARE);
fade_in_->setMode(FadeMode::IN); fade_in_->setMode(Fade::Mode::IN);
fade_in_->activate(); fade_in_->activate();
fade_out_->setColor(param.fade.color); fade_out_->setColor(param.fade.color);
fade_out_->setPostDuration(param.fade.post_duration); fade_out_->setPostDuration(param.fade.post_duration);
fade_out_->setType(FadeType::VENETIAN); fade_out_->setType(Fade::Type::VENETIAN);
background_->setPos(param.game.play_area.rect); background_->setPos(param.game.play_area.rect);
@@ -230,7 +230,7 @@ void Game::updatePlayers() {
handlePlayerCollision(player, balloon); handlePlayerCollision(player, balloon);
if (demo_.enabled && allPlayersAreNotPlaying()) { if (demo_.enabled && allPlayersAreNotPlaying()) {
fade_out_->setType(FadeType::RANDOM_SQUARE); fade_out_->setType(Fade::Type::RANDOM_SQUARE);
fade_out_->activate(); fade_out_->activate();
} }
} }
@@ -549,7 +549,7 @@ void Game::checkBulletCollision() {
} }
// Maneja la colisión entre bala y Tabe // Maneja la colisión entre bala y Tabe
auto Game::checkBulletTabeCollision(std::shared_ptr<Bullet> bullet) -> bool { auto Game::checkBulletTabeCollision(const std::shared_ptr<Bullet> &bullet) -> bool {
if (!tabe_->isEnabled()) { if (!tabe_->isEnabled()) {
return false; return false;
} }
@@ -581,7 +581,7 @@ void Game::handleTabeHitEffects() {
} }
// Maneja la colisión entre bala y globos // Maneja la colisión entre bala y globos
auto Game::checkBulletBalloonCollision(std::shared_ptr<Bullet> bullet) -> bool { auto Game::checkBulletBalloonCollision(const std::shared_ptr<Bullet> &bullet) -> bool {
for (auto &balloon : balloon_manager_->getBalloons()) { for (auto &balloon : balloon_manager_->getBalloons()) {
if (!balloon->isEnabled() || balloon->isInvulnerable()) { if (!balloon->isEnabled() || balloon->isInvulnerable()) {
continue; continue;
@@ -598,7 +598,7 @@ auto Game::checkBulletBalloonCollision(std::shared_ptr<Bullet> bullet) -> bool {
} }
// Procesa el impacto en un globo // Procesa el impacto en un globo
void Game::processBalloonHit(std::shared_ptr<Bullet> bullet, std::shared_ptr<Balloon> balloon) { void Game::processBalloonHit(const std::shared_ptr<Bullet> &bullet, const std::shared_ptr<Balloon> &balloon) {
auto player = getPlayer(bullet->getOwner()); auto player = getPlayer(bullet->getOwner());
handleItemDrop(balloon, player); handleItemDrop(balloon, player);
@@ -608,7 +608,7 @@ void Game::processBalloonHit(std::shared_ptr<Bullet> bullet, std::shared_ptr<Bal
} }
// Maneja la caída de items cuando se destruye un globo // Maneja la caída de items cuando se destruye un globo
void Game::handleItemDrop(std::shared_ptr<Balloon> balloon, std::shared_ptr<Player> player) { void Game::handleItemDrop(const std::shared_ptr<Balloon> &balloon, const std::shared_ptr<Player> &player) {
const auto DROPPED_ITEM = dropItem(); const auto DROPPED_ITEM = dropItem();
if (DROPPED_ITEM == ItemType::NONE || demo_.recording) { if (DROPPED_ITEM == ItemType::NONE || demo_.recording) {
return; return;
@@ -623,9 +623,9 @@ void Game::handleItemDrop(std::shared_ptr<Balloon> balloon, std::shared_ptr<Play
} }
// Maneja la destrucción del globo y puntuación // Maneja la destrucción del globo y puntuación
void Game::handleBalloonDestruction(std::shared_ptr<Balloon> balloon, std::shared_ptr<Player> player) { void Game::handleBalloonDestruction(std::shared_ptr<Balloon> balloon, const std::shared_ptr<Player> &player) {
if (player->isPlaying()) { if (player->isPlaying()) {
auto const SCORE = balloon_manager_->popBalloon(balloon) * player->getScoreMultiplier() * difficulty_score_multiplier_; auto const SCORE = balloon_manager_->popBalloon(std::move(balloon)) * player->getScoreMultiplier() * difficulty_score_multiplier_;
player->addScore(SCORE, Options::settings.hi_score_table.back().score); player->addScore(SCORE, Options::settings.hi_score_table.back().score);
player->incScoreMultiplier(); player->incScoreMultiplier();
} }
@@ -758,7 +758,7 @@ void Game::freeItems() {
} }
// Crea un objeto PathSprite // Crea un objeto PathSprite
void Game::createItemText(int x, std::shared_ptr<Texture> texture) { void Game::createItemText(int x, const std::shared_ptr<Texture> &texture) {
path_sprites_.emplace_back(std::make_unique<PathSprite>(texture)); path_sprites_.emplace_back(std::make_unique<PathSprite>(texture));
const auto W = texture->getWidth(); const auto W = texture->getWidth();
@@ -781,7 +781,7 @@ void Game::createItemText(int x, std::shared_ptr<Texture> texture) {
} }
// Crea un objeto PathSprite // Crea un objeto PathSprite
void Game::createMessage(const std::vector<Path> &paths, std::shared_ptr<Texture> texture) { void Game::createMessage(const std::vector<Path> &paths, const std::shared_ptr<Texture> &texture) {
path_sprites_.emplace_back(std::make_unique<PathSprite>(texture)); path_sprites_.emplace_back(std::make_unique<PathSprite>(texture));
// Inicializa // Inicializa
@@ -1239,7 +1239,7 @@ void Game::checkInput() {
// Verifica si alguno de los controladores ha solicitado una pausa y actualiza el estado de pausa del juego. // Verifica si alguno de los controladores ha solicitado una pausa y actualiza el estado de pausa del juego.
void Game::checkPauseInput() { void Game::checkPauseInput() {
// Comprueba los mandos // Comprueba los mandos
for (auto gamepad : input_->getGamepads()) { for (const auto &gamepad : input_->getGamepads()) {
if (input_->checkAction(Input::Action::PAUSE, Input::DO_NOT_ALLOW_REPEAT, Input::DO_NOT_CHECK_KEYBOARD, gamepad)) { if (input_->checkAction(Input::Action::PAUSE, Input::DO_NOT_ALLOW_REPEAT, Input::DO_NOT_CHECK_KEYBOARD, gamepad)) {
pause_manager_->togglePlayerPause(); pause_manager_->togglePlayerPause();
return; return;
@@ -1616,7 +1616,7 @@ void Game::initPlayers(Player::Id player_id) {
} }
// Registra los jugadores en Options // Registra los jugadores en Options
for (auto player : players_) { for (const auto &player : players_) {
Options::keyboard.addPlayer(player); Options::keyboard.addPlayer(player);
Options::gamepad_manager.addPlayer(player); Options::gamepad_manager.addPlayer(player);
} }
@@ -1660,7 +1660,7 @@ void Game::updateDemo() {
// Activa el fundido antes de acabar con los datos de la demo // Activa el fundido antes de acabar con los datos de la demo
if (demo_.counter == TOTAL_DEMO_DATA - 200) { if (demo_.counter == TOTAL_DEMO_DATA - 200) {
fade_out_->setType(FadeType::RANDOM_SQUARE); fade_out_->setType(Fade::Type::RANDOM_SQUARE);
fade_out_->activate(); fade_out_->activate();
} }
@@ -1777,11 +1777,11 @@ void Game::updateMenace() {
} }
const auto &stage = current_stage.value(); const auto &stage = current_stage.value();
const double fraction = stage_manager_->getCurrentStageProgressFraction(); const double FRACTION = stage_manager_->getCurrentStageProgressFraction();
const int difference = stage.getMaxMenace() - stage.getMinMenace(); const int DIFFERENCE = stage.getMaxMenace() - stage.getMinMenace();
// Aumenta el nivel de amenaza en función del progreso de la fase // Aumenta el nivel de amenaza en función del progreso de la fase
menace_threshold_ = stage.getMinMenace() + (difference * fraction); menace_threshold_ = stage.getMinMenace() + (DIFFERENCE * FRACTION);
if (menace_ < menace_threshold_) { if (menace_ < menace_threshold_) {
balloon_manager_->deployRandomFormation(stage_manager_->getCurrentStageIndex()); balloon_manager_->deployRandomFormation(stage_manager_->getCurrentStageIndex());
@@ -1940,14 +1940,14 @@ void Game::handleDebugEvents(const SDL_Event &event) {
++formation_id_; ++formation_id_;
balloon_manager_->destroyAllBalloons(); balloon_manager_->destroyAllBalloons();
balloon_manager_->deployFormation(formation_id_); balloon_manager_->deployFormation(formation_id_);
std::cout << formation_id_ << std::endl; std::cout << formation_id_ << '\n';
break; break;
} }
case SDLK_KP_MINUS: { case SDLK_KP_MINUS: {
--formation_id_; --formation_id_;
balloon_manager_->destroyAllBalloons(); balloon_manager_->destroyAllBalloons();
balloon_manager_->deployFormation(formation_id_); balloon_manager_->deployFormation(formation_id_);
std::cout << formation_id_ << std::endl; std::cout << formation_id_ << '\n';
break; break;
} }
default: default:

View File

@@ -216,9 +216,9 @@ class Game {
void freeBullets(); // Libera memoria del vector de balas void freeBullets(); // Libera memoria del vector de balas
// --- Colisiones específicas de balas --- // --- Colisiones específicas de balas ---
auto checkBulletTabeCollision(std::shared_ptr<Bullet> bullet) -> bool; // Detecta colisión bala-Tabe auto checkBulletTabeCollision(const std::shared_ptr<Bullet> &bullet) -> bool; // Detecta colisión bala-Tabe
auto checkBulletBalloonCollision(std::shared_ptr<Bullet> bullet) -> bool; // Detecta colisión bala-globo auto checkBulletBalloonCollision(const std::shared_ptr<Bullet> &bullet) -> bool; // Detecta colisión bala-globo
void processBalloonHit(std::shared_ptr<Bullet> bullet, std::shared_ptr<Balloon> balloon); // Procesa impacto en globo void processBalloonHit(const std::shared_ptr<Bullet> &bullet, const std::shared_ptr<Balloon> &balloon); // Procesa impacto en globo
// --- Sistema de ítems y power-ups --- // --- Sistema de ítems y power-ups ---
void updateItems(); // Actualiza posición y estado de todos los ítems void updateItems(); // Actualiza posición y estado de todos los ítems
@@ -235,7 +235,7 @@ class Game {
void throwCoffee(int x, int y); // Crea efecto de café arrojado al ser golpeado void throwCoffee(int x, int y); // Crea efecto de café arrojado al ser golpeado
// --- Gestión de caída de ítems --- // --- Gestión de caída de ítems ---
void handleItemDrop(std::shared_ptr<Balloon> balloon, std::shared_ptr<Player> player); // Gestiona caída de ítem desde globo void handleItemDrop(const std::shared_ptr<Balloon> &balloon, const std::shared_ptr<Player> &player); // Gestiona caída de ítem desde globo
// --- Sprites inteligentes (smartsprites) --- // --- Sprites inteligentes (smartsprites) ---
void updateSmartSprites(); // Actualiza todos los sprites con lógica propia void updateSmartSprites(); // Actualiza todos los sprites con lógica propia
@@ -249,11 +249,11 @@ class Game {
void initPaths(); // Inicializa rutas predefinidas para animaciones void initPaths(); // Inicializa rutas predefinidas para animaciones
// --- Creación de sprites especiales --- // --- Creación de sprites especiales ---
void createItemText(int x, std::shared_ptr<Texture> texture); // Crea texto animado para ítems void createItemText(int x, const std::shared_ptr<Texture> &texture); // Crea texto animado para ítems
void createMessage(const std::vector<Path> &paths, std::shared_ptr<Texture> texture); // Crea mensaje con animación por ruta void createMessage(const std::vector<Path> &paths, const std::shared_ptr<Texture> &texture); // Crea mensaje con animación por ruta
// --- Sistema de globos y enemigos --- // --- Sistema de globos y enemigos ---
void handleBalloonDestruction(std::shared_ptr<Balloon> balloon, std::shared_ptr<Player> player); // Procesa destrucción de globo void handleBalloonDestruction(std::shared_ptr<Balloon> balloon, const std::shared_ptr<Player> &player); // Procesa destrucción de globo
void handleTabeHitEffects(); // Gestiona efectos al golpear a Tabe void handleTabeHitEffects(); // Gestiona efectos al golpear a Tabe
void checkAndUpdateBalloonSpeed(); // Ajusta velocidad de globos según progreso void checkAndUpdateBalloonSpeed(); // Ajusta velocidad de globos según progreso

View File

@@ -36,7 +36,7 @@ HiScoreTable::HiScoreTable()
ticks_(0), ticks_(0),
view_area_(SDL_FRect{0, 0, param.game.width, param.game.height}), view_area_(SDL_FRect{0, 0, param.game.width, param.game.height}),
fade_mode_(FadeMode::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
Section::name = Section::Name::HI_SCORE_TABLE; Section::name = Section::Name::HI_SCORE_TABLE;
@@ -133,13 +133,13 @@ void HiScoreTable::run() {
void HiScoreTable::updateFade() { void HiScoreTable::updateFade() {
fade_->update(); fade_->update();
if (fade_->hasEnded() && fade_mode_ == FadeMode::IN) { if (fade_->hasEnded() && fade_mode_ == Fade::Mode::IN) {
fade_->reset(); fade_->reset();
fade_mode_ = FadeMode::OUT; fade_mode_ = Fade::Mode::OUT;
fade_->setMode(fade_mode_); fade_->setMode(fade_mode_);
} }
if (fade_->hasEnded() && fade_mode_ == FadeMode::OUT) { if (fade_->hasEnded() && fade_mode_ == Fade::Mode::OUT) {
Section::name = (Section::options == Section::Options::HI_SCORE_AFTER_PLAYING) Section::name = (Section::options == Section::Options::HI_SCORE_AFTER_PLAYING)
? Section::Name::TITLE ? Section::Name::TITLE
: Section::Name::INSTRUCTIONS; : Section::Name::INSTRUCTIONS;
@@ -272,7 +272,7 @@ void HiScoreTable::updateSprites() {
// Inicializa el fade // Inicializa el fade
void HiScoreTable::initFade() { void HiScoreTable::initFade() {
fade_->setColor(param.fade.color); fade_->setColor(param.fade.color);
fade_->setType(FadeType::RANDOM_SQUARE); fade_->setType(Fade::Type::RANDOM_SQUARE);
fade_->setPostDuration(param.fade.post_duration); fade_->setPostDuration(param.fade.post_duration);
fade_->setMode(fade_mode_); fade_->setMode(fade_mode_);
fade_->activate(); fade_->activate();

View File

@@ -7,12 +7,11 @@
#include <vector> // Para vector #include <vector> // Para vector
#include "color.h" // Para Color #include "color.h" // Para Color
#include "fade.h" // Para Fade
#include "path_sprite.h" // Para Path, PathSprite (ptr only) #include "path_sprite.h" // Para Path, PathSprite (ptr only)
class Background; class Background;
class Fade;
class Sprite; class Sprite;
enum class FadeMode : Uint8;
// --- Clase HiScoreTable: muestra la tabla de puntuaciones más altas --- // --- Clase HiScoreTable: muestra la tabla de puntuaciones más altas ---
// Esta clase gestiona un estado del programa. Se encarga de mostrar la tabla con las puntuaciones // Esta clase gestiona un estado del programa. Se encarga de mostrar la tabla con las puntuaciones
@@ -48,7 +47,7 @@ class HiScoreTable {
Uint16 counter_ = 0; // Contador Uint16 counter_ = 0; // Contador
Uint64 ticks_; // Contador de ticks para ajustar la velocidad del programa Uint64 ticks_; // Contador de ticks para ajustar la velocidad del programa
SDL_FRect view_area_; // Parte de la textura que se muestra en pantalla SDL_FRect view_area_; // Parte de la textura que se muestra en pantalla
FadeMode fade_mode_; // Modo de fade a utilizar Fade::Mode fade_mode_; // Modo de fade a utilizar
Color background_fade_color_; // Color de atenuación del fondo Color background_fade_color_; // Color de atenuación del fondo
std::vector<Color> entry_colors_; // Colores para destacar las entradas en la tabla std::vector<Color> entry_colors_; // Colores para destacar las entradas en la tabla

View File

@@ -43,9 +43,9 @@ Instructions::Instructions()
// Inicializa objetos // Inicializa objetos
tiled_bg_->setColor(param.title.bg_color); tiled_bg_->setColor(param.title.bg_color);
fade_->setColor(param.fade.color); fade_->setColor(param.fade.color);
fade_->setType(FadeType::FULLSCREEN); fade_->setType(Fade::Type::FULLSCREEN);
fade_->setPostDuration(param.fade.post_duration); fade_->setPostDuration(param.fade.post_duration);
fade_->setMode(FadeMode::IN); fade_->setMode(Fade::Mode::IN);
fade_->activate(); fade_->activate();
// Inicializa las líneas con un retraso progresivo de 50 ms // Inicializa las líneas con un retraso progresivo de 50 ms

View File

@@ -49,7 +49,7 @@ Title::Title()
game_logo_->enable(); game_logo_->enable();
mini_logo_sprite_->setX(param.game.game_area.center_x - mini_logo_sprite_->getWidth() / 2); mini_logo_sprite_->setX(param.game.game_area.center_x - mini_logo_sprite_->getWidth() / 2);
fade_->setColor(param.fade.color); fade_->setColor(param.fade.color);
fade_->setType(FadeType::RANDOM_SQUARE); fade_->setType(Fade::Type::RANDOM_SQUARE);
fade_->setPostDuration(param.fade.post_duration); fade_->setPostDuration(param.fade.post_duration);
initPlayers(); initPlayers();
@@ -201,7 +201,7 @@ void Title::printColorValue(const Color& color) {
<< std::hex << std::setw(2) << std::setfill('0') << (int)color.r << std::hex << std::setw(2) << std::setfill('0') << (int)color.r
<< std::setw(2) << std::setfill('0') << (int)color.g << std::setw(2) << std::setfill('0') << (int)color.g
<< std::setw(2) << std::setfill('0') << (int)color.b << std::setw(2) << std::setfill('0') << (int)color.b
<< std::endl; << '\n';
} }
#endif #endif
@@ -538,7 +538,7 @@ void Title::initPlayers() {
players_.back()->setPlayingState(Player::State::TITLE_HIDDEN); players_.back()->setPlayingState(Player::State::TITLE_HIDDEN);
// Registra los jugadores en Options // Registra los jugadores en Options
for (auto player : players_) { for (const auto& player : players_) {
Options::keyboard.addPlayer(player); Options::keyboard.addPlayer(player);
Options::gamepad_manager.addPlayer(player); Options::gamepad_manager.addPlayer(player);
} }

View File

@@ -13,40 +13,40 @@ namespace SystemShutdown {
#ifndef _WIN32 #ifndef _WIN32
// Función auxiliar para sistemas Unix-like // Función auxiliar para sistemas Unix-like
ShutdownResult executeUnixShutdown(const char* command, char* const args[]) { auto executeUnixShutdown(const char* command, char* const args[]) -> ShutdownResult {
pid_t pid = fork(); pid_t pid = fork();
if (pid == 0) { if (pid == 0) {
// Proceso hijo // Proceso hijo
execvp(command, args); execvp(command, args);
// Si llegamos aquí, execvp falló // Si llegamos aquí, execvp falló
std::cerr << "Error: No se pudo ejecutar " << command << std::endl; std::cerr << "Error: No se pudo ejecutar " << command << '\n';
_exit(1); _exit(1);
} else if (pid > 0) { } else if (pid > 0) {
// Proceso padre // Proceso padre
int status; int status;
waitpid(pid, &status, 0); waitpid(pid, &status, 0);
return (WEXITSTATUS(status) == 0) ? ShutdownResult::SUCCESS : ShutdownResult::ERROR_SYSTEM_CALL; return (WEXITSTATUS(status) == 0) ? ShutdownResult::SUCCESS : ShutdownResult::ERROR_SYSTEM_CALL;
} else { } else {
return ShutdownResult::ERROR_FORK_FAILED; return ShutdownResult::ERROR_FORK_FAILED;
}
} }
}
#endif #endif
// Implementación de las funciones públicas // Implementación de las funciones públicas
ShutdownResult shutdownSystem() { auto shutdownSystem() -> ShutdownResult {
ShutdownConfig config; ShutdownConfig config;
return shutdownSystem(config); return shutdownSystem(config);
} }
ShutdownResult shutdownSystem(int delay_seconds, bool force_apps) { auto shutdownSystem(int delay_seconds, bool force_apps) -> ShutdownResult {
ShutdownConfig config; ShutdownConfig config;
config.delay_seconds = delay_seconds; config.delay_seconds = delay_seconds;
config.force_close_apps = force_apps; config.force_close_apps = force_apps;
return shutdownSystem(config); return shutdownSystem(config);
} }
ShutdownResult shutdownSystem(const ShutdownConfig& config) { auto shutdownSystem(const ShutdownConfig& config) -> ShutdownResult {
#ifdef _WIN32 #ifdef _WIN32
// Windows: Usar CreateProcess // Windows: Usar CreateProcess
STARTUPINFOA si = {0}; STARTUPINFOA si = {0};
@@ -107,42 +107,41 @@ namespace SystemShutdown {
const_cast<char*>("shutdown"), const_cast<char*>("shutdown"),
const_cast<char*>("-h"), const_cast<char*>("-h"),
const_cast<char*>("now"), const_cast<char*>("now"),
NULL nullptr};
};
return executeUnixShutdown("shutdown", args); return executeUnixShutdown("shutdown", args);
#else #else
return ShutdownResult::ERROR_UNSUPPORTED; return ShutdownResult::ERROR_UNSUPPORTED;
#endif #endif
} }
const char* resultToString(ShutdownResult result) { auto resultToString(ShutdownResult result) -> const char* {
switch (result) { switch (result) {
case ShutdownResult::SUCCESS: case ShutdownResult::SUCCESS:
return "Apagado iniciado exitosamente"; return "Apagado iniciado exitosamente";
case ShutdownResult::ERROR_PERMISSION: case ShutdownResult::ERROR_PERMISSION:
return "Error: Permisos insuficientes"; return "Error: Permisos insuficientes";
case ShutdownResult::ERROR_SYSTEM_CALL: case ShutdownResult::ERROR_SYSTEM_CALL:
return "Error: Fallo en la llamada al sistema"; return "Error: Fallo en la llamada al sistema";
case ShutdownResult::ERROR_FORK_FAILED: case ShutdownResult::ERROR_FORK_FAILED:
return "Error: No se pudo crear proceso hijo"; return "Error: No se pudo crear proceso hijo";
case ShutdownResult::ERROR_UNSUPPORTED: case ShutdownResult::ERROR_UNSUPPORTED:
return "Error: Sistema operativo no soportado"; return "Error: Sistema operativo no soportado";
default: default:
return "Error desconocido"; return "Error desconocido";
}
} }
}
bool isShutdownSupported() { auto isShutdownSupported() -> bool {
#if defined(_WIN32) || defined(__APPLE__) || defined(__linux__) #if defined(_WIN32) || defined(__APPLE__) || defined(__linux__)
return true; return true;
#else #else
return false; return false;
#endif #endif
} }
const char* getRequiredPermissions() { auto getRequiredPermissions() -> const char* {
#ifdef _WIN32 #ifdef _WIN32
return "Requiere permisos de Administrador en Windows"; return "Requiere permisos de Administrador en Windows";
#elif defined(__APPLE__) || defined(__linux__) #elif defined(__APPLE__) || defined(__linux__)
@@ -150,6 +149,6 @@ namespace SystemShutdown {
#else #else
return "Sistema no soportado"; return "Sistema no soportado";
#endif #endif
} }
} // namespace SystemShutdown } // namespace SystemShutdown

View File

@@ -14,24 +14,22 @@ enum class ShutdownResult {
// --- Estructuras --- // --- Estructuras ---
struct ShutdownConfig { struct ShutdownConfig {
int delay_seconds; // Segundos de retraso antes del apagado int delay_seconds{5}; // Segundos de retraso antes del apagado
bool force_close_apps; // Forzar cierre de aplicaciones bool force_close_apps{true}; // Forzar cierre de aplicaciones
const char* shutdown_message; // Mensaje mostrado durante el apagado const char* shutdown_message{"El sistema se apagará..."}; // Mensaje mostrado durante el apagado
// Constructor con valores por defecto // Constructor con valores por defecto
ShutdownConfig() ShutdownConfig()
: delay_seconds(5)
, force_close_apps(true) {}
, shutdown_message("El sistema se apagará...")
{}
}; };
// --- Funciones --- // --- Funciones ---
ShutdownResult shutdownSystem(); // Apaga el sistema con configuración por defecto auto shutdownSystem() -> ShutdownResult; // Apaga el sistema con configuración por defecto
ShutdownResult shutdownSystem(const ShutdownConfig& config); // Apaga el sistema con configuración personalizada auto shutdownSystem(const ShutdownConfig& config) -> ShutdownResult; // Apaga el sistema con configuración personalizada
ShutdownResult shutdownSystem(int delay_seconds, bool force_apps = true); // Apaga el sistema con parámetros simples auto shutdownSystem(int delay_seconds, bool force_apps = true) -> ShutdownResult; // Apaga el sistema con parámetros simples
const char* resultToString(ShutdownResult result); // Convierte un código de resultado a string descriptivo auto resultToString(ShutdownResult result) -> const char*; // Convierte un código de resultado a string descriptivo
bool isShutdownSupported(); // Verifica si el sistema actual soporta apagado programático auto isShutdownSupported() -> bool; // Verifica si el sistema actual soporta apagado programático
const char* getRequiredPermissions(); // Obtiene información sobre los permisos necesarios auto getRequiredPermissions() -> const char*; // Obtiene información sobre los permisos necesarios
} // namespace SystemShutdown } // namespace SystemShutdown

View File

@@ -1,6 +1,7 @@
#pragma once #pragma once
#include <memory> // Para shared_ptr #include <memory> // Para shared_ptr
#include <utility>
#include "animated_sprite.h" // Para AnimatedSprite #include "animated_sprite.h" // Para AnimatedSprite
@@ -11,7 +12,7 @@ class SmartSprite : public AnimatedSprite {
public: public:
// --- Constructor y destructor --- // --- Constructor y destructor ---
explicit SmartSprite(std::shared_ptr<Texture> texture) explicit SmartSprite(std::shared_ptr<Texture> texture)
: AnimatedSprite(texture) {} : AnimatedSprite(std::move(texture)) {}
~SmartSprite() override = default; ~SmartSprite() override = default;
// --- Métodos principales --- // --- Métodos principales ---

View File

@@ -1,22 +1,23 @@
#include "sprite.h" #include "sprite.h"
#include <utility>
#include <vector> // Para vector #include <vector> // Para vector
#include "texture.h" // Para Texture #include "texture.h" // Para Texture
// 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_{texture}, : textures_{std::move(texture)},
pos_((SDL_FRect){pos_x, pos_y, width, height}), pos_((SDL_FRect){pos_x, pos_y, width, height}),
sprite_clip_((SDL_FRect){0, 0, pos_.w, pos_.h}) {} sprite_clip_((SDL_FRect){0, 0, pos_.w, pos_.h}) {}
Sprite::Sprite(std::shared_ptr<Texture> texture, SDL_FRect rect) Sprite::Sprite(std::shared_ptr<Texture> texture, SDL_FRect rect)
: textures_{texture}, : textures_{std::move(texture)},
pos_(rect), pos_(rect),
sprite_clip_((SDL_FRect){0, 0, pos_.w, pos_.h}) {} sprite_clip_((SDL_FRect){0, 0, pos_.w, pos_.h}) {}
Sprite::Sprite(std::shared_ptr<Texture> texture) Sprite::Sprite(std::shared_ptr<Texture> texture)
: textures_{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{0, 0, static_cast<float>(textures_.at(texture_index_)->getWidth()), static_cast<float>(textures_.at(texture_index_)->getHeight())}),
sprite_clip_(pos_) {} sprite_clip_(pos_) {}

View File

@@ -4,7 +4,8 @@
#include <cstddef> // Para size_t #include <cstddef> // Para size_t
#include <memory> // Para shared_ptr #include <memory> // Para shared_ptr
#include <vector> // Para vector #include <utility>
#include <vector> // Para vector
class Texture; class Texture;
@@ -52,8 +53,8 @@ class Sprite {
// --- 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_); }
void setTexture(std::shared_ptr<Texture> texture) { textures_.at(texture_index_) = texture; } void setTexture(std::shared_ptr<Texture> texture) { textures_.at(texture_index_) = std::move(texture); }
void addTexture(std::shared_ptr<Texture> texture) { textures_.push_back(texture); } void addTexture(const std::shared_ptr<Texture>& texture) { textures_.push_back(texture); }
auto setActiveTexture(size_t index) -> bool; // Cambia la textura activa por índice auto setActiveTexture(size_t index) -> bool; // Cambia la textura activa por índice
[[nodiscard]] auto getActiveTextureIndex() const -> size_t { return texture_index_; } // Obtiene el índice de la textura activa [[nodiscard]] auto getActiveTextureIndex() const -> size_t { return texture_index_; } // Obtiene el índice de la textura activa
[[nodiscard]] auto getTextureCount() const -> size_t { return textures_.size(); } // Obtiene el número total de texturas [[nodiscard]] auto getTextureCount() const -> size_t { return textures_.size(); } // Obtiene el número total de texturas

View File

@@ -3,11 +3,12 @@
#include <algorithm> #include <algorithm>
#include <fstream> #include <fstream>
#include <sstream> #include <sstream>
#include <utility>
// Implementación de StageData // Implementación de StageData
StageData::StageData(int power_to_complete, int min_menace, int max_menace, const std::string& name) StageData::StageData(int power_to_complete, int min_menace, int max_menace, std::string name)
: status_(StageStatus::LOCKED), : status_(StageStatus::LOCKED),
name_(name), name_(std::move(name)),
power_to_complete_(power_to_complete), power_to_complete_(power_to_complete),
min_menace_(min_menace), min_menace_(min_menace),
max_menace_(max_menace) {} max_menace_(max_menace) {}
@@ -59,7 +60,7 @@ void StageManager::createDefaultStages() {
stages_.emplace_back(950, 7 + (4 * 7), 7 + (4 * 10), "Maestría"); stages_.emplace_back(950, 7 + (4 * 7), 7 + (4 * 10), "Maestría");
} }
bool StageManager::loadStagesFromFile(const std::string& filename) { auto StageManager::loadStagesFromFile(const std::string& filename) -> bool {
std::ifstream file(filename); std::ifstream file(filename);
if (!file.is_open()) { if (!file.is_open()) {
return false; // No se pudo abrir el archivo return false; // No se pudo abrir el archivo
@@ -119,7 +120,7 @@ bool StageManager::loadStagesFromFile(const std::string& filename) {
return !stages_.empty(); return !stages_.empty();
} }
bool StageManager::advanceToNextStage() { auto StageManager::advanceToNextStage() -> bool {
if (!isCurrentStageCompleted() || current_stage_index_ >= stages_.size() - 1) { if (!isCurrentStageCompleted() || current_stage_index_ >= stages_.size() - 1) {
return false; return false;
} }
@@ -130,7 +131,7 @@ bool StageManager::advanceToNextStage() {
return true; return true;
} }
bool StageManager::jumpToStage(size_t target_stage_index) { auto StageManager::jumpToStage(size_t target_stage_index) -> bool {
if (!validateStageIndex(target_stage_index)) { if (!validateStageIndex(target_stage_index)) {
return false; return false;
} }
@@ -150,7 +151,7 @@ bool StageManager::jumpToStage(size_t target_stage_index) {
return true; return true;
} }
bool StageManager::subtractPower(int amount) { auto StageManager::subtractPower(int amount) -> bool {
if (amount <= 0 || current_power_ < amount) { if (amount <= 0 || current_power_ < amount) {
return false; return false;
} }
@@ -168,18 +169,18 @@ void StageManager::disablePowerCollection() {
power_collection_state_ = PowerCollectionState::DISABLED; power_collection_state_ = PowerCollectionState::DISABLED;
} }
std::optional<StageData> StageManager::getCurrentStage() const { auto StageManager::getCurrentStage() const -> std::optional<StageData> {
return getStage(current_stage_index_); return getStage(current_stage_index_);
} }
std::optional<StageData> StageManager::getStage(size_t index) const { auto StageManager::getStage(size_t index) const -> std::optional<StageData> {
if (!validateStageIndex(index)) { if (!validateStageIndex(index)) {
return std::nullopt; return std::nullopt;
} }
return stages_[index]; return stages_[index];
} }
bool StageManager::isCurrentStageCompleted() const { auto StageManager::isCurrentStageCompleted() const -> bool {
auto current_stage = getCurrentStage(); auto current_stage = getCurrentStage();
if (!current_stage.has_value()) { if (!current_stage.has_value()) {
return false; return false;
@@ -188,24 +189,28 @@ bool StageManager::isCurrentStageCompleted() const {
return current_power_ >= current_stage->getPowerToComplete(); return current_power_ >= current_stage->getPowerToComplete();
} }
bool StageManager::isGameCompleted() const { auto StageManager::isGameCompleted() const -> bool {
return current_stage_index_ >= stages_.size() - 1 && isCurrentStageCompleted(); return current_stage_index_ >= stages_.size() - 1 && isCurrentStageCompleted();
} }
double StageManager::getProgressPercentage() const { auto StageManager::getProgressPercentage() const -> double {
if (stages_.empty()) return 0.0; if (stages_.empty()) {
return 0.0;
}
int total_power_needed = getTotalPowerNeededToCompleteGame(); int total_power_needed = getTotalPowerNeededToCompleteGame();
if (total_power_needed == 0) return 100.0; if (total_power_needed == 0) {
return 100.0;
}
return (static_cast<double>(total_power_) / total_power_needed) * 100.0; return (static_cast<double>(total_power_) / total_power_needed) * 100.0;
} }
double StageManager::getCurrentStageProgressPercentage() const { auto StageManager::getCurrentStageProgressPercentage() const -> double {
return getCurrentStageProgressFraction() * 100.0; return getCurrentStageProgressFraction() * 100.0;
} }
double StageManager::getCurrentStageProgressFraction() const { auto StageManager::getCurrentStageProgressFraction() const -> double {
auto current_stage = getCurrentStage(); auto current_stage = getCurrentStage();
if (!current_stage.has_value()) { if (!current_stage.has_value()) {
return 0.0; return 0.0;
@@ -221,7 +226,7 @@ double StageManager::getCurrentStageProgressFraction() const {
return std::min(fraction, 1.0); return std::min(fraction, 1.0);
} }
int StageManager::getPowerNeededForCurrentStage() const { auto StageManager::getPowerNeededForCurrentStage() const -> int {
auto current_stage = getCurrentStage(); auto current_stage = getCurrentStage();
if (!current_stage.has_value()) { if (!current_stage.has_value()) {
return 0; return 0;
@@ -230,7 +235,7 @@ int StageManager::getPowerNeededForCurrentStage() const {
return std::max(0, current_stage->getPowerToComplete() - current_power_); return std::max(0, current_stage->getPowerToComplete() - current_power_);
} }
int StageManager::getTotalPowerNeededToCompleteGame() const { auto StageManager::getTotalPowerNeededToCompleteGame() const -> int {
int total_power_needed = 0; int total_power_needed = 0;
for (const auto& stage : stages_) { for (const auto& stage : stages_) {
total_power_needed += stage.getPowerToComplete(); total_power_needed += stage.getPowerToComplete();
@@ -239,7 +244,7 @@ int StageManager::getTotalPowerNeededToCompleteGame() const {
} }
// Implementación de la interfaz IStageInfo // Implementación de la interfaz IStageInfo
bool StageManager::canCollectPower() const { auto StageManager::canCollectPower() const -> bool {
return power_collection_state_ == PowerCollectionState::ENABLED; return power_collection_state_ == PowerCollectionState::ENABLED;
} }
@@ -267,7 +272,7 @@ void StageManager::addPower(int amount) {
updateStageStatuses(); updateStageStatuses();
} }
int StageManager::getCurrentMenaceLevel() const { auto StageManager::getCurrentMenaceLevel() const -> int {
auto current_stage = getCurrentStage(); auto current_stage = getCurrentStage();
if (!current_stage.has_value()) { if (!current_stage.has_value()) {
return 0; return 0;
@@ -278,7 +283,7 @@ int StageManager::getCurrentMenaceLevel() const {
// Gestión de callbacks // Gestión de callbacks
void StageManager::setPowerChangeCallback(PowerChangeCallback callback) { void StageManager::setPowerChangeCallback(PowerChangeCallback callback) {
power_change_callback_ = callback; power_change_callback_ = std::move(callback);
} }
void StageManager::removePowerChangeCallback() { void StageManager::removePowerChangeCallback() {
@@ -286,7 +291,7 @@ void StageManager::removePowerChangeCallback() {
} }
// Métodos privados // Métodos privados
bool StageManager::validateStageIndex(size_t index) const { auto StageManager::validateStageIndex(size_t index) const -> bool {
return index < stages_.size(); return index < stages_.size();
} }

View File

@@ -23,7 +23,7 @@ enum class StageStatus {
class StageData { class StageData {
public: public:
// --- Constructor --- // --- Constructor ---
StageData(int power_to_complete, int min_menace, int max_menace, const std::string& name = ""); // Constructor de una fase StageData(int power_to_complete, int min_menace, int max_menace, std::string name = ""); // Constructor de una fase
// --- Getters --- // --- Getters ---
[[nodiscard]] auto getPowerToComplete() const -> int { return power_to_complete_; } // Obtiene el poder necesario para completar [[nodiscard]] auto getPowerToComplete() const -> int { return power_to_complete_; } // Obtiene el poder necesario para completar

View File

@@ -10,9 +10,9 @@ public:
virtual ~IStageInfo() = default; virtual ~IStageInfo() = default;
// Interfaz de recolección de poder // Interfaz de recolección de poder
virtual bool canCollectPower() const = 0; [[nodiscard]] virtual auto canCollectPower() const -> bool = 0;
virtual void addPower(int amount) = 0; virtual void addPower(int amount) = 0;
// Ajuste de comportamiento del gameplay // Ajuste de comportamiento del gameplay
virtual int getCurrentMenaceLevel() const = 0; [[nodiscard]] virtual auto getCurrentMenaceLevel() const -> int = 0;
}; };

View File

@@ -20,16 +20,16 @@
namespace SystemUtils { namespace SystemUtils {
// Función auxiliar para crear una carpeta individual // Función auxiliar para crear una carpeta individual
Result createSingleFolder(const std::string& path, int permissions) { auto createSingleFolder(const std::string& path, int permissions) -> Result {
struct stat st = {0}; struct stat st = {0};
// Verificar si ya existe // Verificar si ya existe
if (stat(path.c_str(), &st) == 0) { if (stat(path.c_str(), &st) == 0) {
return Result::SUCCESS; // Ya existe, no es error por defecto return Result::SUCCESS; // Ya existe, no es error por defecto
} }
// Intentar crear la carpeta // Intentar crear la carpeta
int result; int result;
#ifdef _WIN32 #ifdef _WIN32
result = _mkdir(path.c_str()); result = _mkdir(path.c_str());
#else #else
@@ -50,63 +50,63 @@ namespace SystemUtils {
} }
return Result::SUCCESS; return Result::SUCCESS;
} }
// Función auxiliar para crear carpetas padre recursivamente // Función auxiliar para crear carpetas padre recursivamente
Result createParentFolders(const std::string& path, int permissions) { auto createParentFolders(const std::string& path, int permissions) -> Result {
size_t pos = 0; size_t pos = 0;
while ((pos = path.find('/', pos + 1)) != std::string::npos) { while ((pos = path.find('/', pos + 1)) != std::string::npos) {
std::string parent = path.substr(0, pos); std::string parent = path.substr(0, pos);
if (!parent.empty() && !folderExists(parent)) { if (!parent.empty() && !folderExists(parent)) {
Result result = createSingleFolder(parent, permissions); Result result = createSingleFolder(parent, permissions);
if (result != Result::SUCCESS && result != Result::ALREADY_EXISTS) { if (result != Result::SUCCESS && result != Result::ALREADY_EXISTS) {
return result; return result;
}
} }
} }
return Result::SUCCESS;
} }
Result createApplicationFolder(const std::string& app_name, std::string& out_path) { return Result::SUCCESS;
FolderConfig config; }
return createApplicationFolder(app_name, out_path, config);
auto createApplicationFolder(const std::string& app_name, std::string& out_path) -> Result {
FolderConfig config;
return createApplicationFolder(app_name, out_path, config);
}
auto createApplicationFolder(const std::string& app_name, std::string& out_path, const FolderConfig& config) -> Result {
out_path = getApplicationDataPath(app_name);
return createFolder(out_path, config);
}
auto createFolder(const std::string& path) -> Result {
FolderConfig config;
return createFolder(path, config);
}
auto createFolder(const std::string& path, const FolderConfig& config) -> Result {
if (path.empty()) {
return Result::INVALID_PATH;
} }
Result createApplicationFolder(const std::string& app_name, std::string& out_path, const FolderConfig& config) { // Verificar si ya existe y si eso es un error
out_path = getApplicationDataPath(app_name); if (folderExists(path) && config.fail_if_exists) {
return createFolder(out_path, config); return Result::ALREADY_EXISTS;
} }
Result createFolder(const std::string& path) { // Crear carpetas padre si es necesario
FolderConfig config; if (config.create_parents) {
return createFolder(path, config); Result parent_result = createParentFolders(path, config.permissions);
} if (parent_result != Result::SUCCESS) {
return parent_result;
Result createFolder(const std::string& path, const FolderConfig& config) {
if (path.empty()) {
return Result::INVALID_PATH;
} }
// Verificar si ya existe y si eso es un error
if (folderExists(path) && config.fail_if_exists) {
return Result::ALREADY_EXISTS;
}
// Crear carpetas padre si es necesario
if (config.create_parents) {
Result parent_result = createParentFolders(path, config.permissions);
if (parent_result != Result::SUCCESS) {
return parent_result;
}
}
// Crear la carpeta final
return createSingleFolder(path, config.permissions);
} }
std::string getApplicationDataPath(const std::string& app_name) { // Crear la carpeta final
return createSingleFolder(path, config.permissions);
}
auto getApplicationDataPath(const std::string& app_name) -> std::string {
#ifdef _WIN32 #ifdef _WIN32
char* appdata = getenv("APPDATA"); char* appdata = getenv("APPDATA");
if (appdata) { if (appdata) {
@@ -127,33 +127,33 @@ namespace SystemUtils {
std::string home = getHomeDirectory(); std::string home = getHomeDirectory();
return home + "/." + app_name; return home + "/." + app_name;
#endif #endif
} }
bool folderExists(const std::string& path) { auto folderExists(const std::string& path) -> bool {
struct stat st = {0}; struct stat st = {0};
return (stat(path.c_str(), &st) == 0 && S_ISDIR(st.st_mode)); return (stat(path.c_str(), &st) == 0 && S_ISDIR(st.st_mode));
} }
const char* resultToString(Result result) { auto resultToString(Result result) -> const char* {
switch (result) { switch (result) {
case Result::SUCCESS: case Result::SUCCESS:
return "Operación exitosa"; return "Operación exitosa";
case Result::PERMISSION_DENIED: case Result::PERMISSION_DENIED:
return "Error: Permisos insuficientes"; return "Error: Permisos insuficientes";
case Result::PATH_TOO_LONG: case Result::PATH_TOO_LONG:
return "Error: Ruta demasiado larga"; return "Error: Ruta demasiado larga";
case Result::ALREADY_EXISTS: case Result::ALREADY_EXISTS:
return "Error: La carpeta ya existe"; return "Error: La carpeta ya existe";
case Result::INVALID_PATH: case Result::INVALID_PATH:
return "Error: Ruta inválida"; return "Error: Ruta inválida";
case Result::UNKNOWN_ERROR: case Result::UNKNOWN_ERROR:
return "Error desconocido"; return "Error desconocido";
default: default:
return "Error no identificado"; return "Error no identificado";
}
} }
}
std::string getHomeDirectory() { auto getHomeDirectory() -> std::string {
#ifdef _WIN32 #ifdef _WIN32
char* userprofile = getenv("USERPROFILE"); char* userprofile = getenv("USERPROFILE");
if (userprofile) { if (userprofile) {
@@ -162,20 +162,20 @@ namespace SystemUtils {
return "C:/Users/Default"; return "C:/Users/Default";
#else #else
struct passwd *pw = getpwuid(getuid()); struct passwd *pw = getpwuid(getuid());
if (pw && pw->pw_dir) { if ((pw != nullptr) && (pw->pw_dir != nullptr)) {
return std::string(pw->pw_dir); return std::string(pw->pw_dir);
} }
// Fallback // Fallback
char* home = getenv("HOME"); char* home = getenv("HOME");
if (home) { if (home != nullptr) {
return std::string(home); return std::string(home);
} }
return "/tmp"; return "/tmp";
#endif #endif
} }
std::string getTempDirectory() { auto getTempDirectory() -> std::string {
#ifdef _WIN32 #ifdef _WIN32
char* temp = getenv("TEMP"); char* temp = getenv("TEMP");
if (temp) { if (temp) {
@@ -185,6 +185,6 @@ namespace SystemUtils {
#else #else
return "/tmp"; return "/tmp";
#endif #endif
} }
} // namespace SystemUtils } // namespace SystemUtils

View File

@@ -16,25 +16,25 @@ enum class Result { // Códigos de resultado para operaciones del sistema
// --- Estructuras --- // --- Estructuras ---
struct FolderConfig { // Configuración para creación de carpetas struct FolderConfig { // Configuración para creación de carpetas
bool create_parents; // Crear carpetas padre si no existen bool create_parents{true}; // Crear carpetas padre si no existen
bool fail_if_exists; // Fallar si la carpeta ya existe bool fail_if_exists{false}; // Fallar si la carpeta ya existe
int permissions; // Permisos Unix (ignorado en Windows) int permissions{0755}; // Permisos Unix (ignorado en Windows)
// Constructor con valores por defecto // Constructor con valores por defecto
FolderConfig() FolderConfig()
: create_parents(true), fail_if_exists(false), permissions(0755) // rwxr-xr-x
{} {}
}; };
// --- Funciones --- // --- Funciones ---
Result createApplicationFolder(const std::string& app_name, std::string& out_path); // Crea la carpeta del sistema donde guardar datos de la aplicación auto createApplicationFolder(const std::string& app_name, std::string& out_path) -> Result; // Crea la carpeta del sistema donde guardar datos de la aplicación
Result createApplicationFolder(const std::string& app_name, std::string& out_path, const FolderConfig& config); // Crea la carpeta del sistema con configuración personalizada auto createApplicationFolder(const std::string& app_name, std::string& out_path, const FolderConfig& config) -> Result; // Crea la carpeta del sistema con configuración personalizada
Result createFolder(const std::string& path); // Crea una carpeta en la ruta especificada auto createFolder(const std::string& path) -> Result; // Crea una carpeta en la ruta especificada
Result createFolder(const std::string& path, const FolderConfig& config); // Crea una carpeta con configuración personalizada auto createFolder(const std::string& path, const FolderConfig& config) -> Result; // Crea una carpeta con configuración personalizada
std::string getApplicationDataPath(const std::string& app_name); // Obtiene la ruta de datos de la aplicación (sin crearla) auto getApplicationDataPath(const std::string& app_name) -> std::string; // Obtiene la ruta de datos de la aplicación (sin crearla)
bool folderExists(const std::string& path); // Verifica si una carpeta existe auto folderExists(const std::string& path) -> bool; // Verifica si una carpeta existe
const char* resultToString(Result result); // Convierte un código de resultado a string descriptivo auto resultToString(Result result) -> const char*; // Convierte un código de resultado a string descriptivo
std::string getHomeDirectory(); // Obtiene el directorio home del usuario auto getHomeDirectory() -> std::string; // Obtiene el directorio home del usuario
std::string getTempDirectory(); // Obtiene el directorio temporal del sistema auto getTempDirectory() -> std::string; // Obtiene el directorio temporal del sistema
} // namespace SystemUtils } // namespace SystemUtils

View File

@@ -14,7 +14,7 @@
#include "utils.h" // Para getFileName, printWithDots #include "utils.h" // Para getFileName, printWithDots
// Constructor // Constructor
Text::Text(std::shared_ptr<Texture> texture, const std::string &text_file) { Text::Text(const std::shared_ptr<Texture> &texture, const std::string &text_file) {
// Carga los offsets desde el fichero // Carga los offsets desde el fichero
auto tf = loadFile(text_file); auto tf = loadFile(text_file);
@@ -35,7 +35,7 @@ Text::Text(std::shared_ptr<Texture> texture, const std::string &text_file) {
} }
// Constructor // Constructor
Text::Text(std::shared_ptr<Texture> texture, std::shared_ptr<Text::File> text_file) { Text::Text(const std::shared_ptr<Texture> &texture, const std::shared_ptr<Text::File> &text_file) {
// Inicializa variables desde la estructura // Inicializa variables desde la estructura
box_height_ = text_file->box_height; box_height_ = text_file->box_height;
box_width_ = text_file->box_width; box_width_ = text_file->box_width;
@@ -261,7 +261,7 @@ auto Text::loadFile(const std::string &file_path) -> std::shared_ptr<Text::File>
// El fichero no se puede abrir // El fichero no se puede abrir
else { else {
std::cerr << "Error: Fichero no encontrado " << getFileName(file_path) << std::endl; std::cerr << "Error: Fichero no encontrado " << getFileName(file_path) << '\n';
throw std::runtime_error("Fichero no encontrado: " + getFileName(file_path)); throw std::runtime_error("Fichero no encontrado: " + getFileName(file_path));
} }

View File

@@ -52,8 +52,8 @@ class Text {
}; };
// --- Constructores y destructor --- // --- Constructores y destructor ---
Text(std::shared_ptr<Texture> texture, const std::string &text_file); Text(const std::shared_ptr<Texture> &texture, const std::string &text_file);
Text(std::shared_ptr<Texture> texture, std::shared_ptr<Text::File> text_file); Text(const std::shared_ptr<Texture> &texture, const std::shared_ptr<Text::File> &text_file);
~Text() = default; ~Text() = default;
// --- Métodos de escritura en pantalla --- // --- Métodos de escritura en pantalla ---

View File

@@ -24,7 +24,7 @@ Texture::Texture(SDL_Renderer *renderer, std::string path)
// Carga el fichero en la textura // Carga el fichero en la textura
if (!path_.empty()) { if (!path_.empty()) {
// Obtiene la extensión // Obtiene la extensión
const std::string EXTENSION = path_.substr(path_.find_last_of(".") + 1); const std::string EXTENSION = path_.substr(path_.find_last_of('.') + 1);
// .png // .png
if (EXTENSION == "png") { if (EXTENSION == "png") {

View File

@@ -18,7 +18,7 @@
Notifier* Notifier::instance = nullptr; Notifier* Notifier::instance = nullptr;
// Inicializa la instancia única del singleton // Inicializa la instancia única del singleton
void Notifier::init(const std::string& icon_file, std::shared_ptr<Text> text) { Notifier::instance = new Notifier(icon_file, text); } void Notifier::init(const std::string& icon_file, std::shared_ptr<Text> text) { Notifier::instance = new Notifier(icon_file, std::move(text)); }
// Libera la instancia // Libera la instancia
void Notifier::destroy() { delete Notifier::instance; } void Notifier::destroy() { delete Notifier::instance; }
@@ -27,7 +27,7 @@ void Notifier::destroy() { delete Notifier::instance; }
auto Notifier::get() -> Notifier* { return Notifier::instance; } auto Notifier::get() -> Notifier* { return Notifier::instance; }
// Constructor // Constructor
Notifier::Notifier(std::string icon_file, std::shared_ptr<Text> text) Notifier::Notifier(const std::string& icon_file, std::shared_ptr<Text> text)
: renderer_(Screen::get()->getRenderer()), : renderer_(Screen::get()->getRenderer()),
icon_texture_(!icon_file.empty() ? std::make_unique<Texture>(renderer_, icon_file) : nullptr), icon_texture_(!icon_file.empty() ? std::make_unique<Texture>(renderer_, icon_file) : nullptr),
text_(std::move(text)), text_(std::move(text)),
@@ -300,6 +300,7 @@ void Notifier::clearAllNotifications() {
// Obtiene los códigos de las notificaciones // Obtiene los códigos de las notificaciones
auto Notifier::getCodes() -> std::vector<std::string> { auto Notifier::getCodes() -> std::vector<std::string> {
std::vector<std::string> codes; std::vector<std::string> codes;
codes.reserve(notifications_.size());
for (const auto& notification : notifications_) { for (const auto& notification : notifications_) {
codes.emplace_back(notification.code); codes.emplace_back(notification.code);
} }

View File

@@ -98,7 +98,7 @@ class Notifier {
void transitionToStayState(int index); // Cambia el estado de una notificación de RISING a STAY cuando ha alcanzado su posición final void transitionToStayState(int index); // Cambia el estado de una notificación de RISING a STAY cuando ha alcanzado su posición final
// --- Constructores y destructor privados (singleton) --- // --- Constructores y destructor privados (singleton) ---
Notifier(std::string icon_file, std::shared_ptr<Text> text); // Constructor privado Notifier(const std::string &icon_file, std::shared_ptr<Text> text); // Constructor privado
~Notifier() = default; // Destructor privado ~Notifier() = default; // Destructor privado
// --- Instancia singleton --- // --- Instancia singleton ---

View File

@@ -1,5 +1,7 @@
#include "ui/service_menu.h" #include "ui/service_menu.h"
#include <utility>
#include "audio.h" // Para Audio #include "audio.h" // Para Audio
#include "define_buttons.h" // Para DefineButtons #include "define_buttons.h" // Para DefineButtons
#include "difficulty.h" // Para getCodeFromName, getNameFromCode #include "difficulty.h" // Para getCodeFromName, getNameFromCode
@@ -596,7 +598,7 @@ auto ServiceMenu::checkInput() -> bool {
} }
// Mandos // Mandos
for (auto gamepad : input_->getGamepads()) { for (const auto &gamepad : input_->getGamepads()) {
for (const auto &[action, func] : ACTIONS) { for (const auto &[action, func] : ACTIONS) {
if (input_->checkAction(action, Input::DO_NOT_ALLOW_REPEAT, Input::DO_NOT_CHECK_KEYBOARD, gamepad)) { if (input_->checkAction(action, Input::DO_NOT_ALLOW_REPEAT, Input::DO_NOT_CHECK_KEYBOARD, gamepad)) {
func(); func();
@@ -629,7 +631,7 @@ void ServiceMenu::refresh() {
// Método para registrar callback // Método para registrar callback
void ServiceMenu::setStateChangeCallback(StateChangeCallback callback) { void ServiceMenu::setStateChangeCallback(StateChangeCallback callback) {
state_change_callback_ = callback; state_change_callback_ = std::move(callback);
} }
// Método interno que cambia estado y notifica // Método interno que cambia estado y notifica