Compare commits

...

3 Commits

Author SHA1 Message Date
a7ef29b750 jugant amb clang-tidy 2025-07-19 22:38:01 +02:00
1d3fd79a9e jugant amb clang-tidy 2025-07-19 22:25:46 +02:00
e06503a8fc actualitzat cmakelists.txt 2025-07-19 19:41:19 +02:00
50 changed files with 1519 additions and 1337 deletions

View File

@@ -1,5 +1,6 @@
BasedOnStyle: Google
IndentWidth: 4
IndentAccessModifiers: true
ColumnLimit: 0 # Sin límite de longitud de línea
BreakBeforeBraces: Attach # Llaves en la misma línea
AllowShortIfStatementsOnASingleLine: true
@@ -8,4 +9,4 @@ AllowShortFunctionsOnASingleLine: All
AlignOperands: false
AlignAfterOpenBracket: DontAlign
BinPackArguments: false
BinPackParameters: false
BinPackParameters: false

1
.clang-format-ignore Normal file
View File

@@ -0,0 +1 @@
source/external/**

12
.clang-format.bak Normal file
View File

@@ -0,0 +1,12 @@
BasedOnStyle: Google
IndentWidth: 4
IndentAccessModifiers: true
ColumnLimit: 0 # Sin límite de longitud de línea
BreakBeforeBraces: Attach # Llaves en la misma línea
AllowShortIfStatementsOnASingleLine: true
AllowShortBlocksOnASingleLine: true
AllowShortFunctionsOnASingleLine: All
AlignOperands: false
AlignAfterOpenBracket: DontAlign
BinPackArguments: false
BinPackParameters: false

View File

@@ -1,12 +1,9 @@
Checks: >
readability-identifier-naming,
readability-*,
modernize-*,
clang-analyzer-*
readability-identifier-naming
WarningsAsErrors: '*'
HeaderFilterRegex: '.*'
# Solo incluir archivos de tu código fuente
HeaderFilterRegex: '^source/(sections|ui)/.*'
FormatStyle: file
CheckOptions:
@@ -16,25 +13,38 @@ CheckOptions:
# Miembros privados en snake_case con sufijo _
- { key: readability-identifier-naming.PrivateMemberCase, value: lower_case }
- { key: readability-identifier-naming.PrivateMemberSuffix, value: _ }
- { key: readability-identifier-naming.ClassMemberCase, value: lower_case }
- { key: readability-identifier-naming.ClassMemberSuffix, value: _ }
# Miembros protegidos en snake_case con sufijo _
- { key: readability-identifier-naming.ProtectedMemberCase, value: lower_case }
- { key: readability-identifier-naming.ProtectedMemberSuffix, value: _ }
# Miembros públicos en snake_case (sin sufijo)
- { key: readability-identifier-naming.PublicMemberCase, value: lower_case }
# Namespaces en CamelCase
- { key: readability-identifier-naming.NamespaceCase, value: CamelCase }
# Constantes y constexpr en UPPER_CASE
# Variables estáticas privadas como miembros privados
- { key: readability-identifier-naming.StaticVariableCase, value: lower_case }
- { key: readability-identifier-naming.StaticVariableSuffix, value: _ }
# Constantes estáticas sin sufijo
- { key: readability-identifier-naming.StaticConstantCase, value: UPPER_CASE }
# Constantes globales en UPPER_CASE
- { key: readability-identifier-naming.GlobalConstantCase, value: UPPER_CASE }
# Variables constexpr globales en UPPER_CASE
- { key: readability-identifier-naming.ConstexprVariableCase, value: UPPER_CASE }
# Constantes locales en UPPER_CASE
- { key: readability-identifier-naming.LocalConstantCase, value: UPPER_CASE }
# Constantes estáticas dentro de clases con sufijo _
- { key: readability-identifier-naming.ClassConstantCase, value: UPPER_CASE }
- { key: readability-identifier-naming.ClassConstantSuffix, value: _ }
# Constexpr miembros en UPPER_CASE (sin sufijo)
- { key: readability-identifier-naming.ConstexprMemberCase, value: UPPER_CASE }
# Constexpr variables con sufijo _
- { key: readability-identifier-naming.ConstexprVariableCase, value: UPPER_CASE }
- { key: readability-identifier-naming.ConstexprVariableSuffix, value: _ }
# Constexpr miembros privados/protegidos con sufijo _
- { key: readability-identifier-naming.ConstexprMethodCase, value: UPPER_CASE }
# Clases, structs y enums en CamelCase
- { key: readability-identifier-naming.ClassCase, value: CamelCase }
@@ -44,8 +54,14 @@ CheckOptions:
# Valores de enums en UPPER_CASE
- { key: readability-identifier-naming.EnumConstantCase, value: UPPER_CASE }
# Métodos en camelBack
# Métodos en camelBack (sin sufijos)
- { key: readability-identifier-naming.MethodCase, value: camelBack }
- { key: readability-identifier-naming.PrivateMethodCase, value: camelBack }
- { key: readability-identifier-naming.ProtectedMethodCase, value: camelBack }
- { key: readability-identifier-naming.PublicMethodCase, value: camelBack }
# Funciones en camelBack
- { key: readability-identifier-naming.FunctionCase, value: camelBack }
# Parámetros en lower_case
- { key: readability-identifier-naming.ParameterCase, value: lower_case }

68
.clang-tidy.bak Normal file
View File

@@ -0,0 +1,68 @@
Checks: >
readability-identifier-naming,
readability-*,
modernize-*,
clang-analyzer-*,
-readability-identifier-length,
-readability-magic-numbers
WarningsAsErrors: '*'
HeaderFilterRegex: '.*'
FormatStyle: file
CheckOptions:
# Variables locales en snake_case
- { key: readability-identifier-naming.VariableCase, value: lower_case }
# Miembros privados en snake_case con sufijo _
- { key: readability-identifier-naming.PrivateMemberCase, value: lower_case }
- { key: readability-identifier-naming.PrivateMemberSuffix, value: _ }
# Miembros protegidos en snake_case con sufijo _
- { key: readability-identifier-naming.ProtectedMemberCase, value: lower_case }
- { key: readability-identifier-naming.ProtectedMemberSuffix, value: _ }
# Miembros públicos en snake_case (sin sufijo)
- { key: readability-identifier-naming.PublicMemberCase, value: lower_case }
# Namespaces en CamelCase
- { key: readability-identifier-naming.NamespaceCase, value: CamelCase }
# Constantes globales en UPPER_CASE
- { key: readability-identifier-naming.GlobalConstantCase, value: UPPER_CASE }
# Variables constexpr globales en UPPER_CASE
- { key: readability-identifier-naming.ConstexprVariableCase, value: UPPER_CASE }
# Constantes locales en UPPER_CASE
- { key: readability-identifier-naming.LocalConstantCase, value: UPPER_CASE }
# Constantes estáticas dentro de clases en UPPER_CASE (sin sufijo)
- { key: readability-identifier-naming.StaticConstantCase, value: UPPER_CASE }
# Constexpr miembros en UPPER_CASE (sin sufijo)
- { key: readability-identifier-naming.ConstexprMemberCase, value: UPPER_CASE }
# Constexpr miembros privados/protegidos con sufijo _
- { key: readability-identifier-naming.ConstexprMethodCase, value: UPPER_CASE }
# Clases, structs y enums en CamelCase
- { key: readability-identifier-naming.ClassCase, value: CamelCase }
- { key: readability-identifier-naming.StructCase, value: CamelCase }
- { key: readability-identifier-naming.EnumCase, value: CamelCase }
# Valores de enums en UPPER_CASE
- { key: readability-identifier-naming.EnumConstantCase, value: UPPER_CASE }
# Métodos en camelBack (sin sufijos)
- { key: readability-identifier-naming.MethodCase, value: camelBack }
- { key: readability-identifier-naming.PrivateMethodCase, value: camelBack }
- { key: readability-identifier-naming.ProtectedMethodCase, value: camelBack }
- { key: readability-identifier-naming.PublicMethodCase, value: camelBack }
# Funciones en camelBack
- { key: readability-identifier-naming.FunctionCase, value: camelBack }
# Parámetros en lower_case
- { key: readability-identifier-naming.ParameterCase, value: lower_case }

View File

@@ -1,4 +1,4 @@
# CMakeLists.txt (Versión corregida y mejorada)
# CMakeLists.txt
cmake_minimum_required(VERSION 3.10)
project(coffee_crisis_arcade_edition VERSION 2.00)
@@ -7,6 +7,14 @@ project(coffee_crisis_arcade_edition VERSION 2.00)
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED True)
# Establece la política CMP0072 para indicar cómo se debe seleccionar la implementación de OpenGL.
# En este caso, se elige la opción "GLVND", que utiliza bibliotecas modernas y modulares (libOpenGL, libGLX),
# en lugar de la biblioteca OpenGL clásica (libGL). Esto mejora la compatibilidad con drivers recientes
# y evita ambigüedades cuando se encuentran múltiples implementaciones de OpenGL en el sistema.
cmake_policy(SET CMP0072 NEW)
set(OpenGL_GL_PREFERENCE GLVND)
# --- 1. LISTA EXPLÍCITA DE FUENTES ---
set(APP_SOURCES
# --- Archivos Principales del Sistema ---

View File

@@ -0,0 +1,2 @@
Desde l'arrel del projecte executar:
clang-tidy source/fitxer.cpp -p build/ --fix

View File

@@ -77,7 +77,7 @@ void Audio::fadeOutMusic(int milliseconds) const {
// Establece el volumen de los sonidos
void Audio::setSoundVolume(int sound_volume, Group group) const {
if (sound_enabled_) {
sound_volume = std::clamp(sound_volume, MIN_VOLUME_, MAX_VOLUME_);
sound_volume = std::clamp(sound_volume, MIN_VOLUME, MAX_VOLUME);
const float CONVERTED_VOLUME = (sound_volume / 100.0F) * (Options::audio.volume / 100.0F);
JA_SetSoundVolume(CONVERTED_VOLUME, static_cast<int>(group));
}
@@ -86,7 +86,7 @@ void Audio::setSoundVolume(int sound_volume, Group group) const {
// Establece el volumen de la música
void Audio::setMusicVolume(int music_volume) const {
if (music_enabled_) {
music_volume = std::clamp(music_volume, MIN_VOLUME_, MAX_VOLUME_);
music_volume = std::clamp(music_volume, MIN_VOLUME, MAX_VOLUME);
const float CONVERTED_VOLUME = (music_volume / 100.0F) * (Options::audio.volume / 100.0F);
JA_SetMusicVolume(CONVERTED_VOLUME);
}
@@ -101,8 +101,8 @@ void Audio::applySettings() {
void Audio::enable(bool value) {
enabled_ = value;
setSoundVolume(enabled_ ? Options::audio.sound.volume : MIN_VOLUME_);
setMusicVolume(enabled_ ? Options::audio.music.volume : MIN_VOLUME_);
setSoundVolume(enabled_ ? Options::audio.sound.volume : MIN_VOLUME);
setMusicVolume(enabled_ ? Options::audio.music.volume : MIN_VOLUME);
}
// Inicializa SDL Audio
@@ -112,7 +112,7 @@ void Audio::initSDLAudio() {
} else {
SDL_LogInfo(SDL_LOG_CATEGORY_TEST, "\n** SDL_AUDIO: INITIALIZING\n");
JA_Init(FREQUENCY_, SDL_AUDIO_S16LE, 2);
JA_Init(FREQUENCY, SDL_AUDIO_S16LE, 2);
enable(Options::audio.enabled);
SDL_LogInfo(SDL_LOG_CATEGORY_TEST, "** SDL_AUDIO: INITIALIZATION COMPLETE\n");

View File

@@ -13,9 +13,9 @@ class Audio {
};
// --- Constantes ---
static constexpr int MAX_VOLUME_ = 100;
static constexpr int MIN_VOLUME_ = 0;
static constexpr int FREQUENCY_ = 48000;
static constexpr int MAX_VOLUME = 100;
static constexpr int MIN_VOLUME = 0;
static constexpr int FREQUENCY = 48000;
// --- Métodos de singleton ---
static void init(); // Inicializa el objeto Audio
@@ -71,8 +71,8 @@ class Audio {
Music() : state(MusicState::STOPPED), loop(false) {}
// Constructor para inicializar con valores específicos
Music(MusicState initState, std::string initName, bool initLoop)
: state(initState), name(std::move(initName)), loop(initLoop) {}
Music(MusicState init_state, std::string init_name, bool init_loop)
: state(init_state), name(std::move(init_name)), loop(init_loop) {}
};
Music music_;

View File

@@ -74,20 +74,20 @@ Background::Background()
// Inicializa objetos
{
constexpr float top_clouds_speed = 0.1f;
constexpr float bottom_clouds_speed = 0.05f;
constexpr float TOP_CLOUDS_SPEED = 0.1f;
constexpr float BOTTOM_CLOUDS_SPEED = 0.05f;
top_clouds_sprite_a_->setSpriteClip(0, 0, top_clouds_texture_->getWidth(), top_clouds_texture_->getHeight());
top_clouds_sprite_a_->setVelX(-top_clouds_speed);
top_clouds_sprite_a_->setVelX(-TOP_CLOUDS_SPEED);
top_clouds_sprite_b_->setSpriteClip(0, 0, top_clouds_texture_->getWidth(), top_clouds_texture_->getHeight());
top_clouds_sprite_b_->setVelX(-top_clouds_speed);
top_clouds_sprite_b_->setVelX(-TOP_CLOUDS_SPEED);
bottom_clouds_sprite_a_->setSpriteClip(0, 0, bottom_clouds_texture_->getWidth(), bottom_clouds_texture_->getHeight());
bottom_clouds_sprite_a_->setVelX(-bottom_clouds_speed);
bottom_clouds_sprite_a_->setVelX(-BOTTOM_CLOUDS_SPEED);
bottom_clouds_sprite_b_->setSpriteClip(0, 0, bottom_clouds_texture_->getWidth(), bottom_clouds_texture_->getHeight());
bottom_clouds_sprite_b_->setVelX(-bottom_clouds_speed);
bottom_clouds_sprite_b_->setVelX(-BOTTOM_CLOUDS_SPEED);
buildings_sprite_->setY(base_ - buildings_sprite_->getHeight());
grass_sprite_->setY(base_ - grass_sprite_->getHeight());
@@ -317,13 +317,13 @@ void Background::updateClouds() {
// Precalcula el vector con el recorrido del sol
void Background::createSunPath() {
constexpr float CENTER_X = 170;
const float center_y = base_ - 80;
const float CENTER_Y = base_ - 80;
constexpr float RADIUS = 120;
// Generar puntos de la curva desde 90 a 180 grados
for (double theta = M_PI / 2; theta <= M_PI; theta += 0.01) {
float x = CENTER_X + (RADIUS * cos(theta));
float y = center_y - (RADIUS * sin(theta));
float y = CENTER_Y - (RADIUS * sin(theta));
sun_path_.push_back({x, y});
}
@@ -338,13 +338,13 @@ void Background::createSunPath() {
// Precalcula el vector con el recorrido de la luna
void Background::createMoonPath() {
constexpr float CENTER_X = 100;
const float center_y = base_ - 50;
const float CENTER_Y = base_ - 50;
constexpr float RADIUS = 140;
// Generar puntos de la curva desde 0 a 90 grados
for (double theta = 0; theta <= M_PI / 2; theta += 0.01) {
float x = CENTER_X + (RADIUS * cos(theta));
float y = center_y - (RADIUS * sin(theta));
float y = CENTER_Y - (RADIUS * sin(theta));
moon_path_.push_back({x, y});
}
}

View File

@@ -30,15 +30,15 @@ Balloon::Balloon(float x, float y, BalloonType type, BalloonSize size, float vel
vy_ = 0;
max_vy_ = 3.0f;
const int index = static_cast<int>(size_);
gravity_ = param.balloon.settings.at(index).grav;
default_vy_ = param.balloon.settings.at(index).vel;
h_ = w_ = BALLOON_SIZE[index];
power_ = BALLOON_POWER[index];
menace_ = BALLOON_MENACE[index];
score_ = BALLOON_SCORE[index];
bouncing_sound_ = BALLOON_BOUNCING_SOUND[index];
popping_sound_ = BALLOON_POPPING_SOUND[index];
const int INDEX = static_cast<int>(size_);
gravity_ = param.balloon.settings.at(INDEX).grav;
default_vy_ = param.balloon.settings.at(INDEX).vel;
h_ = w_ = BALLOON_SIZE[INDEX];
power_ = BALLOON_POWER[INDEX];
menace_ = BALLOON_MENACE[INDEX];
score_ = BALLOON_SCORE[INDEX];
bouncing_sound_ = BALLOON_BOUNCING_SOUND[INDEX];
popping_sound_ = BALLOON_POPPING_SOUND[INDEX];
break;
}
@@ -47,19 +47,19 @@ Balloon::Balloon(float x, float y, BalloonType type, BalloonSize size, float vel
default_vy_ = max_vy_ = vy_ = fabs(vx_ * 2.0f);
gravity_ = 0.00f;
const int index = static_cast<int>(size_);
h_ = w_ = BALLOON_SIZE[index];
power_ = BALLOON_POWER[index];
menace_ = BALLOON_MENACE[index];
score_ = BALLOON_SCORE[index];
bouncing_sound_ = BALLOON_BOUNCING_SOUND[index];
popping_sound_ = BALLOON_POPPING_SOUND[index];
const int INDEX = static_cast<int>(size_);
h_ = w_ = BALLOON_SIZE[INDEX];
power_ = BALLOON_POWER[INDEX];
menace_ = BALLOON_MENACE[INDEX];
score_ = BALLOON_SCORE[INDEX];
bouncing_sound_ = BALLOON_BOUNCING_SOUND[INDEX];
popping_sound_ = BALLOON_POPPING_SOUND[INDEX];
break;
}
case BalloonType::POWERBALL: {
constexpr int index = 3;
constexpr int INDEX = 3;
h_ = w_ = BALLOON_SIZE[4];
bouncing_sound_ = BALLOON_BOUNCING_SOUND[3];
popping_sound_ = "power_ball_explosion.wav";
@@ -67,8 +67,8 @@ Balloon::Balloon(float x, float y, BalloonType type, BalloonSize size, float vel
vy_ = 0;
max_vy_ = 3.0f;
gravity_ = param.balloon.settings.at(index).grav;
default_vy_ = param.balloon.settings.at(index).vel;
gravity_ = param.balloon.settings.at(INDEX).grav;
default_vy_ = param.balloon.settings.at(INDEX).vel;
sprite_->setRotate(creation_timer <= 0);
sprite_->setRotateAmount(vx_ > 0.0f ? 2.0 : -2.0);
@@ -96,9 +96,9 @@ Balloon::Balloon(float x, float y, BalloonType type, BalloonSize size, float vel
// Centra el globo en la posición X
void Balloon::alignTo(int x) {
x_ = static_cast<float>(x - (w_ / 2));
const int min_x = play_area_.x;
const int max_x = play_area_.w - w_;
x_ = std::clamp(x_, static_cast<float>(min_x), static_cast<float>(max_x));
const int MIN_X = play_area_.x;
const int MAX_X = play_area_.w - w_;
x_ = std::clamp(x_, static_cast<float>(MIN_X), static_cast<float>(MAX_X));
}
// Pinta el globo en la pantalla
@@ -146,13 +146,13 @@ void Balloon::move() {
x_ += vx_ * speed_;
// Colisión en las partes laterales de la zona de juego
const int clip = 2;
const float min_x = play_area_.x - clip;
const float max_x = play_area_.x + play_area_.w - w_ + clip;
if (x_ < min_x || x_ > max_x) {
const int CLIP = 2;
const float MIN_X = play_area_.x - CLIP;
const float MAX_X = play_area_.x + play_area_.w - w_ + CLIP;
if (x_ < MIN_X || x_ > MAX_X) {
if (bouncing_sound_enabled_)
playSound(bouncing_sound_);
x_ = std::clamp(x_, min_x, max_x);
x_ = std::clamp(x_, MIN_X, MAX_X);
vx_ = -vx_;
// Activa el efecto de rebote o invierte la rotación
if (type_ == BalloonType::POWERBALL) {
@@ -167,22 +167,22 @@ void Balloon::move() {
// Colisión en la parte superior solo si el globo va de subida
if (vy_ < 0) {
const int min_y = play_area_.y;
if (y_ < min_y) {
const int MIN_Y = play_area_.y;
if (y_ < MIN_Y) {
if (bouncing_sound_enabled_)
playSound(bouncing_sound_);
y_ = min_y;
y_ = MIN_Y;
vy_ = -vy_;
enableBounce();
}
}
// Colisión en la parte inferior de la zona de juego
const int max_y = play_area_.y + play_area_.h - h_;
if (y_ > max_y) {
const int MAX_Y = play_area_.y + play_area_.h - h_;
if (y_ > MAX_Y) {
if (bouncing_sound_enabled_)
playSound(bouncing_sound_);
y_ = max_y;
y_ = MAX_Y;
vy_ = -default_vy_;
if (type_ != BalloonType::POWERBALL) {
enableBounce();
@@ -240,10 +240,10 @@ void Balloon::updateState() {
x_ += vx_;
// Comprueba no se salga por los laterales
const int min_x = play_area_.x;
const int max_x = play_area_.w - w_;
const int MIN_X = play_area_.x;
const int MAX_X = play_area_.w - w_;
if (x_ < min_x || x_ > max_x) {
if (x_ < MIN_X || x_ > MAX_X) {
// Corrige y cambia el sentido de la velocidad
x_ -= vx_;
vx_ = -vx_;
@@ -340,9 +340,9 @@ void Balloon::disableBounce() {
// Aplica el efecto
void Balloon::updateBounce() {
if (bouncing_.enabled) {
const int index = bouncing_.counter / bouncing_.speed;
bouncing_.zoomW = bouncing_.w[index];
bouncing_.zoomH = bouncing_.h[index];
const int INDEX = bouncing_.counter / bouncing_.speed;
bouncing_.zoomW = bouncing_.w[INDEX];
bouncing_.zoomH = bouncing_.h[INDEX];
zoomSprite();
@@ -371,8 +371,8 @@ void Balloon::playSound(const std::string &name) {
if (!sound_enabled_)
return;
static auto audio = Audio::get();
audio->playSound(name);
static auto audio_ = Audio::get();
audio_->playSound(name);
}
// Explota el globo

View File

@@ -5,22 +5,22 @@
#include "utils.h" // Para ParamGame, Param, Zone, BLOCK
void BalloonFormations::initBalloonFormations() {
constexpr int y4 = -BLOCK;
const int x4_0 = param.game.play_area.rect.x;
const int x4_100 = param.game.play_area.rect.w - BALLOON_SIZE[3];
constexpr int Y4 = -BLOCK;
const int X4_0 = param.game.play_area.rect.x;
const int X4_100 = param.game.play_area.rect.w - BALLOON_SIZE[3];
constexpr int y3 = -BLOCK;
const int x3_0 = param.game.play_area.rect.x;
const int x3_100 = param.game.play_area.rect.w - BALLOON_SIZE[2];
constexpr int Y3 = -BLOCK;
const int X3_0 = param.game.play_area.rect.x;
const int X3_100 = param.game.play_area.rect.w - BALLOON_SIZE[2];
constexpr int y2 = -BLOCK;
const int x2_0 = param.game.play_area.rect.x;
const int x2_100 = param.game.play_area.rect.w - BALLOON_SIZE[1];
constexpr int Y2 = -BLOCK;
const int X2_0 = param.game.play_area.rect.x;
const int X2_100 = param.game.play_area.rect.w - BALLOON_SIZE[1];
constexpr int y1 = -BLOCK;
const int x1_0 = param.game.play_area.rect.x;
const int x1_50 = param.game.play_area.center_x - (BALLOON_SIZE[0] / 2);
const int x1_100 = param.game.play_area.rect.w - BALLOON_SIZE[0];
constexpr int Y1 = -BLOCK;
const int X1_0 = param.game.play_area.rect.x;
const int X1_50 = param.game.play_area.center_x - (BALLOON_SIZE[0] / 2);
const int X1_100 = param.game.play_area.rect.w - BALLOON_SIZE[0];
balloon_formation_.reserve(NUMBER_OF_BALLOON_FORMATIONS);
@@ -29,16 +29,16 @@ void BalloonFormations::initBalloonFormations() {
// #00 - Dos enemigos BALLOON4 uno a cada extremo
{
std::vector<BalloonFormationParams> init_params = {
BalloonFormationParams(x4_0, y4, BALLOON_VELX_POSITIVE, BalloonType::BALLOON, BalloonSize::SIZE4, CREATION_TIME),
BalloonFormationParams(x4_100, y4, BALLOON_VELX_NEGATIVE, BalloonType::BALLOON, BalloonSize::SIZE4, CREATION_TIME)};
BalloonFormationParams(X4_0, Y4, BALLOON_VELX_POSITIVE, BalloonType::BALLOON, BalloonSize::SIZE4, CREATION_TIME),
BalloonFormationParams(X4_100, Y4, BALLOON_VELX_NEGATIVE, BalloonType::BALLOON, BalloonSize::SIZE4, CREATION_TIME)};
balloon_formation_.emplace_back(2, init_params);
}
// #01 - Dos enemigos BALLOON4 uno a cada cuarto. Ambos van hacia el centro
{
std::vector<BalloonFormationParams> init_params = {
BalloonFormationParams(param.game.play_area.first_quarter_x - (BALLOON_SIZE[3] / 2), y4, BALLOON_VELX_POSITIVE, BalloonType::BALLOON, BalloonSize::SIZE4, CREATION_TIME),
BalloonFormationParams(param.game.play_area.third_quarter_x - (BALLOON_SIZE[3] / 2), y4, BALLOON_VELX_NEGATIVE, BalloonType::BALLOON, BalloonSize::SIZE4, CREATION_TIME)};
BalloonFormationParams(param.game.play_area.first_quarter_x - (BALLOON_SIZE[3] / 2), Y4, BALLOON_VELX_POSITIVE, BalloonType::BALLOON, BalloonSize::SIZE4, CREATION_TIME),
BalloonFormationParams(param.game.play_area.third_quarter_x - (BALLOON_SIZE[3] / 2), Y4, BALLOON_VELX_NEGATIVE, BalloonType::BALLOON, BalloonSize::SIZE4, CREATION_TIME)};
balloon_formation_.emplace_back(2, init_params);
}
@@ -46,7 +46,7 @@ void BalloonFormations::initBalloonFormations() {
{
std::vector<BalloonFormationParams> init_params;
for (int i = 0; i < 4; ++i) {
init_params.emplace_back(x2_0 + (i * (BALLOON_SIZE[1] + 1)), y2, BALLOON_VELX_POSITIVE, BalloonType::BALLOON, BalloonSize::SIZE2, CREATION_TIME - (10 * i));
init_params.emplace_back(X2_0 + (i * (BALLOON_SIZE[1] + 1)), Y2, BALLOON_VELX_POSITIVE, BalloonType::BALLOON, BalloonSize::SIZE2, CREATION_TIME - (10 * i));
}
balloon_formation_.emplace_back(4, init_params);
}
@@ -55,7 +55,7 @@ void BalloonFormations::initBalloonFormations() {
{
std::vector<BalloonFormationParams> init_params;
for (int i = 0; i < 4; ++i) {
init_params.emplace_back(x2_100 - (i * (BALLOON_SIZE[1] + 1)), y2, BALLOON_VELX_NEGATIVE, BalloonType::BALLOON, BalloonSize::SIZE2, CREATION_TIME - (10 * i));
init_params.emplace_back(X2_100 - (i * (BALLOON_SIZE[1] + 1)), Y2, BALLOON_VELX_NEGATIVE, BalloonType::BALLOON, BalloonSize::SIZE2, CREATION_TIME - (10 * i));
}
balloon_formation_.emplace_back(4, init_params);
}
@@ -64,7 +64,7 @@ void BalloonFormations::initBalloonFormations() {
{
std::vector<BalloonFormationParams> init_params;
for (int i = 0; i < 3; ++i) {
init_params.emplace_back(x3_0 + (i * (BALLOON_SIZE[2] * 2)), y3, BALLOON_VELX_POSITIVE, BalloonType::BALLOON, BalloonSize::SIZE3, CREATION_TIME - (10 * i));
init_params.emplace_back(X3_0 + (i * (BALLOON_SIZE[2] * 2)), Y3, BALLOON_VELX_POSITIVE, BalloonType::BALLOON, BalloonSize::SIZE3, CREATION_TIME - (10 * i));
}
balloon_formation_.emplace_back(3, init_params);
}
@@ -73,7 +73,7 @@ void BalloonFormations::initBalloonFormations() {
{
std::vector<BalloonFormationParams> init_params;
for (int i = 0; i < 3; ++i) {
init_params.emplace_back(x3_100 - (i * (BALLOON_SIZE[2] * 2)), y3, BALLOON_VELX_NEGATIVE, BalloonType::BALLOON, BalloonSize::SIZE3, CREATION_TIME - (10 * i));
init_params.emplace_back(X3_100 - (i * (BALLOON_SIZE[2] * 2)), Y3, BALLOON_VELX_NEGATIVE, BalloonType::BALLOON, BalloonSize::SIZE3, CREATION_TIME - (10 * i));
}
balloon_formation_.emplace_back(3, init_params);
}
@@ -82,7 +82,7 @@ void BalloonFormations::initBalloonFormations() {
{
std::vector<BalloonFormationParams> init_params;
for (int i = 0; i < 3; ++i) {
init_params.emplace_back(x3_0 + (i * (BALLOON_SIZE[2] + 1)), y3, BALLOON_VELX_POSITIVE, BalloonType::BALLOON, BalloonSize::SIZE3, CREATION_TIME - (10 * i));
init_params.emplace_back(X3_0 + (i * (BALLOON_SIZE[2] + 1)), Y3, BALLOON_VELX_POSITIVE, BalloonType::BALLOON, BalloonSize::SIZE3, CREATION_TIME - (10 * i));
}
balloon_formation_.emplace_back(3, init_params);
}
@@ -91,7 +91,7 @@ void BalloonFormations::initBalloonFormations() {
{
std::vector<BalloonFormationParams> init_params;
for (int i = 0; i < 3; ++i) {
init_params.emplace_back(x3_100 - (i * (BALLOON_SIZE[2] + 1)), y3, BALLOON_VELX_NEGATIVE, BalloonType::BALLOON, BalloonSize::SIZE3, CREATION_TIME - (10 * i));
init_params.emplace_back(X3_100 - (i * (BALLOON_SIZE[2] + 1)), Y3, BALLOON_VELX_NEGATIVE, BalloonType::BALLOON, BalloonSize::SIZE3, CREATION_TIME - (10 * i));
}
balloon_formation_.emplace_back(3, init_params);
}
@@ -100,7 +100,7 @@ void BalloonFormations::initBalloonFormations() {
{
std::vector<BalloonFormationParams> init_params;
for (int i = 0; i < 6; ++i) {
init_params.emplace_back(x1_0 + (i * (BALLOON_SIZE[0] + 1)), y1, BALLOON_VELX_POSITIVE, BalloonType::BALLOON, BalloonSize::SIZE1, CREATION_TIME - (10 * i));
init_params.emplace_back(X1_0 + (i * (BALLOON_SIZE[0] + 1)), Y1, BALLOON_VELX_POSITIVE, BalloonType::BALLOON, BalloonSize::SIZE1, CREATION_TIME - (10 * i));
}
balloon_formation_.emplace_back(6, init_params);
}
@@ -109,7 +109,7 @@ void BalloonFormations::initBalloonFormations() {
{
std::vector<BalloonFormationParams> init_params;
for (int i = 0; i < 6; ++i) {
init_params.emplace_back(x1_100 - (i * (BALLOON_SIZE[0] + 1)), y1, BALLOON_VELX_NEGATIVE, BalloonType::BALLOON, BalloonSize::SIZE1, CREATION_TIME - (10 * i));
init_params.emplace_back(X1_100 - (i * (BALLOON_SIZE[0] + 1)), Y1, BALLOON_VELX_NEGATIVE, BalloonType::BALLOON, BalloonSize::SIZE1, CREATION_TIME - (10 * i));
}
balloon_formation_.emplace_back(6, init_params);
}
@@ -118,7 +118,7 @@ void BalloonFormations::initBalloonFormations() {
{
std::vector<BalloonFormationParams> init_params;
for (int i = 0; i < 3; ++i) {
init_params.emplace_back(x4_0 + (i * (BALLOON_SIZE[3] + 1)), y4, BALLOON_VELX_POSITIVE, BalloonType::BALLOON, BalloonSize::SIZE4, CREATION_TIME - (15 * i));
init_params.emplace_back(X4_0 + (i * (BALLOON_SIZE[3] + 1)), Y4, BALLOON_VELX_POSITIVE, BalloonType::BALLOON, BalloonSize::SIZE4, CREATION_TIME - (15 * i));
}
balloon_formation_.emplace_back(3, init_params);
}
@@ -127,7 +127,7 @@ void BalloonFormations::initBalloonFormations() {
{
std::vector<BalloonFormationParams> init_params;
for (int i = 0; i < 3; ++i) {
init_params.emplace_back(x4_100 - (i * (BALLOON_SIZE[3] + 1)), y4, BALLOON_VELX_NEGATIVE, BalloonType::BALLOON, BalloonSize::SIZE4, CREATION_TIME - (15 * i));
init_params.emplace_back(X4_100 - (i * (BALLOON_SIZE[3] + 1)), Y4, BALLOON_VELX_NEGATIVE, BalloonType::BALLOON, BalloonSize::SIZE4, CREATION_TIME - (15 * i));
}
balloon_formation_.emplace_back(3, init_params);
}
@@ -136,7 +136,7 @@ void BalloonFormations::initBalloonFormations() {
{
std::vector<BalloonFormationParams> init_params;
for (int i = 0; i < 6; ++i) {
init_params.emplace_back(x2_0 + (i * (BALLOON_SIZE[1] + 1)), y2, BALLOON_VELX_POSITIVE, BalloonType::BALLOON, BalloonSize::SIZE2, CREATION_TIME - (10 * i));
init_params.emplace_back(X2_0 + (i * (BALLOON_SIZE[1] + 1)), Y2, BALLOON_VELX_POSITIVE, BalloonType::BALLOON, BalloonSize::SIZE2, CREATION_TIME - (10 * i));
}
balloon_formation_.emplace_back(6, init_params);
}
@@ -145,7 +145,7 @@ void BalloonFormations::initBalloonFormations() {
{
std::vector<BalloonFormationParams> init_params;
for (int i = 0; i < 6; ++i) {
init_params.emplace_back(x2_100 - (i * (BALLOON_SIZE[1] + 1)), y2, BALLOON_VELX_NEGATIVE, BalloonType::BALLOON, BalloonSize::SIZE2, CREATION_TIME - (10 * i));
init_params.emplace_back(X2_100 - (i * (BALLOON_SIZE[1] + 1)), Y2, BALLOON_VELX_NEGATIVE, BalloonType::BALLOON, BalloonSize::SIZE2, CREATION_TIME - (10 * i));
}
balloon_formation_.emplace_back(6, init_params);
}
@@ -154,7 +154,7 @@ void BalloonFormations::initBalloonFormations() {
{
std::vector<BalloonFormationParams> init_params;
for (int i = 0; i < 5; ++i) {
init_params.emplace_back(x3_0 + (i * (BALLOON_SIZE[2] * 2)), y3, BALLOON_VELX_POSITIVE, BalloonType::BALLOON, BalloonSize::SIZE3, CREATION_TIME - (10 * i));
init_params.emplace_back(X3_0 + (i * (BALLOON_SIZE[2] * 2)), Y3, BALLOON_VELX_POSITIVE, BalloonType::BALLOON, BalloonSize::SIZE3, CREATION_TIME - (10 * i));
}
balloon_formation_.emplace_back(5, init_params);
}
@@ -163,7 +163,7 @@ void BalloonFormations::initBalloonFormations() {
{
std::vector<BalloonFormationParams> init_params;
for (int i = 0; i < 5; ++i) {
init_params.emplace_back(x3_100 - (i * (BALLOON_SIZE[2] * 2)), y3, BALLOON_VELX_NEGATIVE, BalloonType::BALLOON, BalloonSize::SIZE3, CREATION_TIME - (10 * i));
init_params.emplace_back(X3_100 - (i * (BALLOON_SIZE[2] * 2)), Y3, BALLOON_VELX_NEGATIVE, BalloonType::BALLOON, BalloonSize::SIZE3, CREATION_TIME - (10 * i));
}
balloon_formation_.emplace_back(5, init_params);
}
@@ -172,7 +172,7 @@ void BalloonFormations::initBalloonFormations() {
{
std::vector<BalloonFormationParams> init_params;
for (int i = 0; i < 5; ++i) {
init_params.emplace_back(x3_0 + (i * (BALLOON_SIZE[2] + 1)), y3, BALLOON_VELX_POSITIVE, BalloonType::BALLOON, BalloonSize::SIZE3, CREATION_TIME - (10 * i));
init_params.emplace_back(X3_0 + (i * (BALLOON_SIZE[2] + 1)), Y3, BALLOON_VELX_POSITIVE, BalloonType::BALLOON, BalloonSize::SIZE3, CREATION_TIME - (10 * i));
}
balloon_formation_.emplace_back(5, init_params);
}
@@ -181,7 +181,7 @@ void BalloonFormations::initBalloonFormations() {
{
std::vector<BalloonFormationParams> init_params;
for (int i = 0; i < 5; ++i) {
init_params.emplace_back(x3_100 - (i * (BALLOON_SIZE[2] + 1)), y3, BALLOON_VELX_NEGATIVE, BalloonType::BALLOON, BalloonSize::SIZE3, CREATION_TIME - (10 * i));
init_params.emplace_back(X3_100 - (i * (BALLOON_SIZE[2] + 1)), Y3, BALLOON_VELX_NEGATIVE, BalloonType::BALLOON, BalloonSize::SIZE3, CREATION_TIME - (10 * i));
}
balloon_formation_.emplace_back(5, init_params);
}
@@ -190,7 +190,7 @@ void BalloonFormations::initBalloonFormations() {
{
std::vector<BalloonFormationParams> init_params;
for (int i = 0; i < 12; ++i) {
init_params.emplace_back(x1_0 + (i * (BALLOON_SIZE[0] + 1)), y1, BALLOON_VELX_POSITIVE, BalloonType::BALLOON, BalloonSize::SIZE1, CREATION_TIME - (10 * i));
init_params.emplace_back(X1_0 + (i * (BALLOON_SIZE[0] + 1)), Y1, BALLOON_VELX_POSITIVE, BalloonType::BALLOON, BalloonSize::SIZE1, CREATION_TIME - (10 * i));
}
balloon_formation_.emplace_back(12, init_params);
}
@@ -199,7 +199,7 @@ void BalloonFormations::initBalloonFormations() {
{
std::vector<BalloonFormationParams> init_params;
for (int i = 0; i < 12; ++i) {
init_params.emplace_back(x1_100 - (i * (BALLOON_SIZE[0] + 1)), y1, BALLOON_VELX_NEGATIVE, BalloonType::BALLOON, BalloonSize::SIZE1, CREATION_TIME - (10 * i));
init_params.emplace_back(X1_100 - (i * (BALLOON_SIZE[0] + 1)), Y1, BALLOON_VELX_NEGATIVE, BalloonType::BALLOON, BalloonSize::SIZE1, CREATION_TIME - (10 * i));
}
balloon_formation_.emplace_back(12, init_params);
}
@@ -207,12 +207,12 @@ void BalloonFormations::initBalloonFormations() {
// #20 - Dos enemigos BALLOON4 seguidos desde la izquierda/derecha. Simétricos
{
std::vector<BalloonFormationParams> init_params;
const int half = 4 / 2;
const int HALF = 4 / 2;
for (int i = 0; i < 4; ++i) {
if (i < half) {
init_params.emplace_back(x4_0 + (i * (BALLOON_SIZE[3] + 1)), y4, BALLOON_VELX_POSITIVE, BalloonType::BALLOON, BalloonSize::SIZE4, CREATION_TIME + (0 * i));
if (i < HALF) {
init_params.emplace_back(X4_0 + (i * (BALLOON_SIZE[3] + 1)), Y4, BALLOON_VELX_POSITIVE, BalloonType::BALLOON, BalloonSize::SIZE4, CREATION_TIME + (0 * i));
} else {
init_params.emplace_back(x4_100 - ((i - half) * (BALLOON_SIZE[3] + 1)), y4, BALLOON_VELX_NEGATIVE, BalloonType::BALLOON, BalloonSize::SIZE4, CREATION_TIME + (0 * i));
init_params.emplace_back(X4_100 - ((i - HALF) * (BALLOON_SIZE[3] + 1)), Y4, BALLOON_VELX_NEGATIVE, BalloonType::BALLOON, BalloonSize::SIZE4, CREATION_TIME + (0 * i));
}
}
balloon_formation_.emplace_back(4, init_params);
@@ -221,12 +221,12 @@ void BalloonFormations::initBalloonFormations() {
// #20 - Dos enemigos BALLOON4 seguidos desde la izquierda/derecha. Simétricos
{
std::vector<BalloonFormationParams> init_params;
const int half = 4 / 2;
const int HALF = 4 / 2;
for (int i = 0; i < 4; ++i) {
if (i < half) {
init_params.emplace_back(x4_0 + (i * (BALLOON_SIZE[3] + 1)), y4, BALLOON_VELX_POSITIVE, BalloonType::BALLOON, BalloonSize::SIZE4, CREATION_TIME + (0 * i));
if (i < HALF) {
init_params.emplace_back(X4_0 + (i * (BALLOON_SIZE[3] + 1)), Y4, BALLOON_VELX_POSITIVE, BalloonType::BALLOON, BalloonSize::SIZE4, CREATION_TIME + (0 * i));
} else {
init_params.emplace_back(x4_100 - ((i - half) * (BALLOON_SIZE[3] + 1)), y4, BALLOON_VELX_NEGATIVE, BalloonType::BALLOON, BalloonSize::SIZE4, CREATION_TIME + (0 * i));
init_params.emplace_back(X4_100 - ((i - HALF) * (BALLOON_SIZE[3] + 1)), Y4, BALLOON_VELX_NEGATIVE, BalloonType::BALLOON, BalloonSize::SIZE4, CREATION_TIME + (0 * i));
}
}
balloon_formation_.emplace_back(4, init_params);
@@ -235,12 +235,12 @@ void BalloonFormations::initBalloonFormations() {
// #21 - Diez enemigos BALLOON2 uno detrás del otro. Izquierda/derecha. Simétricos
{
std::vector<BalloonFormationParams> init_params;
const int half = 10 / 2;
const int HALF = 10 / 2;
for (int i = 0; i < 10; ++i) {
if (i < half) {
init_params.emplace_back(x2_0 + (i * (BALLOON_SIZE[1] + 1)), y2, BALLOON_VELX_POSITIVE, BalloonType::BALLOON, BalloonSize::SIZE2, CREATION_TIME - (3 * i));
if (i < HALF) {
init_params.emplace_back(X2_0 + (i * (BALLOON_SIZE[1] + 1)), Y2, BALLOON_VELX_POSITIVE, BalloonType::BALLOON, BalloonSize::SIZE2, CREATION_TIME - (3 * i));
} else {
init_params.emplace_back(x2_100 - ((i - half) * (BALLOON_SIZE[1] + 1)), y2, BALLOON_VELX_NEGATIVE, BalloonType::BALLOON, BalloonSize::SIZE2, CREATION_TIME - (3 * (i - half)));
init_params.emplace_back(X2_100 - ((i - HALF) * (BALLOON_SIZE[1] + 1)), Y2, BALLOON_VELX_NEGATIVE, BalloonType::BALLOON, BalloonSize::SIZE2, CREATION_TIME - (3 * (i - HALF)));
}
}
balloon_formation_.emplace_back(10, init_params);
@@ -249,12 +249,12 @@ void BalloonFormations::initBalloonFormations() {
// #22 - Diez enemigos BALLOON3. Hacia la derecha/izquierda. Separados. Simétricos
{
std::vector<BalloonFormationParams> init_params;
const int half = 10 / 2;
const int HALF = 10 / 2;
for (int i = 0; i < 10; ++i) {
if (i < half) {
init_params.emplace_back(x3_0 + (i * (BALLOON_SIZE[2] * 2)), y3, BALLOON_VELX_POSITIVE, BalloonType::BALLOON, BalloonSize::SIZE3, CREATION_TIME - (10 * i));
if (i < HALF) {
init_params.emplace_back(X3_0 + (i * (BALLOON_SIZE[2] * 2)), Y3, BALLOON_VELX_POSITIVE, BalloonType::BALLOON, BalloonSize::SIZE3, CREATION_TIME - (10 * i));
} else {
init_params.emplace_back(x3_100 - ((i - half) * (BALLOON_SIZE[2] * 2)), y3, BALLOON_VELX_NEGATIVE, BalloonType::BALLOON, BalloonSize::SIZE3, CREATION_TIME - (10 * (i - half)));
init_params.emplace_back(X3_100 - ((i - HALF) * (BALLOON_SIZE[2] * 2)), Y3, BALLOON_VELX_NEGATIVE, BalloonType::BALLOON, BalloonSize::SIZE3, CREATION_TIME - (10 * (i - HALF)));
}
}
balloon_formation_.emplace_back(10, init_params);
@@ -263,12 +263,12 @@ void BalloonFormations::initBalloonFormations() {
// #23 - Diez enemigos BALLOON3. Hacia la derecha. Juntos. Simétricos
{
std::vector<BalloonFormationParams> init_params;
const int half = 10 / 2;
const int HALF = 10 / 2;
for (int i = 0; i < 10; ++i) {
if (i < half) {
init_params.emplace_back(x3_0 + (i * (BALLOON_SIZE[2] + 1)), y3, BALLOON_VELX_POSITIVE, BalloonType::BALLOON, BalloonSize::SIZE3, CREATION_TIME - (10 * i));
if (i < HALF) {
init_params.emplace_back(X3_0 + (i * (BALLOON_SIZE[2] + 1)), Y3, BALLOON_VELX_POSITIVE, BalloonType::BALLOON, BalloonSize::SIZE3, CREATION_TIME - (10 * i));
} else {
init_params.emplace_back(x3_100 - ((i - half) * (BALLOON_SIZE[2] + 1)), y3, BALLOON_VELX_NEGATIVE, BalloonType::BALLOON, BalloonSize::SIZE3, CREATION_TIME - (10 * (i - half)));
init_params.emplace_back(X3_100 - ((i - HALF) * (BALLOON_SIZE[2] + 1)), Y3, BALLOON_VELX_NEGATIVE, BalloonType::BALLOON, BalloonSize::SIZE3, CREATION_TIME - (10 * (i - HALF)));
}
}
balloon_formation_.emplace_back(10, init_params);
@@ -277,12 +277,12 @@ void BalloonFormations::initBalloonFormations() {
// #24 - Treinta enemigos BALLOON1. Del centro hacia los extremos. Juntos. Simétricos
{
std::vector<BalloonFormationParams> init_params;
const int half = 30 / 2;
const int HALF = 30 / 2;
for (int i = 0; i < 30; ++i) {
if (i < half) {
init_params.emplace_back(x1_50, y1, BALLOON_VELX_POSITIVE, BalloonType::BALLOON, BalloonSize::SIZE1, CREATION_TIME + (5 * i));
if (i < HALF) {
init_params.emplace_back(X1_50, Y1, BALLOON_VELX_POSITIVE, BalloonType::BALLOON, BalloonSize::SIZE1, CREATION_TIME + (5 * i));
} else {
init_params.emplace_back(x1_50, y1, BALLOON_VELX_NEGATIVE, BalloonType::BALLOON, BalloonSize::SIZE1, CREATION_TIME + (5 * (i - half)));
init_params.emplace_back(X1_50, Y1, BALLOON_VELX_NEGATIVE, BalloonType::BALLOON, BalloonSize::SIZE1, CREATION_TIME + (5 * (i - HALF)));
}
}
balloon_formation_.emplace_back(30, init_params);
@@ -291,12 +291,12 @@ void BalloonFormations::initBalloonFormations() {
// #25 - Treinta enemigos BALLOON1. Del centro hacia adentro. Juntos. Simétricos
{
std::vector<BalloonFormationParams> init_params;
const int half = 30 / 2;
const int HALF = 30 / 2;
for (int i = 0; i < 30; ++i) {
if (i < half) {
init_params.emplace_back(x1_50 + 20, y1, BALLOON_VELX_NEGATIVE, BalloonType::BALLOON, BalloonSize::SIZE1, CREATION_TIME - (5 * i));
if (i < HALF) {
init_params.emplace_back(X1_50 + 20, Y1, BALLOON_VELX_NEGATIVE, BalloonType::BALLOON, BalloonSize::SIZE1, CREATION_TIME - (5 * i));
} else {
init_params.emplace_back(x1_50 - 20, y1, BALLOON_VELX_POSITIVE, BalloonType::BALLOON, BalloonSize::SIZE1, CREATION_TIME - (5 * (i - half)));
init_params.emplace_back(X1_50 - 20, Y1, BALLOON_VELX_POSITIVE, BalloonType::BALLOON, BalloonSize::SIZE1, CREATION_TIME - (5 * (i - HALF)));
}
}
balloon_formation_.emplace_back(30, init_params);
@@ -322,10 +322,10 @@ void BalloonFormations::initBalloonFormations() {
// TEST
std::vector<BalloonFormationParams> test_params = {
{10, y1, 0, BalloonType::FLOATER, BalloonSize::SIZE1, 200},
{50, y1, 0, BalloonType::FLOATER, BalloonSize::SIZE2, 200},
{90, y1, 0, BalloonType::FLOATER, BalloonSize::SIZE3, 200},
{140, y1, 0, BalloonType::FLOATER, BalloonSize::SIZE4, 200}};
{10, Y1, 0, BalloonType::FLOATER, BalloonSize::SIZE1, 200},
{50, Y1, 0, BalloonType::FLOATER, BalloonSize::SIZE2, 200},
{90, Y1, 0, BalloonType::FLOATER, BalloonSize::SIZE3, 200},
{140, Y1, 0, BalloonType::FLOATER, BalloonSize::SIZE4, 200}};
balloon_formation_.at(99) = BalloonFormationUnit(4, test_params);
}

View File

@@ -96,10 +96,10 @@ void BalloonManager::deployBalloonFormation(int stage) {
last_balloon_deploy_ = formation;
const auto set = balloon_formations_->getSet(stage, formation);
const auto num_enemies = set.number_of_balloons;
for (int i = 0; i < num_enemies; ++i) {
auto p = set.init[i];
const auto SET = balloon_formations_->getSet(stage, formation);
const auto NUM_ENEMIES = SET.number_of_balloons;
for (int i = 0; i < NUM_ENEMIES; ++i) {
auto p = SET.init[i];
createBalloon(
p.x,
p.y,
@@ -117,20 +117,20 @@ void BalloonManager::deployBalloonFormation(int stage) {
// Crea una formación de enemigos específica
void BalloonManager::deploySet(int set_number) {
const auto set = balloon_formations_->getSet(set_number);
const auto num_enemies = set.number_of_balloons;
for (int i = 0; i < num_enemies; ++i) {
auto p = set.init[i];
const auto SET = balloon_formations_->getSet(set_number);
const auto NUM_ENEMIES = SET.number_of_balloons;
for (int i = 0; i < NUM_ENEMIES; ++i) {
auto p = SET.init[i];
createBalloon(p.x, p.y, p.type, p.size, p.vel_x, balloon_speed_, p.creation_counter);
}
}
// Crea una formación de enemigos específica
void BalloonManager::deploySet(int set_number, int y) {
const auto set = balloon_formations_->getSet(set_number);
const auto num_enemies = set.number_of_balloons;
for (int i = 0; i < num_enemies; ++i) {
auto p = set.init[i];
const auto SET = balloon_formations_->getSet(set_number);
const auto NUM_ENEMIES = SET.number_of_balloons;
for (int i = 0; i < NUM_ENEMIES; ++i) {
auto p = SET.init[i];
createBalloon(p.x, y, p.type, p.size, p.vel_x, balloon_speed_, p.creation_counter);
}
}
@@ -340,14 +340,14 @@ void BalloonManager::createTwoBigBalloons() {
// Crea una disposición de globos aleatoria
void BalloonManager::createRandomBalloons() {
const int num_balloons = 2 + rand() % 4;
for (int i = 0; i < num_balloons; ++i) {
const float x = param.game.game_area.rect.x + (rand() % static_cast<int>(param.game.game_area.rect.w)) - BALLOON_SIZE[3];
const int y = param.game.game_area.rect.y + (rand() % 50);
const BalloonSize size = static_cast<BalloonSize>(rand() % 4);
const float vel_x = (rand() % 2 == 0) ? BALLOON_VELX_POSITIVE : BALLOON_VELX_NEGATIVE;
const int creation_counter = 0;
createBalloon(x, y, BalloonType::BALLOON, size, vel_x, balloon_speed_, creation_counter);
const int NUM_BALLOONS = 2 + rand() % 4;
for (int i = 0; i < NUM_BALLOONS; ++i) {
const float X = param.game.game_area.rect.x + (rand() % static_cast<int>(param.game.game_area.rect.w)) - BALLOON_SIZE[3];
const int Y = param.game.game_area.rect.y + (rand() % 50);
const BalloonSize SIZE = static_cast<BalloonSize>(rand() % 4);
const float VEL_X = (rand() % 2 == 0) ? BALLOON_VELX_POSITIVE : BALLOON_VELX_NEGATIVE;
const int CREATION_COUNTER = 0;
createBalloon(X, Y, BalloonType::BALLOON, SIZE, VEL_X, balloon_speed_, CREATION_COUNTER);
}
}

View File

@@ -38,9 +38,9 @@ void DefineButtons::doControllerButtonDown(const SDL_GamepadButtonEvent &event)
return;
}
const auto button = static_cast<SDL_GamepadButton>(event.button);
if (checkButtonNotInUse(button)) {
buttons_.at(index_button_).button = button;
const auto BUTTON = static_cast<SDL_GamepadButton>(event.button);
if (checkButtonNotInUse(BUTTON)) {
buttons_.at(index_button_).button = BUTTON;
incIndexButton();
}
}

View File

@@ -126,9 +126,9 @@ void Director::loadParams() {
#ifdef ANBERNIC
const std::string paramFilePath = asset->get("param_320x240.txt");
#else
const std::string paramFilePath = overrides.param_file == "--320x240" ? Asset::get()->get("param_320x240.txt") : Asset::get()->get("param_320x256.txt");
const std::string PARAM_FILE_PATH = overrides.param_file == "--320x240" ? Asset::get()->get("param_320x240.txt") : Asset::get()->get("param_320x256.txt");
#endif
loadParamsFromFile(paramFilePath);
loadParamsFromFile(PARAM_FILE_PATH);
}
// Carga el fichero de puntuaciones
@@ -205,8 +205,8 @@ void Director::bindInputs() {
}
// Mapea las asignaciones a los botones desde el archivo de configuración, si se da el caso
const size_t max_controllers = std::min(2, NUM_GAMEPADS);
for (size_t i = 0; i < max_controllers; ++i) {
const size_t MAX_CONTROLLERS = std::min(2, NUM_GAMEPADS);
for (size_t i = 0; i < MAX_CONTROLLERS; ++i) {
for (auto &controller : Options::controllers) {
if (Input::get()->getControllerName(i) == controller.name) {
for (size_t j = 0; j < controller.inputs.size(); ++j) {
@@ -224,7 +224,7 @@ void Director::bindInputs() {
}
// Guarda las asignaciones de botones en las opciones de los dos primeros mandos
for (size_t i = 0; i < max_controllers; ++i) {
for (size_t i = 0; i < MAX_CONTROLLERS; ++i) {
// Variables asociadas al mando
Options::controllers.at(i).index = i;
Options::controllers.at(i).name = Input::get()->getControllerName(i);
@@ -246,186 +246,186 @@ void Director::setFileList() {
#ifdef MACOS_BUNDLE
const std::string prefix = "/../Resources";
#else
const std::string prefix;
const std::string PREFIX;
#endif
// Ficheros de configuración
Asset::get()->add(system_folder_ + "/config.txt", AssetType::DATA, false, true);
Asset::get()->add(system_folder_ + "/score.bin", AssetType::DATA, false, true);
Asset::get()->add(prefix + "/data/config/param_320x240.txt", AssetType::DATA);
Asset::get()->add(prefix + "/data/config/param_320x256.txt", AssetType::DATA);
Asset::get()->add(prefix + "/data/config/demo1.bin", AssetType::DEMODATA);
Asset::get()->add(prefix + "/data/config/demo2.bin", AssetType::DEMODATA);
Asset::get()->add(prefix + "/data/config/gamecontrollerdb.txt", AssetType::DATA);
Asset::get()->add(PREFIX + "/data/config/param_320x240.txt", AssetType::DATA);
Asset::get()->add(PREFIX + "/data/config/param_320x256.txt", AssetType::DATA);
Asset::get()->add(PREFIX + "/data/config/demo1.bin", AssetType::DEMODATA);
Asset::get()->add(PREFIX + "/data/config/demo2.bin", AssetType::DEMODATA);
Asset::get()->add(PREFIX + "/data/config/gamecontrollerdb.txt", AssetType::DATA);
// Musicas
Asset::get()->add(prefix + "/data/music/intro.ogg", AssetType::MUSIC);
Asset::get()->add(prefix + "/data/music/playing.ogg", AssetType::MUSIC);
Asset::get()->add(prefix + "/data/music/title.ogg", AssetType::MUSIC);
Asset::get()->add(prefix + "/data/music/credits.ogg", AssetType::MUSIC);
Asset::get()->add(PREFIX + "/data/music/intro.ogg", AssetType::MUSIC);
Asset::get()->add(PREFIX + "/data/music/playing.ogg", AssetType::MUSIC);
Asset::get()->add(PREFIX + "/data/music/title.ogg", AssetType::MUSIC);
Asset::get()->add(PREFIX + "/data/music/credits.ogg", AssetType::MUSIC);
// Sonidos
Asset::get()->add(prefix + "/data/sound/balloon1.wav", AssetType::SOUND);
Asset::get()->add(prefix + "/data/sound/balloon2.wav", AssetType::SOUND);
Asset::get()->add(prefix + "/data/sound/balloon3.wav", AssetType::SOUND);
Asset::get()->add(prefix + "/data/sound/balloon4.wav", AssetType::SOUND);
Asset::get()->add(prefix + "/data/sound/bubble1.wav", AssetType::SOUND);
Asset::get()->add(prefix + "/data/sound/bubble2.wav", AssetType::SOUND);
Asset::get()->add(prefix + "/data/sound/bubble3.wav", AssetType::SOUND);
Asset::get()->add(prefix + "/data/sound/bubble4.wav", AssetType::SOUND);
Asset::get()->add(prefix + "/data/sound/bullet.wav", AssetType::SOUND);
Asset::get()->add(prefix + "/data/sound/clock.wav", AssetType::SOUND);
Asset::get()->add(prefix + "/data/sound/coffee_out.wav", AssetType::SOUND);
Asset::get()->add(prefix + "/data/sound/continue_clock.wav", AssetType::SOUND);
Asset::get()->add(prefix + "/data/sound/debian_drop.wav", AssetType::SOUND);
Asset::get()->add(prefix + "/data/sound/debian_pickup.wav", AssetType::SOUND);
Asset::get()->add(prefix + "/data/sound/hi_score_achieved.wav", AssetType::SOUND);
Asset::get()->add(prefix + "/data/sound/item_drop.wav", AssetType::SOUND);
Asset::get()->add(prefix + "/data/sound/item_pickup.wav", AssetType::SOUND);
Asset::get()->add(prefix + "/data/sound/jump.wav", AssetType::SOUND);
Asset::get()->add(prefix + "/data/sound/logo.wav", AssetType::SOUND);
Asset::get()->add(prefix + "/data/sound/notify.wav", AssetType::SOUND);
Asset::get()->add(prefix + "/data/sound/player_collision.wav", AssetType::SOUND);
Asset::get()->add(prefix + "/data/sound/power_ball_explosion.wav", AssetType::SOUND);
Asset::get()->add(prefix + "/data/sound/service_menu_adjust.wav", AssetType::SOUND);
Asset::get()->add(prefix + "/data/sound/service_menu_move.wav", AssetType::SOUND);
Asset::get()->add(prefix + "/data/sound/service_menu_select.wav", AssetType::SOUND);
Asset::get()->add(prefix + "/data/sound/stage_change.wav", AssetType::SOUND);
Asset::get()->add(prefix + "/data/sound/tabe_hit.wav", AssetType::SOUND);
Asset::get()->add(prefix + "/data/sound/tabe.wav", AssetType::SOUND);
Asset::get()->add(prefix + "/data/sound/title.wav", AssetType::SOUND);
Asset::get()->add(prefix + "/data/sound/voice_aw_aw_aw.wav", AssetType::SOUND);
Asset::get()->add(prefix + "/data/sound/voice_coffee.wav", AssetType::SOUND);
Asset::get()->add(prefix + "/data/sound/voice_get_ready.wav", AssetType::SOUND);
Asset::get()->add(prefix + "/data/sound/voice_no.wav", AssetType::SOUND);
Asset::get()->add(prefix + "/data/sound/voice_power_up.wav", AssetType::SOUND);
Asset::get()->add(prefix + "/data/sound/voice_thankyou.wav", AssetType::SOUND);
Asset::get()->add(prefix + "/data/sound/walk.wav", AssetType::SOUND);
Asset::get()->add(PREFIX + "/data/sound/balloon1.wav", AssetType::SOUND);
Asset::get()->add(PREFIX + "/data/sound/balloon2.wav", AssetType::SOUND);
Asset::get()->add(PREFIX + "/data/sound/balloon3.wav", AssetType::SOUND);
Asset::get()->add(PREFIX + "/data/sound/balloon4.wav", AssetType::SOUND);
Asset::get()->add(PREFIX + "/data/sound/bubble1.wav", AssetType::SOUND);
Asset::get()->add(PREFIX + "/data/sound/bubble2.wav", AssetType::SOUND);
Asset::get()->add(PREFIX + "/data/sound/bubble3.wav", AssetType::SOUND);
Asset::get()->add(PREFIX + "/data/sound/bubble4.wav", AssetType::SOUND);
Asset::get()->add(PREFIX + "/data/sound/bullet.wav", AssetType::SOUND);
Asset::get()->add(PREFIX + "/data/sound/clock.wav", AssetType::SOUND);
Asset::get()->add(PREFIX + "/data/sound/coffee_out.wav", AssetType::SOUND);
Asset::get()->add(PREFIX + "/data/sound/continue_clock.wav", AssetType::SOUND);
Asset::get()->add(PREFIX + "/data/sound/debian_drop.wav", AssetType::SOUND);
Asset::get()->add(PREFIX + "/data/sound/debian_pickup.wav", AssetType::SOUND);
Asset::get()->add(PREFIX + "/data/sound/hi_score_achieved.wav", AssetType::SOUND);
Asset::get()->add(PREFIX + "/data/sound/item_drop.wav", AssetType::SOUND);
Asset::get()->add(PREFIX + "/data/sound/item_pickup.wav", AssetType::SOUND);
Asset::get()->add(PREFIX + "/data/sound/jump.wav", AssetType::SOUND);
Asset::get()->add(PREFIX + "/data/sound/logo.wav", AssetType::SOUND);
Asset::get()->add(PREFIX + "/data/sound/notify.wav", AssetType::SOUND);
Asset::get()->add(PREFIX + "/data/sound/player_collision.wav", AssetType::SOUND);
Asset::get()->add(PREFIX + "/data/sound/power_ball_explosion.wav", AssetType::SOUND);
Asset::get()->add(PREFIX + "/data/sound/service_menu_adjust.wav", AssetType::SOUND);
Asset::get()->add(PREFIX + "/data/sound/service_menu_move.wav", AssetType::SOUND);
Asset::get()->add(PREFIX + "/data/sound/service_menu_select.wav", AssetType::SOUND);
Asset::get()->add(PREFIX + "/data/sound/stage_change.wav", AssetType::SOUND);
Asset::get()->add(PREFIX + "/data/sound/tabe_hit.wav", AssetType::SOUND);
Asset::get()->add(PREFIX + "/data/sound/tabe.wav", AssetType::SOUND);
Asset::get()->add(PREFIX + "/data/sound/title.wav", AssetType::SOUND);
Asset::get()->add(PREFIX + "/data/sound/voice_aw_aw_aw.wav", AssetType::SOUND);
Asset::get()->add(PREFIX + "/data/sound/voice_coffee.wav", AssetType::SOUND);
Asset::get()->add(PREFIX + "/data/sound/voice_get_ready.wav", AssetType::SOUND);
Asset::get()->add(PREFIX + "/data/sound/voice_no.wav", AssetType::SOUND);
Asset::get()->add(PREFIX + "/data/sound/voice_power_up.wav", AssetType::SOUND);
Asset::get()->add(PREFIX + "/data/sound/voice_thankyou.wav", AssetType::SOUND);
Asset::get()->add(PREFIX + "/data/sound/walk.wav", AssetType::SOUND);
// Shaders
Asset::get()->add(prefix + "/data/shaders/crtpi_256.glsl", AssetType::DATA);
Asset::get()->add(prefix + "/data/shaders/crtpi_240.glsl", AssetType::DATA);
Asset::get()->add(PREFIX + "/data/shaders/crtpi_256.glsl", AssetType::DATA);
Asset::get()->add(PREFIX + "/data/shaders/crtpi_240.glsl", AssetType::DATA);
// Texturas - Balloons
Asset::get()->add(prefix + "/data/gfx/balloon/balloon1.png", AssetType::BITMAP);
Asset::get()->add(prefix + "/data/gfx/balloon/balloon1.ani", AssetType::ANIMATION);
Asset::get()->add(prefix + "/data/gfx/balloon/balloon2.png", AssetType::BITMAP);
Asset::get()->add(prefix + "/data/gfx/balloon/balloon2.ani", AssetType::ANIMATION);
Asset::get()->add(prefix + "/data/gfx/balloon/balloon3.png", AssetType::BITMAP);
Asset::get()->add(prefix + "/data/gfx/balloon/balloon3.ani", AssetType::ANIMATION);
Asset::get()->add(prefix + "/data/gfx/balloon/balloon4.png", AssetType::BITMAP);
Asset::get()->add(prefix + "/data/gfx/balloon/balloon4.ani", AssetType::ANIMATION);
Asset::get()->add(PREFIX + "/data/gfx/balloon/balloon1.png", AssetType::BITMAP);
Asset::get()->add(PREFIX + "/data/gfx/balloon/balloon1.ani", AssetType::ANIMATION);
Asset::get()->add(PREFIX + "/data/gfx/balloon/balloon2.png", AssetType::BITMAP);
Asset::get()->add(PREFIX + "/data/gfx/balloon/balloon2.ani", AssetType::ANIMATION);
Asset::get()->add(PREFIX + "/data/gfx/balloon/balloon3.png", AssetType::BITMAP);
Asset::get()->add(PREFIX + "/data/gfx/balloon/balloon3.ani", AssetType::ANIMATION);
Asset::get()->add(PREFIX + "/data/gfx/balloon/balloon4.png", AssetType::BITMAP);
Asset::get()->add(PREFIX + "/data/gfx/balloon/balloon4.ani", AssetType::ANIMATION);
// Texturas - Explosiones
Asset::get()->add(prefix + "/data/gfx/balloon/explosion1.png", AssetType::BITMAP);
Asset::get()->add(prefix + "/data/gfx/balloon/explosion1.ani", AssetType::ANIMATION);
Asset::get()->add(prefix + "/data/gfx/balloon/explosion2.png", AssetType::BITMAP);
Asset::get()->add(prefix + "/data/gfx/balloon/explosion2.ani", AssetType::ANIMATION);
Asset::get()->add(prefix + "/data/gfx/balloon/explosion3.png", AssetType::BITMAP);
Asset::get()->add(prefix + "/data/gfx/balloon/explosion3.ani", AssetType::ANIMATION);
Asset::get()->add(prefix + "/data/gfx/balloon/explosion4.png", AssetType::BITMAP);
Asset::get()->add(prefix + "/data/gfx/balloon/explosion4.ani", AssetType::ANIMATION);
Asset::get()->add(PREFIX + "/data/gfx/balloon/explosion1.png", AssetType::BITMAP);
Asset::get()->add(PREFIX + "/data/gfx/balloon/explosion1.ani", AssetType::ANIMATION);
Asset::get()->add(PREFIX + "/data/gfx/balloon/explosion2.png", AssetType::BITMAP);
Asset::get()->add(PREFIX + "/data/gfx/balloon/explosion2.ani", AssetType::ANIMATION);
Asset::get()->add(PREFIX + "/data/gfx/balloon/explosion3.png", AssetType::BITMAP);
Asset::get()->add(PREFIX + "/data/gfx/balloon/explosion3.ani", AssetType::ANIMATION);
Asset::get()->add(PREFIX + "/data/gfx/balloon/explosion4.png", AssetType::BITMAP);
Asset::get()->add(PREFIX + "/data/gfx/balloon/explosion4.ani", AssetType::ANIMATION);
// Texturas - Power Ball
Asset::get()->add(prefix + "/data/gfx/balloon/powerball.png", AssetType::BITMAP);
Asset::get()->add(prefix + "/data/gfx/balloon/powerball.ani", AssetType::ANIMATION);
Asset::get()->add(PREFIX + "/data/gfx/balloon/powerball.png", AssetType::BITMAP);
Asset::get()->add(PREFIX + "/data/gfx/balloon/powerball.ani", AssetType::ANIMATION);
// Texturas - Bala
Asset::get()->add(prefix + "/data/gfx/bullet/bullet.png", AssetType::BITMAP);
Asset::get()->add(prefix + "/data/gfx/bullet/bullet.ani", AssetType::ANIMATION);
Asset::get()->add(PREFIX + "/data/gfx/bullet/bullet.png", AssetType::BITMAP);
Asset::get()->add(PREFIX + "/data/gfx/bullet/bullet.ani", AssetType::ANIMATION);
// Texturas - Tabe
Asset::get()->add(prefix + "/data/gfx/tabe/tabe.png", AssetType::BITMAP);
Asset::get()->add(prefix + "/data/gfx/tabe/tabe.ani", AssetType::ANIMATION);
Asset::get()->add(PREFIX + "/data/gfx/tabe/tabe.png", AssetType::BITMAP);
Asset::get()->add(PREFIX + "/data/gfx/tabe/tabe.ani", AssetType::ANIMATION);
// Texturas - Juego
Asset::get()->add(prefix + "/data/gfx/game/game_buildings.png", AssetType::BITMAP);
Asset::get()->add(prefix + "/data/gfx/game/game_clouds1.png", AssetType::BITMAP);
Asset::get()->add(prefix + "/data/gfx/game/game_clouds2.png", AssetType::BITMAP);
Asset::get()->add(prefix + "/data/gfx/game/game_grass.png", AssetType::BITMAP);
Asset::get()->add(prefix + "/data/gfx/game/game_power_meter.png", AssetType::BITMAP);
Asset::get()->add(prefix + "/data/gfx/game/game_sky_colors.png", AssetType::BITMAP);
Asset::get()->add(prefix + "/data/gfx/game/game_sun.png", AssetType::BITMAP);
Asset::get()->add(prefix + "/data/gfx/game/game_moon.png", AssetType::BITMAP);
Asset::get()->add(PREFIX + "/data/gfx/game/game_buildings.png", AssetType::BITMAP);
Asset::get()->add(PREFIX + "/data/gfx/game/game_clouds1.png", AssetType::BITMAP);
Asset::get()->add(PREFIX + "/data/gfx/game/game_clouds2.png", AssetType::BITMAP);
Asset::get()->add(PREFIX + "/data/gfx/game/game_grass.png", AssetType::BITMAP);
Asset::get()->add(PREFIX + "/data/gfx/game/game_power_meter.png", AssetType::BITMAP);
Asset::get()->add(PREFIX + "/data/gfx/game/game_sky_colors.png", AssetType::BITMAP);
Asset::get()->add(PREFIX + "/data/gfx/game/game_sun.png", AssetType::BITMAP);
Asset::get()->add(PREFIX + "/data/gfx/game/game_moon.png", AssetType::BITMAP);
// Texturas - Intro
Asset::get()->add(prefix + "/data/gfx/intro/intro1.png", AssetType::BITMAP);
Asset::get()->add(prefix + "/data/gfx/intro/intro2.png", AssetType::BITMAP);
Asset::get()->add(prefix + "/data/gfx/intro/intro3.png", AssetType::BITMAP);
Asset::get()->add(prefix + "/data/gfx/intro/intro4.png", AssetType::BITMAP);
Asset::get()->add(prefix + "/data/gfx/intro/intro5.png", AssetType::BITMAP);
Asset::get()->add(prefix + "/data/gfx/intro/intro6.png", AssetType::BITMAP);
Asset::get()->add(PREFIX + "/data/gfx/intro/intro1.png", AssetType::BITMAP);
Asset::get()->add(PREFIX + "/data/gfx/intro/intro2.png", AssetType::BITMAP);
Asset::get()->add(PREFIX + "/data/gfx/intro/intro3.png", AssetType::BITMAP);
Asset::get()->add(PREFIX + "/data/gfx/intro/intro4.png", AssetType::BITMAP);
Asset::get()->add(PREFIX + "/data/gfx/intro/intro5.png", AssetType::BITMAP);
Asset::get()->add(PREFIX + "/data/gfx/intro/intro6.png", AssetType::BITMAP);
// Texturas - Logo
Asset::get()->add(prefix + "/data/gfx/logo/logo_jailgames.png", AssetType::BITMAP);
Asset::get()->add(prefix + "/data/gfx/logo/logo_jailgames_mini.png", AssetType::BITMAP);
Asset::get()->add(prefix + "/data/gfx/logo/logo_since_1998.png", AssetType::BITMAP);
Asset::get()->add(PREFIX + "/data/gfx/logo/logo_jailgames.png", AssetType::BITMAP);
Asset::get()->add(PREFIX + "/data/gfx/logo/logo_jailgames_mini.png", AssetType::BITMAP);
Asset::get()->add(PREFIX + "/data/gfx/logo/logo_since_1998.png", AssetType::BITMAP);
// Texturas - Items
Asset::get()->add(prefix + "/data/gfx/item/item_points1_disk.png", AssetType::BITMAP);
Asset::get()->add(prefix + "/data/gfx/item/item_points1_disk.ani", AssetType::ANIMATION);
Asset::get()->add(prefix + "/data/gfx/item/item_points2_gavina.png", AssetType::BITMAP);
Asset::get()->add(prefix + "/data/gfx/item/item_points2_gavina.ani", AssetType::ANIMATION);
Asset::get()->add(prefix + "/data/gfx/item/item_points3_pacmar.png", AssetType::BITMAP);
Asset::get()->add(prefix + "/data/gfx/item/item_points3_pacmar.ani", AssetType::ANIMATION);
Asset::get()->add(prefix + "/data/gfx/item/item_clock.png", AssetType::BITMAP);
Asset::get()->add(prefix + "/data/gfx/item/item_clock.ani", AssetType::ANIMATION);
Asset::get()->add(prefix + "/data/gfx/item/item_coffee.png", AssetType::BITMAP);
Asset::get()->add(prefix + "/data/gfx/item/item_coffee.ani", AssetType::ANIMATION);
Asset::get()->add(prefix + "/data/gfx/item/item_debian.png", AssetType::BITMAP);
Asset::get()->add(prefix + "/data/gfx/item/item_debian.ani", AssetType::ANIMATION);
Asset::get()->add(prefix + "/data/gfx/item/item_coffee_machine.png", AssetType::BITMAP);
Asset::get()->add(prefix + "/data/gfx/item/item_coffee_machine.ani", AssetType::ANIMATION);
Asset::get()->add(PREFIX + "/data/gfx/item/item_points1_disk.png", AssetType::BITMAP);
Asset::get()->add(PREFIX + "/data/gfx/item/item_points1_disk.ani", AssetType::ANIMATION);
Asset::get()->add(PREFIX + "/data/gfx/item/item_points2_gavina.png", AssetType::BITMAP);
Asset::get()->add(PREFIX + "/data/gfx/item/item_points2_gavina.ani", AssetType::ANIMATION);
Asset::get()->add(PREFIX + "/data/gfx/item/item_points3_pacmar.png", AssetType::BITMAP);
Asset::get()->add(PREFIX + "/data/gfx/item/item_points3_pacmar.ani", AssetType::ANIMATION);
Asset::get()->add(PREFIX + "/data/gfx/item/item_clock.png", AssetType::BITMAP);
Asset::get()->add(PREFIX + "/data/gfx/item/item_clock.ani", AssetType::ANIMATION);
Asset::get()->add(PREFIX + "/data/gfx/item/item_coffee.png", AssetType::BITMAP);
Asset::get()->add(PREFIX + "/data/gfx/item/item_coffee.ani", AssetType::ANIMATION);
Asset::get()->add(PREFIX + "/data/gfx/item/item_debian.png", AssetType::BITMAP);
Asset::get()->add(PREFIX + "/data/gfx/item/item_debian.ani", AssetType::ANIMATION);
Asset::get()->add(PREFIX + "/data/gfx/item/item_coffee_machine.png", AssetType::BITMAP);
Asset::get()->add(PREFIX + "/data/gfx/item/item_coffee_machine.ani", AssetType::ANIMATION);
// Texturas - Titulo
Asset::get()->add(prefix + "/data/gfx/title/title_bg_tile.png", AssetType::BITMAP);
Asset::get()->add(prefix + "/data/gfx/title/title_coffee.png", AssetType::BITMAP);
Asset::get()->add(prefix + "/data/gfx/title/title_crisis.png", AssetType::BITMAP);
Asset::get()->add(prefix + "/data/gfx/title/title_arcade_edition.png", AssetType::BITMAP);
Asset::get()->add(prefix + "/data/gfx/title/title_dust.png", AssetType::BITMAP);
Asset::get()->add(prefix + "/data/gfx/title/title_dust.ani", AssetType::ANIMATION);
Asset::get()->add(PREFIX + "/data/gfx/title/title_bg_tile.png", AssetType::BITMAP);
Asset::get()->add(PREFIX + "/data/gfx/title/title_coffee.png", AssetType::BITMAP);
Asset::get()->add(PREFIX + "/data/gfx/title/title_crisis.png", AssetType::BITMAP);
Asset::get()->add(PREFIX + "/data/gfx/title/title_arcade_edition.png", AssetType::BITMAP);
Asset::get()->add(PREFIX + "/data/gfx/title/title_dust.png", AssetType::BITMAP);
Asset::get()->add(PREFIX + "/data/gfx/title/title_dust.ani", AssetType::ANIMATION);
// Texturas - Jugador 1
Asset::get()->add(prefix + "/data/gfx/player/player1.gif", AssetType::BITMAP);
Asset::get()->add(prefix + "/data/gfx/player/player1_coffee1.pal", AssetType::PALETTE);
Asset::get()->add(prefix + "/data/gfx/player/player1_coffee2.pal", AssetType::PALETTE);
Asset::get()->add(prefix + "/data/gfx/player/player1_invencible.pal", AssetType::PALETTE);
Asset::get()->add(prefix + "/data/gfx/player/player1_power.png", AssetType::BITMAP);
Asset::get()->add(PREFIX + "/data/gfx/player/player1.gif", AssetType::BITMAP);
Asset::get()->add(PREFIX + "/data/gfx/player/player1_coffee1.pal", AssetType::PALETTE);
Asset::get()->add(PREFIX + "/data/gfx/player/player1_coffee2.pal", AssetType::PALETTE);
Asset::get()->add(PREFIX + "/data/gfx/player/player1_invencible.pal", AssetType::PALETTE);
Asset::get()->add(PREFIX + "/data/gfx/player/player1_power.png", AssetType::BITMAP);
// Texturas - Jugador 2
Asset::get()->add(prefix + "/data/gfx/player/player2.gif", AssetType::BITMAP);
Asset::get()->add(prefix + "/data/gfx/player/player2_coffee1.pal", AssetType::PALETTE);
Asset::get()->add(prefix + "/data/gfx/player/player2_coffee2.pal", AssetType::PALETTE);
Asset::get()->add(prefix + "/data/gfx/player/player2_invencible.pal", AssetType::PALETTE);
Asset::get()->add(prefix + "/data/gfx/player/player2_power.png", AssetType::BITMAP);
Asset::get()->add(PREFIX + "/data/gfx/player/player2.gif", AssetType::BITMAP);
Asset::get()->add(PREFIX + "/data/gfx/player/player2_coffee1.pal", AssetType::PALETTE);
Asset::get()->add(PREFIX + "/data/gfx/player/player2_coffee2.pal", AssetType::PALETTE);
Asset::get()->add(PREFIX + "/data/gfx/player/player2_invencible.pal", AssetType::PALETTE);
Asset::get()->add(PREFIX + "/data/gfx/player/player2_power.png", AssetType::BITMAP);
// Animaciones del jugador
Asset::get()->add(prefix + "/data/gfx/player/player.ani", AssetType::ANIMATION);
Asset::get()->add(prefix + "/data/gfx/player/player_power.ani", AssetType::ANIMATION);
Asset::get()->add(PREFIX + "/data/gfx/player/player.ani", AssetType::ANIMATION);
Asset::get()->add(PREFIX + "/data/gfx/player/player_power.ani", AssetType::ANIMATION);
// Fuentes de texto
Asset::get()->add(prefix + "/data/font/8bithud.png", AssetType::BITMAP);
Asset::get()->add(prefix + "/data/font/8bithud.txt", AssetType::FONT);
Asset::get()->add(prefix + "/data/font/aseprite.png", AssetType::BITMAP);
Asset::get()->add(prefix + "/data/font/aseprite.txt", AssetType::FONT);
Asset::get()->add(prefix + "/data/font/smb2.png", AssetType::BITMAP);
Asset::get()->add(prefix + "/data/font/smb2_grad.png", AssetType::BITMAP);
Asset::get()->add(prefix + "/data/font/smb2.txt", AssetType::FONT);
Asset::get()->add(prefix + "/data/font/04b_25.png", AssetType::BITMAP);
Asset::get()->add(prefix + "/data/font/04b_25.txt", AssetType::FONT);
Asset::get()->add(prefix + "/data/font/04b_25_2x.png", AssetType::BITMAP);
Asset::get()->add(prefix + "/data/font/04b_25_2x.txt", AssetType::FONT);
Asset::get()->add(prefix + "/data/font/04b_25_metal.png", AssetType::BITMAP);
Asset::get()->add(prefix + "/data/font/04b_25_grey.png", AssetType::BITMAP);
Asset::get()->add(prefix + "/data/font/04b_25_flat.png", AssetType::BITMAP);
Asset::get()->add(prefix + "/data/font/04b_25_reversed.png", AssetType::BITMAP);
Asset::get()->add(prefix + "/data/font/04b_25_flat_2x.png", AssetType::BITMAP);
Asset::get()->add(prefix + "/data/font/04b_25_reversed_2x.png", AssetType::BITMAP);
Asset::get()->add(PREFIX + "/data/font/8bithud.png", AssetType::BITMAP);
Asset::get()->add(PREFIX + "/data/font/8bithud.txt", AssetType::FONT);
Asset::get()->add(PREFIX + "/data/font/aseprite.png", AssetType::BITMAP);
Asset::get()->add(PREFIX + "/data/font/aseprite.txt", AssetType::FONT);
Asset::get()->add(PREFIX + "/data/font/smb2.png", AssetType::BITMAP);
Asset::get()->add(PREFIX + "/data/font/smb2_grad.png", AssetType::BITMAP);
Asset::get()->add(PREFIX + "/data/font/smb2.txt", AssetType::FONT);
Asset::get()->add(PREFIX + "/data/font/04b_25.png", AssetType::BITMAP);
Asset::get()->add(PREFIX + "/data/font/04b_25.txt", AssetType::FONT);
Asset::get()->add(PREFIX + "/data/font/04b_25_2x.png", AssetType::BITMAP);
Asset::get()->add(PREFIX + "/data/font/04b_25_2x.txt", AssetType::FONT);
Asset::get()->add(PREFIX + "/data/font/04b_25_metal.png", AssetType::BITMAP);
Asset::get()->add(PREFIX + "/data/font/04b_25_grey.png", AssetType::BITMAP);
Asset::get()->add(PREFIX + "/data/font/04b_25_flat.png", AssetType::BITMAP);
Asset::get()->add(PREFIX + "/data/font/04b_25_reversed.png", AssetType::BITMAP);
Asset::get()->add(PREFIX + "/data/font/04b_25_flat_2x.png", AssetType::BITMAP);
Asset::get()->add(PREFIX + "/data/font/04b_25_reversed_2x.png", AssetType::BITMAP);
// Textos
Asset::get()->add(prefix + "/data/lang/es_ES.json", AssetType::LANG);
Asset::get()->add(prefix + "/data/lang/en_UK.json", AssetType::LANG);
Asset::get()->add(prefix + "/data/lang/ba_BA.json", AssetType::LANG);
Asset::get()->add(PREFIX + "/data/lang/es_ES.json", AssetType::LANG);
Asset::get()->add(PREFIX + "/data/lang/en_UK.json", AssetType::LANG);
Asset::get()->add(PREFIX + "/data/lang/ba_BA.json", AssetType::LANG);
// Si falta algun fichero, sale del programa
if (!Asset::get()->check()) {

View File

@@ -156,8 +156,8 @@ void Fade::update() {
SDL_SetRenderDrawColor(renderer_, r_, g_, b_, a_);
// Dibuja el cuadrado correspondiente
for (const auto rect : square_) {
SDL_RenderFillRect(renderer_, &rect);
for (const auto RECT : square_) {
SDL_RenderFillRect(renderer_, &RECT);
}
// Deja el renderizador como estaba
@@ -165,10 +165,10 @@ void Fade::update() {
SDL_SetRenderTarget(renderer_, temp);
// Modifica el tamaño de los rectangulos
const auto h = counter_ / 2;
const auto H = counter_ / 2;
for (size_t i = 0; i < square_.size(); ++i) {
// A partir del segundo rectangulo se pinta en función del anterior
square_.at(i).h = i == 0 ? h : std::max(static_cast<int>(square_.at(i - 1).h) - 2, 0);
square_.at(i).h = i == 0 ? H : std::max(static_cast<int>(square_.at(i - 1).h) - 2, 0);
}
int completed = 0;

View File

@@ -35,8 +35,8 @@ GameLogo::GameLogo(int x, int y)
// Inicializa las variables
void GameLogo::init() {
const auto xp = x_ - coffee_texture_->getWidth() / 2;
const auto desp = getInitialVerticalDesp();
const auto XP = x_ - coffee_texture_->getWidth() / 2;
const auto DESP = getInitialVerticalDesp();
// Configura texturas
SDL_SetTextureScaleMode(Resource::get()->getTexture("title_arcade_edition.png")->getSDLTexture(), SDL_SCALEMODE_NEAREST);
@@ -44,12 +44,12 @@ void GameLogo::init() {
// Variables
coffee_crisis_status_ = Status::DISABLED;
arcade_edition_status_ = Status::DISABLED;
shake_.init(1, 2, 8, xp);
shake_.init(1, 2, 8, XP);
zoom_ = 3.0f * ZOOM_FACTOR;
// Inicializa el bitmap de 'Coffee'
coffee_sprite_->setPosX(xp);
coffee_sprite_->setPosY(y_ - coffee_texture_->getHeight() - desp);
coffee_sprite_->setPosX(XP);
coffee_sprite_->setPosY(y_ - coffee_texture_->getHeight() - DESP);
coffee_sprite_->setWidth(coffee_texture_->getWidth());
coffee_sprite_->setHeight(coffee_texture_->getHeight());
coffee_sprite_->setVelX(0.0f);
@@ -59,12 +59,12 @@ void GameLogo::init() {
coffee_sprite_->setSpriteClip(0, 0, coffee_texture_->getWidth(), coffee_texture_->getHeight());
coffee_sprite_->setEnabled(true);
coffee_sprite_->setFinishedCounter(0);
coffee_sprite_->setDestX(xp);
coffee_sprite_->setDestX(XP);
coffee_sprite_->setDestY(y_ - coffee_texture_->getHeight());
// Inicializa el bitmap de 'Crisis'
crisis_sprite_->setPosX(xp + 15);
crisis_sprite_->setPosY(y_ + desp);
crisis_sprite_->setPosX(XP + 15);
crisis_sprite_->setPosY(y_ + DESP);
crisis_sprite_->setWidth(crisis_texture_->getWidth());
crisis_sprite_->setHeight(crisis_texture_->getHeight());
crisis_sprite_->setVelX(0.0f);
@@ -74,7 +74,7 @@ void GameLogo::init() {
crisis_sprite_->setSpriteClip(0, 0, crisis_texture_->getWidth(), crisis_texture_->getHeight());
crisis_sprite_->setEnabled(true);
crisis_sprite_->setFinishedCounter(0);
crisis_sprite_->setDestX(xp + 15);
crisis_sprite_->setDestX(XP + 15);
crisis_sprite_->setDestY(y_);
// Inicializa el bitmap de 'DustRight'
@@ -138,9 +138,9 @@ void GameLogo::update() {
shake_.counter--;
} else {
shake_.counter = shake_.delay;
const auto desp = shake_.remaining % 2 == 0 ? shake_.desp * (-1) : shake_.desp;
coffee_sprite_->setPosX(shake_.origin + desp);
crisis_sprite_->setPosX(shake_.origin + desp + 15);
const auto DESP = shake_.remaining % 2 == 0 ? shake_.desp * (-1) : shake_.desp;
coffee_sprite_->setPosX(shake_.origin + DESP);
crisis_sprite_->setPosX(shake_.origin + DESP + 15);
shake_.remaining--;
}
} else {
@@ -190,8 +190,8 @@ void GameLogo::update() {
shake_.counter--;
} else {
shake_.counter = shake_.delay;
const auto desp = shake_.remaining % 2 == 0 ? shake_.desp * (-1) : shake_.desp;
arcade_edition_sprite_->setX(shake_.origin + desp);
const auto DESP = shake_.remaining % 2 == 0 ? shake_.desp * (-1) : shake_.desp;
arcade_edition_sprite_->setX(shake_.origin + DESP);
shake_.remaining--;
}
} else {

View File

@@ -57,13 +57,13 @@ void Input::bindGameControllerButton(int controller_index, InputAction input_tar
bool Input::checkInput(InputAction input, bool repeat, InputDevice device, int controller_index) {
bool success_keyboard = false;
bool success_controller = false;
const int input_index = static_cast<int>(input);
const int INPUT_INDEX = static_cast<int>(input);
if (device == InputDevice::KEYBOARD || device == InputDevice::ANY) {
if (repeat) { // El usuario quiere saber si está pulsada (estado mantenido)
success_keyboard = key_bindings_[input_index].is_held;
success_keyboard = key_bindings_[INPUT_INDEX].is_held;
} else { // El usuario quiere saber si ACABA de ser pulsada (evento de un solo fotograma)
success_keyboard = key_bindings_[input_index].just_pressed;
success_keyboard = key_bindings_[INPUT_INDEX].just_pressed;
}
}
@@ -73,9 +73,9 @@ bool Input::checkInput(InputAction input, bool repeat, InputDevice device, int c
if (!success_controller) {
if (repeat) { // El usuario quiere saber si está pulsada (estado mantenido)
success_controller = controller_bindings_.at(controller_index).at(input_index).is_held;
success_controller = controller_bindings_.at(controller_index).at(INPUT_INDEX).is_held;
} else { // El usuario quiere saber si ACABA de ser pulsada (evento de un solo fotograma)
success_controller = controller_bindings_.at(controller_index).at(input_index).just_pressed;
success_controller = controller_bindings_.at(controller_index).at(INPUT_INDEX).just_pressed;
}
}
}
@@ -87,11 +87,11 @@ bool Input::checkInput(InputAction input, bool repeat, InputDevice device, int c
// Comprueba si hay almenos un input activo
bool Input::checkAnyInput(InputDevice device, int controller_index) {
// Obtenemos el número total de acciones posibles para iterar sobre ellas.
const int num_actions = static_cast<int>(InputAction::SIZE);
const int NUM_ACTIONS = static_cast<int>(InputAction::SIZE);
// --- Comprobación del Teclado ---
if (device == InputDevice::KEYBOARD || device == InputDevice::ANY) {
for (int i = 0; i < num_actions; ++i) {
for (int i = 0; i < NUM_ACTIONS; ++i) {
// Simplemente leemos el estado pre-calculado por Input::update().
// Ya no se llama a SDL_GetKeyboardState ni se modifica el estado '.active'.
if (key_bindings_.at(i).just_pressed) {
@@ -105,7 +105,7 @@ bool Input::checkAnyInput(InputDevice device, int controller_index) {
if (gameControllerFound() && controller_index >= 0 && controller_index < num_gamepads_) {
if (device == InputDevice::CONTROLLER || device == InputDevice::ANY) {
// Bucle CORREGIDO: Iteramos sobre todas las acciones, no sobre el número de mandos.
for (int i = 0; i < num_actions; ++i) {
for (int i = 0; i < NUM_ACTIONS; ++i) {
// Leemos el estado pre-calculado para el mando y la acción específicos.
if (controller_bindings_.at(controller_index).at(i).just_pressed) {
return true; // Se encontró una acción recién pulsada en el mando.
@@ -241,7 +241,7 @@ void Input::printBindings(InputDevice device, int controller_index) const {
// Muestra los botones asignados
for (auto bi : button_inputs_) {
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "%s : %d", to_string(bi).c_str(), controller_bindings_.at(controller_index).at(static_cast<int>(bi)).button);
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "%s : %d", inputToString(bi).c_str(), controller_bindings_.at(controller_index).at(static_cast<int>(bi)).button);
}
}
}
@@ -258,7 +258,7 @@ int Input::getIndexByName(const std::string &name) const {
}
// Convierte un InputAction a std::string
std::string Input::to_string(InputAction input) const {
std::string Input::inputToString(InputAction input) const {
switch (input) {
case InputAction::FIRE_LEFT:
return "input_fire_left";
@@ -276,16 +276,16 @@ std::string Input::to_string(InputAction input) const {
}
// Convierte un std::string a InputAction
InputAction Input::to_inputs_e(const std::string &name) const {
static const std::unordered_map<std::string, InputAction> inputMap = {
InputAction Input::stringToInput(const std::string &name) const {
static const std::unordered_map<std::string, InputAction> INPUT_MAP = {
{"input_fire_left", InputAction::FIRE_LEFT},
{"input_fire_center", InputAction::FIRE_CENTER},
{"input_fire_right", InputAction::FIRE_RIGHT},
{"input_start", InputAction::START},
{"input_service", InputAction::SERVICE}};
auto it = inputMap.find(name);
return it != inputMap.end() ? it->second : InputAction::NONE;
auto it = INPUT_MAP.find(name);
return it != INPUT_MAP.end() ? it->second : InputAction::NONE;
}
// Comprueba el eje del mando
@@ -295,16 +295,16 @@ bool Input::checkAxisInput(InputAction input, int controller_index, bool repeat)
switch (input) {
case InputAction::LEFT:
axis_active_now = SDL_GetGamepadAxis(connected_controllers_[controller_index], SDL_GAMEPAD_AXIS_LEFTX) < -AXIS_THRESHOLD_;
axis_active_now = SDL_GetGamepadAxis(connected_controllers_[controller_index], SDL_GAMEPAD_AXIS_LEFTX) < -AXIS_THRESHOLD;
break;
case InputAction::RIGHT:
axis_active_now = SDL_GetGamepadAxis(connected_controllers_[controller_index], SDL_GAMEPAD_AXIS_LEFTX) > AXIS_THRESHOLD_;
axis_active_now = SDL_GetGamepadAxis(connected_controllers_[controller_index], SDL_GAMEPAD_AXIS_LEFTX) > AXIS_THRESHOLD;
break;
case InputAction::UP:
axis_active_now = SDL_GetGamepadAxis(connected_controllers_[controller_index], SDL_GAMEPAD_AXIS_LEFTY) < -AXIS_THRESHOLD_;
axis_active_now = SDL_GetGamepadAxis(connected_controllers_[controller_index], SDL_GAMEPAD_AXIS_LEFTY) < -AXIS_THRESHOLD;
break;
case InputAction::DOWN:
axis_active_now = SDL_GetGamepadAxis(connected_controllers_[controller_index], SDL_GAMEPAD_AXIS_LEFTY) > AXIS_THRESHOLD_;
axis_active_now = SDL_GetGamepadAxis(connected_controllers_[controller_index], SDL_GAMEPAD_AXIS_LEFTY) > AXIS_THRESHOLD;
break;
default:
return false;

View File

@@ -68,83 +68,83 @@ enum class InputDevice : int {
// Clase Input: gestiona la entrada de teclado y mandos (singleton)
class Input {
public:
// --- Métodos de singleton ---
static void init(const std::string &game_controller_db_path); // Inicializa el singleton
static void destroy(); // Libera el singleton
static Input *get(); // Obtiene la instancia
public:
// --- Métodos de singleton ---
static void init(const std::string &game_controller_db_path); // Inicializa el singleton
static void destroy(); // Libera el singleton
static Input *get(); // Obtiene la instancia
// --- Métodos de configuración de controles ---
void bindKey(InputAction input, SDL_Scancode code); // Asigna inputs a teclas
void bindGameControllerButton(int controller_index, InputAction input, SDL_GamepadButton button); // Asigna inputs a botones del mando
void bindGameControllerButton(int controller_index, InputAction inputTarget, InputAction inputSource); // Asigna inputs a otros inputs del mando
// --- Métodos de configuración de controles ---
void bindKey(InputAction input, SDL_Scancode code); // Asigna inputs a teclas
void bindGameControllerButton(int controller_index, InputAction input, SDL_GamepadButton button); // Asigna inputs a botones del mando
void bindGameControllerButton(int controller_index, InputAction input_target, InputAction input_source); // Asigna inputs a otros inputs del mando
// --- Métodos de consulta de entrada ---
void update(); // Comprueba fisicamente los botones y teclas que se han pulsado
bool checkInput(InputAction input, bool repeat = true, InputDevice device = InputDevice::ANY, int controller_index = 0); // Comprueba si un input está activo
bool checkAnyInput(InputDevice device = InputDevice::ANY, int controller_index = 0); // Comprueba si hay al menos un input activo
int checkAnyButton(bool repeat = INPUT_DO_NOT_ALLOW_REPEAT); // Comprueba si hay algún botón pulsado
// --- Métodos de consulta de entrada ---
void update(); // Comprueba fisicamente los botones y teclas que se han pulsado
bool checkInput(InputAction input, bool repeat = true, InputDevice device = InputDevice::ANY, int controller_index = 0); // Comprueba si un input está activo
bool checkAnyInput(InputDevice device = InputDevice::ANY, int controller_index = 0); // Comprueba si hay al menos un input activo
int checkAnyButton(bool repeat = INPUT_DO_NOT_ALLOW_REPEAT); // Comprueba si hay algún botón pulsado
// --- Métodos de gestión de mandos ---
bool discoverGameControllers(); // Busca si hay mandos conectados
bool gameControllerFound(); // Comprueba si hay algún mando conectado
int getNumControllers() const; // Obtiene el número de mandos conectados
std::string getControllerName(int controller_index) const; // Obtiene el nombre de un mando de juego
int getJoyIndex(SDL_JoystickID id) const; // Obtiene el índice del controlador a partir de un event.id
// --- Métodos de gestión de mandos ---
bool discoverGameControllers(); // Busca si hay mandos conectados
bool gameControllerFound(); // Comprueba si hay algún mando conectado
int getNumControllers() const; // Obtiene el número de mandos conectados
std::string getControllerName(int controller_index) const; // Obtiene el nombre de un mando de juego
int getJoyIndex(SDL_JoystickID id) const; // Obtiene el índice del controlador a partir de un event.id
// --- Métodos de consulta y utilidades ---
void printBindings(InputDevice device = InputDevice::KEYBOARD, int controller_index = 0) const; // Muestra por consola los controles asignados
SDL_GamepadButton getControllerBinding(int controller_index, InputAction input) const; // Obtiene el SDL_GamepadButton asignado a un input
std::string to_string(InputAction input) const; // Convierte un InputAction a std::string
InputAction to_inputs_e(const std::string &name) const; // Convierte un std::string a InputAction
int getIndexByName(const std::string &name) const; // Obtiene el índice a partir del nombre del mando
// --- Métodos de consulta y utilidades ---
void printBindings(InputDevice device = InputDevice::KEYBOARD, int controller_index = 0) const; // Muestra por consola los controles asignados
SDL_GamepadButton getControllerBinding(int controller_index, InputAction input) const; // Obtiene el SDL_GamepadButton asignado a un input
std::string inputToString(InputAction input) const; // Convierte un InputAction a std::string
InputAction stringToInput(const std::string &name) const; // Convierte un std::string a InputAction
int getIndexByName(const std::string &name) const; // Obtiene el índice a partir del nombre del mando
// --- Métodos de reseteo de estado de entrada ---
void resetInputStates(); // Pone todos los KeyBindings.active y ControllerBindings.active a false
// --- Métodos de reseteo de estado de entrada ---
void resetInputStates(); // Pone todos los KeyBindings.active y ControllerBindings.active a false
private:
// --- Singleton ---
static Input *instance_;
private:
// --- Estructuras internas ---
struct KeyBindings {
Uint8 scancode; // Scancode asociado
bool is_held; // Está pulsada ahora mismo
bool just_pressed; // Se acaba de pulsar en este fotograma
// --- Estructuras internas ---
struct KeyBindings {
Uint8 scancode; // Scancode asociado
bool is_held; // Está pulsada ahora mismo
bool just_pressed; // Se acaba de pulsar en este fotograma
KeyBindings(Uint8 scancode = 0, bool is_held = false, bool just_pressed = false)
: scancode(scancode), is_held(is_held), just_pressed(just_pressed) {}
};
KeyBindings(Uint8 scancode = 0, bool is_held = false, bool just_pressed = false)
: scancode(scancode), is_held(is_held), just_pressed(just_pressed) {}
};
struct ControllerBindings {
SDL_GamepadButton button; // GameControllerButton asociado
bool is_held; // Está pulsada ahora mismo
bool just_pressed; // Se acaba de pulsar en este fotograma
bool axis_active; // Estado del eje
struct ControllerBindings {
SDL_GamepadButton button; // GameControllerButton asociado
bool is_held; // Está pulsada ahora mismo
bool just_pressed; // Se acaba de pulsar en este fotograma
bool axis_active; // Estado del eje
ControllerBindings(SDL_GamepadButton btn = SDL_GAMEPAD_BUTTON_INVALID, bool is_held = false, bool just_pressed = false, bool axis_act = false)
: button(btn), is_held(is_held), just_pressed(just_pressed), axis_active(axis_act) {}
};
ControllerBindings(SDL_GamepadButton btn = SDL_GAMEPAD_BUTTON_INVALID, bool is_held = false, bool just_pressed = false, bool axis_act = false)
: button(btn), is_held(is_held), just_pressed(just_pressed), axis_active(axis_act) {}
};
// --- Constantes ---
static constexpr Sint16 AXIS_THRESHOLD = 30000;
// --- Constantes ---
static constexpr Sint16 AXIS_THRESHOLD_ = 30000;
// --- Variables internas ---
std::vector<SDL_Gamepad *> connected_controllers_; // Vector con todos los mandos conectados
std::vector<SDL_Joystick *> joysticks_; // Vector con todos los joysticks conectados
std::vector<KeyBindings> key_bindings_; // Vector con las teclas asociadas a los inputs predefinidos
std::vector<std::vector<ControllerBindings>> controller_bindings_; // Vector con los botones asociados a los inputs predefinidos para cada mando
std::vector<std::string> controller_names_; // Vector con los nombres de los mandos
std::vector<InputAction> button_inputs_; // Inputs asignados al jugador y a botones, excluyendo direcciones
int num_joysticks_ = 0; // Número de joysticks conectados
int num_gamepads_ = 0; // Número de mandos conectados
std::string game_controller_db_path_; // Ruta al archivo gamecontrollerdb.txt
// --- Variables internas ---
std::vector<SDL_Gamepad *> connected_controllers_; // Vector con todos los mandos conectados
std::vector<SDL_Joystick *> joysticks_; // Vector con todos los joysticks conectados
std::vector<KeyBindings> key_bindings_; // Vector con las teclas asociadas a los inputs predefinidos
std::vector<std::vector<ControllerBindings>> controller_bindings_; // Vector con los botones asociados a los inputs predefinidos para cada mando
std::vector<std::string> controller_names_; // Vector con los nombres de los mandos
std::vector<InputAction> button_inputs_; // Inputs asignados al jugador y a botones, excluyendo direcciones
int num_joysticks_ = 0; // Número de joysticks conectados
int num_gamepads_ = 0; // Número de mandos conectados
std::string game_controller_db_path_; // Ruta al archivo gamecontrollerdb.txt
// --- Métodos internos ---
void initSDLGamePad(); // Inicializa SDL para la gestión de mandos
bool checkAxisInput(InputAction input, int controller_index, bool repeat); // Comprueba el eje del mando
// --- Métodos internos ---
void initSDLGamePad(); // Inicializa SDL para la gestión de mandos
bool checkAxisInput(InputAction input, int controller_index, bool repeat); // Comprueba el eje del mando
// --- Constructor y destructor ---
explicit Input(const std::string &game_controller_db_path); // Constructor privado
~Input() = default; // Destructor privado
// --- Constructor y destructor ---
explicit Input(const std::string &game_controller_db_path); // Constructor privado
~Input() = default; // Destructor privado
// --- Singleton ---
static Input *instance_;
};

View File

@@ -44,13 +44,13 @@ Item::Item(ItemType type, float x, float y, SDL_FRect &play_area, std::shared_pt
}
void Item::alignTo(int x) {
const float min_x = param.game.play_area.rect.x + 1;
const float max_x = play_area_.w - width_ - 1;
const float MIN_X = param.game.play_area.rect.x + 1;
const float MAX_X = play_area_.w - width_ - 1;
pos_x_ = x - (width_ / 2);
// Ajusta para que no quede fuera de la zona de juego
pos_x_ = std::clamp(pos_x_, min_x, max_x);
pos_x_ = std::clamp(pos_x_, MIN_X, MAX_X);
// Actualiza el sprite
shiftSprite();

View File

@@ -1,6 +1,7 @@
#pragma once
#include <string> // Para string, basic_string
#include <utility>
namespace Lang {
// --- Códigos de idioma soportados ---
@@ -16,33 +17,33 @@ struct Language {
std::string name; // Nombre que identifica el idioma
std::string file_name; // Nombre del fichero con los textos
Language(Code c, const std::string &n, const std::string &fn)
: code(c), name(n), file_name(fn) {}
Language(Code c, std::string n, std::string fn)
: code(c), name(std::move(n)), file_name(std::move(fn)) {}
};
// Carga los textos desde el fichero JSON especificado
bool loadFromFile(const std::string &file_path);
auto loadFromFile(const std::string &file_path) -> bool;
// Obtiene el texto por clave
std::string getText(const std::string &key);
auto getText(const std::string &key) -> std::string;
// Obtiene el código del siguiente idioma (circular)
Code getNextLangCode(Code current_lang);
auto getNextLangCode(Code current_lang) -> Code;
// Obtiene el idioma correspondiente al código proporcionado
Language getLanguage(Code code);
auto getLanguage(Code code) -> Language;
// Devuelve el código de un idioma a partir de un nombre
Code getCodeFromName(const std::string &name);
auto getCodeFromName(const std::string &name) -> Code;
// Devuelve el nombre de un idioma a partir de un código
std::string getNameFromCode(Code code);
auto getNameFromCode(Code code) -> std::string;
// Actualiza los nombres de los idiomas
void updateLanguageNames();
// Obtiene el nombre del fichero de textos asociado a un código de idioma
std::string getLanguageFileName(Code code);
auto getLanguageFileName(Code code) -> std::string;
// Establece el idioma actual
void setLanguage(Code lang);

View File

@@ -98,22 +98,22 @@ void MovingSprite::setPos(SDL_FRect rect) {
}
// Establece el valor de las variables
void MovingSprite::setPos(float x, float y) {
x_ = x;
y_ = y;
void MovingSprite::setPos(float pos_x, float pos_y) {
x_ = pos_x;
y_ = pos_y;
pos_.x = static_cast<int>(x_);
pos_.y = static_cast<int>(y_);
}
// Establece el valor de la variable
void MovingSprite::setPosX(float value) {
x_ = value;
void MovingSprite::setPosX(float pos_x) {
x_ = pos_x;
pos_.x = static_cast<int>(x_);
}
// Establece el valor de la variable
void MovingSprite::setPosY(float value) {
y_ = value;
void MovingSprite::setPosY(float pos_y) {
y_ = pos_y;
pos_.y = static_cast<int>(y_);
}

View File

@@ -14,21 +14,21 @@ class MovingSprite : public Sprite {
public:
// --- Estructura para la rotación ---
struct Rotate {
bool enabled; // Indica si ha de rotar
int counter; // Contador
int speed; // Velocidad de giro
double angle; // Ángulo para dibujarlo
float amount; // Cantidad de grados a girar en cada iteración
bool enabled{false}; // Indica si ha de rotar
int counter{0}; // Contador
int speed{1}; // Velocidad de giro
double angle{0.0}; // Ángulo para dibujarlo
float amount{0.0F}; // Cantidad de grados a girar en cada iteración
SDL_FPoint center; // Centro de rotación
Rotate() : enabled(false), counter(0), speed(1), angle(0.0), amount(0.0f), center({0.0f, 0.0f}) {}
Rotate() : center({0.0F, 0.0F}) {}
};
// --- Constructores y destructor ---
MovingSprite(std::shared_ptr<Texture> texture, SDL_FRect pos, MovingSprite::Rotate rotate, float zoom_w, float zoom_h, SDL_FlipMode flip);
MovingSprite(std::shared_ptr<Texture> texture, SDL_FRect pos);
explicit MovingSprite(std::shared_ptr<Texture> texture);
virtual ~MovingSprite() override = default;
~MovingSprite() override = default;
// --- Métodos principales ---
virtual void update(); // Actualiza las variables internas del objeto
@@ -36,12 +36,12 @@ class MovingSprite : public Sprite {
void render() override; // Muestra el sprite por pantalla
// --- Getters de posición y movimiento ---
float getPosX() const { return x_; }
float getPosY() const { return y_; }
float getVelX() const { return vx_; }
float getVelY() const { return vy_; }
float getAccelX() const { return ax_; }
float getAccelY() const { return ay_; }
[[nodiscard]] auto getPosX() const -> float { return x_; }
[[nodiscard]] auto getPosY() const -> float { return y_; }
[[nodiscard]] auto getVelX() const -> float { return vx_; }
[[nodiscard]] auto getVelY() const -> float { return vy_; }
[[nodiscard]] auto getAccelX() const -> float { return ax_; }
[[nodiscard]] auto getAccelY() const -> float { return ay_; }
// --- Setters de movimiento ---
void setVelX(float value) { vx_ = value; }
@@ -50,7 +50,7 @@ class MovingSprite : public Sprite {
void setAccelY(float value) { ay_ = value; }
// --- Rotación ---
bool isRotating() const { return rotate_.enabled; }
[[nodiscard]] auto isRotating() const -> bool { return rotate_.enabled; }
void setZoomW(float value) { zoom_w_ = value; }
void setZoomH(float value) { zoom_h_ = value; }
void setAngle(double value) { rotate_.angle = value; }
@@ -63,24 +63,24 @@ class MovingSprite : public Sprite {
// --- Flip ---
void setFlip(SDL_FlipMode flip) { flip_ = flip; }
void flip() { flip_ = (flip_ == SDL_FLIP_HORIZONTAL) ? SDL_FLIP_NONE : SDL_FLIP_HORIZONTAL; }
SDL_FlipMode getFlip() { return flip_; }
auto getFlip() -> SDL_FlipMode { return flip_; }
// --- Posición y tamaño ---
void setPos(SDL_FRect rect); // Establece la posición y el tamaño del objeto
void setPos(float x, float y); // Establece la posición del objeto
void setPosX(float value); // Establece la posición X
void setPosY(float value); // Establece la posición Y
void setPos(float pos_x, float pos_y); // Establece la posición del objeto
void setPosX(float pos_x); // Establece la posición X
void setPosY(float pos_y); // Establece la posición Y
protected:
// --- Variables de posición y movimiento ---
float x_ = 0.0f; // Posición en el eje X
float y_ = 0.0f; // Posición en el eje Y
float x_ = 0.0F; // Posición en el eje X
float y_ = 0.0F; // Posición en el eje Y
float vx_ = 0.0f; // Velocidad en el eje X. Cantidad de píxeles a desplazarse
float vy_ = 0.0f; // Velocidad en el eje Y. Cantidad de píxeles a desplazarse
float vx_ = 0.0F; // Velocidad en el eje X. Cantidad de píxeles a desplazarse
float vy_ = 0.0F; // Velocidad en el eje Y. Cantidad de píxeles a desplazarse
float ax_ = 0.0f; // Aceleración en el eje X. Variación de la velocidad
float ay_ = 0.0f; // Aceleración en el eje Y. Variación de la velocidad
float ax_ = 0.0F; // Aceleración en el eje X. Variación de la velocidad
float ay_ = 0.0F; // Aceleración en el eje Y. Variación de la velocidad
// --- Efectos visuales ---
Rotate rotate_; // Variables usadas para controlar la rotación del sprite

View File

@@ -66,15 +66,15 @@ void Notifier::update() {
// Comprueba los estados
if (notifications_[i].state == NotificationStatus::RISING) {
const float step = ((float)notifications_[i].counter / notifications_[i].travel_dist);
const int alpha = 255 * step;
const float STEP = ((float)notifications_[i].counter / notifications_[i].travel_dist);
const int ALPHA = 255 * STEP;
if (param.notification.pos_v == NotifyPosition::TOP) {
notifications_[i].rect.y++;
} else {
notifications_[i].rect.y--;
}
notifications_[i].texture->setAlpha(alpha);
notifications_[i].texture->setAlpha(ALPHA);
if (notifications_[i].rect.y == notifications_[i].y) {
notifications_[i].state = NotificationStatus::STAY;
@@ -89,15 +89,15 @@ void Notifier::update() {
notifications_[i].counter = 0;
}
} else if (notifications_[i].state == NotificationStatus::VANISHING) {
const float step = (notifications_[i].counter / (float)notifications_[i].travel_dist);
const int alpha = 255 * (1 - step);
const float STEP = (notifications_[i].counter / (float)notifications_[i].travel_dist);
const int ALPHA = 255 * (1 - STEP);
if (param.notification.pos_v == NotifyPosition::TOP) {
notifications_[i].rect.y--;
} else {
notifications_[i].rect.y++;
}
notifications_[i].texture->setAlpha(alpha);
notifications_[i].texture->setAlpha(ALPHA);
if (notifications_[i].rect.y == notifications_[i].y - notifications_[i].travel_dist) {
notifications_[i].state = NotificationStatus::FINISHED;
@@ -176,7 +176,7 @@ void Notifier::show(std::vector<std::string> texts, int icon, const std::string
// Offset
const auto TRAVEL_DIST = HEIGHT + PADDING_OUT;
auto OFFSET = notifications_.empty()
auto offset = notifications_.empty()
? DESP_V
: notifications_.back().y + (param.notification.pos_v == NotifyPosition::TOP ? TRAVEL_DIST : -TRAVEL_DIST);
@@ -185,11 +185,11 @@ void Notifier::show(std::vector<std::string> texts, int icon, const std::string
// Inicializa variables
n.code = code;
n.y = OFFSET;
n.y = offset;
n.travel_dist = TRAVEL_DIST;
n.texts = texts;
n.shape = SHAPE;
const float POS_Y = OFFSET + (param.notification.pos_v == NotifyPosition::TOP ? -TRAVEL_DIST : TRAVEL_DIST);
const float POS_Y = offset + (param.notification.pos_v == NotifyPosition::TOP ? -TRAVEL_DIST : TRAVEL_DIST);
n.rect = {desp_h, POS_Y, WIDTH, HEIGHT};
// Crea la textura
@@ -234,10 +234,10 @@ void Notifier::show(std::vector<std::string> texts, int icon, const std::string
}
// Escribe el texto de la notificación
const Color color{255, 255, 255};
const Color COLOR{255, 255, 255};
int iterator = 0;
for (const auto &text : texts) {
text_->writeColored(PADDING_IN_H + ICON_SPACE, PADDING_IN_V + iterator * (text_->getCharacterSize() + 1), text, color);
text_->writeColored(PADDING_IN_H + ICON_SPACE, PADDING_IN_V + iterator * (text_->getCharacterSize() + 1), text, COLOR);
++iterator;
}

View File

@@ -53,7 +53,7 @@ struct ParamBalloon {
float vel; // Velocidad inicial al rebotar contra el suelo
// Constructor
explicit Settings(float grav_val = 0.0f, float vel_val = 0.0f)
explicit Settings(float grav_val = 0.0F, float vel_val = 0.0F)
: grav(grav_val), vel(vel_val) {}
};

View File

@@ -6,16 +6,16 @@
#include <utility> // Para move
// Devuelve un vector con los puntos que conforman la ruta
std::vector<SDL_FPoint> createPath(float start, float end, PathType type, float fixed_pos, int steps, const std::function<double(double)> &easingFunction) {
std::vector<SDL_FPoint> createPath(float start, float end, PathType type, float fixed_pos, int steps, const std::function<double(double)> &easing_function) {
std::vector<SDL_FPoint> v;
v.reserve(steps);
for (int i = 0; i < steps; ++i) {
double t = static_cast<double>(i) / (steps - 1);
double value = start + (end - start) * easingFunction(t);
double value = start + (end - start) * easing_function(t);
if ((start > 0 && end < 0) || (start < 0 && end > 0)) {
value = start + (end > 0 ? 1 : -1) * std::abs(end - start) * easingFunction(t);
value = start + (end > 0 ? 1 : -1) * std::abs(end - start) * easing_function(t);
}
switch (type) {
@@ -56,16 +56,16 @@ void PathSprite::addPath(Path path, bool centered) {
switch (path_centered) {
case PathCentered::ON_X: {
const int x = path.spots.back().x - pos_.w / 2;
const int X = path.spots.back().x - pos_.w / 2;
for (auto &spot : path.spots)
spot.x = x;
spot.x = X;
paths_.emplace_back(path);
break;
}
case PathCentered::ON_Y: {
const int y = path.spots.back().y - pos_.h / 2;
const int Y = path.spots.back().y - pos_.h / 2;
for (auto &spot : path.spots)
spot.y = y;
spot.y = Y;
paths_.emplace_back(path);
break;
}
@@ -76,8 +76,8 @@ void PathSprite::addPath(Path path, bool centered) {
}
// Añade un recorrido
void PathSprite::addPath(int start, int end, PathType type, int fixed_pos, int steps, const std::function<double(double)> &easingFunction, int waiting_counter) {
paths_.emplace_back(createPath(start, end, type, fixed_pos, steps, easingFunction), waiting_counter);
void PathSprite::addPath(int start, int end, PathType type, int fixed_pos, int steps, const std::function<double(double)> &easing_function, int waiting_counter) {
paths_.emplace_back(createPath(start, end, type, fixed_pos, steps, easing_function), waiting_counter);
}
// Añade un recorrido
@@ -95,8 +95,8 @@ void PathSprite::enable() {
// Establece la posición
auto &path = paths_.at(current_path_);
const auto &P = path.spots.at(path.counter);
setPosition(P);
const auto &p = path.spots.at(path.counter);
setPosition(p);
}
// Coloca el sprite en los diferentes puntos del recorrido

View File

@@ -174,8 +174,8 @@ void Player::move() {
if (player_sprite_->getPosY() > play_area_.h - HEIGHT_) {
if (player_sprite_->getVelY() < 2.0f) {
// Si la velocidad de rebote es baja, lo detiene y cambia de estado
const auto nextPlayerStatus = IsEligibleForHighScore() ? PlayerState::ENTERING_NAME : PlayerState::CONTINUE;
demo_ ? setPlayingState(PlayerState::LYING_ON_THE_FLOOR_FOREVER) : setPlayingState(nextPlayerStatus);
const auto NEXT_PLAYER_STATUS = IsEligibleForHighScore() ? PlayerState::ENTERING_NAME : PlayerState::CONTINUE;
demo_ ? setPlayingState(PlayerState::LYING_ON_THE_FLOOR_FOREVER) : setPlayingState(NEXT_PLAYER_STATUS);
pos_x_ = player_sprite_->getPosX();
pos_y_ = default_pos_y_;
player_sprite_->clear();
@@ -791,14 +791,14 @@ void Player::playSound(const std::string &name) {
if (demo_)
return;
static auto audio = Audio::get();
audio->playSound(name);
static auto audio_ = Audio::get();
audio_->playSound(name);
}
// Añade una puntuación a la tabla de records
void Player::addScoreToScoreBoard() {
const auto entry = HiScoreEntry(trim(getLastEnterName()), getScore(), get1CC());
const auto ENTRY = HiScoreEntry(trim(getLastEnterName()), getScore(), get1CC());
auto manager = std::make_unique<ManageHiScoreTable>(Options::settings.hi_score_table);
Options::settings.last_hi_score_entry.at(getId() - 1) = manager->add(entry);
Options::settings.last_hi_score_entry.at(getId() - 1) = manager->add(ENTRY);
manager->saveToFile(Asset::get()->get("score.bin"));
}

View File

@@ -234,9 +234,9 @@ void Resource::loadAnimations() {
void Resource::loadDemoData() {
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "\n>> DEMO FILES");
constexpr std::array<const char *, 2> demo_files = {"demo1.bin", "demo2.bin"};
constexpr std::array<const char *, 2> DEMO_FILES = {"demo1.bin", "demo2.bin"};
for (const auto &file : demo_files) {
for (const auto &file : DEMO_FILES) {
updateLoadingProgress(file);
demos_.emplace_back(loadDemoDataFromFile(Asset::get()->get(file)));
}
@@ -286,7 +286,7 @@ void Resource::createTextures() {
}
// Texturas de tamaño doble
std::vector<NameAndText> strings2X = {
std::vector<NameAndText> strings2_x = {
{"game_text_100000_points", "100.000"},
{"game_text_get_ready", Lang::getText("[GAME_TEXT] 7")},
{"game_text_last_stage", Lang::getText("[GAME_TEXT] 3")},
@@ -294,7 +294,7 @@ void Resource::createTextures() {
{"game_text_game_over", "Game Over"}};
auto text2 = getText("04b_25_2x");
for (const auto &s : strings2X) {
for (const auto &s : strings2_x) {
textures_.emplace_back(Resource::ResourceTexture(s.name, text2->writeToTexture(s.text, 1, -4)));
printWithDots("Texture : ", s.name, "[ DONE ]");
}
@@ -304,11 +304,11 @@ void Resource::createTextures() {
void Resource::createText() {
struct ResourceInfo {
std::string key;
std::string textureFile;
std::string textFile;
std::string texture_file;
std::string text_file;
ResourceInfo(const std::string &k, const std::string &tFile, const std::string &txtFile)
: key(k), textureFile(tFile), textFile(txtFile) {}
ResourceInfo(const std::string &k, const std::string &t_file, const std::string &txt_file)
: key(k), texture_file(t_file), text_file(txt_file) {}
};
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "\n>> CREATING TEXT OBJECTS");
@@ -328,7 +328,7 @@ void Resource::createText() {
{"smb2_grad", "smb2_grad.png", "smb2.txt"}};
for (const auto &resource : resources) {
texts_.emplace_back(Resource::ResourceText(resource.key, std::make_shared<Text>(getTexture(resource.textureFile), getTextFile(resource.textFile))));
texts_.emplace_back(Resource::ResourceText(resource.key, std::make_shared<Text>(getTexture(resource.texture_file), getTextFile(resource.text_file))));
printWithDots("Text : ", resource.key, "[ DONE ]");
}
}
@@ -387,7 +387,7 @@ void Resource::renderProgress() {
screen->start();
screen->clean();
auto color = param.resource.color.darken();
auto color = param.resource.color.DARKEN();
// Dibuja el interior de la barra de progreso
SDL_SetRenderDrawColor(renderer, param.resource.color.r, param.resource.color.g, param.resource.color.b, param.resource.color.a);

View File

@@ -5,6 +5,7 @@
#include <memory> // Para shared_ptr
#include <string> // Para basic_string, string
#include <utility>
#include <vector> // Para vector
#include "animated_sprite.h" // Para AnimationsFileBuffer
@@ -21,16 +22,16 @@ class Resource {
// --- Métodos de singleton ---
static void init(); // Inicializa el objeto Resource
static void destroy(); // Libera el objeto Resource
static Resource *get(); // Obtiene el puntero al objeto Resource
static auto get() -> Resource *; // Obtiene el puntero al objeto Resource
// --- Métodos de acceso a recursos ---
JA_Sound_t *getSound(const std::string &name); // Obtiene el sonido por nombre
JA_Music_t *getMusic(const std::string &name); // Obtiene la música por nombre
std::shared_ptr<Texture> getTexture(const std::string &name); // Obtiene la textura por nombre
std::shared_ptr<TextFile> getTextFile(const std::string &name); // Obtiene el fichero de texto por nombre
std::shared_ptr<Text> getText(const std::string &name); // Obtiene el objeto de texto por nombre
AnimationsFileBuffer &getAnimation(const std::string &name); // Obtiene la animación por nombre
DemoData &getDemoData(int index); // Obtiene los datos de demo por índice
auto getSound(const std::string &name) -> JA_Sound_t *; // Obtiene el sonido por nombre
auto getMusic(const std::string &name) -> JA_Music_t *; // Obtiene la música por nombre
auto getTexture(const std::string &name) -> std::shared_ptr<Texture>; // Obtiene la textura por nombre
auto getTextFile(const std::string &name) -> std::shared_ptr<TextFile>; // Obtiene el fichero de texto por nombre
auto getText(const std::string &name) -> std::shared_ptr<Text>; // Obtiene el objeto de texto por nombre
auto getAnimation(const std::string &name) -> AnimationsFileBuffer &; // Obtiene la animación por nombre
auto getDemoData(int index) -> DemoData &; // Obtiene los datos de demo por índice
// --- Métodos de recarga de recursos ---
void reload(); // Recarga todos los recursos
@@ -42,48 +43,48 @@ class Resource {
std::string name; // Nombre del sonido
JA_Sound_t *sound; // Objeto con el sonido
ResourceSound(const std::string &name, JA_Sound_t *sound)
: name(name), sound(sound) {}
ResourceSound(std::string name, JA_Sound_t *sound)
: name(std::move(name)), sound(sound) {}
};
struct ResourceMusic {
std::string name; // Nombre de la música
JA_Music_t *music; // Objeto con la música
ResourceMusic(const std::string &name, JA_Music_t *music)
: name(name), music(music) {}
ResourceMusic(std::string name, JA_Music_t *music)
: name(std::move(name)), music(music) {}
};
struct ResourceTexture {
std::string name; // Nombre de la textura
std::shared_ptr<Texture> texture; // Objeto con la textura
ResourceTexture(const std::string &name, std::shared_ptr<Texture> texture)
: name(name), texture(texture) {}
ResourceTexture(std::string name, std::shared_ptr<Texture> texture)
: name(std::move(name)), texture(std::move(texture)) {}
};
struct ResourceTextFile {
std::string name; // Nombre del fichero
std::shared_ptr<TextFile> text_file; // Objeto con los descriptores de la fuente de texto
ResourceTextFile(const std::string &name, std::shared_ptr<TextFile> text_file)
: name(name), text_file(text_file) {}
ResourceTextFile(std::string name, std::shared_ptr<TextFile> text_file)
: name(std::move(name)), text_file(std::move(text_file)) {}
};
struct ResourceText {
std::string name; // Nombre del objeto
std::shared_ptr<Text> text; // Objeto de texto
ResourceText(const std::string &name, std::shared_ptr<Text> text)
: name(name), text(text) {}
ResourceText(std::string name, std::shared_ptr<Text> text)
: name(std::move(name)), text(std::move(text)) {}
};
struct ResourceAnimation {
std::string name; // Nombre de la animación
AnimationsFileBuffer animation; // Objeto con las animaciones
ResourceAnimation(const std::string &name, const AnimationsFileBuffer &animation)
: name(name), animation(animation) {}
ResourceAnimation(std::string name, AnimationsFileBuffer animation)
: name(std::move(name)), animation(std::move(animation)) {}
};
// --- Estructura para el progreso de carga ---
@@ -96,14 +97,11 @@ class Resource {
void add(size_t amount) { loaded += amount; }
void increase() { loaded++; }
float getPercentage() const {
return total > 0 ? static_cast<float>(loaded) / static_cast<float>(total) : 0.0f;
[[nodiscard]] auto getPercentage() const -> float {
return total > 0 ? static_cast<float>(loaded) / static_cast<float>(total) : 0.0F;
}
};
// --- Instancia singleton ---
static Resource *instance_; // Instancia única de Resource
// --- Vectores de recursos ---
std::vector<ResourceSound> sounds_; // Vector con los sonidos
std::vector<ResourceMusic> musics_; // Vector con las músicas
@@ -146,4 +144,7 @@ class Resource {
// --- Constructores y destructor privados (singleton) ---
Resource(); // Constructor privado
~Resource(); // Destructor privado
// --- Instancia singleton ---
static Resource *instance_; // Instancia única de Resource
};

View File

@@ -120,8 +120,8 @@ void Scoreboard::render() {
void Scoreboard::setColor(Color color) {
// Actualiza las variables de colores
color_ = color;
text_color1_ = param.scoreboard.text_autocolor ? color_.lighten(100) : param.scoreboard.text_color1;
text_color2_ = param.scoreboard.text_autocolor ? color_.lighten(150) : param.scoreboard.text_color2;
text_color1_ = param.scoreboard.text_autocolor ? color_.LIGHTEN(100) : param.scoreboard.text_color1;
text_color2_ = param.scoreboard.text_autocolor ? color_.LIGHTEN(150) : param.scoreboard.text_color2;
// Aplica los colores
power_meter_sprite_->getTexture()->setColor(text_color2_);
@@ -213,8 +213,8 @@ void Scoreboard::fillPanelTextures() {
// HI-SCORE
text_scoreboard_->writeDX(TEXT_CENTER | TEXT_COLOR, slot4_3_.x, slot4_3_.y, Lang::getText("[SCOREBOARD] 4"), 1, text_color1_);
const std::string name = hi_score_name_ == "" ? "" : hi_score_name_ + " - ";
text_scoreboard_->writeDX(TEXT_CENTER | TEXT_COLOR, slot4_4_.x, slot4_4_.y, name + updateScoreText(hi_score_), 1, text_color2_);
const std::string NAME = hi_score_name_ == "" ? "" : hi_score_name_ + " - ";
text_scoreboard_->writeDX(TEXT_CENTER | TEXT_COLOR, slot4_4_.x, slot4_4_.y, NAME + updateScoreText(hi_score_), 1, text_color2_);
break;
}
@@ -242,18 +242,18 @@ void Scoreboard::fillPanelTextures() {
// Recorre todos los slots de letras del nombre
for (size_t j = 0; j < NAME_SIZE; ++j) {
// Selecciona el color
const Color color = j < selector_pos_[i] ? text_color2_ : text_color1_;
const Color COLOR = j < selector_pos_[i] ? text_color2_ : text_color1_;
if (j != selector_pos_[i] || time_counter_ % 3 == 0) {
// Dibuja la linea
if (j >= selector_pos_[i]) {
SDL_SetRenderDrawColor(renderer_, color.r, color.g, color.b, 255);
SDL_SetRenderDrawColor(renderer_, COLOR.r, COLOR.g, COLOR.b, 255);
SDL_RenderLine(renderer_, rect.x, rect.y + rect.h, rect.x + rect.w, rect.y + rect.h);
}
// Dibuja la letra
if (j < record_name_[i].size()) {
text_scoreboard_->writeColored(rect.x, rect.y, record_name_[i].substr(j, 1), color);
text_scoreboard_->writeColored(rect.x, rect.y, record_name_[i].substr(j, 1), COLOR);
}
}
rect.x += 7;
@@ -323,11 +323,11 @@ void Scoreboard::fillBackgroundTexture() {
// Recalcula las anclas de los elementos
void Scoreboard::recalculateAnchors() {
// Recalcula la posición y el tamaño de los paneles
const float panel_width = (float)rect_.w / (float)SCOREBOARD_MAX_PANELS;
const float PANEL_WIDTH = (float)rect_.w / (float)SCOREBOARD_MAX_PANELS;
for (int i = 0; i < SCOREBOARD_MAX_PANELS; ++i) {
panel_[i].pos.x = roundf(panel_width * i);
panel_[i].pos.x = roundf(PANEL_WIDTH * i);
panel_[i].pos.y = 0;
panel_[i].pos.w = roundf(panel_width * (i + 1)) - panel_[i].pos.x;
panel_[i].pos.w = roundf(PANEL_WIDTH * (i + 1)) - panel_[i].pos.x;
panel_[i].pos.h = rect_.h;
}
@@ -342,7 +342,7 @@ void Scoreboard::recalculateAnchors() {
const float ROW4 = 1 + (ROW_SIZE * 3) + (TEXT_HEIGHT / 2) - 3;
// Columna
const float COL = panel_width / 2;
const float COL = PANEL_WIDTH / 2;
// Slots de 4
slot4_1_ = {COL, ROW1};
@@ -351,8 +351,8 @@ void Scoreboard::recalculateAnchors() {
slot4_4_ = {COL, ROW4};
// Primer cuadrado para poner el nombre de record
const int enter_name_lenght = text_scoreboard_->lenght(std::string(NAME_SIZE, 'A'));
enter_name_pos_.x = COL - (enter_name_lenght / 2);
const int ENTER_NAME_LENGHT = text_scoreboard_->lenght(std::string(NAME_SIZE, 'A'));
enter_name_pos_.x = COL - (ENTER_NAME_LENGHT / 2);
enter_name_pos_.y = ROW4;
// Recoloca los sprites
@@ -395,18 +395,18 @@ void Scoreboard::createPanelTextures() {
// Dibuja la linea que separa la zona de juego del marcador
void Scoreboard::renderSeparator() {
// Dibuja la linea que separa el marcador de la zona de juego
auto color = param.scoreboard.separator_autocolor ? color_.darken() : param.scoreboard.separator_color;
auto color = param.scoreboard.separator_autocolor ? color_.DARKEN() : param.scoreboard.separator_color;
SDL_SetRenderDrawColor(renderer_, color.r, color.g, color.b, 255);
SDL_RenderLine(renderer_, 0, 0, rect_.w, 0);
}
// Inicializa el vector de colores para el nombre
void Scoreboard::iniNameColors() {
Color color = color_.inverse();
Color color = color_.INVERSE();
name_colors_.clear();
name_colors_.emplace_back(color.lighten(50));
name_colors_.emplace_back(color.lighten(25));
name_colors_.emplace_back(color.LIGHTEN(50));
name_colors_.emplace_back(color.LIGHTEN(25));
name_colors_.emplace_back(color);
name_colors_.emplace_back(color.darken(25));
name_colors_.emplace_back(color.DARKEN(25));
}

View File

@@ -211,11 +211,11 @@ void Screen::renderShake() {
void Screen::renderInfo() {
if (debug_info_.show) {
// Resolution
debug_info_.text->writeDX(TEXT_COLOR | TEXT_STROKE, param.game.width - debug_info_.text->lenght(Options::video.info) - 2, 1, Options::video.info, 1, param.debug.color, 1, param.debug.color.darken(150));
debug_info_.text->writeDX(TEXT_COLOR | TEXT_STROKE, param.game.width - debug_info_.text->lenght(Options::video.info) - 2, 1, Options::video.info, 1, param.debug.color, 1, param.debug.color.DARKEN(150));
// FPS
const std::string FPS_TEXT = std::to_string(fps_.lastValue) + " FPS";
debug_info_.text->writeDX(TEXT_COLOR | TEXT_STROKE, param.game.width - debug_info_.text->lenght(FPS_TEXT) - 2, 1 + debug_info_.text->getCharacterSize(), FPS_TEXT, 1, param.debug.color, 1, param.debug.color.darken(150));
debug_info_.text->writeDX(TEXT_COLOR | TEXT_STROKE, param.game.width - debug_info_.text->lenght(FPS_TEXT) - 2, 1 + debug_info_.text->getCharacterSize(), FPS_TEXT, 1, param.debug.color, 1, param.debug.color.DARKEN(150));
}
}
#endif

View File

@@ -257,8 +257,8 @@ void Credits::fillCanvas() {
// Dibuja el rectangulo rojo
// SDL_SetRenderDrawColor(Screen::get()->getRenderer(), 0xFF, 0, 0, 0xFF);
const Color color = color_.lighten();
SDL_SetRenderDrawColor(Screen::get()->getRenderer(), color.r, color.g, color.b, 0xFF);
const Color COLOR = color_.LIGHTEN();
SDL_SetRenderDrawColor(Screen::get()->getRenderer(), COLOR.r, COLOR.g, COLOR.b, 0xFF);
SDL_RenderRect(Screen::get()->getRenderer(), &red_rect);
// Si el mini_logo está en su destino, lo dibuja encima de lo anterior
@@ -305,19 +305,19 @@ void Credits::updateTextureDstRects() {
// Tira globos al escenario
void Credits::throwBalloons() {
constexpr int speed = 200;
const std::vector<int> sets = {0, 63, 25, 67, 17, 75, 13, 50};
constexpr int SPEED = 200;
const std::vector<int> SETS = {0, 63, 25, 67, 17, 75, 13, 50};
if (counter_ > ((sets.size() - 1) * speed) * 3) {
if (counter_ > ((SETS.size() - 1) * SPEED) * 3) {
return;
}
if (counter_ % speed == 0) {
const int index = (counter_ / speed) % sets.size();
balloon_manager_->deploySet(sets.at(index), -60);
if (counter_ % SPEED == 0) {
const int INDEX = (counter_ / SPEED) % SETS.size();
balloon_manager_->deploySet(SETS.at(INDEX), -60);
}
if (counter_ % (speed * 4) == 0 && counter_ > 0) {
if (counter_ % (SPEED * 4) == 0 && counter_ > 0) {
balloon_manager_->createPowerBall();
}
}
@@ -365,7 +365,7 @@ void Credits::initPlayers() {
// Actualiza los rectangulos negros
void Credits::updateBlackRects() {
static int current_step = steps_;
static int current_step_ = steps_;
if (top_black_rect_.h != param.game.game_area.center_y - 1 && bottom_black_rect_.y != param.game.game_area.center_y + 1) {
// Si los rectangulos superior e inferior no han llegado al centro
if (counter_ % 4 == 0) {
@@ -376,8 +376,8 @@ void Credits::updateBlackRects() {
++bottom_black_rect_.h;
bottom_black_rect_.y = std::max(bottom_black_rect_.y - 1, param.game.game_area.center_y + 1);
--current_step;
setVolume(static_cast<int>(initial_volume_ * current_step / steps_));
--current_step_;
setVolume(static_cast<int>(initial_volume_ * current_step_ / steps_));
}
} else {
// Si los rectangulos superior e inferior han llegado al centro
@@ -391,8 +391,8 @@ void Credits::updateBlackRects() {
right_black_rect_.w += SPEED;
right_black_rect_.x = std::max(right_black_rect_.x - SPEED, param.game.game_area.center_x);
--current_step;
setVolume(static_cast<int>(initial_volume_ * current_step / steps_));
--current_step_;
setVolume(static_cast<int>(initial_volume_ * current_step_ / steps_));
} else {
// Si los rectangulos izquierdo y derecho han llegado al centro
setVolume(0);
@@ -452,33 +452,33 @@ void Credits::cycleColors() {
constexpr int UPPER_LIMIT = 140; // Límite superior
constexpr int LOWER_LIMIT = 30; // Límite inferior
static float r = static_cast<float>(UPPER_LIMIT);
static float g = static_cast<float>(LOWER_LIMIT);
static float b = static_cast<float>(LOWER_LIMIT);
static float stepR = -0.5f; // Paso flotante para transiciones suaves
static float stepG = 0.3f;
static float stepB = 0.1f;
static float r_ = static_cast<float>(UPPER_LIMIT);
static float g_ = static_cast<float>(LOWER_LIMIT);
static float b_ = static_cast<float>(LOWER_LIMIT);
static float step_r_ = -0.5f; // Paso flotante para transiciones suaves
static float step_g_ = 0.3f;
static float step_b_ = 0.1f;
// Ajustar valores de R
r += stepR;
if (r >= UPPER_LIMIT || r <= LOWER_LIMIT) {
stepR = -stepR; // Cambia de dirección al alcanzar los límites
r_ += step_r_;
if (r_ >= UPPER_LIMIT || r_ <= LOWER_LIMIT) {
step_r_ = -step_r_; // Cambia de dirección al alcanzar los límites
}
// Ajustar valores de G
g += stepG;
if (g >= UPPER_LIMIT || g <= LOWER_LIMIT) {
stepG = -stepG; // Cambia de dirección al alcanzar los límites
g_ += step_g_;
if (g_ >= UPPER_LIMIT || g_ <= LOWER_LIMIT) {
step_g_ = -step_g_; // Cambia de dirección al alcanzar los límites
}
// Ajustar valores de B
b += stepB;
if (b >= UPPER_LIMIT || b <= LOWER_LIMIT) {
stepB = -stepB; // Cambia de dirección al alcanzar los límites
b_ += step_b_;
if (b_ >= UPPER_LIMIT || b_ <= LOWER_LIMIT) {
step_b_ = -step_b_; // Cambia de dirección al alcanzar los límites
}
// Aplicar el color, redondeando a enteros antes de usar
color_ = Color(static_cast<int>(r), static_cast<int>(g), static_cast<int>(b));
color_ = Color(static_cast<int>(r_), static_cast<int>(g_), static_cast<int>(b_));
tiled_bg_->setColor(color_);
}

View File

@@ -253,14 +253,14 @@ void Game::updateStage() {
createMessage(paths, Resource::get()->getTexture("game_text_last_stage"));
} else {
auto text = Resource::get()->getText("04b_25_2x");
const std::string caption = std::to_string(10 - Stage::number) + Lang::getText("[GAME_TEXT] 2");
createMessage(paths, text->writeToTexture(caption, 1, -4));
const std::string CAPTION = std::to_string(10 - Stage::number) + Lang::getText("[GAME_TEXT] 2");
createMessage(paths, text->writeToTexture(CAPTION, 1, -4));
}
}
// Modifica el color de fondo al llegar a la Fase 10
if (Stage::number == 9) {
background_->setColor(Color(0xdd, 0x19, 0x1d).darken());
background_->setColor(Color(0xdd, 0x19, 0x1d).DARKEN());
background_->setAlpha(96);
}
}
@@ -422,48 +422,48 @@ void Game::checkPlayerItemCollision(std::shared_ptr<Player> &player) {
switch (item->getType()) {
case ItemType::DISK: {
player->addScore(1000);
const auto x = item->getPosX() + (item->getWidth() - game_text_textures_.at(0)->getWidth()) / 2;
createItemText(x, game_text_textures_.at(0));
const auto X = item->getPosX() + (item->getWidth() - game_text_textures_.at(0)->getWidth()) / 2;
createItemText(X, game_text_textures_.at(0));
playSound("item_pickup.wav");
break;
}
case ItemType::GAVINA: {
player->addScore(2500);
const auto x = item->getPosX() + (item->getWidth() - game_text_textures_.at(1)->getWidth()) / 2;
createItemText(x, game_text_textures_.at(1));
const auto X = item->getPosX() + (item->getWidth() - game_text_textures_.at(1)->getWidth()) / 2;
createItemText(X, game_text_textures_.at(1));
playSound("item_pickup.wav");
break;
}
case ItemType::PACMAR: {
player->addScore(5000);
const auto x = item->getPosX() + (item->getWidth() - game_text_textures_.at(2)->getWidth()) / 2;
createItemText(x, game_text_textures_.at(2));
const auto X = item->getPosX() + (item->getWidth() - game_text_textures_.at(2)->getWidth()) / 2;
createItemText(X, game_text_textures_.at(2));
playSound("item_pickup.wav");
break;
}
case ItemType::DEBIAN: {
player->addScore(100000);
const auto x = item->getPosX() + (item->getWidth() - game_text_textures_.at(6)->getWidth()) / 2;
createItemText(x, game_text_textures_.at(6));
const auto X = item->getPosX() + (item->getWidth() - game_text_textures_.at(6)->getWidth()) / 2;
createItemText(X, game_text_textures_.at(6));
playSound("debian_pickup.wav");
break;
}
case ItemType::CLOCK: {
enableTimeStopItem();
const auto x = item->getPosX() + (item->getWidth() - game_text_textures_.at(5)->getWidth()) / 2;
createItemText(x, game_text_textures_.at(5));
const auto X = item->getPosX() + (item->getWidth() - game_text_textures_.at(5)->getWidth()) / 2;
createItemText(X, game_text_textures_.at(5));
playSound("item_pickup.wav");
break;
}
case ItemType::COFFEE: {
if (player->getCoffees() == 2) {
player->addScore(5000);
const auto x = item->getPosX() + (item->getWidth() - game_text_textures_.at(2)->getWidth()) / 2;
createItemText(x, game_text_textures_.at(2));
const auto X = item->getPosX() + (item->getWidth() - game_text_textures_.at(2)->getWidth()) / 2;
createItemText(X, game_text_textures_.at(2));
} else {
player->giveExtraHit();
const auto x = item->getPosX() + (item->getWidth() - game_text_textures_.at(4)->getWidth()) / 2;
createItemText(x, game_text_textures_.at(4));
const auto X = item->getPosX() + (item->getWidth() - game_text_textures_.at(4)->getWidth()) / 2;
createItemText(X, game_text_textures_.at(4));
}
playSound("voice_coffee.wav");
break;
@@ -471,8 +471,8 @@ void Game::checkPlayerItemCollision(std::shared_ptr<Player> &player) {
case ItemType::COFFEE_MACHINE: {
player->setPowerUp();
coffee_machine_enabled_ = false;
const auto x = item->getPosX() + (item->getWidth() - game_text_textures_.at(3)->getWidth()) / 2;
createItemText(x, game_text_textures_.at(3));
const auto X = item->getPosX() + (item->getWidth() - game_text_textures_.at(3)->getWidth()) / 2;
createItemText(X, game_text_textures_.at(3));
playSound("voice_power_up.wav");
break;
}
@@ -516,12 +516,12 @@ void Game::checkBulletCollision() {
auto player = getPlayer(bullet->getOwner());
// Suelta el item si se da el caso
const auto dropped_item = dropItem();
if (dropped_item != ItemType::NONE && !demo_.recording) {
if (dropped_item != ItemType::COFFEE_MACHINE) {
createItem(dropped_item, balloon->getPosX(), balloon->getPosY());
const auto DROPPED_ITEM = dropItem();
if (DROPPED_ITEM != ItemType::NONE && !demo_.recording) {
if (DROPPED_ITEM != ItemType::COFFEE_MACHINE) {
createItem(DROPPED_ITEM, balloon->getPosX(), balloon->getPosY());
} else {
createItem(dropped_item, player->getPosX(), param.game.game_area.rect.y - Item::COFFEE_MACHINE_HEIGHT);
createItem(DROPPED_ITEM, player->getPosX(), param.game.game_area.rect.y - Item::COFFEE_MACHINE_HEIGHT);
coffee_machine_enabled_ = true;
}
}
@@ -595,32 +595,32 @@ void Game::renderItems() {
// Devuelve un item al azar y luego segun sus probabilidades
ItemType Game::dropItem() {
const auto lucky_number = rand() % 100;
const auto item = rand() % 6;
const auto LUCKY_NUMBER = rand() % 100;
const auto ITEM = rand() % 6;
switch (item) {
switch (ITEM) {
case 0:
if (lucky_number < helper_.item_disk_odds) {
if (LUCKY_NUMBER < helper_.item_disk_odds) {
return ItemType::DISK;
}
break;
case 1:
if (lucky_number < helper_.item_gavina_odds) {
if (LUCKY_NUMBER < helper_.item_gavina_odds) {
return ItemType::GAVINA;
}
break;
case 2:
if (lucky_number < helper_.item_pacmar_odds) {
if (LUCKY_NUMBER < helper_.item_pacmar_odds) {
return ItemType::GAVINA;
}
break;
case 3:
if (lucky_number < helper_.item_clock_odds) {
if (LUCKY_NUMBER < helper_.item_clock_odds) {
return ItemType::CLOCK;
}
break;
case 4:
if (lucky_number < helper_.item_coffee_odds) {
if (LUCKY_NUMBER < helper_.item_coffee_odds) {
helper_.item_coffee_odds = ITEM_COFFEE_ODDS_;
return ItemType::COFFEE;
} else {
@@ -630,7 +630,7 @@ ItemType Game::dropItem() {
}
break;
case 5:
if (lucky_number < helper_.item_coffee_machine_odds) {
if (LUCKY_NUMBER < helper_.item_coffee_machine_odds) {
helper_.item_coffee_machine_odds = ITEM_COFFEE_MACHINE_ODDS_;
if (!coffee_machine_enabled_ && helper_.need_coffee_machine) {
return ItemType::COFFEE_MACHINE;
@@ -666,22 +666,22 @@ void Game::freeItems() {
void Game::createItemText(int x, std::shared_ptr<Texture> texture) {
path_sprites_.emplace_back(std::make_unique<PathSprite>(texture));
const auto w = texture->getWidth();
const auto h = texture->getHeight();
const auto W = texture->getWidth();
const auto H = texture->getHeight();
const int y0 = param.game.play_area.rect.h - h;
const int y1 = 160 - (h / 2);
const int y2 = -h;
const int Y0 = param.game.play_area.rect.h - H;
const int Y1 = 160 - (H / 2);
const int Y2 = -H;
// Ajusta para que no se dibuje fuera de pantalla
x = std::clamp(x, 2, static_cast<int>(param.game.play_area.rect.w) - w - 2);
x = std::clamp(x, 2, static_cast<int>(param.game.play_area.rect.w) - W - 2);
// Inicializa
path_sprites_.back()->setWidth(w);
path_sprites_.back()->setHeight(h);
path_sprites_.back()->setSpriteClip({0, 0, static_cast<float>(w), static_cast<float>(h)});
path_sprites_.back()->addPath(y0, y1, PathType::VERTICAL, x, 100, easeOutQuint, 0);
path_sprites_.back()->addPath(y1, y2, PathType::VERTICAL, x, 80, easeInQuint, 0);
path_sprites_.back()->setWidth(W);
path_sprites_.back()->setHeight(H);
path_sprites_.back()->setSpriteClip({0, 0, static_cast<float>(W), static_cast<float>(H)});
path_sprites_.back()->addPath(Y0, Y1, PathType::VERTICAL, x, 100, easeOutQuint, 0);
path_sprites_.back()->addPath(Y1, Y2, PathType::VERTICAL, x, 80, easeInQuint, 0);
path_sprites_.back()->enable();
}
@@ -866,19 +866,19 @@ void Game::updateBackground() {
// Calcula la velocidad en función de los globos explotados y el total de globos a explotar para acabar el juego
constexpr float CLOUDS_INITIAL_SPEED = 0.05f;
constexpr float CLOUDS_FINAL_SPEED = 2.00f - CLOUDS_INITIAL_SPEED;
const float cloudsSpeed = (-CLOUDS_INITIAL_SPEED) + (-CLOUDS_FINAL_SPEED * (static_cast<float>(Stage::total_power) / total_power_to_complete_game_));
background_->setCloudsSpeed(cloudsSpeed);
const float CLOUDS_SPEED = (-CLOUDS_INITIAL_SPEED) + (-CLOUDS_FINAL_SPEED * (static_cast<float>(Stage::total_power) / total_power_to_complete_game_));
background_->setCloudsSpeed(CLOUDS_SPEED);
// Calcula la transición de los diferentes fondos
constexpr float num = 1525.0f; // total_power_to_complete div 4
const float gradient_number = std::min(Stage::total_power / num, 3.0f);
const float percent = gradient_number - static_cast<int>(gradient_number);
background_->setGradientNumber(static_cast<int>(gradient_number));
background_->setTransition(percent);
constexpr float NUM = 1525.0f; // total_power_to_complete div 4
const float GRADIENT_NUMBER = std::min(Stage::total_power / NUM, 3.0f);
const float PERCENT = GRADIENT_NUMBER - static_cast<int>(GRADIENT_NUMBER);
background_->setGradientNumber(static_cast<int>(GRADIENT_NUMBER));
background_->setTransition(PERCENT);
// Calcula la posición del sol
constexpr float sun_final_power = num * 2;
background_->setSunProgression(Stage::total_power / sun_final_power);
constexpr float SUN_FINAL_POWER = NUM * 2;
background_->setSunProgression(Stage::total_power / SUN_FINAL_POWER);
background_->setMoonProgression(Stage::total_power / static_cast<float>(total_power_to_complete_game_));
// Actualiza el objeto
@@ -955,51 +955,51 @@ void Game::initPaths() {
// Recorrido para el texto de "Get Ready!" (0,1)
{
const auto &texture = Resource::get()->getTexture("game_text_get_ready");
const auto w = texture->getWidth();
const int x0 = -w;
const int x1 = param.game.play_area.center_x - w / 2;
const int x2 = param.game.play_area.rect.w;
const int y = param.game.play_area.center_y;
paths_.emplace_back(Path(createPath(x0, x1, PathType::HORIZONTAL, y, 80, easeOutQuint), 20));
paths_.emplace_back(Path(createPath(x1, x2, PathType::HORIZONTAL, y, 80, easeInQuint), 0));
const auto W = texture->getWidth();
const int X0 = -W;
const int X1 = param.game.play_area.center_x - W / 2;
const int X2 = param.game.play_area.rect.w;
const int Y = param.game.play_area.center_y;
paths_.emplace_back(Path(createPath(X0, X1, PathType::HORIZONTAL, Y, 80, easeOutQuint), 20));
paths_.emplace_back(Path(createPath(X1, X2, PathType::HORIZONTAL, Y, 80, easeInQuint), 0));
}
// Recorrido para el texto de "Last Stage!" o de "X stages left" o "Game Over" (2,3)
{
const auto &texture = Resource::get()->getTexture("game_text_last_stage");
const auto h = texture->getHeight();
const int y0 = param.game.play_area.rect.h - h;
const int y1 = param.game.play_area.center_y - h / 2;
const int y2 = -h;
const int x = param.game.play_area.center_x;
paths_.emplace_back(Path(createPath(y0, y1, PathType::VERTICAL, x, 80, easeOutQuint), 20));
paths_.emplace_back(Path(createPath(y1, y2, PathType::VERTICAL, x, 80, easeInQuint), 0));
const auto H = texture->getHeight();
const int Y0 = param.game.play_area.rect.h - H;
const int Y1 = param.game.play_area.center_y - H / 2;
const int Y2 = -H;
const int X = param.game.play_area.center_x;
paths_.emplace_back(Path(createPath(Y0, Y1, PathType::VERTICAL, X, 80, easeOutQuint), 20));
paths_.emplace_back(Path(createPath(Y1, Y2, PathType::VERTICAL, X, 80, easeInQuint), 0));
}
// Recorrido para el texto de "Congratulations!!" (3,4)
{
const auto &texture = Resource::get()->getTexture("game_text_congratulations");
const auto w = texture->getWidth();
const auto h = texture->getHeight();
const int x0 = -w;
const int x1 = param.game.play_area.center_x - w / 2;
const int x2 = param.game.play_area.rect.w;
const int y = param.game.play_area.center_y - h / 2 - 20;
paths_.emplace_back(Path(createPath(x0, x1, PathType::HORIZONTAL, y, 80, easeOutQuint), 400));
paths_.emplace_back(Path(createPath(x1, x2, PathType::HORIZONTAL, y, 80, easeInQuint), 0));
const auto W = texture->getWidth();
const auto H = texture->getHeight();
const int X0 = -W;
const int X1 = param.game.play_area.center_x - W / 2;
const int X2 = param.game.play_area.rect.w;
const int Y = param.game.play_area.center_y - H / 2 - 20;
paths_.emplace_back(Path(createPath(X0, X1, PathType::HORIZONTAL, Y, 80, easeOutQuint), 400));
paths_.emplace_back(Path(createPath(X1, X2, PathType::HORIZONTAL, Y, 80, easeInQuint), 0));
}
// Recorrido para el texto de "1.000.000 points!" (5,6)
{
const auto &texture = Resource::get()->getTexture("game_text_1000000_points");
const auto w = texture->getWidth();
const auto h = texture->getHeight();
const int x0 = param.game.play_area.rect.w;
const int x1 = param.game.play_area.center_x - w / 2;
const int x2 = -w;
const int y = param.game.play_area.center_y + h / 2 - 20;
paths_.emplace_back(Path(createPath(x0, x1, PathType::HORIZONTAL, y, 80, easeOutQuint), 400));
paths_.emplace_back(Path(createPath(x1, x2, PathType::HORIZONTAL, y, 80, easeInQuint), 0));
const auto W = texture->getWidth();
const auto H = texture->getHeight();
const int X0 = param.game.play_area.rect.w;
const int X1 = param.game.play_area.center_x - W / 2;
const int X2 = -W;
const int Y = param.game.play_area.center_y + H / 2 - 20;
paths_.emplace_back(Path(createPath(X0, X1, PathType::HORIZONTAL, Y, 80, easeOutQuint), 400));
paths_.emplace_back(Path(createPath(X1, X2, PathType::HORIZONTAL, Y, 80, easeInQuint), 0));
}
}
@@ -1097,17 +1097,17 @@ void Game::pause(bool value) {
// Añade una puntuación a la tabla de records
void Game::addScoreToScoreBoard(const std::shared_ptr<Player> &player) {
const auto entry = HiScoreEntry(trim(player->getLastEnterName()), player->getScore(), player->get1CC());
const auto ENTRY = HiScoreEntry(trim(player->getLastEnterName()), player->getScore(), player->get1CC());
auto manager = std::make_unique<ManageHiScoreTable>(Options::settings.hi_score_table);
Options::settings.last_hi_score_entry.at(player->getId() - 1) = manager->add(entry);
Options::settings.last_hi_score_entry.at(player->getId() - 1) = manager->add(ENTRY);
manager->saveToFile(Asset::get()->get("score.bin"));
hi_score_.name = Options::settings.hi_score_table.front().name;
}
// Saca del estado de GAME OVER al jugador si el otro está activo
void Game::checkAndUpdatePlayerStatus(int activePlayerIndex, int inactivePlayerIndex) {
if (players_[activePlayerIndex]->isGameOver() && !players_[inactivePlayerIndex]->isGameOver() && !players_[inactivePlayerIndex]->isWaiting()) {
players_[activePlayerIndex]->setPlayingState(PlayerState::WAITING);
void Game::checkAndUpdatePlayerStatus(int active_player_index, int inactive_player_index) {
if (players_[active_player_index]->isGameOver() && !players_[inactive_player_index]->isGameOver() && !players_[inactive_player_index]->isWaiting()) {
players_[active_player_index]->setPlayingState(PlayerState::WAITING);
}
}
@@ -1210,21 +1210,21 @@ void Game::DEMO_handleInput() {
// Procesa las entradas para un jugador específico durante el modo demo.
void Game::DEMO_handlePlayerInput(const std::shared_ptr<Player> &player, int index) {
const auto &demoData = demo_.data[index][demo_.counter];
const auto &demo_data = demo_.data[index][demo_.counter];
if (demoData.left == 1) {
if (demo_data.left == 1) {
player->setInput(InputAction::LEFT);
} else if (demoData.right == 1) {
} else if (demo_data.right == 1) {
player->setInput(InputAction::RIGHT);
} else if (demoData.no_input == 1) {
} else if (demo_data.no_input == 1) {
player->setInput(InputAction::NONE);
}
if (demoData.fire == 1) {
if (demo_data.fire == 1) {
handleFireInput(player, BulletType::UP);
} else if (demoData.fire_left == 1) {
} else if (demo_data.fire_left == 1) {
handleFireInput(player, BulletType::LEFT);
} else if (demoData.fire_right == 1) {
} else if (demo_data.fire_right == 1) {
handleFireInput(player, BulletType::RIGHT);
}
}
@@ -1275,31 +1275,31 @@ void Game::handleFireInput(const std::shared_ptr<Player> &player, BulletType bul
// Gestiona las entradas de todos los jugadores en el modo normal (fuera del modo demo).
void Game::handlePlayersInput() {
for (const auto &PLAYER : players_) {
if (PLAYER->isPlaying()) {
for (const auto &player : players_) {
if (player->isPlaying()) {
// Maneja el input de los jugadores en modo normal.
handleNormalPlayerInput(PLAYER);
} else if (PLAYER->isContinue() || PLAYER->isWaiting()) {
handleNormalPlayerInput(player);
} else if (player->isContinue() || player->isWaiting()) {
// Gestiona la continuación del jugador.
handlePlayerContinue(PLAYER);
} else if (PLAYER->isEnteringName() || PLAYER->isEnteringNameGameCompleted() || PLAYER->isShowingName()) {
handlePlayerContinue(player);
} else if (player->isEnteringName() || player->isEnteringNameGameCompleted() || player->isShowingName()) {
// Gestiona la introducción del nombre del jugador.
handleNameInput(PLAYER);
handleNameInput(player);
}
}
}
// Maneja las entradas de movimiento y disparo para un jugador en modo normal.
void Game::handleNormalPlayerInput(const std::shared_ptr<Player> &player) {
const auto &CONTROLLER = Options::controllers.at(player->getController());
const auto &controller = Options::controllers.at(player->getController());
const bool AUTOFIRE = player->isPowerUp() || Options::settings.autofire;
if (input_->checkInput(InputAction::LEFT, INPUT_ALLOW_REPEAT, CONTROLLER.type, CONTROLLER.index)) {
if (input_->checkInput(InputAction::LEFT, INPUT_ALLOW_REPEAT, controller.type, controller.index)) {
player->setInput(InputAction::LEFT);
#ifdef RECORDING
demo_.keys.left = 1;
#endif
} else if (input_->checkInput(InputAction::RIGHT, INPUT_ALLOW_REPEAT, CONTROLLER.type, CONTROLLER.index)) {
} else if (input_->checkInput(InputAction::RIGHT, INPUT_ALLOW_REPEAT, controller.type, controller.index)) {
player->setInput(InputAction::RIGHT);
#ifdef RECORDING
demo_.keys.right = 1;
@@ -1315,18 +1315,18 @@ void Game::handleNormalPlayerInput(const std::shared_ptr<Player> &player) {
}
// Procesa las entradas de disparo del jugador, permitiendo disparos automáticos si está habilitado.
void Game::handleFireInputs(const std::shared_ptr<Player> &player, bool autofire, int controllerIndex) {
if (input_->checkInput(InputAction::FIRE_CENTER, autofire, Options::controllers[controllerIndex].type, Options::controllers[controllerIndex].index)) {
void Game::handleFireInputs(const std::shared_ptr<Player> &player, bool autofire, int controller_index) {
if (input_->checkInput(InputAction::FIRE_CENTER, autofire, Options::controllers[controller_index].type, Options::controllers[controller_index].index)) {
handleFireInput(player, BulletType::UP);
#ifdef RECORDING
demo_.keys.fire = 1;
#endif
} else if (input_->checkInput(InputAction::FIRE_LEFT, autofire, Options::controllers[controllerIndex].type, Options::controllers[controllerIndex].index)) {
} else if (input_->checkInput(InputAction::FIRE_LEFT, autofire, Options::controllers[controller_index].type, Options::controllers[controller_index].index)) {
handleFireInput(player, BulletType::LEFT);
#ifdef RECORDING
demo_.keys.fire_left = 1;
#endif
} else if (input_->checkInput(InputAction::FIRE_RIGHT, autofire, Options::controllers[controllerIndex].type, Options::controllers[controllerIndex].index)) {
} else if (input_->checkInput(InputAction::FIRE_RIGHT, autofire, Options::controllers[controller_index].type, Options::controllers[controller_index].index)) {
handleFireInput(player, BulletType::RIGHT);
#ifdef RECORDING
demo_.keys.fire_right = 1;
@@ -1336,15 +1336,15 @@ void Game::handleFireInputs(const std::shared_ptr<Player> &player, bool autofire
// Maneja la continuación del jugador cuando no está jugando, permitiendo que continúe si se pulsa el botón de inicio.
void Game::handlePlayerContinue(const std::shared_ptr<Player> &player) {
const auto controllerIndex = player->getController();
if (input_->checkInput(InputAction::START, INPUT_DO_NOT_ALLOW_REPEAT, Options::controllers[controllerIndex].type, Options::controllers[controllerIndex].index)) {
const auto CONTROLLER_INDEX = player->getController();
if (input_->checkInput(InputAction::START, INPUT_DO_NOT_ALLOW_REPEAT, Options::controllers[CONTROLLER_INDEX].type, Options::controllers[CONTROLLER_INDEX].index)) {
player->setPlayingState(PlayerState::RESPAWNING);
}
// Disminuye el contador de continuación si se presiona cualquier botón de disparo.
if (input_->checkInput(InputAction::FIRE_LEFT, INPUT_DO_NOT_ALLOW_REPEAT, Options::controllers[controllerIndex].type, Options::controllers[controllerIndex].index) ||
input_->checkInput(InputAction::FIRE_CENTER, INPUT_DO_NOT_ALLOW_REPEAT, Options::controllers[controllerIndex].type, Options::controllers[controllerIndex].index) ||
input_->checkInput(InputAction::FIRE_RIGHT, INPUT_DO_NOT_ALLOW_REPEAT, Options::controllers[controllerIndex].type, Options::controllers[controllerIndex].index)) {
if (input_->checkInput(InputAction::FIRE_LEFT, INPUT_DO_NOT_ALLOW_REPEAT, Options::controllers[CONTROLLER_INDEX].type, Options::controllers[CONTROLLER_INDEX].index) ||
input_->checkInput(InputAction::FIRE_CENTER, INPUT_DO_NOT_ALLOW_REPEAT, Options::controllers[CONTROLLER_INDEX].type, Options::controllers[CONTROLLER_INDEX].index) ||
input_->checkInput(InputAction::FIRE_RIGHT, INPUT_DO_NOT_ALLOW_REPEAT, Options::controllers[CONTROLLER_INDEX].type, Options::controllers[CONTROLLER_INDEX].index)) {
if (player->getContinueCounter() < param.scoreboard.skip_countdown_value) {
player->decContinueCounter();
}
@@ -1353,8 +1353,8 @@ void Game::handlePlayerContinue(const std::shared_ptr<Player> &player) {
// Procesa las entradas para la introducción del nombre del jugador.
void Game::handleNameInput(const std::shared_ptr<Player> &player) {
const auto controllerIndex = player->getController();
if (input_->checkInput(InputAction::FIRE_LEFT, INPUT_DO_NOT_ALLOW_REPEAT, Options::controllers[controllerIndex].type, Options::controllers[controllerIndex].index)) {
const auto CONTROLLER_INDEX = player->getController();
if (input_->checkInput(InputAction::FIRE_LEFT, INPUT_DO_NOT_ALLOW_REPEAT, Options::controllers[CONTROLLER_INDEX].type, Options::controllers[CONTROLLER_INDEX].index)) {
if (player->isShowingName()) {
player->setPlayingState(PlayerState::CONTINUE);
} else if (player->getEnterNamePositionOverflow()) {
@@ -1364,18 +1364,18 @@ void Game::handleNameInput(const std::shared_ptr<Player> &player) {
} else {
player->setInput(InputAction::RIGHT);
}
} else if (input_->checkInput(InputAction::FIRE_CENTER, INPUT_DO_NOT_ALLOW_REPEAT, Options::controllers[controllerIndex].type, Options::controllers[controllerIndex].index) ||
input_->checkInput(InputAction::FIRE_RIGHT, INPUT_DO_NOT_ALLOW_REPEAT, Options::controllers[controllerIndex].type, Options::controllers[controllerIndex].index)) {
} else if (input_->checkInput(InputAction::FIRE_CENTER, INPUT_DO_NOT_ALLOW_REPEAT, Options::controllers[CONTROLLER_INDEX].type, Options::controllers[CONTROLLER_INDEX].index) ||
input_->checkInput(InputAction::FIRE_RIGHT, INPUT_DO_NOT_ALLOW_REPEAT, Options::controllers[CONTROLLER_INDEX].type, Options::controllers[CONTROLLER_INDEX].index)) {
if (player->isShowingName()) {
player->setPlayingState(PlayerState::CONTINUE);
} else {
player->setInput(InputAction::LEFT);
}
} else if (input_->checkInput(InputAction::UP, INPUT_DO_NOT_ALLOW_REPEAT, Options::controllers[controllerIndex].type, Options::controllers[controllerIndex].index)) {
} else if (input_->checkInput(InputAction::UP, INPUT_DO_NOT_ALLOW_REPEAT, Options::controllers[CONTROLLER_INDEX].type, Options::controllers[CONTROLLER_INDEX].index)) {
player->setInput(InputAction::UP);
} else if (input_->checkInput(InputAction::DOWN, INPUT_DO_NOT_ALLOW_REPEAT, Options::controllers[controllerIndex].type, Options::controllers[controllerIndex].index)) {
} else if (input_->checkInput(InputAction::DOWN, INPUT_DO_NOT_ALLOW_REPEAT, Options::controllers[CONTROLLER_INDEX].type, Options::controllers[CONTROLLER_INDEX].index)) {
player->setInput(InputAction::DOWN);
} else if (input_->checkInput(InputAction::START, INPUT_DO_NOT_ALLOW_REPEAT, Options::controllers[controllerIndex].type, Options::controllers[controllerIndex].index)) {
} else if (input_->checkInput(InputAction::START, INPUT_DO_NOT_ALLOW_REPEAT, Options::controllers[CONTROLLER_INDEX].type, Options::controllers[CONTROLLER_INDEX].index)) {
if (player->isShowingName()) {
player->setPlayingState(PlayerState::CONTINUE);
} else {
@@ -1666,12 +1666,12 @@ void Game::cleanVectors() {
// Gestiona el nivel de amenaza
void Game::updateMenace() {
if (state_ == GameState::PLAYING) {
const auto stage = Stage::get(Stage::number);
const float percent = Stage::power / stage.power_to_complete;
const int difference = stage.max_menace - stage.min_menace;
const auto STAGE = Stage::get(Stage::number);
const float PERCENT = Stage::power / STAGE.power_to_complete;
const int DIFFERENCE = STAGE.max_menace - STAGE.min_menace;
// Aumenta el nivel de amenaza en función de la puntuación
menace_threshold_ = stage.min_menace + (difference * percent);
menace_threshold_ = STAGE.min_menace + (DIFFERENCE * PERCENT);
// Si el nivel de amenza es inferior al umbral
if (menace_current_ < menace_threshold_) {
@@ -1694,11 +1694,11 @@ void Game::checkAndUpdateBalloonSpeed() {
if (difficulty_ != Options::DifficultyCode::NORMAL)
return;
const float percent = static_cast<float>(Stage::power) / Stage::get(Stage::number).power_to_complete;
const float thresholds[] = {0.2f, 0.4f, 0.6f, 0.8f};
const float PERCENT = static_cast<float>(Stage::power) / Stage::get(Stage::number).power_to_complete;
const float THRESHOLDS[] = {0.2f, 0.4f, 0.6f, 0.8f};
for (size_t i = 0; i < std::size(thresholds); ++i) {
if (balloon_manager_->getBalloonSpeed() == BALLOON_SPEED[i] && percent > thresholds[i]) {
for (size_t i = 0; i < std::size(THRESHOLDS); ++i) {
if (balloon_manager_->getBalloonSpeed() == BALLOON_SPEED[i] && PERCENT > THRESHOLDS[i]) {
balloon_manager_->setBalloonSpeed(BALLOON_SPEED[i + 1]);
break; // Salir del bucle una vez actualizada la velocidad y aplicada
}
@@ -1715,8 +1715,8 @@ void Game::playSound(const std::string &name) {
if (demo_.enabled)
return;
static auto audio = Audio::get();
audio->playSound(name);
static auto audio_ = Audio::get();
audio_->playSound(name);
}
// Organiza los jugadores para que los vivos se pinten sobre los muertos
@@ -1727,9 +1727,9 @@ void Game::movePlayersToFront() {
for (auto &player : players_to_reorder) {
auto it = std::find(players_.begin(), players_.end(), player);
if (it != players_.end() && it != players_.begin()) {
std::shared_ptr<Player> dyingPlayer = *it;
std::shared_ptr<Player> dying_player = *it;
players_.erase(it);
players_.insert(players_.begin(), dyingPlayer);
players_.insert(players_.begin(), dying_player);
}
}
players_to_reorder.clear();
@@ -1740,21 +1740,21 @@ void Game::checkServiceMenu() {
if (demo_.enabled)
return;
static bool was_paused_before_service_menu = false;
static bool service_menu_was_active = false;
static bool was_paused_before_service_menu_ = false;
static bool service_menu_was_active_ = false;
bool service_menu_is_active = ServiceMenu::get()->isEnabled();
if (service_menu_is_active && !service_menu_was_active) {
if (service_menu_is_active && !service_menu_was_active_) {
// El menú acaba de abrirse
was_paused_before_service_menu = paused_;
was_paused_before_service_menu_ = paused_;
pause(true);
} else if (!service_menu_is_active && service_menu_was_active) {
} else if (!service_menu_is_active && service_menu_was_active_) {
// El menú acaba de cerrarse
pause(was_paused_before_service_menu);
pause(was_paused_before_service_menu_);
}
service_menu_was_active = service_menu_is_active;
service_menu_was_active_ = service_menu_is_active;
}
#ifdef DEBUG
@@ -1770,9 +1770,9 @@ void Game::checkDebugEvents(const SDL_Event &event) {
}
case SDLK_2: // Activa o desactiva la aparición de globos
{
static bool deploy_balloons = true;
deploy_balloons = !deploy_balloons;
balloon_manager_->enableBalloonDeployment(deploy_balloons);
static bool deploy_balloons_ = true;
deploy_balloons_ = !deploy_balloons_;
balloon_manager_->enableBalloonDeployment(deploy_balloons_);
break;
}
case SDLK_3: // Activa el modo para pasar el juego automaticamente

View File

@@ -169,19 +169,19 @@ void HiScoreTable::updateFade() {
// Convierte un entero a un string con separadores de miles
std::string HiScoreTable::format(int number) {
const std::string separator = ".";
const std::string score = std::to_string(number);
const std::string SEPARATOR = ".";
const std::string SCORE = std::to_string(number);
auto index = (int)score.size() - 1;
auto index = (int)SCORE.size() - 1;
std::string result;
auto i = 0;
while (index >= 0) {
result = score.at(index) + result;
result = SCORE.at(index) + result;
index--;
i++;
if (i == 3) {
i = 0;
result = separator + result;
result = SEPARATOR + result;
}
}
@@ -200,44 +200,44 @@ void HiScoreTable::createSprites() {
constexpr int ENTRY_LENGHT = 22;
constexpr int MAX_NAMES = 10;
const int space_between_header = entry_text->getCharacterSize() * 4;
const int space_between_lines = entry_text->getCharacterSize() * 2;
const int size = space_between_header + space_between_lines * (MAX_NAMES - 1) + entry_text->getCharacterSize();
const int first_line = (param.game.height - size) / 2;
const int SPACE_BETWEEN_HEADER = entry_text->getCharacterSize() * 4;
const int SPACE_BETWEEN_LINES = entry_text->getCharacterSize() * 2;
const int SIZE = SPACE_BETWEEN_HEADER + SPACE_BETWEEN_LINES * (MAX_NAMES - 1) + entry_text->getCharacterSize();
const int FIRST_LINE = (param.game.height - SIZE) / 2;
// Crea el sprite para el texto de cabecera
header_ = std::make_unique<Sprite>(header_text->writeDXToTexture(TEXT_COLOR, Lang::getText("[HIGHSCORE_TABLE] CAPTION"), -2, background_fade_color_.inverse().lighten(25)));
header_->setPosition(param.game.game_area.center_x - (header_->getWidth() / 2), first_line);
header_ = std::make_unique<Sprite>(header_text->writeDXToTexture(TEXT_COLOR, Lang::getText("[HIGHSCORE_TABLE] CAPTION"), -2, background_fade_color_.INVERSE().LIGHTEN(25)));
header_->setPosition(param.game.game_area.center_x - (header_->getWidth() / 2), FIRST_LINE);
// Crea los sprites para las entradas en la tabla de puntuaciones
const int animation = rand() % 4;
const std::string sample_line(ENTRY_LENGHT + 3, ' ');
auto sample_entry = std::make_unique<Sprite>(entry_text->writeDXToTexture(TEXT_SHADOW, sample_line, 1, NO_TEXT_COLOR, 1, SHADOW_TEXT_COLOR));
const auto entry_width = sample_entry->getWidth();
const int ANIMATION = rand() % 4;
const std::string SAMPLE_LINE(ENTRY_LENGHT + 3, ' ');
auto sample_entry = std::make_unique<Sprite>(entry_text->writeDXToTexture(TEXT_SHADOW, SAMPLE_LINE, 1, NO_TEXT_COLOR, 1, SHADOW_TEXT_COLOR));
const auto ENTRY_WIDTH = sample_entry->getWidth();
for (int i = 0; i < MAX_NAMES; ++i) {
const auto table_position = format(i + 1) + ". ";
const auto score = format(Options::settings.hi_score_table.at(i).score);
const auto num_dots = ENTRY_LENGHT - Options::settings.hi_score_table.at(i).name.size() - score.size();
const auto one_cc = Options::settings.hi_score_table.at(i).one_credit_complete ? " }" : "";
const auto TABLE_POSITION = format(i + 1) + ". ";
const auto SCORE = format(Options::settings.hi_score_table.at(i).score);
const auto NUM_DOTS = ENTRY_LENGHT - Options::settings.hi_score_table.at(i).name.size() - SCORE.size();
const auto ONE_CC = Options::settings.hi_score_table.at(i).one_credit_complete ? " }" : "";
std::string dots;
for (int j = 0; j < (int)num_dots; ++j) {
for (int j = 0; j < (int)NUM_DOTS; ++j) {
dots = dots + ".";
}
const auto line = table_position + Options::settings.hi_score_table.at(i).name + dots + score + one_cc;
const auto LINE = TABLE_POSITION + Options::settings.hi_score_table.at(i).name + dots + SCORE + ONE_CC;
entry_names_.emplace_back(std::make_shared<PathSprite>(entry_text->writeDXToTexture(TEXT_SHADOW, line, 1, NO_TEXT_COLOR, 1, SHADOW_TEXT_COLOR)));
const int default_pos_x = (backbuffer_width - entry_width) / 2;
const int pos_x = (i < 9) ? default_pos_x : default_pos_x - entry_text->getCharacterSize();
const int pos_y = (i * space_between_lines) + first_line + space_between_header;
constexpr int steps = 80;
switch (animation) {
entry_names_.emplace_back(std::make_shared<PathSprite>(entry_text->writeDXToTexture(TEXT_SHADOW, LINE, 1, NO_TEXT_COLOR, 1, SHADOW_TEXT_COLOR)));
const int DEFAULT_POS_X = (backbuffer_width - ENTRY_WIDTH) / 2;
const int POS_X = (i < 9) ? DEFAULT_POS_X : DEFAULT_POS_X - entry_text->getCharacterSize();
const int POS_Y = (i * SPACE_BETWEEN_LINES) + FIRST_LINE + SPACE_BETWEEN_HEADER;
constexpr int STEPS = 80;
switch (ANIMATION) {
case 0: // Ambos lados alternativamente
{
if (i % 2 == 0) {
entry_names_.back()->addPath(-entry_names_.back()->getWidth(), pos_x, PathType::HORIZONTAL, pos_y, steps, easeOutQuint);
entry_names_.back()->addPath(-entry_names_.back()->getWidth(), POS_X, PathType::HORIZONTAL, POS_Y, STEPS, easeOutQuint);
entry_names_.back()->setPosition(-entry_names_.back()->getWidth(), 0);
} else {
entry_names_.back()->addPath(backbuffer_width, pos_x, PathType::HORIZONTAL, pos_y, steps, easeOutQuint);
entry_names_.back()->addPath(backbuffer_width, POS_X, PathType::HORIZONTAL, POS_Y, STEPS, easeOutQuint);
entry_names_.back()->setPosition(backbuffer_width, 0);
}
break;
@@ -245,21 +245,21 @@ void HiScoreTable::createSprites() {
case 1: // Entran por la izquierda
{
entry_names_.back()->addPath(-entry_names_.back()->getWidth(), pos_x, PathType::HORIZONTAL, pos_y, steps, easeOutQuint);
entry_names_.back()->addPath(-entry_names_.back()->getWidth(), POS_X, PathType::HORIZONTAL, POS_Y, STEPS, easeOutQuint);
entry_names_.back()->setPosition(-entry_names_.back()->getWidth(), 0);
break;
}
case 2: // Entran por la derecha
{
entry_names_.back()->addPath(backbuffer_width, pos_x, PathType::HORIZONTAL, pos_y, steps, easeOutQuint);
entry_names_.back()->addPath(backbuffer_width, POS_X, PathType::HORIZONTAL, POS_Y, STEPS, easeOutQuint);
entry_names_.back()->setPosition(backbuffer_width, 0);
break;
}
case 3: // Entran desde la parte inferior
{
entry_names_.back()->addPath(backbuffer_height, pos_y, PathType::VERTICAL, pos_x, steps, easeOutQuint);
entry_names_.back()->addPath(backbuffer_height, POS_Y, PathType::VERTICAL, POS_X, STEPS, easeOutQuint);
entry_names_.back()->setPosition(0, backbuffer_height);
}
@@ -271,12 +271,12 @@ void HiScoreTable::createSprites() {
// Actualiza las posiciones de los sprites de texto
void HiScoreTable::updateSprites() {
constexpr int init_counter = 190;
const int counter_between_entries = 16;
if (counter_ >= init_counter) {
const int counter2 = counter_ - init_counter;
if (counter2 % counter_between_entries == 0) {
int index = counter2 / counter_between_entries;
constexpr int INIT_COUNTER = 190;
const int COUNTER_BETWEEN_ENTRIES = 16;
if (counter_ >= INIT_COUNTER) {
const int COUNTER2 = counter_ - INIT_COUNTER;
if (COUNTER2 % COUNTER_BETWEEN_ENTRIES == 0) {
int index = COUNTER2 / COUNTER_BETWEEN_ENTRIES;
if (index < static_cast<int>(entry_names_.size())) {
entry_names_.at(index)->enable();
}
@@ -303,8 +303,8 @@ void HiScoreTable::initBackground() {
background_->setPos(param.game.game_area.rect);
background_->setCloudsSpeed(-0.1f);
const int lucky = rand() % 3;
switch (lucky) {
const int LUCKY = rand() % 3;
switch (LUCKY) {
case 0: // Fondo verde
{
background_->setGradientNumber(2);
@@ -341,9 +341,9 @@ void HiScoreTable::initBackground() {
}
// Obtiene un color del vector de colores de entradas
Color HiScoreTable::getEntryColor(int counter_) {
Color HiScoreTable::getEntryColor(int counter) {
int cycle_length = entry_colors_.size() * 2 - 2;
size_t n = counter_ % cycle_length;
size_t n = counter % cycle_length;
size_t index;
if (n < entry_colors_.size()) {
@@ -358,18 +358,18 @@ Color HiScoreTable::getEntryColor(int counter_) {
// Inicializa los colores de las entradas
void HiScoreTable::iniEntryColors() {
entry_colors_.clear();
entry_colors_.emplace_back(background_fade_color_.inverse().lighten(75));
entry_colors_.emplace_back(background_fade_color_.inverse().lighten(50));
entry_colors_.emplace_back(background_fade_color_.inverse().lighten(25));
entry_colors_.emplace_back(background_fade_color_.inverse());
entry_colors_.emplace_back(background_fade_color_.INVERSE().LIGHTEN(75));
entry_colors_.emplace_back(background_fade_color_.INVERSE().LIGHTEN(50));
entry_colors_.emplace_back(background_fade_color_.INVERSE().LIGHTEN(25));
entry_colors_.emplace_back(background_fade_color_.INVERSE());
}
// Hace brillar los nombres de la tabla de records
void HiScoreTable::glowEntryNames() {
const Color entry_color = getEntryColor(counter_ / 5);
const Color ENTRY_COLOR = getEntryColor(counter_ / 5);
for (const auto &entry_index : Options::settings.last_hi_score_entry) {
if (entry_index != -1) {
entry_names_.at(entry_index)->getTexture()->setColor(entry_color);
entry_names_.at(entry_index)->getTexture()->setColor(ENTRY_COLOR);
}
}
}
@@ -379,7 +379,7 @@ void HiScoreTable::updateCounter() {
++counter_;
if (counter_ == 150) {
background_->setColor(background_fade_color_.darken());
background_->setColor(background_fade_color_.DARKEN());
background_->setAlpha(96);
}

View File

@@ -110,7 +110,7 @@ void Instructions::updateSprites() {
// Rellena la textura de texto
void Instructions::fillTexture() {
const int desp_x = param.game.item_size + 8;
const int DESP_X = param.game.item_size + 8;
// Modifica el renderizador para pintar en la textura
auto temp = SDL_GetRenderTarget(renderer_);
@@ -121,19 +121,19 @@ void Instructions::fillTexture() {
SDL_RenderClear(renderer_);
// Constantes
constexpr int num_lines = 4;
constexpr int num_item_lines = 4;
constexpr int num_post_headers = 2;
constexpr int num_pre_headers = 1;
constexpr int NUM_LINES = 4;
constexpr int NUM_ITEM_LINES = 4;
constexpr int NUM_POST_HEADERS = 2;
constexpr int NUM_PRE_HEADERS = 1;
constexpr int space_post_header = 20;
constexpr int space_pre_header = 28;
const int space_between_lines = text_->getCharacterSize() * 1.5f;
const int space_between_item_lines = param.game.item_size + item_space_;
const int space_new_paragraph = space_between_lines * 0.5f;
constexpr int SPACE_POST_HEADER = 20;
constexpr int SPACE_PRE_HEADER = 28;
const int SPACE_BETWEEN_LINES = text_->getCharacterSize() * 1.5f;
const int SPACE_BETWEEN_ITEM_LINES = param.game.item_size + item_space_;
const int SPACE_NEW_PARAGRAPH = SPACE_BETWEEN_LINES * 0.5f;
const int size = (num_lines * space_between_lines) + (num_item_lines * space_between_item_lines) + (num_post_headers * space_post_header) + (num_pre_headers * space_pre_header) + (space_new_paragraph);
const int first_line = (param.game.height - size) / 2;
const int SIZE = (NUM_LINES * SPACE_BETWEEN_LINES) + (NUM_ITEM_LINES * SPACE_BETWEEN_ITEM_LINES) + (NUM_POST_HEADERS * SPACE_POST_HEADER) + (NUM_PRE_HEADERS * SPACE_PRE_HEADER) + (SPACE_NEW_PARAGRAPH);
const int FIRST_LINE = (param.game.height - SIZE) / 2;
// Calcula cual es el texto más largo de las descripciones de los items
int lenght = 0;
@@ -144,39 +144,39 @@ void Instructions::fillTexture() {
Lang::getText("[INSTRUCTIONS] 10"),
Lang::getText("[INSTRUCTIONS] 11")};
for (const auto &desc : ITEM_DESCRIPTIONS) {
const int l = text_->lenght(desc);
lenght = l > lenght ? l : lenght;
const int L = text_->lenght(desc);
lenght = L > lenght ? L : lenght;
}
const int ANCHOR_ITEM = (param.game.width - (lenght + desp_x)) / 2;
const int ANCHOR_ITEM = (param.game.width - (lenght + DESP_X)) / 2;
constexpr Color ORANGE_COLOR = Color(0XFF, 0X7A, 0X00);
// Escribe el texto de las instrucciones
text_->writeDX(TEXT_CENTER | TEXT_COLOR | TEXT_SHADOW, param.game.game_area.center_x, first_line, Lang::getText("[INSTRUCTIONS] 01"), 1, ORANGE_COLOR, 1, SHADOW_TEXT_COLOR);
text_->writeDX(TEXT_CENTER | TEXT_COLOR | TEXT_SHADOW, param.game.game_area.center_x, FIRST_LINE, Lang::getText("[INSTRUCTIONS] 01"), 1, ORANGE_COLOR, 1, SHADOW_TEXT_COLOR);
const int anchor1 = first_line + space_post_header;
text_->writeDX(TEXT_CENTER | TEXT_COLOR | TEXT_SHADOW, param.game.game_area.center_x, anchor1 + space_between_lines * 0, Lang::getText("[INSTRUCTIONS] 02"), 1, NO_TEXT_COLOR, 1, SHADOW_TEXT_COLOR);
text_->writeDX(TEXT_CENTER | TEXT_COLOR | TEXT_SHADOW, param.game.game_area.center_x, anchor1 + space_between_lines * 1, Lang::getText("[INSTRUCTIONS] 03"), 1, NO_TEXT_COLOR, 1, SHADOW_TEXT_COLOR);
text_->writeDX(TEXT_CENTER | TEXT_COLOR | TEXT_SHADOW, param.game.game_area.center_x, anchor1 + space_new_paragraph + space_between_lines * 2, Lang::getText("[INSTRUCTIONS] 04"), 1, NO_TEXT_COLOR, 1, SHADOW_TEXT_COLOR);
text_->writeDX(TEXT_CENTER | TEXT_COLOR | TEXT_SHADOW, param.game.game_area.center_x, anchor1 + space_new_paragraph + space_between_lines * 3, Lang::getText("[INSTRUCTIONS] 05"), 1, NO_TEXT_COLOR, 1, SHADOW_TEXT_COLOR);
const int ANCHOR1 = FIRST_LINE + SPACE_POST_HEADER;
text_->writeDX(TEXT_CENTER | TEXT_COLOR | TEXT_SHADOW, param.game.game_area.center_x, ANCHOR1 + SPACE_BETWEEN_LINES * 0, Lang::getText("[INSTRUCTIONS] 02"), 1, NO_TEXT_COLOR, 1, SHADOW_TEXT_COLOR);
text_->writeDX(TEXT_CENTER | TEXT_COLOR | TEXT_SHADOW, param.game.game_area.center_x, ANCHOR1 + SPACE_BETWEEN_LINES * 1, Lang::getText("[INSTRUCTIONS] 03"), 1, NO_TEXT_COLOR, 1, SHADOW_TEXT_COLOR);
text_->writeDX(TEXT_CENTER | TEXT_COLOR | TEXT_SHADOW, param.game.game_area.center_x, ANCHOR1 + SPACE_NEW_PARAGRAPH + SPACE_BETWEEN_LINES * 2, Lang::getText("[INSTRUCTIONS] 04"), 1, NO_TEXT_COLOR, 1, SHADOW_TEXT_COLOR);
text_->writeDX(TEXT_CENTER | TEXT_COLOR | TEXT_SHADOW, param.game.game_area.center_x, ANCHOR1 + SPACE_NEW_PARAGRAPH + SPACE_BETWEEN_LINES * 3, Lang::getText("[INSTRUCTIONS] 05"), 1, NO_TEXT_COLOR, 1, SHADOW_TEXT_COLOR);
// Escribe el texto de los objetos y sus puntos
const int anchor2 = anchor1 + space_pre_header + space_new_paragraph + space_between_lines * 3;
text_->writeDX(TEXT_CENTER | TEXT_COLOR | TEXT_SHADOW, param.game.game_area.center_x, anchor2, Lang::getText("[INSTRUCTIONS] 06"), 1, ORANGE_COLOR, 1, SHADOW_TEXT_COLOR);
const int ANCHOR2 = ANCHOR1 + SPACE_PRE_HEADER + SPACE_NEW_PARAGRAPH + SPACE_BETWEEN_LINES * 3;
text_->writeDX(TEXT_CENTER | TEXT_COLOR | TEXT_SHADOW, param.game.game_area.center_x, ANCHOR2, Lang::getText("[INSTRUCTIONS] 06"), 1, ORANGE_COLOR, 1, SHADOW_TEXT_COLOR);
const int anchor3 = anchor2 + space_post_header;
text_->writeShadowed(ANCHOR_ITEM + desp_x, anchor3 + space_between_item_lines * 0, Lang::getText("[INSTRUCTIONS] 07"), SHADOW_TEXT_COLOR);
text_->writeShadowed(ANCHOR_ITEM + desp_x, anchor3 + space_between_item_lines * 1, Lang::getText("[INSTRUCTIONS] 08"), SHADOW_TEXT_COLOR);
text_->writeShadowed(ANCHOR_ITEM + desp_x, anchor3 + space_between_item_lines * 2, Lang::getText("[INSTRUCTIONS] 09"), SHADOW_TEXT_COLOR);
text_->writeShadowed(ANCHOR_ITEM + desp_x, anchor3 + space_between_item_lines * 3, Lang::getText("[INSTRUCTIONS] 10"), SHADOW_TEXT_COLOR);
text_->writeShadowed(ANCHOR_ITEM + desp_x, anchor3 + space_between_item_lines * 4, Lang::getText("[INSTRUCTIONS] 11"), SHADOW_TEXT_COLOR);
const int ANCHOR3 = ANCHOR2 + SPACE_POST_HEADER;
text_->writeShadowed(ANCHOR_ITEM + DESP_X, ANCHOR3 + SPACE_BETWEEN_ITEM_LINES * 0, Lang::getText("[INSTRUCTIONS] 07"), SHADOW_TEXT_COLOR);
text_->writeShadowed(ANCHOR_ITEM + DESP_X, ANCHOR3 + SPACE_BETWEEN_ITEM_LINES * 1, Lang::getText("[INSTRUCTIONS] 08"), SHADOW_TEXT_COLOR);
text_->writeShadowed(ANCHOR_ITEM + DESP_X, ANCHOR3 + SPACE_BETWEEN_ITEM_LINES * 2, Lang::getText("[INSTRUCTIONS] 09"), SHADOW_TEXT_COLOR);
text_->writeShadowed(ANCHOR_ITEM + DESP_X, ANCHOR3 + SPACE_BETWEEN_ITEM_LINES * 3, Lang::getText("[INSTRUCTIONS] 10"), SHADOW_TEXT_COLOR);
text_->writeShadowed(ANCHOR_ITEM + DESP_X, ANCHOR3 + SPACE_BETWEEN_ITEM_LINES * 4, Lang::getText("[INSTRUCTIONS] 11"), SHADOW_TEXT_COLOR);
// Deja el renderizador como estaba
SDL_SetRenderTarget(renderer_, temp);
// Da valor a la variable
sprite_pos_.x = ANCHOR_ITEM;
sprite_pos_.y = anchor3 - ((param.game.item_size - text_->getCharacterSize()) / 2);
sprite_pos_.y = ANCHOR3 - ((param.game.item_size - text_->getCharacterSize()) / 2);
}
// Rellena el backbuffer
@@ -289,14 +289,14 @@ std::vector<Line> Instructions::initializeLines(int height) {
}
// Método para mover las líneas con suavizado
bool Instructions::moveLines(std::vector<Line> &lines, int width, float duration, Uint32 startDelay) {
bool Instructions::moveLines(std::vector<Line> &lines, int width, float duration, Uint32 start_delay) {
Uint32 current_time = SDL_GetTicks();
bool all_lines_off_screen = true;
for (auto &line : lines) {
// Establecer startTime en el primer cuadro de animación
if (line.startTime == 0) {
line.startTime = current_time + line.y * startDelay;
line.startTime = current_time + line.y * start_delay;
}
float elapsed_time = (current_time - line.startTime) / 1000.0f; // Convertir a segundos
@@ -319,10 +319,10 @@ bool Instructions::moveLines(std::vector<Line> &lines, int width, float duration
// Método para renderizar las líneas
void Instructions::renderLines(SDL_Renderer *renderer, SDL_Texture *texture, const std::vector<Line> &lines) {
for (const auto &LINE : lines) {
SDL_FRect srcRect = {0, static_cast<float>(LINE.y), 320, 1};
SDL_FRect dstRect = {static_cast<float>(LINE.x), static_cast<float>(LINE.y), 320, 1};
SDL_RenderTexture(renderer, texture, &srcRect, &dstRect);
for (const auto &line : lines) {
SDL_FRect src_rect = {0, static_cast<float>(line.y), 320, 1};
SDL_FRect dst_rect = {static_cast<float>(line.x), static_cast<float>(line.y), 320, 1};
SDL_RenderTexture(renderer, texture, &src_rect, &dst_rect);
}
}

View File

@@ -52,64 +52,64 @@ void Intro::checkEvents() {
while (SDL_PollEvent(&event)) {
#ifdef DEBUG
if (event.type == SDL_EVENT_KEY_DOWN && event.key.repeat == 1) {
static Color color = param.intro.bg_color;
static Color color_ = param.intro.bg_color;
switch (event.key.key) {
case SDLK_A:
if (color.r < 255)
++color.r;
if (color_.r < 255)
++color_.r;
break;
case SDLK_Z:
if (color.r > 0)
--color.r;
if (color_.r > 0)
--color_.r;
break;
case SDLK_S:
if (color.g < 255)
++color.g;
if (color_.g < 255)
++color_.g;
break;
case SDLK_X:
if (color.g > 0)
--color.g;
if (color_.g > 0)
--color_.g;
break;
case SDLK_D:
if (color.b < 255)
++color.b;
if (color_.b < 255)
++color_.b;
break;
case SDLK_C:
if (color.b > 0)
--color.b;
if (color_.b > 0)
--color_.b;
break;
case SDLK_F:
if (color.r < 255)
++color.r;
if (color.g < 255)
++color.g;
if (color.b < 255)
++color.b;
if (color_.r < 255)
++color_.r;
if (color_.g < 255)
++color_.g;
if (color_.b < 255)
++color_.b;
break;
case SDLK_V:
if (color.r > 0)
--color.r;
if (color.g > 0)
--color.g;
if (color.b > 0)
--color.b;
if (color_.r > 0)
--color_.r;
if (color_.g > 0)
--color_.g;
if (color_.b > 0)
--color_.b;
break;
default:
break;
}
tiled_bg_->setColor(color);
tiled_bg_->setColor(color_);
std::cout << "#"
<< 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.b
<< 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_.b
<< std::endl;
}
#endif
@@ -542,15 +542,15 @@ void Intro::updatePostState() {
if (ELAPSED_TIME >= 1000) {
tiled_bg_->stopGracefully();
if (!bg_color_.isEqualTo(param.title.bg_color)) {
bg_color_ = bg_color_.approachTo(param.title.bg_color, 1);
if (!bg_color_.IS_EQUAL_TO(param.title.bg_color)) {
bg_color_ = bg_color_.APPROACH_TO(param.title.bg_color, 1);
}
tiled_bg_->setColor(bg_color_);
}
// Cambia de estado si el fondo se ha detenido y recuperado el color
if (tiled_bg_->isStopped() && bg_color_.isEqualTo(param.title.bg_color)) {
if (tiled_bg_->isStopped() && bg_color_.IS_EQUAL_TO(param.title.bg_color)) {
post_state_ = IntroPostState::END;
state_start_time_ = SDL_GetTicks();
}
@@ -572,7 +572,7 @@ void Intro::updatePostState() {
void Intro::renderTextRect() {
static const float HEIGHT = Resource::get()->getText("04b_25_metal")->getCharacterSize();
static SDL_FRect rect = {0.0f, param.game.height - param.intro.text_distance_from_bottom - HEIGHT, param.game.width, HEIGHT * 3};
static SDL_FRect rect_ = {0.0f, param.game.height - param.intro.text_distance_from_bottom - HEIGHT, param.game.width, HEIGHT * 3};
SDL_SetRenderDrawColor(Screen::get()->getRenderer(), param.intro.shadow_color.r, param.intro.shadow_color.g, param.intro.shadow_color.b, param.intro.shadow_color.a);
SDL_RenderFillRect(Screen::get()->getRenderer(), &rect);
SDL_RenderFillRect(Screen::get()->getRenderer(), &rect_);
}

View File

@@ -110,18 +110,18 @@ void Logo::updateJAILGAMES() {
// Gestiona el color de las texturas
void Logo::updateTextureColors() {
constexpr int inc = 4;
constexpr int INC = 4;
// Manejo de 'sinceTexture'
for (int i = 0; i <= 7; ++i) {
if (counter_ == SHOW_SINCE_SPRITE_COUNTER_MARK + inc * i) {
if (counter_ == SHOW_SINCE_SPRITE_COUNTER_MARK + INC * i) {
since_texture_->setColor(color_[i].r, color_[i].g, color_[i].b);
}
}
// Manejo de 'jailTexture' y 'sinceTexture' en el fade
for (int i = 0; i <= 6; ++i) {
if (counter_ == INIT_FADE_COUNTER_MARK + inc * i) {
if (counter_ == INIT_FADE_COUNTER_MARK + INC * i) {
jail_texture_->setColor(color_[6 - i].r, color_[6 - i].g, color_[6 - i].b);
since_texture_->setColor(color_[6 - i].r, color_[6 - i].g, color_[6 - i].b);
}

View File

@@ -109,65 +109,65 @@ void Title::checkEvents() {
while (SDL_PollEvent(&event)) {
#ifdef DEBUG
if (event.type == SDL_EVENT_KEY_DOWN && event.key.repeat == 1) {
static Color color = param.title.bg_color;
static Color color_ = param.title.bg_color;
switch (event.key.key) {
case SDLK_A:
if (color.r < 255)
++color.r;
if (color_.r < 255)
++color_.r;
break;
case SDLK_Z:
if (color.r > 0)
--color.r;
if (color_.r > 0)
--color_.r;
break;
case SDLK_S:
if (color.g < 255)
++color.g;
if (color_.g < 255)
++color_.g;
break;
case SDLK_X:
if (color.g > 0)
--color.g;
if (color_.g > 0)
--color_.g;
break;
case SDLK_D:
if (color.b < 255)
++color.b;
if (color_.b < 255)
++color_.b;
break;
case SDLK_C:
if (color.b > 0)
--color.b;
if (color_.b > 0)
--color_.b;
break;
case SDLK_F:
if (color.r < 255)
++color.r;
if (color.g < 255)
++color.g;
if (color.b < 255)
++color.b;
if (color_.r < 255)
++color_.r;
if (color_.g < 255)
++color_.g;
if (color_.b < 255)
++color_.b;
break;
case SDLK_V:
if (color.r > 0)
--color.r;
if (color.g > 0)
--color.g;
if (color.b > 0)
--color.b;
if (color_.r > 0)
--color_.r;
if (color_.g > 0)
--color_.g;
if (color_.b > 0)
--color_.b;
break;
default:
break;
}
counter_ = 0;
tiled_bg_->setColor(color);
tiled_bg_->setColor(color_);
std::cout << "#"
<< 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.b
<< 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_.b
<< std::endl;
}
#endif
@@ -218,11 +218,11 @@ void Title::checkInput() {
if (!ServiceMenu::get()->isEnabled()) {
// Comprueba todos los métodos de control
for (const auto &CONTROLLER : Options::controllers) {
for (const auto &controller : Options::controllers) {
// Boton START
if (Input::get()->checkInput(InputAction::START, INPUT_DO_NOT_ALLOW_REPEAT, CONTROLLER.type, CONTROLLER.index)) {
if (Input::get()->checkInput(InputAction::START, INPUT_DO_NOT_ALLOW_REPEAT, controller.type, controller.index)) {
if ((state_ != TitleState::LOGO_ANIMATING || ALLOW_TITLE_ANIMATION_SKIP)) {
if (CONTROLLER.player_id == 1) {
if (controller.player_id == 1) {
if (!player1_start_pressed_) {
player1_start_pressed_ = true;
getPlayer(1)->setPlayingState(PlayerState::TITLE_ANIMATION);
@@ -231,7 +231,7 @@ void Title::checkInput() {
}
}
if (CONTROLLER.player_id == 2) {
if (controller.player_id == 2) {
if (!player2_start_pressed_) {
player2_start_pressed_ = true;
getPlayer(2)->setPlayingState(PlayerState::TITLE_ANIMATION);
@@ -292,9 +292,9 @@ void Title::showControllers() {
// Genera el texto correspondiente
for (size_t i = 0; i < NUM_CONTROLLERS; ++i) {
const size_t index = player_controller_index.at(i);
if (Options::controllers.at(index).plugged) {
text.at(i) = Lang::getText("[DEFINE_BUTTONS] PLAYER") + std::to_string(i + 1) + ": " + Options::controllers.at(index).name;
const size_t INDEX = player_controller_index.at(i);
if (Options::controllers.at(INDEX).plugged) {
text.at(i) = Lang::getText("[DEFINE_BUTTONS] PLAYER") + std::to_string(i + 1) + ": " + Options::controllers.at(INDEX).name;
}
}

View File

@@ -3,9 +3,9 @@
#include "texture.h" // Para Texture
// Constructor
Sprite::Sprite(std::shared_ptr<Texture> texture, float x, float y, float w, float h)
Sprite::Sprite(std::shared_ptr<Texture> texture, float pos_x, float pos_y, float width, float height)
: texture_(texture),
pos_((SDL_FRect){x, y, w, h}),
pos_((SDL_FRect){pos_x, pos_y, width, height}),
sprite_clip_((SDL_FRect){0, 0, pos_.w, pos_.h}) {}
Sprite::Sprite(std::shared_ptr<Texture> texture, SDL_FRect rect)
@@ -24,15 +24,15 @@ void Sprite::render() {
}
// Establece la posición del objeto
void Sprite::setPosition(float x, float y) {
pos_.x = x;
pos_.y = y;
void Sprite::setPosition(float pos_x, float pos_y) {
pos_.x = pos_x;
pos_.y = pos_y;
}
// Establece la posición del objeto
void Sprite::setPosition(SDL_FPoint p) {
pos_.x = p.x;
pos_.y = p.y;
void Sprite::setPosition(SDL_FPoint point) {
pos_.x = point.x;
pos_.y = point.y;
}
// Reinicia las variables a cero

View File

@@ -10,7 +10,7 @@ class Texture;
class Sprite {
public:
// --- Constructores y destructor ---
Sprite(std::shared_ptr<Texture> texture, float x, float y, float w, float h);
Sprite(std::shared_ptr<Texture> texture, float pos_x, float pos_y, float width, float height);
Sprite(std::shared_ptr<Texture> texture, SDL_FRect rect);
explicit Sprite(std::shared_ptr<Texture> texture);
virtual ~Sprite() = default;
@@ -20,21 +20,21 @@ class Sprite {
virtual void clear(); // Reinicia las variables a cero
// --- Getters de posición y tamaño ---
float getX() const { return pos_.x; }
float getY() const { return pos_.y; }
float getWidth() const { return pos_.w; }
float getHeight() const { return pos_.h; }
SDL_FRect getPosition() const { return pos_; }
SDL_FRect &getRect() { return pos_; }
[[nodiscard]] auto getX() const -> float { return pos_.x; }
[[nodiscard]] auto getY() const -> float { return pos_.y; }
[[nodiscard]] auto getWidth() const -> float { return pos_.w; }
[[nodiscard]] auto getHeight() const -> float { return pos_.h; }
[[nodiscard]] auto getPosition() const -> SDL_FRect { return pos_; }
auto getRect() -> SDL_FRect& { return pos_; }
// --- Setters de posición y tamaño ---
void setX(float x) { pos_.x = x; }
void setY(float y) { pos_.y = y; }
void setWidth(float w) { pos_.w = w; }
void setHeight(float h) { pos_.h = h; }
void setPosition(float x, float y);
void setPosition(SDL_FPoint p);
void setPosition(SDL_FRect r) { pos_ = r; }
void setX(float pos_x) { pos_.x = pos_x; }
void setY(float pos_y) { pos_.y = pos_y; }
void setWidth(float width) { pos_.w = width; }
void setHeight(float height) { pos_.h = height; }
void setPosition(float pos_x, float pos_y);
void setPosition(SDL_FPoint point);
void setPosition(SDL_FRect rect) { pos_ = rect; }
// --- Zoom ---
void setZoom(float zoom) { zoom_ = zoom; }
@@ -44,12 +44,12 @@ class Sprite {
void incY(float value) { pos_.y += value; }
// --- Sprite clip ---
SDL_FRect getSpriteClip() const { return sprite_clip_; }
[[nodiscard]] auto getSpriteClip() const -> SDL_FRect { return sprite_clip_; }
void setSpriteClip(SDL_FRect rect) { sprite_clip_ = rect; }
void setSpriteClip(float x, float y, float w, float h) { sprite_clip_ = SDL_FRect{x, y, w, h}; }
void setSpriteClip(float pos_x, float pos_y, float width, float height) { sprite_clip_ = SDL_FRect{pos_x, pos_y, width, height}; }
// --- Textura ---
std::shared_ptr<Texture> getTexture() const { return texture_; }
[[nodiscard]] auto getTexture() const -> std::shared_ptr<Texture> { return texture_; }
void setTexture(std::shared_ptr<Texture> texture) { texture_ = texture; }
protected:
@@ -57,5 +57,5 @@ class Sprite {
std::shared_ptr<Texture> texture_; // Textura donde están todos los dibujos del sprite
SDL_FRect pos_; // Posición y tamaño donde dibujar el sprite
SDL_FRect sprite_clip_; // Rectángulo de origen de la textura que se dibujará en pantalla
double zoom_ = 1.0f; // Zoom aplicado a la textura
double zoom_ = 1.0F; // Zoom aplicado a la textura
};

View File

@@ -2,10 +2,10 @@
#include "tabe.h"
#include <SDL3/SDL.h> // Para SDL_FlipMode, SDL_GetTicks
#include <stdlib.h> // Para rand, abs
#include <algorithm> // Para max
#include <cmath> // Para abs
#include <cstdlib> // Para rand, abs
#include <string> // Para basic_string
#include "audio.h" // Para Audio
@@ -16,7 +16,7 @@
// Constructor
Tabe::Tabe()
: sprite_(std::make_unique<AnimatedSprite>(Resource::get()->getTexture("tabe.png"), Resource::get()->getAnimation("tabe.ani"))),
timer_(TabeTimer(2.5f, 4.0f)) {}
timer_(TabeTimer(2.5F, 4.0F)) {}
// Actualiza la lógica
void Tabe::update() {
@@ -27,7 +27,7 @@ void Tabe::update() {
}
timer_.update();
if (timer_.should_spawn()) {
if (timer_.shouldSpawn()) {
enable();
}
}
@@ -41,50 +41,50 @@ void Tabe::render() {
// Mueve el objeto
void Tabe::move() {
const int x = static_cast<int>(x_);
speed_ += accel_;
x_ += speed_;
fly_distance_ -= std::abs(x - static_cast<int>(x_));
const int X = static_cast<int>(x_);
speed_ += accel_;
x_ += speed_;
fly_distance_ -= std::abs(X - static_cast<int>(x_));
// Comprueba si sale por los bordes
const float min_x = param.game.game_area.rect.x - WIDTH_;
const float max_x = param.game.game_area.rect.x + param.game.game_area.rect.w;
switch (destiny_) {
case TabeDirection::TO_THE_LEFT: {
if (x_ < min_x) {
disable();
}
if (x_ > param.game.game_area.rect.x + param.game.game_area.rect.w - WIDTH_ && direction_ == TabeDirection::TO_THE_RIGHT) {
setRandomFlyPath(TabeDirection::TO_THE_LEFT, 80);
x_ = param.game.game_area.rect.x + param.game.game_area.rect.w - WIDTH_;
}
break;
}
// Comprueba si sale por los bordes
const float MIN_X = param.game.game_area.rect.x - WIDTH;
const float MAX_X = param.game.game_area.rect.x + param.game.game_area.rect.w;
switch (destiny_) {
case TabeDirection::TO_THE_LEFT: {
if (x_ < MIN_X) {
disable();
}
if (x_ > param.game.game_area.rect.x + param.game.game_area.rect.w - WIDTH && direction_ == TabeDirection::TO_THE_RIGHT) {
setRandomFlyPath(TabeDirection::TO_THE_LEFT, 80);
x_ = param.game.game_area.rect.x + param.game.game_area.rect.w - WIDTH;
}
break;
}
case TabeDirection::TO_THE_RIGHT: {
if (x_ > max_x) {
disable();
}
if (x_ < param.game.game_area.rect.x && direction_ == TabeDirection::TO_THE_LEFT) {
setRandomFlyPath(TabeDirection::TO_THE_RIGHT, 80);
x_ = param.game.game_area.rect.x;
}
break;
}
default:
break;
case TabeDirection::TO_THE_RIGHT: {
if (x_ > MAX_X) {
disable();
}
if (x_ < param.game.game_area.rect.x && direction_ == TabeDirection::TO_THE_LEFT) {
setRandomFlyPath(TabeDirection::TO_THE_RIGHT, 80);
x_ = param.game.game_area.rect.x;
}
break;
}
default:
break;
}
if (fly_distance_ <= 0) {
if (waiting_counter_ > 0) {
accel_ = speed_ = 0.0f;
--waiting_counter_;
accel_ = speed_ = 0.0F;
--waiting_counter_;
} else {
constexpr int CHOICES = 4;
const TabeDirection left[CHOICES] = {TabeDirection::TO_THE_LEFT, TabeDirection::TO_THE_LEFT, TabeDirection::TO_THE_LEFT, TabeDirection::TO_THE_RIGHT};
const TabeDirection right[CHOICES] = {TabeDirection::TO_THE_LEFT, TabeDirection::TO_THE_RIGHT, TabeDirection::TO_THE_RIGHT, TabeDirection::TO_THE_RIGHT};
const TabeDirection direction = destiny_ == TabeDirection::TO_THE_LEFT ? left[rand() % CHOICES] : right[rand() % CHOICES];
setRandomFlyPath(direction, 20 + rand() % 40);
const TabeDirection LEFT[CHOICES] = {TabeDirection::TO_THE_LEFT, TabeDirection::TO_THE_LEFT, TabeDirection::TO_THE_LEFT, TabeDirection::TO_THE_RIGHT};
const TabeDirection RIGHT[CHOICES] = {TabeDirection::TO_THE_LEFT, TabeDirection::TO_THE_RIGHT, TabeDirection::TO_THE_RIGHT, TabeDirection::TO_THE_RIGHT};
const TabeDirection DIRECTION = destiny_ == TabeDirection::TO_THE_LEFT ? LEFT[rand() % CHOICES] : RIGHT[rand() % CHOICES];
setRandomFlyPath(DIRECTION, 20 + rand() % 40);
}
}
@@ -98,13 +98,13 @@ void Tabe::enable() {
has_bonus_ = true;
hit_counter_ = 0;
number_of_hits_ = 0;
y_ = param.game.game_area.rect.y + 20.0f;
y_ = param.game.game_area.rect.y + 20.0F;
// Establece una dirección aleatoria
destiny_ = direction_ = rand() % 2 == 0 ? TabeDirection::TO_THE_LEFT : TabeDirection::TO_THE_RIGHT;
// Establece la posición inicial
x_ = (direction_ == TabeDirection::TO_THE_LEFT) ? param.game.game_area.rect.x + param.game.game_area.rect.w : param.game.game_area.rect.x - WIDTH_;
x_ = (direction_ == TabeDirection::TO_THE_LEFT) ? param.game.game_area.rect.x + param.game.game_area.rect.w : param.game.game_area.rect.x - WIDTH;
// Crea una ruta de vuelo
setRandomFlyPath(direction_, 60);
@@ -119,19 +119,19 @@ void Tabe::setRandomFlyPath(TabeDirection direction, int lenght) {
waiting_counter_ = 5 + rand() % 15;
Audio::get()->playSound("tabe.wav");
constexpr float SPEED = 2.0f;
constexpr float SPEED = 2.0F;
switch (direction) {
case TabeDirection::TO_THE_LEFT: {
speed_ = -1.0f * SPEED;
accel_ = -1.0f * (1 + rand() % 10) / 30.0f;
sprite_->setFlip(SDL_FLIP_NONE);
break;
speed_ = -1.0F * SPEED;
accel_ = -1.0F * (1 + rand() % 10) / 30.0F;
sprite_->setFlip(SDL_FLIP_NONE);
break;
}
case TabeDirection::TO_THE_RIGHT: {
speed_ = SPEED;
accel_ = (1 + rand() % 10) / 30.0f;
accel_ = (1 + rand() % 10) / 30.0F;
sprite_->setFlip(SDL_FLIP_HORIZONTAL);
break;
}
@@ -174,12 +174,12 @@ void Tabe::updateState() {
}
// Intenta obtener el bonus
bool Tabe::tryToGetBonus() {
if (has_bonus_ && rand() % std::max(1, 15 - number_of_hits_) == 0) {
has_bonus_ = false;
return true;
}
return false;
auto Tabe::tryToGetBonus() -> bool {
if (has_bonus_ && rand() % std::max(1, 15 - number_of_hits_) == 0) {
has_bonus_ = false;
return true;
}
return false;
}
// Actualiza el temporizador

View File

@@ -1,86 +1,91 @@
#pragma once
#include <SDL3/SDL.h> // Para Uint32, SDL_GetTicks, SDL_FRect
#include <stdlib.h> // Para rand
#include <memory> // Para unique_ptr
#include <cstdlib> // Para rand
#include <memory> // Para unique_ptr
#include "animated_sprite.h" // Para AnimatedSprite
// --- Enumeraciones para dirección y estado ---
enum class TabeDirection : int {
TO_THE_LEFT = 0,
TO_THE_RIGHT = 1,
TO_THE_LEFT = 0,
TO_THE_RIGHT = 1,
};
enum class TabeState : int {
FLY = 0,
HIT = 1,
FLY = 0,
HIT = 1,
};
// --- Estructura para el temporizador del Tabe ---
struct TabeTimer {
private:
static constexpr Uint32 MINUTES_TO_MILLISECONDS = 60000; // Factor de conversión de minutos a milisegundos
public:
Uint32 time_until_next_spawn; // Tiempo restante para la próxima aparición
Uint32 min_spawn_time; // Tiempo mínimo entre apariciones
Uint32 max_spawn_time; // Tiempo máximo entre apariciones
Uint32 min_spawn_time; // Tiempo mínimo entre apariciones (en milisegundos)
Uint32 max_spawn_time; // Tiempo máximo entre apariciones (en milisegundos)
Uint32 current_time; // Tiempo actual
Uint32 delta_time; // Diferencia de tiempo desde la última actualización
Uint32 last_time; // Tiempo de la última actualización
bool is_paused; // Indica si el temporizador está pausado
bool is_paused{false}; // Indica si el temporizador está pausado
// Constructor
TabeTimer(float minTime, float maxTime)
: min_spawn_time(minTime * 60000), max_spawn_time(maxTime * 60000),
current_time(SDL_GetTicks()), is_paused(false) {
reset();
// Constructor - los parámetros min_time y max_time están en mintos
TabeTimer(float min_time, float max_time)
: min_spawn_time(static_cast<Uint32>(min_time * MINUTES_TO_MILLISECONDS)),
max_spawn_time(static_cast<Uint32>(max_time * MINUTES_TO_MILLISECONDS)),
current_time(SDL_GetTicks()) {
reset();
}
// Restablece el temporizador con un nuevo tiempo hasta la próxima aparición
void reset() {
Uint32 range = max_spawn_time - min_spawn_time;
time_until_next_spawn = min_spawn_time + rand() % (range + 1);
last_time = SDL_GetTicks();
Uint32 range = max_spawn_time - min_spawn_time;
time_until_next_spawn = min_spawn_time + rand() % (range + 1);
last_time = SDL_GetTicks();
}
// Actualiza el temporizador, decrementando el tiempo hasta la próxima aparición
void update() {
current_time = SDL_GetTicks();
// Solo actualizar si no está pausado
if (!is_paused) {
delta_time = current_time - last_time;
if (time_until_next_spawn > delta_time) {
time_until_next_spawn -= delta_time;
} else {
time_until_next_spawn = 0;
}
current_time = SDL_GetTicks();
// Solo actualizar si no está pausado
if (!is_paused) {
delta_time = current_time - last_time;
if (time_until_next_spawn > delta_time) {
time_until_next_spawn -= delta_time;
} else {
time_until_next_spawn = 0;
}
// Siempre actualizar last_time para evitar saltos de tiempo al despausar
last_time = current_time;
}
// Siempre actualizar last_time para evitar saltos de tiempo al despausar
last_time = current_time;
}
// Pausa o reanuda el temporizador
void setPaused(bool paused) {
if (is_paused != paused) {
is_paused = paused;
// Al despausar, actualizar last_time para evitar saltos
if (!paused) {
last_time = SDL_GetTicks();
}
if (is_paused != paused) {
is_paused = paused;
// Al despausar, actualizar last_time para evitar saltos
if (!paused) {
last_time = SDL_GetTicks();
}
}
}
// Indica si el temporizador ha finalizado
bool should_spawn() const {
return time_until_next_spawn == 0 && !is_paused;
[[nodiscard]] auto shouldSpawn() const -> bool {
return time_until_next_spawn == 0 && !is_paused;
}
};
// --- Clase Tabe ---
class Tabe {
public:
public:
// --- Constructores y destructor ---
Tabe();
~Tabe() = default;
@@ -90,17 +95,17 @@ class Tabe {
void render(); // Dibuja el objeto
void enable(); // Habilita el objeto
void setState(TabeState state); // Establece el estado
bool tryToGetBonus(); // Intenta obtener el bonus
auto tryToGetBonus() -> bool; // Intenta obtener el bonus
void pauseTimer(bool value); // Detiene/activa el timer
// --- Getters ---
SDL_FRect &getCollider() { return sprite_->getRect(); } // Obtiene el área de colisión
bool isEnabled() const { return enabled_; } // Indica si el objeto está activo
auto getCollider() -> SDL_FRect& { return sprite_->getRect(); } // Obtiene el área de colisión
[[nodiscard]] auto isEnabled() const -> bool { return enabled_; } // Indica si el objeto está activo
private:
private:
// --- Constantes ---
static constexpr int WIDTH_ = 32;
static constexpr int HEIGHT_ = 32;
static constexpr int WIDTH = 32;
static constexpr int HEIGHT = 32;
// --- Objetos y punteros ---
std::unique_ptr<AnimatedSprite> sprite_; // Sprite con los gráficos y animaciones
@@ -108,8 +113,8 @@ class Tabe {
// --- Variables de estado ---
float x_ = 0; // Posición X
float y_ = 0; // Posición Y
float speed_ = 0.0f; // Velocidad de movimiento
float accel_ = 0.0f; // Aceleración
float speed_ = 0.0F; // Velocidad de movimiento
float accel_ = 0.0F; // Aceleración
int fly_distance_ = 0; // Distancia de vuelo
int waiting_counter_ = 0; // Tiempo que pasa quieto
bool enabled_ = false; // Indica si el objeto está activo

View File

@@ -159,7 +159,7 @@ std::shared_ptr<Texture> Text::writeToTexture(const std::string &text, int zoom,
}
// Escribe el texto con extras en una textura
std::shared_ptr<Texture> Text::writeDXToTexture(Uint8 flags, const std::string &text, int kerning, Color textColor, Uint8 shadow_distance, Color shadow_color, int lenght) {
std::shared_ptr<Texture> Text::writeDXToTexture(Uint8 flags, const std::string &text, int kerning, Color text_color, Uint8 shadow_distance, Color shadow_color, int lenght) {
auto renderer = Screen::get()->getRenderer();
auto texture = std::make_shared<Texture>(renderer);
auto width = Text::lenght(text, kerning) + shadow_distance;
@@ -170,7 +170,7 @@ std::shared_ptr<Texture> Text::writeDXToTexture(Uint8 flags, const std::string &
texture->setAsRenderTarget(renderer);
SDL_SetRenderDrawColor(renderer, 0, 0, 0, 0);
SDL_RenderClear(renderer);
writeDX(flags, 0, 0, text, kerning, textColor, shadow_distance, shadow_color, lenght);
writeDX(flags, 0, 0, text, kerning, text_color, shadow_distance, shadow_color, lenght);
SDL_SetRenderTarget(renderer, temp);
return texture;
@@ -198,21 +198,21 @@ void Text::writeCentered(int x, int y, const std::string &text, int kerning, int
}
// Escribe texto con extras
void Text::writeDX(Uint8 flags, int x, int y, const std::string &text, int kerning, Color textColor, Uint8 shadow_distance, Color shadow_color, int lenght) {
const auto centered = ((flags & TEXT_CENTER) == TEXT_CENTER);
const auto shadowed = ((flags & TEXT_SHADOW) == TEXT_SHADOW);
const auto colored = ((flags & TEXT_COLOR) == TEXT_COLOR);
const auto stroked = ((flags & TEXT_STROKE) == TEXT_STROKE);
void Text::writeDX(Uint8 flags, int x, int y, const std::string &text, int kerning, Color text_color, Uint8 shadow_distance, Color shadow_color, int lenght) {
const auto CENTERED = ((flags & TEXT_CENTER) == TEXT_CENTER);
const auto SHADOWED = ((flags & TEXT_SHADOW) == TEXT_SHADOW);
const auto COLORED = ((flags & TEXT_COLOR) == TEXT_COLOR);
const auto STROKED = ((flags & TEXT_STROKE) == TEXT_STROKE);
if (centered) {
if (CENTERED) {
x -= (Text::lenght(text, kerning) / 2);
}
if (shadowed) {
if (SHADOWED) {
writeColored(x + shadow_distance, y + shadow_distance, text, shadow_color, kerning, lenght);
}
if (stroked) {
if (STROKED) {
for (int dist = 1; dist <= shadow_distance; ++dist) {
for (int dy = -dist; dy <= dist; ++dy) {
for (int dx = -dist; dx <= dist; ++dx) {
@@ -222,8 +222,8 @@ void Text::writeDX(Uint8 flags, int x, int y, const std::string &text, int kerni
}
}
if (colored) {
writeColored(x, y, text, textColor, kerning, lenght);
if (COLORED) {
writeColored(x, y, text, text_color, kerning, lenght);
} else {
write(x, y, text, kerning, lenght);
}

View File

@@ -28,7 +28,7 @@ struct TextFile {
};
// Llena una estructura TextFile desde un fichero
std::shared_ptr<TextFile> loadTextFile(const std::string &file_path);
auto loadTextFile(const std::string &file_path) -> std::shared_ptr<TextFile>;
// --- Clase Text: pinta texto en pantalla a partir de un bitmap ---
class Text {
@@ -43,18 +43,18 @@ class Text {
void write2X(int x, int y, const std::string &text, int kerning = 1); // Escribe el texto al doble de tamaño
// --- Escritura en textura ---
std::shared_ptr<Texture> writeToTexture(const std::string &text, int zoom = 1, int kerning = 1); // Escribe el texto en una textura
std::shared_ptr<Texture> writeDXToTexture(Uint8 flags, const std::string &text, int kerning = 1, Color textColor = Color(), Uint8 shadow_distance = 1, Color shadow_color = Color(), int lenght = -1); // Escribe el texto con extras en una textura
auto writeToTexture(const std::string &text, int zoom = 1, int kerning = 1) -> std::shared_ptr<Texture>; // Escribe el texto en una textura
auto writeDXToTexture(Uint8 flags, const std::string &text, int kerning = 1, Color text_color = Color(), Uint8 shadow_distance = 1, Color shadow_color = Color(), int lenght = -1) -> std::shared_ptr<Texture>; // Escribe el texto con extras en una textura
// --- Métodos de escritura avanzada ---
void writeColored(int x, int y, const std::string &text, Color color, int kerning = 1, int lenght = -1); // Escribe el texto con colores
void writeShadowed(int x, int y, const std::string &text, Color color, Uint8 shadow_distance = 1, int kerning = 1, int lenght = -1); // Escribe el texto con sombra
void writeCentered(int x, int y, const std::string &text, int kerning = 1, int lenght = -1); // Escribe el texto centrado en un punto x
void writeDX(Uint8 flags, int x, int y, const std::string &text, int kerning = 1, Color textColor = Color(), Uint8 shadow_distance = 1, Color shadow_color = Color(), int lenght = -1); // Escribe texto con extras
void writeDX(Uint8 flags, int x, int y, const std::string &text, int kerning = 1, Color text_color = Color(), Uint8 shadow_distance = 1, Color shadow_color = Color(), int lenght = -1); // Escribe texto con extras
// --- Utilidades ---
int lenght(const std::string &text, int kerning = 1) const; // Obtiene la longitud en pixels de una cadena
int getCharacterSize() const; // Devuelve el tamaño de caracter actual
[[nodiscard]] auto lenght(const std::string &text, int kerning = 1) const -> int; // Obtiene la longitud en pixels de una cadena
[[nodiscard]] auto getCharacterSize() const -> int; // Devuelve el tamaño de caracter actual
// --- Configuración ---
void setFixedWidth(bool value); // Establece si se usa un tamaño fijo de letra

View File

@@ -22,15 +22,15 @@ Texture::Texture(SDL_Renderer *renderer, const std::string &path)
// Carga el fichero en la textura
if (!path_.empty()) {
// 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
if (extension == "png") {
if (EXTENSION == "png") {
loadFromFile(path_);
}
// .gif
else if (extension == "gif") {
else if (EXTENSION == "gif") {
// Crea la surface desde un fichero
surface_ = loadSurface(path_);
@@ -149,28 +149,28 @@ void Texture::setAlpha(Uint8 alpha) {
}
// Renderiza la textura en un punto específico
void Texture::render(int x, int y, SDL_FRect *clip, float zoomW, float zoomH, double angle, SDL_FPoint *center, SDL_FlipMode flip) {
void Texture::render(int x, int y, SDL_FRect *clip, float zoom_w, float zoom_h, double angle, SDL_FPoint *center, SDL_FlipMode flip) {
// Establece el destino de renderizado en la pantalla
SDL_FRect renderQuad = {static_cast<float>(x), static_cast<float>(y), static_cast<float>(width_), static_cast<float>(height_)};
SDL_FRect render_quad = {static_cast<float>(x), static_cast<float>(y), static_cast<float>(width_), static_cast<float>(height_)};
// Obtiene las dimesiones del clip de renderizado
if (clip != nullptr) {
renderQuad.w = clip->w;
renderQuad.h = clip->h;
render_quad.w = clip->w;
render_quad.h = clip->h;
}
// Calcula el zoom y las coordenadas
if (zoomH != 1.0f || zoomW != 1.0f) {
renderQuad.x = renderQuad.x + (renderQuad.w / 2);
renderQuad.y = renderQuad.y + (renderQuad.h / 2);
renderQuad.w = renderQuad.w * zoomW;
renderQuad.h = renderQuad.h * zoomH;
renderQuad.x = renderQuad.x - (renderQuad.w / 2);
renderQuad.y = renderQuad.y - (renderQuad.h / 2);
if (zoom_h != 1.0f || zoom_w != 1.0f) {
render_quad.x = render_quad.x + (render_quad.w / 2);
render_quad.y = render_quad.y + (render_quad.h / 2);
render_quad.w = render_quad.w * zoom_w;
render_quad.h = render_quad.h * zoom_h;
render_quad.x = render_quad.x - (render_quad.w / 2);
render_quad.y = render_quad.y - (render_quad.h / 2);
}
// Renderiza a pantalla
SDL_RenderTextureRotated(renderer_, texture_, clip, &renderQuad, angle, center, flip);
SDL_RenderTextureRotated(renderer_, texture_, clip, &render_quad, angle, center, flip);
}
// Establece la textura como objetivo de renderizado
@@ -231,16 +231,16 @@ std::shared_ptr<Surface> Texture::loadSurface(const std::string &file_path) {
// Crear un objeto Gif y llamar a la función loadGif
GIF::Gif gif;
Uint16 w = 0, h = 0;
std::vector<Uint8> rawPixels = gif.loadGif(buffer.data(), w, h);
if (rawPixels.empty()) {
std::vector<Uint8> raw_pixels = gif.loadGif(buffer.data(), w, h);
if (raw_pixels.empty()) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: No se pudo cargar el GIF %s", file_path.c_str());
return nullptr;
}
// Si el constructor de Surface espera un std::shared_ptr<Uint8[]>:
size_t pixelCount = rawPixels.size();
auto pixels = std::shared_ptr<Uint8[]>(new Uint8[pixelCount], std::default_delete<Uint8[]>());
std::memcpy(pixels.get(), rawPixels.data(), pixelCount);
size_t pixel_count = raw_pixels.size();
auto pixels = std::shared_ptr<Uint8[]>(new Uint8[pixel_count], std::default_delete<Uint8[]>());
std::memcpy(pixels.get(), raw_pixels.data(), pixel_count);
auto surface = std::make_shared<Surface>(w, h, pixels);

View File

@@ -6,6 +6,7 @@
#include <array> // Para array
#include <memory> // Para shared_ptr
#include <string> // Para string, basic_string
#include <utility>
#include <vector> // Para vector
struct Color;
@@ -20,7 +21,7 @@ struct Surface {
// Constructor
Surface(Uint16 width, Uint16 height, std::shared_ptr<Uint8[]> pixels)
: data(pixels), w(width), h(height) {}
: data(std::move(pixels)), w(width), h(height) {}
};
// Clase Texture: gestiona texturas, paletas y renderizado
@@ -31,12 +32,12 @@ class Texture {
~Texture();
// --- Carga y creación ---
bool loadFromFile(const std::string &path); // Carga una imagen desde un fichero
bool createBlank(int width, int height, SDL_PixelFormat format = SDL_PIXELFORMAT_RGBA8888, SDL_TextureAccess access = SDL_TEXTUREACCESS_STREAMING); // Crea una textura en blanco
bool reLoad(); // Recarga la textura
auto loadFromFile(const std::string &path) -> bool; // Carga una imagen desde un fichero
auto createBlank(int width, int height, SDL_PixelFormat format = SDL_PIXELFORMAT_RGBA8888, SDL_TextureAccess access = SDL_TEXTUREACCESS_STREAMING) -> bool; // Crea una textura en blanco
auto reLoad() -> bool; // Recarga la textura
// --- Renderizado ---
void render(int x, int y, SDL_FRect *clip = nullptr, float zoomW = 1, float zoomH = 1, double angle = 0.0, SDL_FPoint *center = nullptr, SDL_FlipMode flip = SDL_FLIP_NONE); // Renderiza la textura en un punto específico
void render(int x, int y, SDL_FRect *clip = nullptr, float zoom_w = 1, float zoom_h = 1, double angle = 0.0, SDL_FPoint *center = nullptr, SDL_FlipMode flip = SDL_FLIP_NONE); // Renderiza la textura en un punto específico
void setAsRenderTarget(SDL_Renderer *renderer); // Establece la textura como objetivo de renderizado
// --- Modificadores de color y blending ---
@@ -52,12 +53,12 @@ class Texture {
void setPalette(size_t palette); // Cambia la paleta de la textura
// --- Getters ---
int getWidth(); // Obtiene el ancho de la imagen
int getHeight(); // Obtiene el alto de la imagen
SDL_Texture *getSDLTexture(); // Obtiene la textura SDL
SDL_Renderer *getRenderer(); // Obtiene el renderizador
auto getWidth() -> int; // Obtiene el ancho de la imagen
auto getHeight() -> int; // Obtiene el alto de la imagen
auto getSDLTexture() -> SDL_Texture *; // Obtiene la textura SDL
auto getRenderer() -> SDL_Renderer *; // Obtiene el renderizador
private:
private:
// --- Objetos y punteros ---
SDL_Renderer *renderer_; // Renderizador donde dibujar la textura
SDL_Texture *texture_ = nullptr; // La textura
@@ -71,10 +72,10 @@ class Texture {
int current_palette_ = 0; // Índice de la paleta en uso
// --- Métodos internos ---
std::shared_ptr<Surface> loadSurface(const std::string &file_name); // Crea una surface desde un fichero .gif
auto loadSurface(const std::string &file_name) -> std::shared_ptr<Surface>; // Crea una surface desde un fichero .gif
void flipSurface(); // Vuelca la surface en la textura
Palette loadPaletteFromFile(const std::string &file_name); // Carga una paleta desde un fichero
auto loadPaletteFromFile(const std::string &file_name) -> Palette; // Carga una paleta desde un fichero
void unloadTexture(); // Libera la memoria de la textura
void unloadSurface(); // Libera la surface actual
Palette readPalFile(const std::string &file_path); // Carga una paleta desde un archivo .pal
auto readPalFile(const std::string &file_path) -> Palette; // Carga una paleta desde un archivo .pal
};

View File

@@ -60,11 +60,11 @@ void TiledBG::fillTexture() {
SDL_SetRenderTarget(renderer_, canvas_);
// Rellena la textura con el tile
const auto i_max = pos_.w * 2 / TILE_WIDTH_;
const auto j_max = pos_.h * 2 / TILE_HEIGHT_;
const auto I_MAX = pos_.w * 2 / TILE_WIDTH_;
const auto J_MAX = pos_.h * 2 / TILE_HEIGHT_;
tile->setSpriteClip(0, 0, TILE_WIDTH_, TILE_HEIGHT_);
for (int i = 0; i < i_max; ++i) {
for (int j = 0; j < j_max; ++j) {
for (int i = 0; i < I_MAX; ++i) {
for (int j = 0; j < J_MAX; ++j) {
tile->setX(i * TILE_WIDTH_);
tile->setY(j * TILE_HEIGHT_);
tile->render();

View File

@@ -15,9 +15,9 @@ MenuRenderer::MenuRenderer(const ServiceMenu *menu_state, std::shared_ptr<Text>
void MenuRenderer::render(const ServiceMenu *menu_state) {
// Dibuja la sombra
if (param.service_menu.drop_shadow) {
SDL_FRect shadowRect = {rect_.x + 5, rect_.y + 5, rect_.w, rect_.h};
SDL_FRect shadow_rect = {rect_.x + 5, rect_.y + 5, rect_.w, rect_.h};
SDL_SetRenderDrawColor(Screen::get()->getRenderer(), 0, 0, 0, 64);
SDL_RenderFillRect(Screen::get()->getRenderer(), &shadowRect);
SDL_RenderFillRect(Screen::get()->getRenderer(), &shadow_rect);
}
// Dibuja el fondo
@@ -25,7 +25,7 @@ void MenuRenderer::render(const ServiceMenu *menu_state) {
SDL_RenderFillRect(Screen::get()->getRenderer(), &rect_);
// Dibuja el borde
const Color BORDER_COLOR = param.service_menu.title_color.darken();
const Color BORDER_COLOR = param.service_menu.title_color.DARKEN();
SDL_SetRenderDrawColor(Screen::get()->getRenderer(), BORDER_COLOR.r, BORDER_COLOR.g, BORDER_COLOR.b, 255);
SDL_RenderRect(Screen::get()->getRenderer(), &rect_);
SDL_RenderRect(Screen::get()->getRenderer(), &border_rect_);
@@ -43,8 +43,8 @@ void MenuRenderer::render(const ServiceMenu *menu_state) {
y = options_y_;
const auto &option_pairs = menu_state->getOptionPairs();
for (size_t i = 0; i < option_pairs.size(); ++i) {
const bool is_selected = (i == menu_state->getSelectedIndex());
const Color &current_color = is_selected ? param.service_menu.selected_color : param.service_menu.text_color;
const bool IS_SELECTED = (i == menu_state->getSelectedIndex());
const Color &current_color = IS_SELECTED ? param.service_menu.selected_color : param.service_menu.text_color;
if (menu_state->getCurrentGroupAlignment() == ServiceMenu::GroupAlignment::LEFT) {
element_text_->writeColored(rect_.x + ServiceMenu::OPTIONS_HORIZONTAL_PADDING_, y, option_pairs.at(i).first, current_color, -2);
@@ -177,17 +177,17 @@ int MenuRenderer::getMenuWidthForGroup(ServiceMenu::SettingsGroup group) const {
}
void MenuRenderer::updateColorCounter() {
static Uint64 lastUpdate = SDL_GetTicks();
Uint64 currentTicks = SDL_GetTicks();
if (currentTicks - lastUpdate >= 50) {
static Uint64 last_update_ = SDL_GetTicks();
Uint64 current_ticks = SDL_GetTicks();
if (current_ticks - last_update_ >= 50) {
color_counter_++;
lastUpdate = currentTicks;
last_update_ = current_ticks;
}
}
Color MenuRenderer::getAnimatedSelectedColor() {
static auto colorCycle = generateMirroredCycle(param.service_menu.selected_color, ColorCycleStyle::HueWave);
return colorCycle.at(color_counter_ % colorCycle.size());
static auto color_cycle_ = generateMirroredCycle(param.service_menu.selected_color, ColorCycleStyle::HUE_WAVE);
return color_cycle_.at(color_counter_ % color_cycle_.size());
}
SDL_FRect MenuRenderer::setRect(SDL_FRect rect) {

View File

@@ -17,9 +17,9 @@
Overrides overrides = Overrides();
// Obtiene un color del vector de colores imitando al Coche Fantástico
Color getColorLikeKnightRider(const std::vector<Color> &colors, int counter_) {
auto getColorLikeKnightRider(const std::vector<Color> &colors, int counter) -> Color {
int cycle_length = colors.size() * 2 - 2;
size_t n = counter_ % cycle_length;
size_t n = counter % cycle_length;
size_t index;
if (n < colors.size()) {
@@ -32,14 +32,14 @@ Color getColorLikeKnightRider(const std::vector<Color> &colors, int counter_) {
}
// Calcula el cuadrado de la distancia entre dos puntos
double distanceSquared(int x1, int y1, int x2, int y2) {
const int delta_x = x2 - x1;
const int delta_y = y2 - y1;
return delta_x * delta_x + delta_y * delta_y;
auto distanceSquared(int x1, int y1, int x2, int y2) -> double {
const int DELTA_X = x2 - x1;
const int DELTA_Y = y2 - y1;
return DELTA_X * DELTA_X + DELTA_Y * DELTA_Y;
}
// Detector de colisiones entre dos circulos
bool checkCollision(const Circle &a, const Circle &b) {
auto checkCollision(const Circle &a, const Circle &b) -> bool {
// Calcula el radio total al cuadrado
int total_radius_squared = (a.r + b.r) * (a.r + b.r);
@@ -48,84 +48,96 @@ bool checkCollision(const Circle &a, const Circle &b) {
}
// Detector de colisiones entre un circulo y un rectangulo
bool checkCollision(const Circle &a, const SDL_FRect &b) {
auto checkCollision(const Circle &a, const SDL_FRect &b) -> bool {
// Encuentra el punto más cercano en el rectángulo
float cX = std::clamp(static_cast<float>(a.x), b.x, b.x + b.w);
float cY = std::clamp(static_cast<float>(a.y), b.y, b.y + b.h);
float c_x = std::clamp(static_cast<float>(a.x), b.x, b.x + b.w);
float c_y = std::clamp(static_cast<float>(a.y), b.y, b.y + b.h);
// Si el punto más cercano está dentro del círculo
return distanceSquared(static_cast<float>(a.x), static_cast<float>(a.y), cX, cY) < static_cast<float>(a.r) * a.r;
return distanceSquared(static_cast<float>(a.x), static_cast<float>(a.y), c_x, c_y) < static_cast<float>(a.r) * a.r;
}
// Detector de colisiones entre dos rectangulos
bool checkCollision(const SDL_FRect &a, const SDL_FRect &b) {
const int leftA = a.x, rightA = a.x + a.w, topA = a.y, bottomA = a.y + a.h;
const int leftB = b.x, rightB = b.x + b.w, topB = b.y, bottomB = b.y + b.h;
auto checkCollision(const SDL_FRect &a, const SDL_FRect &b) -> bool {
const int LEFT_A = a.x;
const int RIGHT_A = a.x + a.w;
const int TOP_A = a.y;
const int BOTTOM_A = a.y + a.h;
const int LEFT_B = b.x;
const int RIGHT_B = b.x + b.w;
const int TOP_B = b.y;
const int BOTTOM_B = b.y + b.h;
if (bottomA <= topB)
if (BOTTOM_A <= TOP_B) {
return false;
if (topA >= bottomB)
}
if (TOP_A >= BOTTOM_B) {
return false;
if (rightA <= leftB)
}
if (RIGHT_A <= LEFT_B) {
return false;
if (leftA >= rightB)
}
if (LEFT_A >= RIGHT_B) {
return false;
}
return true;
}
// Detector de colisiones entre un punto y un rectangulo
bool checkCollision(const SDL_FPoint &p, const SDL_FRect &r) {
if (p.x < r.x || p.x > r.x + r.w)
auto checkCollision(const SDL_FPoint &p, const SDL_FRect &r) -> bool {
if (p.x < r.x || p.x > r.x + r.w) {
return false;
if (p.y < r.y || p.y > r.y + r.h)
}
if (p.y < r.y || p.y > r.y + r.h) {
return false;
}
return true;
}
// Convierte una cadena en un valor booleano
bool stringToBool(const std::string &str) {
auto stringToBool(const std::string &str) -> bool {
std::string s = trim(toLower(str));
return (s == "true" || s == "1" || s == "yes" || s == "on");
}
// Convierte un valor booleano en una cadena
std::string boolToString(bool value) {
auto boolToString(bool value) -> std::string {
return value ? "true" : "false";
}
// Convierte un valor booleano en una cadena "on" o "off"
std::string boolToOnOff(bool value) {
auto boolToOnOff(bool value) -> std::string {
return value ? Lang::getText("[NOTIFICATIONS] 06") : Lang::getText("[NOTIFICATIONS] 07");
}
// Convierte una cadena a minusculas
std::string toLower(const std::string &str) {
auto toLower(const std::string &str) -> std::string {
std::string result = str;
std::transform(result.begin(), result.end(), result.begin(), [](unsigned char c) { return std::tolower(c); });
return result;
}
// Dibuja un circulo
void DrawCircle(SDL_Renderer *renderer, int32_t centerX, int32_t centerY, int32_t radius) {
const int32_t diameter = (radius * 2);
void drawCircle(SDL_Renderer *renderer, int32_t center_x, int32_t center_y, int32_t radius) {
const int32_t DIAMETER = (radius * 2);
int32_t x = (radius - 1);
int32_t y = 0;
int32_t tx = 1;
int32_t ty = 1;
int32_t error = (tx - diameter);
int32_t error = (tx - DIAMETER);
while (x >= y) {
// Each of the following renders an octant of the circle
SDL_RenderPoint(renderer, centerX + x, centerY - y);
SDL_RenderPoint(renderer, centerX + x, centerY + y);
SDL_RenderPoint(renderer, centerX - x, centerY - y);
SDL_RenderPoint(renderer, centerX - x, centerY + y);
SDL_RenderPoint(renderer, centerX + y, centerY - x);
SDL_RenderPoint(renderer, centerX + y, centerY + x);
SDL_RenderPoint(renderer, centerX - y, centerY - x);
SDL_RenderPoint(renderer, centerX - y, centerY + x);
SDL_RenderPoint(renderer, center_x + x, center_y - y);
SDL_RenderPoint(renderer, center_x + x, center_y + y);
SDL_RenderPoint(renderer, center_x - x, center_y - y);
SDL_RenderPoint(renderer, center_x - x, center_y + y);
SDL_RenderPoint(renderer, center_x + y, center_y - x);
SDL_RenderPoint(renderer, center_x + y, center_y + x);
SDL_RenderPoint(renderer, center_x - y, center_y - x);
SDL_RenderPoint(renderer, center_x - y, center_y + x);
if (error <= 0) {
++y;
@@ -136,110 +148,135 @@ void DrawCircle(SDL_Renderer *renderer, int32_t centerX, int32_t centerY, int32_
if (error > 0) {
--x;
tx += 2;
error += (tx - diameter);
error += (tx - DIAMETER);
}
}
}
// Aclara el color
Color lightenColor(const Color &color, int amount) {
Color newColor;
newColor.r = std::min(255, color.r + amount);
newColor.g = std::min(255, color.g + amount);
newColor.b = std::min(255, color.b + amount);
return newColor;
auto lightenColor(const Color &color, int amount) -> Color {
Color new_color;
new_color.r = std::min(255, color.r + amount);
new_color.g = std::min(255, color.g + amount);
new_color.b = std::min(255, color.b + amount);
return new_color;
}
// Oscurece el color
Color DarkenColor(const Color &color, int amount) {
Color newColor;
newColor.r = std::min(255, color.r - +amount);
newColor.g = std::min(255, color.g - +amount);
newColor.b = std::min(255, color.b - +amount);
return newColor;
auto darkenColor(const Color &color, int amount) -> Color {
Color new_color;
new_color.r = std::min(255, color.r - +amount);
new_color.g = std::min(255, color.g - +amount);
new_color.b = std::min(255, color.b - +amount);
return new_color;
}
// Quita los espacioes en un string
std::string trim(const std::string &str) {
auto trim(const std::string &str) -> std::string {
auto start = std::find_if_not(str.begin(), str.end(), ::isspace);
auto end = std::find_if_not(str.rbegin(), str.rend(), ::isspace).base();
return (start < end ? std::string(start, end) : std::string());
}
// Función de suavizado
double easeOutQuint(double t) {
return 1 - std::pow(1 - t, 5);
auto easeOutQuint(double time) -> double {
return 1 - std::pow(1 - time, 5);
}
// Función de suavizado
double easeInQuint(double t) {
return pow(t, 5);
auto easeInQuint(double time) -> double {
return pow(time, 5);
}
// Función de suavizado
double easeInOutQuint(double t) {
return t < 0.5 ? 16 * pow(t, 5) : 1 - pow(-2 * t + 2, 5) / 2;
auto easeInOutQuint(double time) -> double {
return time < 0.5 ? 16 * pow(time, 5) : 1 - pow(-2 * time + 2, 5) / 2;
}
// Función de suavizado
double easeInQuad(double t) {
return t * t;
auto easeInQuad(double time) -> double {
return time * time;
}
// Función de suavizado
double easeOutQuad(double t) {
return 1 - (1 - t) * (1 - t);
auto easeOutQuad(double time) -> double {
return 1 - (1 - time) * (1 - time);
}
// Función de suavizado
double easeInOutSine(double t) {
return -0.5 * (std::cos(M_PI * t) - 1);
auto easeInOutSine(double time) -> double {
return -0.5 * (std::cos(M_PI * time) - 1);
}
// Función de suavizado
double easeInOut(double t) {
return t < 0.5 ? 2 * t * t : -1 + (4 - 2 * t) * t;
auto easeInOut(double time) -> double {
return time < 0.5 ? 2 * time * time : -1 + (4 - 2 * time) * time;
}
// Función de suavizado
double easeInOutExpo(double t) {
return t == 0 ? 0 : (t == 1 ? 1 : (t < 0.5 ? pow(2, 20 * t - 10) / 2 : (2 - pow(2, -20 * t + 10)) / 2));
// Función de suavizado (easeInOutExpo)
auto easeInOutExpo(double time) -> double {
if (time == 0) {
return 0;
}
if (time == 1) {
return 1;
}
if (time < 0.5) {
return pow(2, 20 * time - 10) / 2;
}
return (2 - pow(2, -20 * time + 10)) / 2;
}
// Función de suavizado (easeInElastic)
double easeInElastic(double t) {
return t == 0 ? 0 : (t == 1 ? 1 : -pow(2, 10 * t - 10) * sin((t * 10 - 10.75) * (2 * M_PI) / 3));
}
// Función de suavizado
double easeOutBounce(double t) {
if (t < 1 / 2.75) {
return 7.5625 * t * t;
} else if (t < 2 / 2.75) {
t -= 1.5 / 2.75;
return 7.5625 * t * t + 0.75;
} else if (t < 2.5 / 2.75) {
t -= 2.25 / 2.75;
return 7.5625 * t * t + 0.9375;
} else {
t -= 2.625 / 2.75;
return 7.5625 * t * t + 0.984375;
auto easeInElastic(double time) -> double {
if (time == 0) {
return 0;
}
if (time == 1) {
return 1;
}
const double C4 = (2 * M_PI) / 3;
return -pow(2, 10 * time - 10) * sin((time * 10 - 10.75) * C4);
}
// Función de suavizado
double easeOutElastic(double t) {
const double c4 = (2 * M_PI) / 3; // Constante para controlar la elasticidad
auto easeOutBounce(double time) -> double {
if (time < 1 / 2.75) {
return 7.5625 * time * time;
}
if (time < 2 / 2.75) {
time -= 1.5 / 2.75;
return 7.5625 * time * time + 0.75;
}
if (time < 2.5 / 2.75) {
time -= 2.25 / 2.75;
return 7.5625 * time * time + 0.9375;
}
time -= 2.625 / 2.75;
return 7.5625 * time * time + 0.984375;
}
return t == 0
? 0
: (t == 1
? 1
: pow(2, -10 * t) * sin((t * 10 - 0.75) * c4) + 1);
// Función de suavizado (easeOutElastic)
auto easeOutElastic(double time) -> double {
if (time == 0) {
return 0;
}
if (time == 1) {
return 1;
}
const double C4 = (2 * M_PI) / 3; // Constante para controlar la elasticidad
return pow(2, -10 * time) * sin((time * 10 - 0.75) * C4) + 1;
}
// Comprueba si una vector contiene una cadena
bool stringInVector(const std::vector<std::string> &vec, const std::string &str) {
auto stringInVector(const std::vector<std::string> &vec, const std::string &str) -> bool {
return std::find(vec.begin(), vec.end(), str) != vec.end();
}
@@ -270,27 +307,26 @@ void printWithDots(const std::string &text1, const std::string &text2, const std
}
// Carga el fichero de datos para la demo
DemoData loadDemoDataFromFile(const std::string &file_path) {
auto loadDemoDataFromFile(const std::string &file_path) -> DemoData {
DemoData dd;
// Indicador de éxito en la carga
auto file = SDL_IOFromFile(file_path.c_str(), "r+b");
if (!file) {
auto *file = SDL_IOFromFile(file_path.c_str(), "r+b");
if (file == nullptr) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: Fichero no encontrado %s", file_path.c_str());
throw std::runtime_error("Fichero no encontrado: " + file_path);
} else {
printWithDots("DemoData : ", getFileName(file_path), "[ LOADED ]");
// Lee todos los datos del fichero y los deja en el destino
for (int i = 0; i < TOTAL_DEMO_DATA; ++i) {
DemoKeys dk = DemoKeys();
SDL_ReadIO(file, &dk, sizeof(DemoKeys));
dd.push_back(dk);
}
// Cierra el fichero
SDL_CloseIO(file);
}
printWithDots("DemoData : ", getFileName(file_path), "[ LOADED ]");
// Lee todos los datos del fichero y los deja en el destino
for (int i = 0; i < TOTAL_DEMO_DATA; ++i) {
DemoKeys dk = DemoKeys();
SDL_ReadIO(file, &dk, sizeof(DemoKeys));
dd.push_back(dk);
}
// Cierra el fichero
SDL_CloseIO(file);
return dd;
}
@@ -325,50 +361,54 @@ bool saveDemoFile(const std::string &file_path, const DemoData &dd) {
#endif // RECORDING
// Obtiene el nombre de un fichero a partir de una ruta completa
std::string getFileName(const std::string &path) {
auto getFileName(const std::string &path) -> std::string {
return std::filesystem::path(path).filename().string();
}
// Obtiene la ruta eliminando el nombre del fichero
std::string getPath(const std::string &full_path) {
auto getPath(const std::string &full_path) -> std::string {
std::filesystem::path path(full_path);
return path.parent_path().string();
}
constexpr HSV rgbToHsv(Color color) {
float r = color.r / 255.0f;
float g = color.g / 255.0f;
float b = color.b / 255.0f;
constexpr auto rgbToHsv(Color color) -> HSV {
float r = color.r / 255.0F;
float g = color.g / 255.0F;
float b = color.b / 255.0F;
float max = fmaxf(fmaxf(r, g), b);
float min = fminf(fminf(r, g), b);
float delta = max - min;
float h = 0.0f;
if (delta > 0.00001f) {
if (max == r)
h = fmodf((g - b) / delta, 6.0f);
else if (max == g)
h = ((b - r) / delta) + 2.0f;
else
h = ((r - g) / delta) + 4.0f;
h *= 60.0f;
if (h < 0.0f)
h += 360.0f;
float h = 0.0F;
if (delta > 0.00001F) {
if (max == r) {
h = fmodf((g - b) / delta, 6.0F);
} else if (max == g) {
h = ((b - r) / delta) + 2.0F;
} else {
h = ((r - g) / delta) + 4.0F;
}
h *= 60.0F;
if (h < 0.0F) {
h += 360.0F;
}
}
float s = (max <= 0.0f) ? 0.0f : delta / max;
float s = (max <= 0.0F) ? 0.0F : delta / max;
float v = max;
return {h, s, v};
}
constexpr Color hsvToRgb(HSV hsv) {
constexpr auto hsvToRgb(HSV hsv) -> Color {
float c = hsv.v * hsv.s;
float x = c * (1 - std::abs(std::fmod(hsv.h / 60.0f, 2) - 1));
float x = c * (1 - std::abs(std::fmod(hsv.h / 60.0F, 2) - 1));
float m = hsv.v - c;
float r = 0, g = 0, b = 0;
float r = 0;
float g = 0;
float b = 0;
if (hsv.h < 60) {
r = c;
@@ -402,50 +442,50 @@ constexpr Color hsvToRgb(HSV hsv) {
static_cast<uint8_t>(roundf((b + m) * 255)));
}
ColorCycle generateMirroredCycle(Color base, ColorCycleStyle style) {
auto generateMirroredCycle(Color base, ColorCycleStyle style) -> ColorCycle {
ColorCycle result{};
HSV baseHSV = rgbToHsv(base);
HSV base_hsv = rgbToHsv(base);
for (size_t i = 0; i < COLOR_CYCLE_SIZE; ++i) {
float t = static_cast<float>(i) / (COLOR_CYCLE_SIZE - 1); // 0 → 1
float hueShift = 0.0f;
float satShift = 0.0f;
float valShift = 0.0f;
float hue_shift = 0.0F;
float sat_shift = 0.0F;
float val_shift = 0.0F;
switch (style) {
case ColorCycleStyle::SubtlePulse:
case ColorCycleStyle::SUBTLE_PULSE:
// Solo brillo suave
valShift = 0.07f * sinf(t * M_PI);
val_shift = 0.07F * sinf(t * M_PI);
break;
case ColorCycleStyle::HueWave:
case ColorCycleStyle::HUE_WAVE:
// Oscilación leve de tono
hueShift = 15.0f * (t - 0.5f) * 2.0f;
valShift = 0.05f * sinf(t * M_PI);
hue_shift = 15.0F * (t - 0.5F) * 2.0F;
val_shift = 0.05F * sinf(t * M_PI);
break;
case ColorCycleStyle::Vibrant:
case ColorCycleStyle::VIBRANT:
// Cambios fuertes en tono y brillo
hueShift = 35.0f * sinf(t * M_PI);
valShift = 0.2f * sinf(t * M_PI);
satShift = -0.2f * sinf(t * M_PI);
hue_shift = 35.0F * sinf(t * M_PI);
val_shift = 0.2F * sinf(t * M_PI);
sat_shift = -0.2F * sinf(t * M_PI);
break;
case ColorCycleStyle::DarkenGlow:
case ColorCycleStyle::DARKEN_GLOW:
// Se oscurece al centro
valShift = -0.15f * sinf(t * M_PI);
val_shift = -0.15F * sinf(t * M_PI);
break;
case ColorCycleStyle::LightFlash:
case ColorCycleStyle::LIGHT_FLASH:
// Se ilumina al centro
valShift = 0.25f * sinf(t * M_PI);
val_shift = 0.25F * sinf(t * M_PI);
break;
}
HSV adjusted = {
fmodf(baseHSV.h + hueShift + 360.0f, 360.0f),
fminf(1.0f, fmaxf(0.0f, baseHSV.s + satShift)),
fminf(1.0f, fmaxf(0.0f, baseHSV.v + valShift))};
fmodf(base_hsv.h + hue_shift + 360.0F, 360.0F),
fminf(1.0F, fmaxf(0.0F, base_hsv.s + sat_shift)),
fminf(1.0F, fmaxf(0.0F, base_hsv.v + val_shift))};
Color c = hsvToRgb(adjusted);
result[i] = c;

View File

@@ -1,11 +1,11 @@
#pragma once
#include <SDL3/SDL.h> // Para Uint8, SDL_FRect, SDL_FPoint, SDL_Renderer
#include <stdint.h> // Para int32_t
#include <algorithm> // Para max, min
#include <array> // Para array
#include <cctype> // Para isxdigit
#include <cstdint> // Para int32_t
#include <cstdlib> // Para abs, size_t
#include <stdexcept> // Para invalid_argument
#include <string> // Para string, basic_string, stoi
@@ -18,105 +18,131 @@ constexpr size_t COLOR_CYCLE_SIZE = 6; // Mitad del ciclo espejado
// --- Estructuras y tipos ---
struct Overrides {
std::string param_file; // Fichero de parametros a utilizar
bool clear_hi_score_table; // Reinicia la tabla de records
std::string param_file; // Fichero de parametros a utilizar
bool clear_hi_score_table{false}; // Reinicia la tabla de records
Overrides()
: param_file(""), clear_hi_score_table(false) {}
Overrides() = default;
};
extern Overrides overrides;
// Estructura para definir un circulo
struct Circle {
int x, y, r;
Circle() : x(0), y(0), r(0) {}
Circle(int xCoord, int yCoord, int radius)
: x(xCoord), y(yCoord), r(radius) {}
int x, y, r;
Circle() : x(0), y(0), r(0) {}
Circle(int x_coord, int y_coord, int radius)
: x(x_coord), y(y_coord), r(radius) {}
};
// Estructura para definir un color RGBA
struct Color {
Uint8 r, g, b, a;
constexpr Color() : r(0), g(0), b(0), a(255) {}
explicit constexpr Color(Uint8 red, Uint8 green, Uint8 blue, Uint8 alpha = 255) : r(red), g(green), b(blue), a(alpha) {}
private:
static constexpr Uint8 MAX_COLOR_VALUE = 255;
static constexpr Uint8 MIN_COLOR_VALUE = 0;
static constexpr Uint8 DEFAULT_ALPHA = 255;
static constexpr int DEFAULT_LIGHTEN_AMOUNT = 50;
static constexpr int DEFAULT_DARKEN_AMOUNT = 50;
static constexpr int DEFAULT_APPROACH_STEP = 1;
static constexpr size_t HEX_RGB_LENGTH = 6;
static constexpr size_t HEX_RGBA_LENGTH = 8;
static constexpr int HEX_BASE = 16;
static constexpr size_t HEX_COMPONENT_LENGTH = 2;
constexpr Color inverse() const { return Color(255 - r, 255 - g, 255 - b, a); }
constexpr Color lighten(int amount = 50) const {
return Color(
std::min(255, r + amount),
std::min(255, g + amount),
std::min(255, b + amount),
a);
}
constexpr Color darken(int amount = 50) const {
return Color(
std::max(0, r - amount),
std::max(0, g - amount),
std::max(0, b - amount),
a);
}
public:
Uint8 r, g, b, a;
// Método estático para crear Color desde string hexadecimal
static Color fromHex(const std::string &hexStr) {
std::string hex = hexStr;
constexpr Color() : r(MIN_COLOR_VALUE), g(MIN_COLOR_VALUE), b(MIN_COLOR_VALUE), a(DEFAULT_ALPHA) {}
// Quitar '#' si existe
if (!hex.empty() && hex[0] == '#') {
hex = hex.substr(1);
explicit constexpr Color(Uint8 red, Uint8 green, Uint8 blue, Uint8 alpha = DEFAULT_ALPHA)
: r(red), g(green), b(blue), a(alpha) {}
[[nodiscard]] constexpr auto INVERSE() const -> Color {
return Color(MAX_COLOR_VALUE - r, MAX_COLOR_VALUE - g, MAX_COLOR_VALUE - b, a);
}
// Verificar longitud válida (6 para RGB o 8 para RGBA)
if (hex.length() != 6 && hex.length() != 8) {
throw std::invalid_argument("String hexadecimal debe tener 6 o 8 caracteres");
[[nodiscard]] constexpr auto LIGHTEN(int amount = DEFAULT_LIGHTEN_AMOUNT) const -> Color {
return Color(
std::min(static_cast<int>(MAX_COLOR_VALUE), r + amount),
std::min(static_cast<int>(MAX_COLOR_VALUE), g + amount),
std::min(static_cast<int>(MAX_COLOR_VALUE), b + amount),
a);
}
// Verificar que todos los caracteres sean hexadecimales válidos
for (char c : hex) {
if (!std::isxdigit(c)) {
throw std::invalid_argument("String contiene caracteres no hexadecimales");
[[nodiscard]] constexpr auto DARKEN(int amount = DEFAULT_DARKEN_AMOUNT) const -> Color {
return Color(
std::max(static_cast<int>(MIN_COLOR_VALUE), r - amount),
std::max(static_cast<int>(MIN_COLOR_VALUE), g - amount),
std::max(static_cast<int>(MIN_COLOR_VALUE), b - amount),
a);
}
// Método estático para crear Color desde string hexadecimal
static auto fromHex(const std::string &hex_str) -> Color {
std::string hex = hex_str;
// Quitar '#' si existe
if (!hex.empty() && hex[0] == '#') {
hex = hex.substr(1);
}
// Verificar longitud válida (6 para RGB o 8 para RGBA)
if (hex.length() != HEX_RGB_LENGTH && hex.length() != HEX_RGBA_LENGTH) {
throw std::invalid_argument("String hexadecimal debe tener 6 o 8 caracteres");
}
// Verificar que todos los caracteres sean hexadecimales válidos
for (char c : hex) {
if (std::isxdigit(c) == 0) {
throw std::invalid_argument("String contiene caracteres no hexadecimales");
}
}
// Convertir cada par de caracteres a valores RGB(A)
Uint8 r = static_cast<Uint8>(std::stoi(hex.substr(0, HEX_COMPONENT_LENGTH), nullptr, HEX_BASE));
Uint8 g = static_cast<Uint8>(std::stoi(hex.substr(HEX_COMPONENT_LENGTH, HEX_COMPONENT_LENGTH), nullptr, HEX_BASE));
Uint8 b = static_cast<Uint8>(std::stoi(hex.substr(HEX_COMPONENT_LENGTH * 2, HEX_COMPONENT_LENGTH), nullptr, HEX_BASE));
Uint8 a = DEFAULT_ALPHA; // Alpha por defecto
// Si tiene 8 caracteres, extraer el alpha
if (hex.length() == HEX_RGBA_LENGTH) {
a = static_cast<Uint8>(std::stoi(hex.substr(HEX_COMPONENT_LENGTH * 3, HEX_COMPONENT_LENGTH), nullptr, HEX_BASE));
}
return Color(r, g, b, a);
}
// Convertir cada par de caracteres a valores RGB(A)
Uint8 r = static_cast<Uint8>(std::stoi(hex.substr(0, 2), nullptr, 16));
Uint8 g = static_cast<Uint8>(std::stoi(hex.substr(2, 2), nullptr, 16));
Uint8 b = static_cast<Uint8>(std::stoi(hex.substr(4, 2), nullptr, 16));
Uint8 a = 255; // Alpha por defecto
// Si tiene 8 caracteres, extraer el alpha
if (hex.length() == 8) {
a = static_cast<Uint8>(std::stoi(hex.substr(6, 2), nullptr, 16));
[[nodiscard]] constexpr auto IS_EQUAL_TO(const Color &other) const -> bool {
return r == other.r && g == other.g && b == other.b && a == other.a;
}
return Color(r, g, b, a);
}
[[nodiscard]] constexpr auto APPROACH_TO(const Color &target, int step = DEFAULT_APPROACH_STEP) const -> Color {
auto approach_component = [step](Uint8 current, Uint8 target_val) -> Uint8 {
if (std::abs(current - target_val) <= step) {
return target_val;
}
return (current < target_val) ? current + step : current - step;
};
constexpr bool isEqualTo(const Color &other) const {
return r == other.r && g == other.g && b == other.b && a == other.a;
}
Uint8 new_r = approach_component(r, target.r);
Uint8 new_g = approach_component(g, target.g);
Uint8 new_b = approach_component(b, target.b);
Uint8 new_a = approach_component(a, target.a);
constexpr Color approachTo(const Color &target, int step = 1) const {
Uint8 newR = (std::abs(r - target.r) <= step) ? target.r : (r < target.r ? r + step : r - step);
Uint8 newG = (std::abs(g - target.g) <= step) ? target.g : (g < target.g ? g + step : g - step);
Uint8 newB = (std::abs(b - target.b) <= step) ? target.b : (b < target.b ? b + step : b - step);
Uint8 newA = (std::abs(a - target.a) <= step) ? target.a : (a < target.a ? a + step : a - step);
return Color(newR, newG, newB, newA);
}
return Color(new_r, new_g, new_b, new_a);
}
};
// Estructura para definir un color HSV
struct HSV {
float h, s, v;
float h, s, v;
};
// Estructura para definir el ciclo de color
enum class ColorCycleStyle {
SubtlePulse, // Variación leve en brillo (por defecto)
HueWave, // Variación suave en tono (sin verde)
Vibrant, // Cambios agresivos en tono y brillo
DarkenGlow, // Oscurece hacia el centro y regresa
LightFlash // Ilumina hacia el centro y regresa
SUBTLE_PULSE, // Variación leve en brillo (por defecto)
HUE_WAVE, // Variación suave en tono (sin verde)
VIBRANT, // Cambios agresivos en tono y brillo
DARKEN_GLOW, // Oscurece hacia el centro y regresa
LIGHT_FLASH // Ilumina hacia el centro y regresa
};
// Posiciones de las notificaciones
@@ -130,40 +156,40 @@ enum class NotifyPosition {
// Estructura para datos de la demo
struct DemoKeys {
Uint8 left;
Uint8 right;
Uint8 no_input;
Uint8 fire;
Uint8 fire_left;
Uint8 fire_right;
Uint8 left;
Uint8 right;
Uint8 no_input;
Uint8 fire;
Uint8 fire_left;
Uint8 fire_right;
explicit DemoKeys(Uint8 l = 0, Uint8 r = 0, Uint8 ni = 0, Uint8 f = 0, Uint8 fl = 0, Uint8 fr = 0)
: left(l), right(r), no_input(ni), fire(f), fire_left(fl), fire_right(fr) {}
explicit DemoKeys(Uint8 l = 0, Uint8 r = 0, Uint8 ni = 0, Uint8 f = 0, Uint8 fl = 0, Uint8 fr = 0)
: left(l), right(r), no_input(ni), fire(f), fire_left(fl), fire_right(fr) {}
};
using DemoData = std::vector<DemoKeys>;
struct Demo {
bool enabled; // Indica si está activo el modo demo
bool recording; // Indica si está activado el modo para grabar la demo
int counter; // Contador para el modo demo
DemoKeys keys; // Variable con las pulsaciones de teclas del modo demo
std::vector<DemoData> data; // Vector con diferentes sets de datos con los movimientos para la demo
bool enabled; // Indica si está activo el modo demo
bool recording; // Indica si está activado el modo para grabar la demo
int counter; // Contador para el modo demo
DemoKeys keys; // Variable con las pulsaciones de teclas del modo demo
std::vector<DemoData> data; // Vector con diferentes sets de datos con los movimientos para la demo
Demo() : enabled(false), recording(false), counter(0), keys(), data() {}
Demo(bool e, bool r, int c, const DemoKeys &k, const std::vector<DemoData> &d)
: enabled(e), recording(r), counter(c), keys(k), data(d) {}
Demo() : enabled(false), recording(false), counter(0) {}
Demo(bool e, bool r, int c, const DemoKeys &k, const std::vector<DemoData> &d)
: enabled(e), recording(r), counter(c), keys(k), data(d) {}
};
// Posiciones dentro de un rectangulo
struct Zone {
SDL_FRect rect; // Rectangulo que define la zona
float center_x; // Anclaje al 50% del eje X
float first_quarter_x; // Anclaje al 25% del eje X
float third_quarter_x; // Anclaje al 75% del eje X
float center_y; // Anclaje al 50% del eje Y
float first_quarter_y; // Anclaje al 25% del eje Y
float third_quarter_y; // Anclaje al 75% del eje Y
SDL_FRect rect; // Rectangulo que define la zona
float center_x; // Anclaje al 50% del eje X
float first_quarter_x; // Anclaje al 25% del eje X
float third_quarter_x; // Anclaje al 75% del eje X
float center_y; // Anclaje al 50% del eje Y
float first_quarter_y; // Anclaje al 25% del eje Y
float third_quarter_y; // Anclaje al 75% del eje Y
};
// --- Alias ---
@@ -183,56 +209,56 @@ constexpr Color PINK_SKY_COLOR = Color(0XFF, 0X6B, 0X97);
constexpr Color GREEN_SKY_COLOR = Color(0X00, 0X79, 0X6B);
// Colores y gráficos
Color getColorLikeKnightRider(const std::vector<Color> &colors, int counter_);
constexpr HSV rgbToHsv(Color color);
constexpr Color hsvToRgb(HSV hsv);
ColorCycle generateMirroredCycle(Color base, ColorCycleStyle style = ColorCycleStyle::SubtlePulse);
auto getColorLikeKnightRider(const std::vector<Color> &colors, int counter) -> Color;
constexpr auto rgbToHsv(Color color) -> HSV;
constexpr auto hsvToRgb(HSV hsv) -> Color;
auto generateMirroredCycle(Color base, ColorCycleStyle style = ColorCycleStyle::SUBTLE_PULSE) -> ColorCycle;
// Colisiones y geometría
double distanceSquared(int x1, int y1, int x2, int y2);
bool checkCollision(const Circle &a, const Circle &b);
bool checkCollision(const Circle &a, const SDL_FRect &b);
bool checkCollision(const SDL_FRect &a, const SDL_FRect &b);
bool checkCollision(const SDL_FPoint &p, const SDL_FRect &r);
auto distanceSquared(int x1, int y1, int x2, int y2) -> double;
auto checkCollision(const Circle &a, const Circle &b) -> bool;
auto checkCollision(const Circle &a, const SDL_FRect &b) -> bool;
auto checkCollision(const SDL_FRect &a, const SDL_FRect &b) -> bool;
auto checkCollision(const SDL_FPoint &p, const SDL_FRect &r) -> bool;
// Conversión y manipulación de cadenas
bool stringToBool(const std::string &str);
std::string boolToString(bool value);
std::string boolToOnOff(bool value);
std::string toLower(const std::string &str);
std::string trim(const std::string &str);
auto stringToBool(const std::string &str) -> bool;
auto boolToString(bool value) -> std::string;
auto boolToOnOff(bool value) -> std::string;
auto toLower(const std::string &str) -> std::string;
auto trim(const std::string &str) -> std::string;
// Dibujo
void DrawCircle(SDL_Renderer *renderer, int32_t centerX, int32_t centerY, int32_t radius);
void drawCircle(SDL_Renderer *renderer, int32_t center_x, int32_t center_y, int32_t radius);
// Manipulación de color
Color lightenColor(const Color &color, int amount);
Color DarkenColor(const Color &color, int amount);
auto lightenColor(const Color &color, int amount) -> Color;
auto darkenColor(const Color &color, int amount) -> Color;
// Funciones de suavizado (easing)
double easeOutQuint(double t);
double easeInQuint(double t);
double easeInOutQuint(double t);
double easeInQuad(double t);
double easeOutQuad(double t);
double easeInOutSine(double t);
double easeInOut(double t);
double easeInOutExpo(double t);
double easeOutBounce(double t);
double easeOutElastic(double t);
double easeInElastic(double t);
auto easeOutQuint(double time) -> double;
auto easeInQuint(double time) -> double;
auto easeInOutQuint(double time) -> double;
auto easeInQuad(double time) -> double;
auto easeOutQuad(double time) -> double;
auto easeInOutSine(double time) -> double;
auto easeInOut(double time) -> double;
auto easeInOutExpo(double time) -> double;
auto easeOutBounce(double time) -> double;
auto easeOutElastic(double time) -> double;
auto easeInElastic(double time) -> double;
// Utilidades varias
bool stringInVector(const std::vector<std::string> &vec, const std::string &str); // Comprueba si un vector contiene una cadena
auto stringInVector(const std::vector<std::string> &vec, const std::string &str) -> bool; // Comprueba si un vector contiene una cadena
void printWithDots(const std::string &text1, const std::string &text2, const std::string &text3); // Imprime una línea con puntos
// Demo
DemoData loadDemoDataFromFile(const std::string &file_path);
auto loadDemoDataFromFile(const std::string &file_path) -> DemoData;
#ifdef RECORDING
bool saveDemoFile(const std::string &file_path, const DemoData &dd);
#endif
// Ficheros y rutas
std::string getFileName(const std::string &path); // Obtiene el nombre de un fichero a partir de una ruta
std::string getPath(const std::string &full_path); // Obtiene la ruta eliminando el nombre del fichero
auto getFileName(const std::string &path) -> std::string; // Obtiene el nombre de un fichero a partir de una ruta
auto getPath(const std::string &full_path) -> std::string; // Obtiene la ruta eliminando el nombre del fichero