Compare commits
2 Commits
a7ef29b750
...
1f0184fde2
| Author | SHA1 | Date | |
|---|---|---|---|
| 1f0184fde2 | |||
| bfda842d3c |
@@ -1,5 +1,6 @@
|
|||||||
Checks: >
|
Checks: >
|
||||||
readability-identifier-naming
|
readability-identifier-naming,
|
||||||
|
modernize-*
|
||||||
|
|
||||||
WarningsAsErrors: '*'
|
WarningsAsErrors: '*'
|
||||||
# Solo incluir archivos de tu código fuente
|
# Solo incluir archivos de tu código fuente
|
||||||
|
|||||||
@@ -9,16 +9,16 @@
|
|||||||
#include "utils.h" // Para getFileName
|
#include "utils.h" // Para getFileName
|
||||||
|
|
||||||
// Singleton
|
// Singleton
|
||||||
Asset *Asset::instance_ = nullptr;
|
Asset *Asset::instance = nullptr;
|
||||||
|
|
||||||
// Inicializa la instancia única del singleton
|
// Inicializa la instancia única del singleton
|
||||||
void Asset::init(const std::string &executable_path) { Asset::instance_ = new Asset(executable_path); }
|
void Asset::init(const std::string &executable_path) { Asset::instance = new Asset(executable_path); }
|
||||||
|
|
||||||
// Libera la instancia
|
// Libera la instancia
|
||||||
void Asset::destroy() { delete Asset::instance_; }
|
void Asset::destroy() { delete Asset::instance; }
|
||||||
|
|
||||||
// Obtiene la instancia
|
// Obtiene la instancia
|
||||||
auto Asset::get() -> Asset * { return Asset::instance_; }
|
auto Asset::get() -> Asset * { return Asset::instance; }
|
||||||
|
|
||||||
// Añade un elemento a la lista
|
// Añade un elemento a la lista
|
||||||
void Asset::add(const std::string &file, AssetType type, bool required, bool absolute) {
|
void Asset::add(const std::string &file, AssetType type, bool required, bool absolute) {
|
||||||
|
|||||||
@@ -41,8 +41,8 @@ class Asset { // Gestor de recursos (singleton)
|
|||||||
AssetType type; // Tipo de recurso
|
AssetType type; // Tipo de recurso
|
||||||
bool required; // Indica si el fichero es obligatorio
|
bool required; // Indica si el fichero es obligatorio
|
||||||
|
|
||||||
AssetItem(std::string filePath, AssetType assetType, bool isRequired)
|
AssetItem(std::string file_path, AssetType asset_type, bool is_required)
|
||||||
: file(std::move(filePath)), type(assetType), required(isRequired) {} // Constructor
|
: file(std::move(file_path)), type(asset_type), required(is_required) {} // Constructor
|
||||||
};
|
};
|
||||||
|
|
||||||
// --- Variables internas ---
|
// --- Variables internas ---
|
||||||
@@ -60,5 +60,5 @@ class Asset { // Gestor de recursos (singleton)
|
|||||||
~Asset() = default; // Destructor
|
~Asset() = default; // Destructor
|
||||||
|
|
||||||
// --- Singleton ---
|
// --- Singleton ---
|
||||||
static Asset *instance_; // Instancia singleton
|
static Asset *instance; // Instancia singleton
|
||||||
};
|
};
|
||||||
@@ -9,16 +9,16 @@
|
|||||||
#include "resource.h" // Para Resource
|
#include "resource.h" // Para Resource
|
||||||
|
|
||||||
// Singleton
|
// Singleton
|
||||||
Audio *Audio::instance_ = nullptr;
|
Audio *Audio::instance = nullptr;
|
||||||
|
|
||||||
// Inicializa la instancia única del singleton
|
// Inicializa la instancia única del singleton
|
||||||
void Audio::init() { Audio::instance_ = new Audio(); }
|
void Audio::init() { Audio::instance = new Audio(); }
|
||||||
|
|
||||||
// Libera la instancia
|
// Libera la instancia
|
||||||
void Audio::destroy() { delete Audio::instance_; }
|
void Audio::destroy() { delete Audio::instance; }
|
||||||
|
|
||||||
// Obtiene la instancia
|
// Obtiene la instancia
|
||||||
auto Audio::get() -> Audio * { return Audio::instance_; }
|
auto Audio::get() -> Audio * { return Audio::instance; }
|
||||||
|
|
||||||
// Constructor
|
// Constructor
|
||||||
Audio::Audio() { initSDLAudio(); }
|
Audio::Audio() { initSDLAudio(); }
|
||||||
|
|||||||
@@ -90,5 +90,5 @@ class Audio {
|
|||||||
~Audio(); // Destructor privado
|
~Audio(); // Destructor privado
|
||||||
|
|
||||||
// --- Singleton ---
|
// --- Singleton ---
|
||||||
static Audio *instance_;
|
static Audio *instance;
|
||||||
};
|
};
|
||||||
@@ -321,7 +321,11 @@ void Background::createSunPath() {
|
|||||||
constexpr float RADIUS = 120;
|
constexpr float RADIUS = 120;
|
||||||
|
|
||||||
// Generar puntos de la curva desde 90 a 180 grados
|
// Generar puntos de la curva desde 90 a 180 grados
|
||||||
for (double theta = M_PI / 2; theta <= M_PI; theta += 0.01) {
|
constexpr double STEP = 0.01;
|
||||||
|
const int NUM_STEPS = static_cast<int>((M_PI - M_PI / 2) / STEP) + 1;
|
||||||
|
|
||||||
|
for (int i = 0; i < NUM_STEPS; ++i) {
|
||||||
|
double theta = M_PI / 2 + i * STEP;
|
||||||
float x = CENTER_X + (RADIUS * cos(theta));
|
float x = CENTER_X + (RADIUS * cos(theta));
|
||||||
float y = CENTER_Y - (RADIUS * sin(theta));
|
float y = CENTER_Y - (RADIUS * sin(theta));
|
||||||
sun_path_.push_back({x, y});
|
sun_path_.push_back({x, y});
|
||||||
@@ -342,7 +346,11 @@ void Background::createMoonPath() {
|
|||||||
constexpr float RADIUS = 140;
|
constexpr float RADIUS = 140;
|
||||||
|
|
||||||
// Generar puntos de la curva desde 0 a 90 grados
|
// Generar puntos de la curva desde 0 a 90 grados
|
||||||
for (double theta = 0; theta <= M_PI / 2; theta += 0.01) {
|
constexpr double STEP = 0.01;
|
||||||
|
const int NUM_STEPS = static_cast<int>((M_PI / 2 - 0) / STEP) + 1;
|
||||||
|
|
||||||
|
for (int i = 0; i < NUM_STEPS; ++i) {
|
||||||
|
double theta = 0 + i * STEP;
|
||||||
float x = CENTER_X + (RADIUS * cos(theta));
|
float x = CENTER_X + (RADIUS * cos(theta));
|
||||||
float y = CENTER_Y - (RADIUS * sin(theta));
|
float y = CENTER_Y - (RADIUS * sin(theta));
|
||||||
moon_path_.push_back({x, y});
|
moon_path_.push_back({x, y});
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
#include <SDL3/SDL.h> // Para SDL_FRect, SDL_FPoint, SDL_Texture, SDL_Renderer
|
#include <SDL3/SDL.h> // Para SDL_FRect, SDL_FPoint, SDL_Texture, SDL_Renderer
|
||||||
#include <stddef.h> // Para size_t
|
|
||||||
|
|
||||||
|
#include <cstddef> // Para size_t
|
||||||
#include <memory> // Para unique_ptr, shared_ptr
|
#include <memory> // Para unique_ptr, shared_ptr
|
||||||
#include <vector> // Para vector
|
#include <vector> // Para vector
|
||||||
|
|
||||||
|
|||||||
@@ -319,8 +319,8 @@ void Balloon::shiftSprite() {
|
|||||||
|
|
||||||
// Establece el nivel de zoom del sprite
|
// Establece el nivel de zoom del sprite
|
||||||
void Balloon::zoomSprite() {
|
void Balloon::zoomSprite() {
|
||||||
sprite_->setZoomW(bouncing_.zoomW);
|
sprite_->setZoomW(bouncing_.zoom_w);
|
||||||
sprite_->setZoomH(bouncing_.zoomH);
|
sprite_->setZoomH(bouncing_.zoom_h);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Activa el efecto
|
// Activa el efecto
|
||||||
@@ -341,8 +341,8 @@ void Balloon::disableBounce() {
|
|||||||
void Balloon::updateBounce() {
|
void Balloon::updateBounce() {
|
||||||
if (bouncing_.enabled) {
|
if (bouncing_.enabled) {
|
||||||
const int INDEX = bouncing_.counter / bouncing_.speed;
|
const int INDEX = bouncing_.counter / bouncing_.speed;
|
||||||
bouncing_.zoomW = bouncing_.w[INDEX];
|
bouncing_.zoom_w = bouncing_.w[INDEX];
|
||||||
bouncing_.zoomH = bouncing_.h[INDEX];
|
bouncing_.zoom_h = bouncing_.h[INDEX];
|
||||||
|
|
||||||
zoomSprite();
|
zoomSprite();
|
||||||
|
|
||||||
|
|||||||
@@ -77,23 +77,23 @@ class Balloon {
|
|||||||
void useNormalColor(); // Pone el color normal en el globo
|
void useNormalColor(); // Pone el color normal en el globo
|
||||||
|
|
||||||
// --- Getters ---
|
// --- Getters ---
|
||||||
float getPosX() const { return x_; }
|
[[nodiscard]] auto getPosX() const -> float { return x_; }
|
||||||
float getPosY() const { return y_; }
|
[[nodiscard]] auto getPosY() const -> float { return y_; }
|
||||||
int getWidth() const { return w_; }
|
[[nodiscard]] auto getWidth() const -> int { return w_; }
|
||||||
int getHeight() const { return h_; }
|
[[nodiscard]] auto getHeight() const -> int { return h_; }
|
||||||
BalloonSize getSize() const { return size_; }
|
[[nodiscard]] auto getSize() const -> BalloonSize { return size_; }
|
||||||
BalloonType getType() const { return type_; }
|
[[nodiscard]] auto getType() const -> BalloonType { return type_; }
|
||||||
Uint16 getScore() const { return score_; }
|
[[nodiscard]] auto getScore() const -> Uint16 { return score_; }
|
||||||
Circle &getCollider() { return collider_; }
|
auto getCollider() -> Circle & { return collider_; }
|
||||||
Uint8 getMenace() const { return isEnabled() ? menace_ : 0; }
|
[[nodiscard]] auto getMenace() const -> Uint8 { return isEnabled() ? menace_ : 0; }
|
||||||
Uint8 getPower() const { return power_; }
|
[[nodiscard]] auto getPower() const -> Uint8 { return power_; }
|
||||||
bool isStopped() const { return stopped_; }
|
[[nodiscard]] auto isStopped() const -> bool { return stopped_; }
|
||||||
bool isPowerBall() const { return type_ == BalloonType::POWERBALL; }
|
[[nodiscard]] auto isPowerBall() const -> bool { return type_ == BalloonType::POWERBALL; }
|
||||||
bool isInvulnerable() const { return invulnerable_; }
|
[[nodiscard]] auto isInvulnerable() const -> bool { return invulnerable_; }
|
||||||
bool isBeingCreated() const { return being_created_; }
|
[[nodiscard]] auto isBeingCreated() const -> bool { return being_created_; }
|
||||||
bool isEnabled() const { return enabled_; }
|
[[nodiscard]] auto isEnabled() const -> bool { return enabled_; }
|
||||||
bool isUsingReversedColor() { return use_reversed_colors_; }
|
auto isUsingReversedColor() -> bool { return use_reversed_colors_; }
|
||||||
bool canBePopped() const { return !isBeingCreated(); }
|
[[nodiscard]] auto canBePopped() const -> bool { return !isBeingCreated(); }
|
||||||
|
|
||||||
// --- Setters ---
|
// --- Setters ---
|
||||||
void setVelY(float vel_y) { vy_ = vel_y; }
|
void setVelY(float vel_y) { vy_ = vel_y; }
|
||||||
@@ -109,10 +109,10 @@ class Balloon {
|
|||||||
bool enabled = false; // Si el efecto está activo
|
bool enabled = false; // Si el efecto está activo
|
||||||
Uint8 counter = 0; // Contador para el efecto
|
Uint8 counter = 0; // Contador para el efecto
|
||||||
Uint8 speed = 2; // Velocidad del efecto
|
Uint8 speed = 2; // Velocidad del efecto
|
||||||
float zoomW = 1.0f; // Zoom en anchura
|
float zoom_w = 1.0f; // Zoom en anchura
|
||||||
float zoomH = 1.0f; // Zoom en altura
|
float zoom_h = 1.0f; // Zoom en altura
|
||||||
float despX = 0.0f; // Desplazamiento X antes de pintar
|
float desp_x = 0.0f; // Desplazamiento X antes de pintar
|
||||||
float despY = 0.0f; // Desplazamiento Y antes de pintar
|
float desp_y = 0.0f; // Desplazamiento Y antes de pintar
|
||||||
|
|
||||||
float w[MAX_BOUNCE] = {1.10f, 1.05f, 1.00f, 0.95f, 0.90f, 0.95f, 1.00f, 1.02f, 1.05f, 1.02f}; // Zoom ancho
|
float w[MAX_BOUNCE] = {1.10f, 1.05f, 1.00f, 0.95f, 0.90f, 0.95f, 1.00f, 1.02f, 1.05f, 1.02f}; // Zoom ancho
|
||||||
float h[MAX_BOUNCE] = {0.90f, 0.95f, 1.00f, 1.05f, 1.10f, 1.05f, 1.00f, 0.98f, 0.95f, 0.98f}; // Zoom alto
|
float h[MAX_BOUNCE] = {0.90f, 0.95f, 1.00f, 1.05f, 1.10f, 1.05f, 1.00f, 0.98f, 0.95f, 0.98f}; // Zoom alto
|
||||||
@@ -120,10 +120,10 @@ class Balloon {
|
|||||||
Bouncing() = default;
|
Bouncing() = default;
|
||||||
void reset() {
|
void reset() {
|
||||||
counter = 0;
|
counter = 0;
|
||||||
zoomW = 1.0f;
|
zoom_w = 1.0f;
|
||||||
zoomH = 1.0f;
|
zoom_h = 1.0f;
|
||||||
despX = 0.0f;
|
desp_x = 0.0f;
|
||||||
despY = 0.0f;
|
desp_y = 0.0f;
|
||||||
}
|
}
|
||||||
} bouncing_;
|
} bouncing_;
|
||||||
|
|
||||||
|
|||||||
@@ -52,11 +52,11 @@ class BalloonFormations {
|
|||||||
~BalloonFormations() = default;
|
~BalloonFormations() = default;
|
||||||
|
|
||||||
// --- Getters ---
|
// --- Getters ---
|
||||||
const BalloonFormationPool &getPool(int pool) { return balloon_formation_pool_.at(pool); }
|
auto getPool(int pool) -> const BalloonFormationPool & { return balloon_formation_pool_.at(pool); }
|
||||||
const BalloonFormationUnit &getSet(int pool, int set) { return *balloon_formation_pool_.at(pool).at(set); }
|
auto getSet(int pool, int set) -> const BalloonFormationUnit & { return *balloon_formation_pool_.at(pool).at(set); }
|
||||||
const BalloonFormationUnit &getSet(int set) const { return balloon_formation_.at(set); }
|
[[nodiscard]] auto getSet(int set) const -> const BalloonFormationUnit & { return balloon_formation_.at(set); }
|
||||||
|
|
||||||
private:
|
private:
|
||||||
// --- Datos ---
|
// --- Datos ---
|
||||||
std::vector<BalloonFormationUnit> balloon_formation_; // Vector con todas las formaciones enemigas
|
std::vector<BalloonFormationUnit> balloon_formation_; // Vector con todas las formaciones enemigas
|
||||||
std::vector<BalloonFormationPool> balloon_formation_pool_; // Conjuntos de formaciones enemigas
|
std::vector<BalloonFormationPool> balloon_formation_pool_; // Conjuntos de formaciones enemigas
|
||||||
|
|||||||
@@ -1,8 +1,7 @@
|
|||||||
#include "balloon_manager.h"
|
#include "balloon_manager.h"
|
||||||
|
|
||||||
#include <stdlib.h> // Para rand
|
|
||||||
|
|
||||||
#include <algorithm> // Para remove_if
|
#include <algorithm> // Para remove_if
|
||||||
|
#include <cstdlib> // Para rand
|
||||||
#include <numeric> // Para accumulate
|
#include <numeric> // Para accumulate
|
||||||
|
|
||||||
#include "balloon.h" // Para Balloon, BALLOON_SCORE, BALLOON_VELX...
|
#include "balloon.h" // Para Balloon, BALLOON_SCORE, BALLOON_VELX...
|
||||||
@@ -149,15 +148,15 @@ void BalloonManager::updateBalloonDeployCounter() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Indica si se puede crear una powerball
|
// Indica si se puede crear una powerball
|
||||||
bool BalloonManager::canPowerBallBeCreated() { return (!power_ball_enabled_) && (calculateScreenPower() > POWERBALL_SCREENPOWER_MINIMUM) && (power_ball_counter_ == 0); }
|
auto BalloonManager::canPowerBallBeCreated() -> bool { return (!power_ball_enabled_) && (calculateScreenPower() > POWERBALL_SCREENPOWER_MINIMUM) && (power_ball_counter_ == 0); }
|
||||||
|
|
||||||
// Calcula el poder actual de los globos en pantalla
|
// Calcula el poder actual de los globos en pantalla
|
||||||
int BalloonManager::calculateScreenPower() {
|
auto BalloonManager::calculateScreenPower() -> int {
|
||||||
return std::accumulate(balloons_.begin(), balloons_.end(), 0, [](int sum, const auto &balloon) { return sum + (balloon->isEnabled() ? balloon->getPower() : 0); });
|
return std::accumulate(balloons_.begin(), balloons_.end(), 0, [](int sum, const auto &balloon) { return sum + (balloon->isEnabled() ? balloon->getPower() : 0); });
|
||||||
}
|
}
|
||||||
|
|
||||||
// Crea un globo nuevo en el vector de globos
|
// Crea un globo nuevo en el vector de globos
|
||||||
std::shared_ptr<Balloon> BalloonManager::createBalloon(float x, int y, BalloonType type, BalloonSize size, float velx, float speed, int creation_timer) {
|
auto BalloonManager::createBalloon(float x, int y, BalloonType type, BalloonSize size, float velx, float speed, int creation_timer) -> std::shared_ptr<Balloon> {
|
||||||
if (can_deploy_balloons_) {
|
if (can_deploy_balloons_) {
|
||||||
const int INDEX = static_cast<int>(size);
|
const int INDEX = static_cast<int>(size);
|
||||||
balloons_.emplace_back(std::make_shared<Balloon>(x, y, type, size, velx, speed, creation_timer, play_area_, balloon_textures_.at(INDEX), balloon_animations_.at(INDEX)));
|
balloons_.emplace_back(std::make_shared<Balloon>(x, y, type, size, velx, speed, creation_timer, play_area_, balloon_textures_.at(INDEX), balloon_animations_.at(INDEX)));
|
||||||
@@ -230,7 +229,7 @@ void BalloonManager::setBalloonSpeed(float speed) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Explosiona un globo. Lo destruye y crea otros dos si es el caso
|
// Explosiona un globo. Lo destruye y crea otros dos si es el caso
|
||||||
int BalloonManager::popBalloon(std::shared_ptr<Balloon> balloon) {
|
auto BalloonManager::popBalloon(std::shared_ptr<Balloon> balloon) -> int {
|
||||||
Stage::addPower(1);
|
Stage::addPower(1);
|
||||||
int score = 0;
|
int score = 0;
|
||||||
|
|
||||||
@@ -255,7 +254,7 @@ int BalloonManager::popBalloon(std::shared_ptr<Balloon> balloon) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Explosiona un globo. Lo destruye = no crea otros globos
|
// Explosiona un globo. Lo destruye = no crea otros globos
|
||||||
int BalloonManager::destroyBalloon(std::shared_ptr<Balloon> &balloon) {
|
auto BalloonManager::destroyBalloon(std::shared_ptr<Balloon> &balloon) -> int {
|
||||||
int score = 0;
|
int score = 0;
|
||||||
|
|
||||||
// Calcula la puntuación y el poder que generaria el globo en caso de romperlo a él y a sus hijos
|
// Calcula la puntuación y el poder que generaria el globo en caso de romperlo a él y a sus hijos
|
||||||
@@ -288,7 +287,7 @@ int BalloonManager::destroyBalloon(std::shared_ptr<Balloon> &balloon) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Destruye todos los globos
|
// Destruye todos los globos
|
||||||
int BalloonManager::destroyAllBalloons() {
|
auto BalloonManager::destroyAllBalloons() -> int {
|
||||||
int score = 0;
|
int score = 0;
|
||||||
for (auto &balloon : balloons_) {
|
for (auto &balloon : balloons_) {
|
||||||
score += destroyBalloon(balloon);
|
score += destroyBalloon(balloon);
|
||||||
@@ -344,7 +343,7 @@ void BalloonManager::createRandomBalloons() {
|
|||||||
for (int i = 0; i < NUM_BALLOONS; ++i) {
|
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 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 int Y = param.game.game_area.rect.y + (rand() % 50);
|
||||||
const BalloonSize SIZE = static_cast<BalloonSize>(rand() % 4);
|
const auto SIZE = static_cast<BalloonSize>(rand() % 4);
|
||||||
const float VEL_X = (rand() % 2 == 0) ? BALLOON_VELX_POSITIVE : BALLOON_VELX_NEGATIVE;
|
const float VEL_X = (rand() % 2 == 0) ? BALLOON_VELX_POSITIVE : BALLOON_VELX_NEGATIVE;
|
||||||
const int CREATION_COUNTER = 0;
|
const int CREATION_COUNTER = 0;
|
||||||
createBalloon(X, Y, BalloonType::BALLOON, SIZE, VEL_X, balloon_speed_, CREATION_COUNTER);
|
createBalloon(X, Y, BalloonType::BALLOON, SIZE, VEL_X, balloon_speed_, CREATION_COUNTER);
|
||||||
@@ -352,7 +351,7 @@ void BalloonManager::createRandomBalloons() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Obtiene el nivel de ameza actual generado por los globos
|
// Obtiene el nivel de ameza actual generado por los globos
|
||||||
int BalloonManager::getMenace() {
|
auto BalloonManager::getMenace() -> int {
|
||||||
return std::accumulate(balloons_.begin(), balloons_.end(), 0, [](int sum, const auto &balloon) { return sum + (balloon->isEnabled() ? balloon->getMenace() : 0); });
|
return std::accumulate(balloons_.begin(), balloons_.end(), 0, [](int sum, const auto &balloon) { return sum + (balloon->isEnabled() ? balloon->getMenace() : 0); });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -36,7 +36,7 @@ class BalloonManager {
|
|||||||
void deploySet(int set, int y); // Crea una formación específica con coordenadas
|
void deploySet(int set, int y); // Crea una formación específica con coordenadas
|
||||||
|
|
||||||
// Creación de globos
|
// Creación de globos
|
||||||
std::shared_ptr<Balloon> createBalloon(float x, int y, BalloonType type, BalloonSize size, float velx, float speed, int creation_timer); // Crea un nuevo globo
|
auto createBalloon(float x, int y, BalloonType type, BalloonSize size, float velx, float speed, int creation_timer) -> std::shared_ptr<Balloon>; // Crea un nuevo globo
|
||||||
void createChildBalloon(const std::shared_ptr<Balloon> &balloon, const std::string &direction); // Crea un globo a partir de otro
|
void createChildBalloon(const std::shared_ptr<Balloon> &balloon, const std::string &direction); // Crea un globo a partir de otro
|
||||||
void createPowerBall(); // Crea una PowerBall
|
void createPowerBall(); // Crea una PowerBall
|
||||||
void createTwoBigBalloons(); // Crea dos globos grandes
|
void createTwoBigBalloons(); // Crea dos globos grandes
|
||||||
@@ -47,13 +47,13 @@ class BalloonManager {
|
|||||||
void setDefaultBalloonSpeed(float speed) { default_balloon_speed_ = speed; }; // Establece la velocidad base
|
void setDefaultBalloonSpeed(float speed) { default_balloon_speed_ = speed; }; // Establece la velocidad base
|
||||||
void resetBalloonSpeed() { setBalloonSpeed(default_balloon_speed_); }; // Restablece la velocidad de los globos
|
void resetBalloonSpeed() { setBalloonSpeed(default_balloon_speed_); }; // Restablece la velocidad de los globos
|
||||||
void updateBalloonDeployCounter(); // Actualiza el contador de despliegue
|
void updateBalloonDeployCounter(); // Actualiza el contador de despliegue
|
||||||
bool canPowerBallBeCreated(); // Indica si se puede crear una PowerBall
|
auto canPowerBallBeCreated() -> bool; // Indica si se puede crear una PowerBall
|
||||||
int calculateScreenPower(); // Calcula el poder de los globos en pantalla
|
auto calculateScreenPower() -> int; // Calcula el poder de los globos en pantalla
|
||||||
|
|
||||||
// Manipulación de globos existentes
|
// Manipulación de globos existentes
|
||||||
int popBalloon(std::shared_ptr<Balloon> balloon); // Explosiona un globo, creando otros si aplica
|
auto popBalloon(std::shared_ptr<Balloon> balloon) -> int; // Explosiona un globo, creando otros si aplica
|
||||||
int destroyBalloon(std::shared_ptr<Balloon> &balloon); // Explosiona un globo sin crear otros
|
auto destroyBalloon(std::shared_ptr<Balloon> &balloon) -> int; // Explosiona un globo sin crear otros
|
||||||
int destroyAllBalloons(); // Destruye todos los globos
|
auto destroyAllBalloons() -> int; // Destruye todos los globos
|
||||||
void stopAllBalloons(); // Detiene el movimiento de los globos
|
void stopAllBalloons(); // Detiene el movimiento de los globos
|
||||||
void startAllBalloons(); // Reactiva el movimiento de los globos
|
void startAllBalloons(); // Reactiva el movimiento de los globos
|
||||||
|
|
||||||
@@ -72,12 +72,12 @@ class BalloonManager {
|
|||||||
void enableBalloonDeployment(bool value) { can_deploy_balloons_ = value; }; // Activa o desactiva la generación de globos
|
void enableBalloonDeployment(bool value) { can_deploy_balloons_ = value; }; // Activa o desactiva la generación de globos
|
||||||
|
|
||||||
// Obtención de información
|
// Obtención de información
|
||||||
int getMenace(); // Obtiene el nivel de amenaza generado por los globos
|
auto getMenace() -> int; // Obtiene el nivel de amenaza generado por los globos
|
||||||
float getBalloonSpeed() const { return balloon_speed_; }
|
[[nodiscard]] auto getBalloonSpeed() const -> float { return balloon_speed_; }
|
||||||
Balloons &getBalloons() { return balloons_; }
|
auto getBalloons() -> Balloons & { return balloons_; }
|
||||||
int getNumBalloons() const { return balloons_.size(); }
|
[[nodiscard]] auto getNumBalloons() const -> int { return balloons_.size(); }
|
||||||
|
|
||||||
private:
|
private:
|
||||||
Balloons balloons_; // Vector con los globos activos
|
Balloons balloons_; // Vector con los globos activos
|
||||||
std::unique_ptr<Explosions> explosions_; // Objeto para gestionar explosiones
|
std::unique_ptr<Explosions> explosions_; // Objeto para gestionar explosiones
|
||||||
std::unique_ptr<BalloonFormations> balloon_formations_; // Objeto para manejar formaciones enemigas
|
std::unique_ptr<BalloonFormations> balloon_formations_; // Objeto para manejar formaciones enemigas
|
||||||
|
|||||||
@@ -13,8 +13,8 @@ Bullet::Bullet(float x, float y, BulletType bullet_type, bool powered, int owner
|
|||||||
pos_y_(y),
|
pos_y_(y),
|
||||||
bullet_type_(bullet_type),
|
bullet_type_(bullet_type),
|
||||||
owner_(owner) {
|
owner_(owner) {
|
||||||
vel_x_ = (bullet_type_ == BulletType::LEFT) ? VEL_X_LEFT_
|
vel_x_ = (bullet_type_ == BulletType::LEFT) ? VEL_X_LEFT
|
||||||
: (bullet_type_ == BulletType::RIGHT) ? VEL_X_RIGHT_
|
: (bullet_type_ == BulletType::RIGHT) ? VEL_X_RIGHT
|
||||||
: 0;
|
: 0;
|
||||||
|
|
||||||
std::string powered_type = powered ? "powered_" : "normal_";
|
std::string powered_type = powered ? "powered_" : "normal_";
|
||||||
@@ -46,20 +46,20 @@ void Bullet::render() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Actualiza el estado del objeto
|
// Actualiza el estado del objeto
|
||||||
BulletMoveStatus Bullet::update() {
|
auto Bullet::update() -> BulletMoveStatus {
|
||||||
sprite_->update();
|
sprite_->update();
|
||||||
return move();
|
return move();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Implementación del movimiento usando BulletMoveStatus
|
// Implementación del movimiento usando BulletMoveStatus
|
||||||
BulletMoveStatus Bullet::move() {
|
auto Bullet::move() -> BulletMoveStatus {
|
||||||
pos_x_ += vel_x_;
|
pos_x_ += vel_x_;
|
||||||
if (pos_x_ < param.game.play_area.rect.x - WIDTH || pos_x_ > param.game.play_area.rect.w) {
|
if (pos_x_ < param.game.play_area.rect.x - WIDTH || pos_x_ > param.game.play_area.rect.w) {
|
||||||
disable();
|
disable();
|
||||||
return BulletMoveStatus::OUT;
|
return BulletMoveStatus::OUT;
|
||||||
}
|
}
|
||||||
|
|
||||||
pos_y_ += VEL_Y_;
|
pos_y_ += VEL_Y;
|
||||||
if (pos_y_ < param.game.play_area.rect.y - HEIGHT) {
|
if (pos_y_ < param.game.play_area.rect.y - HEIGHT) {
|
||||||
disable();
|
disable();
|
||||||
return BulletMoveStatus::OUT;
|
return BulletMoveStatus::OUT;
|
||||||
@@ -71,7 +71,7 @@ BulletMoveStatus Bullet::move() {
|
|||||||
return BulletMoveStatus::OK;
|
return BulletMoveStatus::OK;
|
||||||
}
|
}
|
||||||
|
|
||||||
bool Bullet::isEnabled() const {
|
auto Bullet::isEnabled() const -> bool {
|
||||||
return bullet_type_ != BulletType::NONE;
|
return bullet_type_ != BulletType::NONE;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -79,11 +79,11 @@ void Bullet::disable() {
|
|||||||
bullet_type_ = BulletType::NONE;
|
bullet_type_ = BulletType::NONE;
|
||||||
}
|
}
|
||||||
|
|
||||||
int Bullet::getOwner() const {
|
auto Bullet::getOwner() const -> int {
|
||||||
return owner_;
|
return owner_;
|
||||||
}
|
}
|
||||||
|
|
||||||
Circle &Bullet::getCollider() {
|
auto Bullet::getCollider() -> Circle& {
|
||||||
return collider_;
|
return collider_;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -34,21 +34,21 @@ class Bullet {
|
|||||||
|
|
||||||
// Métodos principales
|
// Métodos principales
|
||||||
void render(); // Dibuja la bala en pantalla
|
void render(); // Dibuja la bala en pantalla
|
||||||
BulletMoveStatus update(); // Actualiza el estado del objeto
|
auto update() -> BulletMoveStatus; // Actualiza el estado del objeto
|
||||||
|
|
||||||
// Estado de la bala
|
// Estado de la bala
|
||||||
bool isEnabled() const; // Comprueba si está activa
|
[[nodiscard]] auto isEnabled() const -> bool; // Comprueba si está activa
|
||||||
void disable(); // Desactiva la bala
|
void disable(); // Desactiva la bala
|
||||||
|
|
||||||
// Getters
|
// Getters
|
||||||
int getOwner() const; // Devuelve el identificador del dueño
|
[[nodiscard]] auto getOwner() const -> int; // Devuelve el identificador del dueño
|
||||||
Circle &getCollider(); // Devuelve el círculo de colisión
|
auto getCollider() -> Circle &; // Devuelve el círculo de colisión
|
||||||
|
|
||||||
private:
|
private:
|
||||||
// Constantes
|
// Constantes
|
||||||
static constexpr float VEL_Y_ = -3.0f;
|
static constexpr float VEL_Y = -3.0f;
|
||||||
static constexpr float VEL_X_LEFT_ = -2.0f;
|
static constexpr float VEL_X_LEFT = -2.0f;
|
||||||
static constexpr float VEL_X_RIGHT_ = 2.0f;
|
static constexpr float VEL_X_RIGHT = 2.0f;
|
||||||
|
|
||||||
// Propiedades
|
// Propiedades
|
||||||
std::unique_ptr<AnimatedSprite> sprite_; // Sprite con los gráficos
|
std::unique_ptr<AnimatedSprite> sprite_; // Sprite con los gráficos
|
||||||
@@ -64,5 +64,5 @@ class Bullet {
|
|||||||
// Métodos internos
|
// Métodos internos
|
||||||
void shiftColliders(); // Ajusta el círculo de colisión
|
void shiftColliders(); // Ajusta el círculo de colisión
|
||||||
void shiftSprite(); // Ajusta el sprite
|
void shiftSprite(); // Ajusta el sprite
|
||||||
BulletMoveStatus move(); // Mueve la bala y devuelve su estado
|
auto move() -> BulletMoveStatus; // Mueve la bala y devuelve su estado
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -73,7 +73,7 @@ void DefineButtons::checkEvents(const SDL_Event &event) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Habilita el objeto
|
// Habilita el objeto
|
||||||
bool DefineButtons::enable(int index) {
|
auto DefineButtons::enable(int index) -> bool {
|
||||||
if (index < input_->getNumControllers()) {
|
if (index < input_->getNumControllers()) {
|
||||||
enabled_ = true;
|
enabled_ = true;
|
||||||
finished_ = false;
|
finished_ = false;
|
||||||
@@ -87,7 +87,7 @@ bool DefineButtons::enable(int index) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Comprueba si está habilitado
|
// Comprueba si está habilitado
|
||||||
bool DefineButtons::isEnabled() const { return enabled_; }
|
auto DefineButtons::isEnabled() const -> bool { return enabled_; }
|
||||||
|
|
||||||
// Incrementa el indice de los botones
|
// Incrementa el indice de los botones
|
||||||
void DefineButtons::incIndexButton() {
|
void DefineButtons::incIndexButton() {
|
||||||
@@ -109,7 +109,7 @@ void DefineButtons::saveBindingsToOptions() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Comprueba que un botón no esté ya asignado
|
// Comprueba que un botón no esté ya asignado
|
||||||
bool DefineButtons::checkButtonNotInUse(SDL_GamepadButton button) {
|
auto DefineButtons::checkButtonNotInUse(SDL_GamepadButton button) -> bool {
|
||||||
for (const auto &b : buttons_) {
|
for (const auto &b : buttons_) {
|
||||||
if (b.button == button) {
|
if (b.button == button) {
|
||||||
return false;
|
return false;
|
||||||
|
|||||||
@@ -1,10 +1,11 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
#include <SDL3/SDL.h> // Para SDL_GamepadButton, SDL_Event, SDL_GamepadButtonEvent
|
#include <SDL3/SDL.h> // Para SDL_GamepadButton, SDL_Event, SDL_GamepadButtonEvent
|
||||||
#include <stddef.h> // Para size_t
|
|
||||||
|
|
||||||
|
#include <cstddef> // Para size_t
|
||||||
#include <memory> // Para shared_ptr
|
#include <memory> // Para shared_ptr
|
||||||
#include <string> // Para basic_string, string
|
#include <string> // Para basic_string, string
|
||||||
|
#include <utility>
|
||||||
#include <vector> // Para vector
|
#include <vector> // Para vector
|
||||||
|
|
||||||
// Declaraciones adelantadas
|
// Declaraciones adelantadas
|
||||||
@@ -18,8 +19,8 @@ struct DefineButtonsButton {
|
|||||||
InputAction input; // Acción asociada
|
InputAction input; // Acción asociada
|
||||||
SDL_GamepadButton button; // Botón del mando
|
SDL_GamepadButton button; // Botón del mando
|
||||||
|
|
||||||
DefineButtonsButton(const std::string &lbl, InputAction inp, SDL_GamepadButton btn)
|
DefineButtonsButton(std::string lbl, InputAction inp, SDL_GamepadButton btn)
|
||||||
: label(lbl), input(inp), button(btn) {}
|
: label(std::move(lbl)), input(inp), button(btn) {}
|
||||||
};
|
};
|
||||||
|
|
||||||
// Clase DefineButtons
|
// Clase DefineButtons
|
||||||
@@ -30,10 +31,10 @@ class DefineButtons {
|
|||||||
|
|
||||||
void render(); // Dibuja el objeto en pantalla
|
void render(); // Dibuja el objeto en pantalla
|
||||||
void checkEvents(const SDL_Event &event); // Procesa los eventos
|
void checkEvents(const SDL_Event &event); // Procesa los eventos
|
||||||
bool enable(int index_controller); // Habilita la redefinición de botones
|
auto enable(int index_controller) -> bool; // Habilita la redefinición de botones
|
||||||
bool isEnabled() const; // Comprueba si está habilitado
|
[[nodiscard]] auto isEnabled() const -> bool; // Comprueba si está habilitado
|
||||||
|
|
||||||
private:
|
private:
|
||||||
// Objetos
|
// Objetos
|
||||||
Input *input_ = nullptr; // Gestión de entrada
|
Input *input_ = nullptr; // Gestión de entrada
|
||||||
std::shared_ptr<Text> text_; // Renderizado de texto
|
std::shared_ptr<Text> text_; // Renderizado de texto
|
||||||
@@ -52,7 +53,7 @@ class DefineButtons {
|
|||||||
void doControllerButtonDown(const SDL_GamepadButtonEvent &event); // Procesa pulsaciones
|
void doControllerButtonDown(const SDL_GamepadButtonEvent &event); // Procesa pulsaciones
|
||||||
void bindButtons(); // Asigna botones al sistema de entrada
|
void bindButtons(); // Asigna botones al sistema de entrada
|
||||||
void saveBindingsToOptions(); // Guarda configuraciones
|
void saveBindingsToOptions(); // Guarda configuraciones
|
||||||
bool checkButtonNotInUse(SDL_GamepadButton button); // Verifica uso de botones
|
auto checkButtonNotInUse(SDL_GamepadButton button) -> bool; // Verifica uso de botones
|
||||||
void clearButtons(); // Limpia asignaciones actuales
|
void clearButtons(); // Limpia asignaciones actuales
|
||||||
void checkEnd(); // Comprueba si ha finalizado
|
void checkEnd(); // Comprueba si ha finalizado
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -2,12 +2,12 @@
|
|||||||
#include "director.h"
|
#include "director.h"
|
||||||
|
|
||||||
#include <SDL3/SDL.h> // Para SDL_Scancode, SDL_GamepadButton
|
#include <SDL3/SDL.h> // Para SDL_Scancode, SDL_GamepadButton
|
||||||
#include <errno.h> // Para errno, EEXIST, EACCES, ENAMETOOLONG
|
|
||||||
#include <stdio.h> // Para printf, perror
|
|
||||||
#include <sys/stat.h> // Para mkdir, stat, S_IRWXU
|
#include <sys/stat.h> // Para mkdir, stat, S_IRWXU
|
||||||
#include <unistd.h> // Para getuid
|
#include <unistd.h> // Para getuid
|
||||||
|
|
||||||
#include <algorithm> // Para min
|
#include <algorithm> // Para min
|
||||||
|
#include <cerrno> // Para errno, EEXIST, EACCES, ENAMETOOLONG
|
||||||
|
#include <cstdio> // Para printf, perror
|
||||||
#include <cstdlib> // Para exit, EXIT_FAILURE, size_t, srand
|
#include <cstdlib> // Para exit, EXIT_FAILURE, size_t, srand
|
||||||
#include <ctime> // Para time
|
#include <ctime> // Para time
|
||||||
#include <memory> // Para make_unique, unique_ptr
|
#include <memory> // Para make_unique, unique_ptr
|
||||||
@@ -596,7 +596,7 @@ void Director::reset() {
|
|||||||
Section::name = Section::Name::LOGO;
|
Section::name = Section::Name::LOGO;
|
||||||
}
|
}
|
||||||
|
|
||||||
int Director::run() {
|
auto Director::run() -> int {
|
||||||
// Bucle principal
|
// Bucle principal
|
||||||
while (Section::name != Section::Name::QUIT) {
|
while (Section::name != Section::Name::QUIT) {
|
||||||
switch (Section::name) {
|
switch (Section::name) {
|
||||||
|
|||||||
@@ -13,9 +13,9 @@ class Director {
|
|||||||
~Director();
|
~Director();
|
||||||
|
|
||||||
// --- Bucle principal ---
|
// --- Bucle principal ---
|
||||||
int run();
|
auto run() -> int;
|
||||||
|
|
||||||
private:
|
private:
|
||||||
// --- Variables internas ---
|
// --- Variables internas ---
|
||||||
std::string executable_path_; // Ruta del ejecutable
|
std::string executable_path_; // Ruta del ejecutable
|
||||||
std::string system_folder_; // Carpeta del sistema para almacenar datos
|
std::string system_folder_; // Carpeta del sistema para almacenar datos
|
||||||
@@ -46,7 +46,7 @@ class Director {
|
|||||||
void reset(); // Reinicia objetos y vuelve a la sección inicial
|
void reset(); // Reinicia objetos y vuelve a la sección inicial
|
||||||
|
|
||||||
// --- Gestión de archivos de idioma ---
|
// --- Gestión de archivos de idioma ---
|
||||||
std::string getLangFile(Lang::Code code); // Obtiene un fichero de idioma según el código
|
auto getLangFile(Lang::Code code) -> std::string; // Obtiene un fichero de idioma según el código
|
||||||
|
|
||||||
// --- Apagado del sistema ---
|
// --- Apagado del sistema ---
|
||||||
void shutdownSystem(bool should_shutdown); // Apaga el sistema
|
void shutdownSystem(bool should_shutdown); // Apaga el sistema
|
||||||
|
|||||||
@@ -1,8 +1,7 @@
|
|||||||
#include "enter_name.h"
|
#include "enter_name.h"
|
||||||
|
|
||||||
#include <stddef.h> // Para size_t
|
#include <cstddef> // Para size_t
|
||||||
#include <stdlib.h> // Para rand
|
#include <cstdlib> // Para rand
|
||||||
|
|
||||||
#include <string_view> // Para basic_string_view, string_view
|
#include <string_view> // Para basic_string_view, string_view
|
||||||
|
|
||||||
#include "utils.h" // Para trim
|
#include "utils.h" // Para trim
|
||||||
@@ -133,7 +132,7 @@ void EnterName::initCharacterIndex(const std::string &name) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Encuentra el indice de un caracter en "character_list_"
|
// Encuentra el indice de un caracter en "character_list_"
|
||||||
int EnterName::findIndex(char character) const {
|
auto EnterName::findIndex(char character) const -> int {
|
||||||
for (size_t i = 0; i < character_list_.size(); ++i) {
|
for (size_t i = 0; i < character_list_.size(); ++i) {
|
||||||
if (character == character_list_.at(i)) {
|
if (character == character_list_.at(i)) {
|
||||||
return i;
|
return i;
|
||||||
@@ -143,13 +142,13 @@ int EnterName::findIndex(char character) const {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Devuelve un nombre al azar
|
// Devuelve un nombre al azar
|
||||||
std::string EnterName::getRandomName() {
|
auto EnterName::getRandomName() -> std::string {
|
||||||
static constexpr std::array<std::string_view, 8> NAMES = {
|
static constexpr std::array<std::string_view, 8> NAMES = {
|
||||||
"BAL1", "TABE", "DOC", "MON", "SAM1", "JORDI", "JDES", "PEPE"};
|
"BAL1", "TABE", "DOC", "MON", "SAM1", "JORDI", "JDES", "PEPE"};
|
||||||
return std::string(NAMES[rand() % NAMES.size()]);
|
return std::string(NAMES[rand() % NAMES.size()]);
|
||||||
}
|
}
|
||||||
// Obtiene el nombre final introducido
|
// Obtiene el nombre final introducido
|
||||||
std::string EnterName::getFinalName() {
|
auto EnterName::getFinalName() -> std::string {
|
||||||
auto name = trim(name_.substr(0, position_));
|
auto name = trim(name_.substr(0, position_));
|
||||||
if (name.empty()) {
|
if (name.empty()) {
|
||||||
name = getRandomName();
|
name = getRandomName();
|
||||||
|
|||||||
@@ -1,8 +1,7 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
#include <stddef.h> // Para size_t
|
|
||||||
|
|
||||||
#include <array> // Para array
|
#include <array> // Para array
|
||||||
|
#include <cstddef> // Para size_t
|
||||||
#include <string> // Para string, basic_string
|
#include <string> // Para string, basic_string
|
||||||
|
|
||||||
#include "utils.h" // Para trim
|
#include "utils.h" // Para trim
|
||||||
@@ -23,13 +22,13 @@ class EnterName {
|
|||||||
void incIndex(); // Incrementa el índice del carácter en la lista
|
void incIndex(); // Incrementa el índice del carácter en la lista
|
||||||
void decIndex(); // Decrementa el índice del carácter en la lista
|
void decIndex(); // Decrementa el índice del carácter en la lista
|
||||||
|
|
||||||
std::string getFinalName(); // Obtiene el nombre final introducido
|
auto getFinalName() -> std::string; // Obtiene el nombre final introducido
|
||||||
std::string getCurrentName() const { return trim(name_); } // Obtiene el nombre actual en proceso
|
[[nodiscard]] auto getCurrentName() const -> std::string { return trim(name_); } // Obtiene el nombre actual en proceso
|
||||||
|
|
||||||
int getPosition() const { return position_; } // Posición actual del carácter editado
|
[[nodiscard]] auto getPosition() const -> int { return position_; } // Posición actual del carácter editado
|
||||||
bool getPositionOverflow() const { return position_overflow_; } // Indica si la posición excede el límite
|
[[nodiscard]] auto getPositionOverflow() const -> bool { return position_overflow_; } // Indica si la posición excede el límite
|
||||||
|
|
||||||
private:
|
private:
|
||||||
std::string character_list_; // Lista de caracteres permitidos
|
std::string character_list_; // Lista de caracteres permitidos
|
||||||
std::string name_; // Nombre en proceso
|
std::string name_; // Nombre en proceso
|
||||||
size_t position_ = 0; // Índice del carácter que se edita
|
size_t position_ = 0; // Índice del carácter que se edita
|
||||||
@@ -38,6 +37,6 @@ class EnterName {
|
|||||||
|
|
||||||
void updateNameFromCharacterIndex(); // Actualiza "name_" según "character_index_"
|
void updateNameFromCharacterIndex(); // Actualiza "name_" según "character_index_"
|
||||||
void initCharacterIndex(const std::string &name); // Inicializa índices desde el nombre
|
void initCharacterIndex(const std::string &name); // Inicializa índices desde el nombre
|
||||||
int findIndex(char character) const; // Busca el índice de un carácter en "character_list_"
|
[[nodiscard]] auto findIndex(char character) const -> int; // Busca el índice de un carácter en "character_list_"
|
||||||
static std::string getRandomName(); // Devuelve un nombre al azar
|
static auto getRandomName() -> std::string; // Devuelve un nombre al azar
|
||||||
};
|
};
|
||||||
@@ -23,7 +23,7 @@ void Explosions::render() {
|
|||||||
|
|
||||||
// Añade texturas al objeto
|
// Añade texturas al objeto
|
||||||
void Explosions::addTexture(int size, std::shared_ptr<Texture> texture, const std::vector<std::string> &animation) {
|
void Explosions::addTexture(int size, std::shared_ptr<Texture> texture, const std::vector<std::string> &animation) {
|
||||||
textures_.emplace_back(ExplosionTexture(size, texture, animation));
|
textures_.emplace_back(size, texture, animation);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Añade una explosión
|
// Añade una explosión
|
||||||
@@ -45,7 +45,7 @@ void Explosions::freeExplosions() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Busca una textura a partir del tamaño
|
// Busca una textura a partir del tamaño
|
||||||
int Explosions::getIndexBySize(int size) {
|
auto Explosions::getIndexBySize(int size) -> int {
|
||||||
for (int i = 0; i < (int)textures_.size(); ++i) {
|
for (int i = 0; i < (int)textures_.size(); ++i) {
|
||||||
if (size == textures_[i].size) {
|
if (size == textures_[i].size) {
|
||||||
return i;
|
return i;
|
||||||
|
|||||||
@@ -2,6 +2,7 @@
|
|||||||
|
|
||||||
#include <memory> // Para unique_ptr, shared_ptr
|
#include <memory> // Para unique_ptr, shared_ptr
|
||||||
#include <string> // Para string
|
#include <string> // Para string
|
||||||
|
#include <utility>
|
||||||
#include <vector> // Para vector
|
#include <vector> // Para vector
|
||||||
|
|
||||||
#include "animated_sprite.h" // Para AnimatedSprite
|
#include "animated_sprite.h" // Para AnimatedSprite
|
||||||
@@ -15,7 +16,7 @@ struct ExplosionTexture {
|
|||||||
std::vector<std::string> animation; // Animación para la textura
|
std::vector<std::string> animation; // Animación para la textura
|
||||||
|
|
||||||
ExplosionTexture(int sz, std::shared_ptr<Texture> tex, const std::vector<std::string> &anim)
|
ExplosionTexture(int sz, std::shared_ptr<Texture> tex, const std::vector<std::string> &anim)
|
||||||
: size(sz), texture(tex), animation(anim) {}
|
: size(sz), texture(std::move(tex)), animation(anim) {}
|
||||||
};
|
};
|
||||||
|
|
||||||
// Clase Explosions
|
// Clase Explosions
|
||||||
@@ -48,5 +49,5 @@ class Explosions {
|
|||||||
void freeExplosions();
|
void freeExplosions();
|
||||||
|
|
||||||
// Busca una textura a partir del tamaño
|
// Busca una textura a partir del tamaño
|
||||||
int getIndexBySize(int size);
|
auto getIndexBySize(int size) -> int;
|
||||||
};
|
};
|
||||||
1
source/external/.clang-tidy
vendored
Normal file
1
source/external/.clang-tidy
vendored
Normal file
@@ -0,0 +1 @@
|
|||||||
|
Checks: '-*'
|
||||||
12
source/external/json.hpp
vendored
12
source/external/json.hpp
vendored
@@ -6059,7 +6059,7 @@ inline void to_json(BasicJsonType& j, const std::pair<T1, T2>& p)
|
|||||||
j = { p.first, p.second };
|
j = { p.first, p.second };
|
||||||
}
|
}
|
||||||
|
|
||||||
// Para https://github.com/nlohmann/json/pull/1134
|
// for https://github.com/nlohmann/json/pull/1134
|
||||||
template<typename BasicJsonType, typename T,
|
template<typename BasicJsonType, typename T,
|
||||||
enable_if_t<std::is_same<T, iteration_proxy_value<typename BasicJsonType::iterator>>::value, int> = 0>
|
enable_if_t<std::is_same<T, iteration_proxy_value<typename BasicJsonType::iterator>>::value, int> = 0>
|
||||||
inline void to_json(BasicJsonType& j, const T& b)
|
inline void to_json(BasicJsonType& j, const T& b)
|
||||||
@@ -6624,7 +6624,7 @@ class iterator_input_adapter
|
|||||||
return char_traits<char_type>::eof();
|
return char_traits<char_type>::eof();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Para general iterators, we cannot really do something better than falling back to processing the range one-by-one
|
// for general iterators, we cannot really do something better than falling back to processing the range one-by-one
|
||||||
template<class T>
|
template<class T>
|
||||||
std::size_t get_elements(T* dest, std::size_t count = 1)
|
std::size_t get_elements(T* dest, std::size_t count = 1)
|
||||||
{
|
{
|
||||||
@@ -14558,7 +14558,7 @@ class json_pointer
|
|||||||
};
|
};
|
||||||
|
|
||||||
public:
|
public:
|
||||||
// Para backwards compatibility accept BasicJsonType
|
// for backwards compatibility accept BasicJsonType
|
||||||
using string_t = typename string_t_helper<RefStringType>::type;
|
using string_t = typename string_t_helper<RefStringType>::type;
|
||||||
|
|
||||||
/// @brief create JSON pointer
|
/// @brief create JSON pointer
|
||||||
@@ -18087,7 +18087,7 @@ inline cached_power get_cached_power_for_binary_exponent(int e)
|
|||||||
|
|
||||||
// This computation gives exactly the same results for k as
|
// This computation gives exactly the same results for k as
|
||||||
// k = ceil((kAlpha - e - 1) * 0.30102999566398114)
|
// k = ceil((kAlpha - e - 1) * 0.30102999566398114)
|
||||||
// Para |e| <= 1500, but doesn't require floating-point operations.
|
// for |e| <= 1500, but doesn't require floating-point operations.
|
||||||
// NB: log_10(2) ~= 78913 / 2^18
|
// NB: log_10(2) ~= 78913 / 2^18
|
||||||
JSON_ASSERT(e >= -1500);
|
JSON_ASSERT(e >= -1500);
|
||||||
JSON_ASSERT(e <= 1500);
|
JSON_ASSERT(e <= 1500);
|
||||||
@@ -19727,7 +19727,7 @@ NLOHMANN_JSON_NAMESPACE_END
|
|||||||
#include <initializer_list> // initializer_list
|
#include <initializer_list> // initializer_list
|
||||||
#include <iterator> // input_iterator_tag, iterator_traits
|
#include <iterator> // input_iterator_tag, iterator_traits
|
||||||
#include <memory> // allocator
|
#include <memory> // allocator
|
||||||
#include <stdexcept> // Para out_of_range
|
#include <stdexcept> // for out_of_range
|
||||||
#include <type_traits> // enable_if, is_convertible
|
#include <type_traits> // enable_if, is_convertible
|
||||||
#include <utility> // pair
|
#include <utility> // pair
|
||||||
#include <vector> // vector
|
#include <vector> // vector
|
||||||
@@ -19740,7 +19740,7 @@ NLOHMANN_JSON_NAMESPACE_END
|
|||||||
NLOHMANN_JSON_NAMESPACE_BEGIN
|
NLOHMANN_JSON_NAMESPACE_BEGIN
|
||||||
|
|
||||||
/// ordered_map: a minimal map-like container that preserves insertion order
|
/// ordered_map: a minimal map-like container that preserves insertion order
|
||||||
/// Para use within nlohmann::basic_json<ordered_map>
|
/// for use within nlohmann::basic_json<ordered_map>
|
||||||
template <class Key, class T, class IgnoredLess = std::less<Key>,
|
template <class Key, class T, class IgnoredLess = std::less<Key>,
|
||||||
class Allocator = std::allocator<std::pair<const Key, T>>>
|
class Allocator = std::allocator<std::pair<const Key, T>>>
|
||||||
struct ordered_map : std::vector<std::pair<const Key, T>, Allocator>
|
struct ordered_map : std::vector<std::pair<const Key, T>, Allocator>
|
||||||
|
|||||||
@@ -1,9 +1,9 @@
|
|||||||
#include "fade.h"
|
#include "fade.h"
|
||||||
|
|
||||||
#include <SDL3/SDL.h> // Para SDL_SetRenderTarget, SDL_FRect, SDL_GetRenderT...
|
#include <SDL3/SDL.h> // Para SDL_SetRenderTarget, SDL_FRect, SDL_GetRenderT...
|
||||||
#include <stdlib.h> // Para rand, size_t
|
|
||||||
|
|
||||||
#include <algorithm> // Para min, max
|
#include <algorithm> // Para min, max
|
||||||
|
#include <cstdlib> // Para rand, size_t
|
||||||
|
|
||||||
#include "param.h" // Para Param, param, ParamGame, ParamFade
|
#include "param.h" // Para Param, param, ParamGame, ParamFade
|
||||||
#include "screen.h" // Para Screen
|
#include "screen.h" // Para Screen
|
||||||
@@ -312,7 +312,7 @@ void Fade::cleanBackbuffer(Uint8 r, Uint8 g, Uint8 b, Uint8 a) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Calcula el valor del estado del fade
|
// Calcula el valor del estado del fade
|
||||||
int Fade::calculateValue(int min, int max, int current) {
|
auto Fade::calculateValue(int min, int max, int current) -> int {
|
||||||
if (current < min) {
|
if (current < min) {
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -50,11 +50,11 @@ class Fade {
|
|||||||
void setPreDuration(int value) { pre_duration_ = value; }
|
void setPreDuration(int value) { pre_duration_ = value; }
|
||||||
|
|
||||||
// --- Getters ---
|
// --- Getters ---
|
||||||
int getValue() const { return value_; }
|
[[nodiscard]] auto getValue() const -> int { return value_; }
|
||||||
bool isEnabled() const { return state_ != FadeState::NOT_ENABLED; }
|
[[nodiscard]] auto isEnabled() const -> bool { return state_ != FadeState::NOT_ENABLED; }
|
||||||
bool hasEnded() const { return state_ == FadeState::FINISHED; }
|
[[nodiscard]] auto hasEnded() const -> bool { return state_ == FadeState::FINISHED; }
|
||||||
|
|
||||||
private:
|
private:
|
||||||
// --- Objetos y punteros ---
|
// --- Objetos y punteros ---
|
||||||
SDL_Renderer *renderer_; // Renderizador de la ventana
|
SDL_Renderer *renderer_; // Renderizador de la ventana
|
||||||
SDL_Texture *backbuffer_; // Backbuffer para efectos
|
SDL_Texture *backbuffer_; // Backbuffer para efectos
|
||||||
@@ -86,5 +86,5 @@ class Fade {
|
|||||||
// --- Métodos internos ---
|
// --- Métodos internos ---
|
||||||
void init(); // Inicializa variables
|
void init(); // Inicializa variables
|
||||||
void cleanBackbuffer(Uint8 r, Uint8 g, Uint8 b, Uint8 a); // Limpia el backbuffer
|
void cleanBackbuffer(Uint8 r, Uint8 g, Uint8 b, Uint8 a); // Limpia el backbuffer
|
||||||
int calculateValue(int min, int max, int current); // Calcula el valor del fade
|
auto calculateValue(int min, int max, int current) -> int; // Calcula el valor del fade
|
||||||
};
|
};
|
||||||
@@ -219,12 +219,12 @@ void GameLogo::enable() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Indica si ha terminado la animación
|
// Indica si ha terminado la animación
|
||||||
bool GameLogo::hasFinished() const {
|
auto GameLogo::hasFinished() const -> bool {
|
||||||
return post_finished_counter_ == 0;
|
return post_finished_counter_ == 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Calcula el desplazamiento vertical inicial
|
// Calcula el desplazamiento vertical inicial
|
||||||
int GameLogo::getInitialVerticalDesp() {
|
auto GameLogo::getInitialVerticalDesp() -> int {
|
||||||
const float OFFSET_UP = y_;
|
const float OFFSET_UP = y_;
|
||||||
const float OFFSET_DOWN = param.game.height - y_;
|
const float OFFSET_DOWN = param.game.height - y_;
|
||||||
|
|
||||||
|
|||||||
@@ -21,9 +21,9 @@ class GameLogo {
|
|||||||
void enable(); // Activa la clase
|
void enable(); // Activa la clase
|
||||||
|
|
||||||
// --- Getters ---
|
// --- Getters ---
|
||||||
bool hasFinished() const; // Indica si ha terminado la animación
|
[[nodiscard]] auto hasFinished() const -> bool; // Indica si ha terminado la animación
|
||||||
|
|
||||||
private:
|
private:
|
||||||
// --- Tipos internos ---
|
// --- Tipos internos ---
|
||||||
enum class Status {
|
enum class Status {
|
||||||
DISABLED,
|
DISABLED,
|
||||||
@@ -78,5 +78,5 @@ class GameLogo {
|
|||||||
|
|
||||||
// --- Métodos internos ---
|
// --- Métodos internos ---
|
||||||
void init(); // Inicializa las variables
|
void init(); // Inicializa las variables
|
||||||
int getInitialVerticalDesp(); // Calcula el desplazamiento vertical inicial
|
auto getInitialVerticalDesp() -> int; // Calcula el desplazamiento vertical inicial
|
||||||
};
|
};
|
||||||
@@ -65,7 +65,7 @@ void toggleShaders() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Obtiene una fichero a partir de un lang::Code
|
// Obtiene una fichero a partir de un lang::Code
|
||||||
std::string getLangFile(Lang::Code code) {
|
auto getLangFile(Lang::Code code) -> std::string {
|
||||||
switch (code) {
|
switch (code) {
|
||||||
case Lang::Code::VALENCIAN:
|
case Lang::Code::VALENCIAN:
|
||||||
return Asset::get()->get("ba_BA.json");
|
return Asset::get()->get("ba_BA.json");
|
||||||
@@ -80,7 +80,7 @@ std::string getLangFile(Lang::Code code) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Obtiene una cadena a partir de un lang::Code
|
// Obtiene una cadena a partir de un lang::Code
|
||||||
std::string getLangName(Lang::Code code) {
|
auto getLangName(Lang::Code code) -> std::string {
|
||||||
switch (code) {
|
switch (code) {
|
||||||
case Lang::Code::VALENCIAN:
|
case Lang::Code::VALENCIAN:
|
||||||
return " \"ba_BA\"";
|
return " \"ba_BA\"";
|
||||||
@@ -161,7 +161,7 @@ void incWindowSize() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Comprueba el boton de servicio
|
// Comprueba el boton de servicio
|
||||||
bool checkServiceButton() {
|
auto checkServiceButton() -> bool {
|
||||||
// Teclado
|
// Teclado
|
||||||
if (Input::get()->checkInput(InputAction::SERVICE, INPUT_DO_NOT_ALLOW_REPEAT, InputDevice::KEYBOARD)) {
|
if (Input::get()->checkInput(InputAction::SERVICE, INPUT_DO_NOT_ALLOW_REPEAT, InputDevice::KEYBOARD)) {
|
||||||
toggleServiceMenu();
|
toggleServiceMenu();
|
||||||
@@ -181,7 +181,7 @@ bool checkServiceButton() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Comprueba las entradas del menú de servicio
|
// Comprueba las entradas del menú de servicio
|
||||||
bool checkServiceInputs() {
|
auto checkServiceInputs() -> bool {
|
||||||
if (!ServiceMenu::get()->isEnabled())
|
if (!ServiceMenu::get()->isEnabled())
|
||||||
return false;
|
return false;
|
||||||
|
|
||||||
@@ -268,7 +268,7 @@ bool checkServiceInputs() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Comprueba las entradas fuera del menú de servicio
|
// Comprueba las entradas fuera del menú de servicio
|
||||||
bool checkInputs() {
|
auto checkInputs() -> bool {
|
||||||
// Teclado
|
// Teclado
|
||||||
{
|
{
|
||||||
// Comprueba el teclado para cambiar entre pantalla completa y ventana
|
// Comprueba el teclado para cambiar entre pantalla completa y ventana
|
||||||
@@ -361,7 +361,7 @@ bool checkInputs() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Comprueba los inputs que se pueden introducir en cualquier sección del juego
|
// Comprueba los inputs que se pueden introducir en cualquier sección del juego
|
||||||
bool check() {
|
auto check() -> bool {
|
||||||
if (checkServiceButton())
|
if (checkServiceButton())
|
||||||
return true;
|
return true;
|
||||||
if (checkServiceInputs())
|
if (checkServiceInputs())
|
||||||
|
|||||||
@@ -2,5 +2,5 @@
|
|||||||
|
|
||||||
namespace GlobalInputs {
|
namespace GlobalInputs {
|
||||||
// Comprueba los inputs que se pueden introducir en cualquier sección del juego
|
// Comprueba los inputs que se pueden introducir en cualquier sección del juego
|
||||||
bool check();
|
auto check() -> bool;
|
||||||
} // namespace GlobalInputs
|
} // namespace GlobalInputs
|
||||||
@@ -1,28 +1,28 @@
|
|||||||
#include "input.h"
|
#include "input.h"
|
||||||
|
|
||||||
#include <SDL3/SDL.h> // Para SDL_LogInfo, SDL_LogCategory, SDL_GetGamepa...
|
#include <SDL3/SDL.h> // Para SDL_LogInfo, SDL_LogCategory, SDL_GetGamepa...
|
||||||
#include <stddef.h> // Para size_t
|
|
||||||
|
|
||||||
#include <algorithm> // Para find
|
#include <algorithm> // Para find
|
||||||
|
#include <cstddef> // Para size_t
|
||||||
#include <iterator> // Para distance
|
#include <iterator> // Para distance
|
||||||
#include <unordered_map> // Para unordered_map, _Node_const_iterator, operat...
|
#include <unordered_map> // Para unordered_map, _Node_const_iterator, operat...
|
||||||
#include <utility> // Para pair
|
#include <utility> // Para pair
|
||||||
|
|
||||||
// Singleton
|
// Singleton
|
||||||
Input *Input::instance_ = nullptr;
|
Input *Input::instance = nullptr;
|
||||||
|
|
||||||
// Inicializa la instancia única del singleton
|
// Inicializa la instancia única del singleton
|
||||||
void Input::init(const std::string &game_controller_db_path) { Input::instance_ = new Input(game_controller_db_path); }
|
void Input::init(const std::string &game_controller_db_path) { Input::instance = new Input(game_controller_db_path); }
|
||||||
|
|
||||||
// Libera la instancia
|
// Libera la instancia
|
||||||
void Input::destroy() { delete Input::instance_; }
|
void Input::destroy() { delete Input::instance; }
|
||||||
|
|
||||||
// Obtiene la instancia
|
// Obtiene la instancia
|
||||||
Input *Input::get() { return Input::instance_; }
|
auto Input::get() -> Input * { return Input::instance; }
|
||||||
|
|
||||||
// Constructor
|
// Constructor
|
||||||
Input::Input(const std::string &game_controller_db_path)
|
Input::Input(std::string game_controller_db_path)
|
||||||
: game_controller_db_path_(game_controller_db_path) {
|
: game_controller_db_path_(std::move(game_controller_db_path)) {
|
||||||
// Inicializa el subsistema SDL_INIT_GAMEPAD
|
// Inicializa el subsistema SDL_INIT_GAMEPAD
|
||||||
initSDLGamePad();
|
initSDLGamePad();
|
||||||
|
|
||||||
@@ -54,7 +54,7 @@ void Input::bindGameControllerButton(int controller_index, InputAction input_tar
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Comprueba si un input esta activo
|
// Comprueba si un input esta activo
|
||||||
bool Input::checkInput(InputAction input, bool repeat, InputDevice device, int controller_index) {
|
auto Input::checkInput(InputAction input, bool repeat, InputDevice device, int controller_index) -> bool {
|
||||||
bool success_keyboard = false;
|
bool success_keyboard = false;
|
||||||
bool success_controller = false;
|
bool success_controller = false;
|
||||||
const int INPUT_INDEX = static_cast<int>(input);
|
const int INPUT_INDEX = static_cast<int>(input);
|
||||||
@@ -85,7 +85,7 @@ bool Input::checkInput(InputAction input, bool repeat, InputDevice device, int c
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Comprueba si hay almenos un input activo
|
// Comprueba si hay almenos un input activo
|
||||||
bool Input::checkAnyInput(InputDevice device, int controller_index) {
|
auto Input::checkAnyInput(InputDevice device, int controller_index) -> bool {
|
||||||
// Obtenemos el número total de acciones posibles para iterar sobre ellas.
|
// 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);
|
||||||
|
|
||||||
@@ -119,7 +119,7 @@ bool Input::checkAnyInput(InputDevice device, int controller_index) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Comprueba si hay algún botón pulsado. Devuelve 0 en caso de no encontrar nada o el indice del dispositivo + 1. Se hace así para poder gastar el valor devuelto como un valor "booleano"
|
// Comprueba si hay algún botón pulsado. Devuelve 0 en caso de no encontrar nada o el indice del dispositivo + 1. Se hace así para poder gastar el valor devuelto como un valor "booleano"
|
||||||
int Input::checkAnyButton(bool repeat) {
|
auto Input::checkAnyButton(bool repeat) -> int {
|
||||||
// Solo comprueba los botones definidos previamente
|
// Solo comprueba los botones definidos previamente
|
||||||
for (auto bi : button_inputs_) {
|
for (auto bi : button_inputs_) {
|
||||||
// Comprueba el teclado
|
// Comprueba el teclado
|
||||||
@@ -139,7 +139,7 @@ int Input::checkAnyButton(bool repeat) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Busca si hay mandos conectados
|
// Busca si hay mandos conectados
|
||||||
bool Input::discoverGameControllers() {
|
auto Input::discoverGameControllers() -> bool {
|
||||||
bool found = false;
|
bool found = false;
|
||||||
|
|
||||||
if (SDL_AddGamepadMappingsFromFile(game_controller_db_path_.c_str()) < 0) {
|
if (SDL_AddGamepadMappingsFromFile(game_controller_db_path_.c_str()) < 0) {
|
||||||
@@ -207,16 +207,16 @@ bool Input::discoverGameControllers() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Comprueba si hay algun mando conectado
|
// Comprueba si hay algun mando conectado
|
||||||
bool Input::gameControllerFound() { return num_gamepads_ > 0 ? true : false; }
|
auto Input::gameControllerFound() -> bool { return num_gamepads_ > 0 ? true : false; }
|
||||||
|
|
||||||
// Obten el nombre de un mando de juego
|
// Obten el nombre de un mando de juego
|
||||||
std::string Input::getControllerName(int controller_index) const { return num_gamepads_ > 0 ? controller_names_.at(controller_index) : std::string(); }
|
auto Input::getControllerName(int controller_index) const -> std::string { return num_gamepads_ > 0 ? controller_names_.at(controller_index) : std::string(); }
|
||||||
|
|
||||||
// Obten el número de mandos conectados
|
// Obten el número de mandos conectados
|
||||||
int Input::getNumControllers() const { return num_gamepads_; }
|
auto Input::getNumControllers() const -> int { return num_gamepads_; }
|
||||||
|
|
||||||
// Obtiene el indice del controlador a partir de un event.id
|
// Obtiene el indice del controlador a partir de un event.id
|
||||||
int Input::getJoyIndex(SDL_JoystickID id) const {
|
auto Input::getJoyIndex(SDL_JoystickID id) const -> int {
|
||||||
for (int i = 0; i < num_joysticks_; ++i) {
|
for (int i = 0; i < num_joysticks_; ++i) {
|
||||||
if (SDL_GetJoystickID(joysticks_[i]) == id) {
|
if (SDL_GetJoystickID(joysticks_[i]) == id) {
|
||||||
return i;
|
return i;
|
||||||
@@ -247,18 +247,18 @@ void Input::printBindings(InputDevice device, int controller_index) const {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Obtiene el SDL_GamepadButton asignado a un input
|
// Obtiene el SDL_GamepadButton asignado a un input
|
||||||
SDL_GamepadButton Input::getControllerBinding(int controller_index, InputAction input) const {
|
auto Input::getControllerBinding(int controller_index, InputAction input) const -> SDL_GamepadButton {
|
||||||
return controller_bindings_[controller_index][static_cast<int>(input)].button;
|
return controller_bindings_[controller_index][static_cast<int>(input)].button;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Obtiene el indice a partir del nombre del mando
|
// Obtiene el indice a partir del nombre del mando
|
||||||
int Input::getIndexByName(const std::string &name) const {
|
auto Input::getIndexByName(const std::string &name) const -> int {
|
||||||
auto it = std::find(controller_names_.begin(), controller_names_.end(), name);
|
auto it = std::find(controller_names_.begin(), controller_names_.end(), name);
|
||||||
return it != controller_names_.end() ? std::distance(controller_names_.begin(), it) : -1;
|
return it != controller_names_.end() ? std::distance(controller_names_.begin(), it) : -1;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Convierte un InputAction a std::string
|
// Convierte un InputAction a std::string
|
||||||
std::string Input::inputToString(InputAction input) const {
|
auto Input::inputToString(InputAction input) const -> std::string {
|
||||||
switch (input) {
|
switch (input) {
|
||||||
case InputAction::FIRE_LEFT:
|
case InputAction::FIRE_LEFT:
|
||||||
return "input_fire_left";
|
return "input_fire_left";
|
||||||
@@ -276,7 +276,7 @@ std::string Input::inputToString(InputAction input) const {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Convierte un std::string a InputAction
|
// Convierte un std::string a InputAction
|
||||||
InputAction Input::stringToInput(const std::string &name) const {
|
auto Input::stringToInput(const std::string &name) const -> InputAction {
|
||||||
static const std::unordered_map<std::string, InputAction> INPUT_MAP = {
|
static const std::unordered_map<std::string, InputAction> INPUT_MAP = {
|
||||||
{"input_fire_left", InputAction::FIRE_LEFT},
|
{"input_fire_left", InputAction::FIRE_LEFT},
|
||||||
{"input_fire_center", InputAction::FIRE_CENTER},
|
{"input_fire_center", InputAction::FIRE_CENTER},
|
||||||
@@ -289,7 +289,7 @@ InputAction Input::stringToInput(const std::string &name) const {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Comprueba el eje del mando
|
// Comprueba el eje del mando
|
||||||
bool Input::checkAxisInput(InputAction input, int controller_index, bool repeat) {
|
auto Input::checkAxisInput(InputAction input, int controller_index, bool repeat) -> bool {
|
||||||
// Umbral para considerar el eje como activo
|
// Umbral para considerar el eje como activo
|
||||||
bool axis_active_now = false;
|
bool axis_active_now = false;
|
||||||
|
|
||||||
@@ -362,12 +362,12 @@ void Input::update() {
|
|||||||
// --- TECLADO ---
|
// --- TECLADO ---
|
||||||
const bool *key_states = SDL_GetKeyboardState(nullptr);
|
const bool *key_states = SDL_GetKeyboardState(nullptr);
|
||||||
|
|
||||||
for (size_t i = 0; i < key_bindings_.size(); ++i) {
|
for (auto &key_binding : key_bindings_) {
|
||||||
bool key_is_down_now = key_states[key_bindings_[i].scancode];
|
bool key_is_down_now = key_states[key_binding.scancode];
|
||||||
|
|
||||||
// El estado .is_held del fotograma anterior nos sirve para saber si es un pulso nuevo
|
// El estado .is_held del fotograma anterior nos sirve para saber si es un pulso nuevo
|
||||||
key_bindings_[i].just_pressed = key_is_down_now && !key_bindings_[i].is_held;
|
key_binding.just_pressed = key_is_down_now && !key_binding.is_held;
|
||||||
key_bindings_[i].is_held = key_is_down_now;
|
key_binding.is_held = key_is_down_now;
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- MANDOS ---
|
// --- MANDOS ---
|
||||||
|
|||||||
@@ -72,7 +72,7 @@ class Input {
|
|||||||
// --- Métodos de singleton ---
|
// --- Métodos de singleton ---
|
||||||
static void init(const std::string &game_controller_db_path); // Inicializa el singleton
|
static void init(const std::string &game_controller_db_path); // Inicializa el singleton
|
||||||
static void destroy(); // Libera el singleton
|
static void destroy(); // Libera el singleton
|
||||||
static Input *get(); // Obtiene la instancia
|
static auto get() -> Input *; // Obtiene la instancia
|
||||||
|
|
||||||
// --- Métodos de configuración de controles ---
|
// --- Métodos de configuración de controles ---
|
||||||
void bindKey(InputAction input, SDL_Scancode code); // Asigna inputs a teclas
|
void bindKey(InputAction input, SDL_Scancode code); // Asigna inputs a teclas
|
||||||
@@ -81,23 +81,23 @@ class Input {
|
|||||||
|
|
||||||
// --- Métodos de consulta de entrada ---
|
// --- Métodos de consulta de entrada ---
|
||||||
void update(); // Comprueba fisicamente los botones y teclas que se han pulsado
|
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
|
auto checkInput(InputAction input, bool repeat = true, InputDevice device = InputDevice::ANY, int controller_index = 0) -> bool; // Comprueba si un input está activo
|
||||||
bool checkAnyInput(InputDevice device = InputDevice::ANY, int controller_index = 0); // Comprueba si hay al menos un input activo
|
auto checkAnyInput(InputDevice device = InputDevice::ANY, int controller_index = 0) -> bool; // Comprueba si hay al menos un input activo
|
||||||
int checkAnyButton(bool repeat = INPUT_DO_NOT_ALLOW_REPEAT); // Comprueba si hay algún botón pulsado
|
auto checkAnyButton(bool repeat = INPUT_DO_NOT_ALLOW_REPEAT) -> int; // Comprueba si hay algún botón pulsado
|
||||||
|
|
||||||
// --- Métodos de gestión de mandos ---
|
// --- Métodos de gestión de mandos ---
|
||||||
bool discoverGameControllers(); // Busca si hay mandos conectados
|
auto discoverGameControllers() -> bool; // Busca si hay mandos conectados
|
||||||
bool gameControllerFound(); // Comprueba si hay algún mando conectado
|
auto gameControllerFound() -> bool; // Comprueba si hay algún mando conectado
|
||||||
int getNumControllers() const; // Obtiene el número de mandos conectados
|
[[nodiscard]] auto getNumControllers() const -> int; // Obtiene el número de mandos conectados
|
||||||
std::string getControllerName(int controller_index) const; // Obtiene el nombre de un mando de juego
|
[[nodiscard]] auto getControllerName(int controller_index) const -> std::string; // 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
|
[[nodiscard]] auto getJoyIndex(SDL_JoystickID id) const -> int; // Obtiene el índice del controlador a partir de un event.id
|
||||||
|
|
||||||
// --- Métodos de consulta y utilidades ---
|
// --- Métodos de consulta y utilidades ---
|
||||||
void printBindings(InputDevice device = InputDevice::KEYBOARD, int controller_index = 0) const; // Muestra por consola los controles asignados
|
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
|
[[nodiscard]] auto getControllerBinding(int controller_index, InputAction input) const -> SDL_GamepadButton; // Obtiene el SDL_GamepadButton asignado a un input
|
||||||
std::string inputToString(InputAction input) const; // Convierte un InputAction a std::string
|
[[nodiscard]] auto inputToString(InputAction input) const -> std::string; // Convierte un InputAction a std::string
|
||||||
InputAction stringToInput(const std::string &name) const; // Convierte un std::string a InputAction
|
[[nodiscard]] auto stringToInput(const std::string &name) const -> InputAction; // Convierte un std::string a InputAction
|
||||||
int getIndexByName(const std::string &name) const; // Obtiene el índice a partir del nombre del mando
|
[[nodiscard]] auto getIndexByName(const std::string &name) const -> int; // Obtiene el índice a partir del nombre del mando
|
||||||
|
|
||||||
// --- Métodos de reseteo de estado de entrada ---
|
// --- Métodos de reseteo de estado de entrada ---
|
||||||
void resetInputStates(); // Pone todos los KeyBindings.active y ControllerBindings.active a false
|
void resetInputStates(); // Pone todos los KeyBindings.active y ControllerBindings.active a false
|
||||||
@@ -139,12 +139,12 @@ class Input {
|
|||||||
|
|
||||||
// --- Métodos internos ---
|
// --- Métodos internos ---
|
||||||
void initSDLGamePad(); // Inicializa SDL para la gestión de mandos
|
void initSDLGamePad(); // Inicializa SDL para la gestión de mandos
|
||||||
bool checkAxisInput(InputAction input, int controller_index, bool repeat); // Comprueba el eje del mando
|
auto checkAxisInput(InputAction input, int controller_index, bool repeat) -> bool; // Comprueba el eje del mando
|
||||||
|
|
||||||
// --- Constructor y destructor ---
|
// --- Constructor y destructor ---
|
||||||
explicit Input(const std::string &game_controller_db_path); // Constructor privado
|
explicit Input(std::string game_controller_db_path); // Constructor privado
|
||||||
~Input() = default; // Destructor privado
|
~Input() = default; // Destructor privado
|
||||||
|
|
||||||
// --- Singleton ---
|
// --- Singleton ---
|
||||||
static Input *instance_;
|
static Input *instance;
|
||||||
};
|
};
|
||||||
@@ -1,8 +1,7 @@
|
|||||||
#include "item.h"
|
#include "item.h"
|
||||||
|
|
||||||
#include <stdlib.h> // Para rand
|
|
||||||
|
|
||||||
#include <algorithm> // Para clamp
|
#include <algorithm> // Para clamp
|
||||||
|
#include <cstdlib> // Para rand
|
||||||
|
|
||||||
#include "animated_sprite.h" // Para AnimatedSprite
|
#include "animated_sprite.h" // Para AnimatedSprite
|
||||||
#include "param.h" // Para Param, ParamGame, param
|
#include "param.h" // Para Param, ParamGame, param
|
||||||
@@ -161,7 +160,7 @@ void Item::shiftSprite() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Calcula la zona de aparición de la máquina de café
|
// Calcula la zona de aparición de la máquina de café
|
||||||
int Item::getCoffeeMachineSpawn(int player_x, int item_width, int area_width, int margin) {
|
auto Item::getCoffeeMachineSpawn(int player_x, int item_width, int area_width, int margin) -> int {
|
||||||
// Distancia mínima del jugador (ajusta según necesites)
|
// Distancia mínima del jugador (ajusta según necesites)
|
||||||
const int MIN_DISTANCE_FROM_PLAYER = area_width / 2;
|
const int MIN_DISTANCE_FROM_PLAYER = area_width / 2;
|
||||||
|
|
||||||
|
|||||||
@@ -54,16 +54,16 @@ class Item {
|
|||||||
void update();
|
void update();
|
||||||
|
|
||||||
// Getters
|
// Getters
|
||||||
float getPosX() const { return pos_x_; }
|
[[nodiscard]] auto getPosX() const -> float { return pos_x_; }
|
||||||
float getPosY() const { return pos_y_; }
|
[[nodiscard]] auto getPosY() const -> float { return pos_y_; }
|
||||||
int getWidth() const { return width_; }
|
[[nodiscard]] auto getWidth() const -> int { return width_; }
|
||||||
int getHeight() const { return height_; }
|
[[nodiscard]] auto getHeight() const -> int { return height_; }
|
||||||
ItemType getType() const { return type_; }
|
[[nodiscard]] auto getType() const -> ItemType { return type_; }
|
||||||
bool isEnabled() const { return enabled_; }
|
[[nodiscard]] auto isEnabled() const -> bool { return enabled_; }
|
||||||
bool isOnFloor() const { return floor_collision_; }
|
[[nodiscard]] auto isOnFloor() const -> bool { return floor_collision_; }
|
||||||
Circle &getCollider() { return collider_; }
|
auto getCollider() -> Circle & { return collider_; }
|
||||||
|
|
||||||
private:
|
private:
|
||||||
// Objetos y punteros
|
// Objetos y punteros
|
||||||
std::unique_ptr<AnimatedSprite> sprite_; // Sprite con los gráficos del objeto
|
std::unique_ptr<AnimatedSprite> sprite_; // Sprite con los gráficos del objeto
|
||||||
|
|
||||||
@@ -100,5 +100,5 @@ class Item {
|
|||||||
void updateTimeToLive();
|
void updateTimeToLive();
|
||||||
|
|
||||||
// Calcula la zona de aparición de la máquina de café
|
// Calcula la zona de aparición de la máquina de café
|
||||||
int getCoffeeMachineSpawn(int player_x, int item_width, int area_width, int margin = 2);
|
auto getCoffeeMachineSpawn(int player_x, int item_width, int area_width, int margin = 2) -> int;
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
#include "lang.h"
|
#include "lang.h"
|
||||||
|
|
||||||
#include <stddef.h> // Para size_t
|
#include <cstddef> // Para size_t
|
||||||
|
|
||||||
#include <exception> // Para exception
|
#include <exception> // Para exception
|
||||||
#include <fstream> // Para basic_ifstream, basic_istream, ifstream
|
#include <fstream> // Para basic_ifstream, basic_istream, ifstream
|
||||||
#include <unordered_map> // Para unordered_map, _Node_iterator, operator==
|
#include <unordered_map> // Para unordered_map, _Node_iterator, operator==
|
||||||
@@ -24,7 +23,7 @@ std::vector<Language> languages = {
|
|||||||
{Code::ENGLISH, "Ingles", "en_UK.json"}};
|
{Code::ENGLISH, "Ingles", "en_UK.json"}};
|
||||||
|
|
||||||
// Inicializa los textos del juego en el idioma seleccionado
|
// Inicializa los textos del juego en el idioma seleccionado
|
||||||
bool loadFromFile(const std::string &file_path) {
|
auto loadFromFile(const std::string &file_path) -> bool {
|
||||||
texts.clear();
|
texts.clear();
|
||||||
|
|
||||||
std::ifstream rfile(file_path);
|
std::ifstream rfile(file_path);
|
||||||
@@ -47,7 +46,7 @@ bool loadFromFile(const std::string &file_path) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Obtiene el texto por clave
|
// Obtiene el texto por clave
|
||||||
std::string getText(const std::string &key) {
|
auto getText(const std::string &key) -> std::string {
|
||||||
auto it = texts.find(key);
|
auto it = texts.find(key);
|
||||||
if (it != texts.end())
|
if (it != texts.end())
|
||||||
return it->second;
|
return it->second;
|
||||||
@@ -56,7 +55,7 @@ std::string getText(const std::string &key) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Obtiene el código del siguiente idioma disponible
|
// Obtiene el código del siguiente idioma disponible
|
||||||
Code getNextLangCode(Code lang) {
|
auto getNextLangCode(Code lang) -> Code {
|
||||||
for (size_t i = 0; i < languages.size(); ++i) {
|
for (size_t i = 0; i < languages.size(); ++i) {
|
||||||
if (languages[i].code == lang) {
|
if (languages[i].code == lang) {
|
||||||
return languages[(i + 1) % languages.size()].code;
|
return languages[(i + 1) % languages.size()].code;
|
||||||
@@ -67,7 +66,7 @@ Code getNextLangCode(Code lang) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Obtiene un idioma del vector de idiomas a partir de un código
|
// Obtiene un idioma del vector de idiomas a partir de un código
|
||||||
Language getLanguage(Code code) {
|
auto getLanguage(Code code) -> Language {
|
||||||
for (const auto &lang : languages) {
|
for (const auto &lang : languages) {
|
||||||
if (lang.code == code)
|
if (lang.code == code)
|
||||||
return lang;
|
return lang;
|
||||||
@@ -77,7 +76,7 @@ Language getLanguage(Code code) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Devuelve el código de un idioma a partir de un nombre
|
// Devuelve el código de un idioma a partir de un nombre
|
||||||
Code getCodeFromName(const std::string &name) {
|
auto getCodeFromName(const std::string &name) -> Code {
|
||||||
for (const auto &lang : languages) {
|
for (const auto &lang : languages) {
|
||||||
if (lang.name == name)
|
if (lang.name == name)
|
||||||
return lang.code;
|
return lang.code;
|
||||||
@@ -87,7 +86,7 @@ Code getCodeFromName(const std::string &name) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Devuelve el nombre de un idioma a partir de un código
|
// Devuelve el nombre de un idioma a partir de un código
|
||||||
std::string getNameFromCode(Code code) {
|
auto getNameFromCode(Code code) -> std::string {
|
||||||
for (const auto &lang : languages) {
|
for (const auto &lang : languages) {
|
||||||
if (lang.code == code)
|
if (lang.code == code)
|
||||||
return lang.name;
|
return lang.name;
|
||||||
@@ -137,7 +136,7 @@ void updateDifficultyNames() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Obtiene una fichero a partir de un lang::Code
|
// Obtiene una fichero a partir de un lang::Code
|
||||||
std::string getLanguageFileName(Lang::Code code) {
|
auto getLanguageFileName(Lang::Code code) -> std::string {
|
||||||
for (const auto &lang : languages) {
|
for (const auto &lang : languages) {
|
||||||
if (lang.code == code)
|
if (lang.code == code)
|
||||||
return Asset::get()->get(lang.file_name);
|
return Asset::get()->get(lang.file_name);
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ Actualizando a la versión "Arcade Edition" en 08/05/2024
|
|||||||
|
|
||||||
#include "director.h" // Para Director
|
#include "director.h" // Para Director
|
||||||
|
|
||||||
int main(int argc, char *argv[]) {
|
auto main(int argc, char *argv[]) -> int {
|
||||||
// Crea el objeto Director
|
// Crea el objeto Director
|
||||||
auto director = std::make_unique<Director>(argc, const_cast<const char **>(argv));
|
auto director = std::make_unique<Director>(argc, const_cast<const char **>(argv));
|
||||||
|
|
||||||
|
|||||||
@@ -13,22 +13,22 @@ void ManageHiScoreTable::clear() {
|
|||||||
table_.clear();
|
table_.clear();
|
||||||
|
|
||||||
// Añade 10 entradas predefinidas
|
// Añade 10 entradas predefinidas
|
||||||
table_.push_back(HiScoreEntry("BRY", 1000000));
|
table_.emplace_back("BRY", 1000000);
|
||||||
table_.push_back(HiScoreEntry("USUFO", 500000));
|
table_.emplace_back("USUFO", 500000);
|
||||||
table_.push_back(HiScoreEntry("GLUCA", 100000));
|
table_.emplace_back("GLUCA", 100000);
|
||||||
table_.push_back(HiScoreEntry("PARRA", 50000));
|
table_.emplace_back("PARRA", 50000);
|
||||||
table_.push_back(HiScoreEntry("CAGAM", 10000));
|
table_.emplace_back("CAGAM", 10000);
|
||||||
table_.push_back(HiScoreEntry("PEPE", 5000));
|
table_.emplace_back("PEPE", 5000);
|
||||||
table_.push_back(HiScoreEntry("ROSIT", 1000));
|
table_.emplace_back("ROSIT", 1000);
|
||||||
table_.push_back(HiScoreEntry("SAM", 500));
|
table_.emplace_back("SAM", 500);
|
||||||
table_.push_back(HiScoreEntry("PACMQ", 200));
|
table_.emplace_back("PACMQ", 200);
|
||||||
table_.push_back(HiScoreEntry("PELEC", 100));
|
table_.emplace_back("PELEC", 100);
|
||||||
|
|
||||||
sort();
|
sort();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Añade un elemento a la tabla
|
// Añade un elemento a la tabla
|
||||||
int ManageHiScoreTable::add(const HiScoreEntry &entry) {
|
auto ManageHiScoreTable::add(const HiScoreEntry &entry) -> int {
|
||||||
// Añade la entrada a la tabla
|
// Añade la entrada a la tabla
|
||||||
table_.push_back(entry);
|
table_.push_back(entry);
|
||||||
|
|
||||||
@@ -63,14 +63,14 @@ int ManageHiScoreTable::add(const HiScoreEntry &entry) {
|
|||||||
void ManageHiScoreTable::sort() {
|
void ManageHiScoreTable::sort() {
|
||||||
struct
|
struct
|
||||||
{
|
{
|
||||||
bool operator()(const HiScoreEntry &a, const HiScoreEntry &b) const { return a.score > b.score; }
|
auto operator()(const HiScoreEntry &a, const HiScoreEntry &b) const -> bool { return a.score > b.score; }
|
||||||
} score_descending_comparator;
|
} score_descending_comparator;
|
||||||
|
|
||||||
std::sort(table_.begin(), table_.end(), score_descending_comparator);
|
std::sort(table_.begin(), table_.end(), score_descending_comparator);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Carga la tabla desde un fichero
|
// Carga la tabla desde un fichero
|
||||||
bool ManageHiScoreTable::loadFromFile(const std::string &file_path) {
|
auto ManageHiScoreTable::loadFromFile(const std::string &file_path) -> bool {
|
||||||
clear();
|
clear();
|
||||||
auto success = true;
|
auto success = true;
|
||||||
auto file = SDL_IOFromFile(file_path.c_str(), "rb");
|
auto file = SDL_IOFromFile(file_path.c_str(), "rb");
|
||||||
@@ -117,7 +117,7 @@ bool ManageHiScoreTable::loadFromFile(const std::string &file_path) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Guarda la tabla en un fichero
|
// Guarda la tabla en un fichero
|
||||||
bool ManageHiScoreTable::saveToFile(const std::string &file_path) {
|
auto ManageHiScoreTable::saveToFile(const std::string &file_path) -> bool {
|
||||||
auto success = true;
|
auto success = true;
|
||||||
auto file = SDL_IOFromFile(file_path.c_str(), "w+b");
|
auto file = SDL_IOFromFile(file_path.c_str(), "w+b");
|
||||||
|
|
||||||
|
|||||||
@@ -36,15 +36,15 @@ class ManageHiScoreTable {
|
|||||||
void clear();
|
void clear();
|
||||||
|
|
||||||
// Añade un elemento a la tabla (devuelve la posición en la que se inserta)
|
// Añade un elemento a la tabla (devuelve la posición en la que se inserta)
|
||||||
int add(const HiScoreEntry &entry);
|
auto add(const HiScoreEntry &entry) -> int;
|
||||||
|
|
||||||
// Carga la tabla con los datos de un fichero
|
// Carga la tabla con los datos de un fichero
|
||||||
bool loadFromFile(const std::string &file_path);
|
auto loadFromFile(const std::string &file_path) -> bool;
|
||||||
|
|
||||||
// Guarda la tabla en un fichero
|
// Guarda la tabla en un fichero
|
||||||
bool saveToFile(const std::string &file_path);
|
auto saveToFile(const std::string &file_path) -> bool;
|
||||||
|
|
||||||
private:
|
private:
|
||||||
// Referencia a la tabla con los records
|
// Referencia a la tabla con los records
|
||||||
std::vector<HiScoreEntry> &table_;
|
std::vector<HiScoreEntry> &table_;
|
||||||
|
|
||||||
|
|||||||
@@ -23,8 +23,7 @@ MovingSprite::MovingSprite(std::shared_ptr<Texture> texture, SDL_FRect pos)
|
|||||||
|
|
||||||
MovingSprite::MovingSprite(std::shared_ptr<Texture> texture)
|
MovingSprite::MovingSprite(std::shared_ptr<Texture> texture)
|
||||||
: Sprite(texture),
|
: Sprite(texture),
|
||||||
x_(0.0f),
|
|
||||||
y_(0.0f),
|
|
||||||
rotate_(Rotate()),
|
rotate_(Rotate()),
|
||||||
zoom_w_(1.0f),
|
zoom_w_(1.0f),
|
||||||
zoom_h_(1.0f),
|
zoom_h_(1.0f),
|
||||||
|
|||||||
@@ -4,6 +4,7 @@
|
|||||||
|
|
||||||
#include <algorithm> // Para remove_if
|
#include <algorithm> // Para remove_if
|
||||||
#include <string> // Para basic_string, string
|
#include <string> // Para basic_string, string
|
||||||
|
#include <utility>
|
||||||
#include <vector> // Para vector
|
#include <vector> // Para vector
|
||||||
|
|
||||||
#include "audio.h" // Para Audio
|
#include "audio.h" // Para Audio
|
||||||
@@ -14,22 +15,22 @@
|
|||||||
#include "texture.h" // Para Texture
|
#include "texture.h" // Para Texture
|
||||||
|
|
||||||
// Singleton
|
// Singleton
|
||||||
Notifier *Notifier::instance_ = nullptr;
|
Notifier *Notifier::instance = nullptr;
|
||||||
|
|
||||||
// Inicializa la instancia única del singleton
|
// Inicializa la instancia única del singleton
|
||||||
void Notifier::init(const std::string &icon_file, std::shared_ptr<Text> text) { Notifier::instance_ = new Notifier(icon_file, text); }
|
void Notifier::init(const std::string &icon_file, std::shared_ptr<Text> text) { Notifier::instance = new Notifier(icon_file, text); }
|
||||||
|
|
||||||
// Libera la instancia
|
// Libera la instancia
|
||||||
void Notifier::destroy() { delete Notifier::instance_; }
|
void Notifier::destroy() { delete Notifier::instance; }
|
||||||
|
|
||||||
// Obtiene la instancia
|
// Obtiene la instancia
|
||||||
Notifier *Notifier::get() { return Notifier::instance_; }
|
auto Notifier::get() -> Notifier * { return Notifier::instance; }
|
||||||
|
|
||||||
// Constructor
|
// Constructor
|
||||||
Notifier::Notifier(std::string icon_file, std::shared_ptr<Text> text)
|
Notifier::Notifier(std::string icon_file, std::shared_ptr<Text> text)
|
||||||
: renderer_(Screen::get()->getRenderer()),
|
: renderer_(Screen::get()->getRenderer()),
|
||||||
icon_texture_(!icon_file.empty() ? std::make_unique<Texture>(renderer_, icon_file) : nullptr),
|
icon_texture_(!icon_file.empty() ? std::make_unique<Texture>(renderer_, icon_file) : nullptr),
|
||||||
text_(text),
|
text_(std::move(text)),
|
||||||
bg_color_(param.notification.color),
|
bg_color_(param.notification.color),
|
||||||
wait_time_(150),
|
wait_time_(150),
|
||||||
stack_(false),
|
stack_(false),
|
||||||
@@ -264,7 +265,7 @@ void Notifier::clearAllNotifications() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Obtiene los códigos de las notificaciones
|
// Obtiene los códigos de las notificaciones
|
||||||
std::vector<std::string> Notifier::getCodes() {
|
auto Notifier::getCodes() -> std::vector<std::string> {
|
||||||
std::vector<std::string> codes;
|
std::vector<std::string> codes;
|
||||||
for (const auto ¬ification : notifications_) {
|
for (const auto ¬ification : notifications_) {
|
||||||
codes.emplace_back(notification.code);
|
codes.emplace_back(notification.code);
|
||||||
|
|||||||
@@ -18,7 +18,7 @@ class Notifier {
|
|||||||
// --- Métodos de singleton ---
|
// --- Métodos de singleton ---
|
||||||
static void init(const std::string &icon_file, std::shared_ptr<Text> text); // Inicializa el singleton
|
static void init(const std::string &icon_file, std::shared_ptr<Text> text); // Inicializa el singleton
|
||||||
static void destroy(); // Libera el singleton
|
static void destroy(); // Libera el singleton
|
||||||
static Notifier *get(); // Obtiene la instancia
|
static auto get() -> Notifier *; // Obtiene la instancia
|
||||||
|
|
||||||
// --- Métodos principales ---
|
// --- Métodos principales ---
|
||||||
void render(); // Dibuja las notificaciones por pantalla
|
void render(); // Dibuja las notificaciones por pantalla
|
||||||
@@ -26,13 +26,13 @@ class Notifier {
|
|||||||
|
|
||||||
// --- Gestión de notificaciones ---
|
// --- Gestión de notificaciones ---
|
||||||
void show(std::vector<std::string> texts, int icon = -1, const std::string &code = std::string()); // Muestra una notificación de texto por pantalla
|
void show(std::vector<std::string> texts, int icon = -1, const std::string &code = std::string()); // Muestra una notificación de texto por pantalla
|
||||||
bool isActive() const { return !notifications_.empty(); } // Indica si hay notificaciones activas
|
[[nodiscard]] auto isActive() const -> bool { return !notifications_.empty(); } // Indica si hay notificaciones activas
|
||||||
std::vector<std::string> getCodes(); // Obtiene los códigos de las notificaciones activas
|
auto getCodes() -> std::vector<std::string>; // Obtiene los códigos de las notificaciones activas
|
||||||
bool checkCode(const std::string &code) { return stringInVector(getCodes(), code); } // Comprueba si hay alguna notificación con un código concreto
|
auto checkCode(const std::string &code) -> bool { return stringInVector(getCodes(), code); } // Comprueba si hay alguna notificación con un código concreto
|
||||||
|
|
||||||
private:
|
private:
|
||||||
// --- Singleton ---
|
// --- Singleton ---
|
||||||
static Notifier *instance_;
|
static Notifier *instance;
|
||||||
|
|
||||||
// --- Tipos internos ---
|
// --- Tipos internos ---
|
||||||
enum class NotificationStatus {
|
enum class NotificationStatus {
|
||||||
@@ -52,17 +52,17 @@ class Notifier {
|
|||||||
std::shared_ptr<Texture> texture; // Textura de la notificación
|
std::shared_ptr<Texture> texture; // Textura de la notificación
|
||||||
std::shared_ptr<Sprite> sprite; // Sprite asociado
|
std::shared_ptr<Sprite> sprite; // Sprite asociado
|
||||||
std::vector<std::string> texts; // Textos a mostrar
|
std::vector<std::string> texts; // Textos a mostrar
|
||||||
int counter; // Contador de tiempo
|
int counter{0}; // Contador de tiempo
|
||||||
NotificationStatus state; // Estado de la notificación
|
NotificationStatus state{NotificationStatus::RISING}; // Estado de la notificación
|
||||||
NotificationShape shape; // Forma de la notificación
|
NotificationShape shape{NotificationShape::SQUARED}; // Forma de la notificación
|
||||||
SDL_FRect rect; // Rectángulo de la notificación
|
SDL_FRect rect; // Rectángulo de la notificación
|
||||||
int y; // Posición vertical
|
int y{0}; // Posición vertical
|
||||||
int travel_dist; // Distancia a recorrer
|
int travel_dist{0}; // Distancia a recorrer
|
||||||
std::string code; // Código identificador de la notificación
|
std::string code; // Código identificador de la notificación
|
||||||
|
|
||||||
// Constructor
|
// Constructor
|
||||||
explicit Notification()
|
explicit Notification()
|
||||||
: texture(nullptr), sprite(nullptr), texts(), counter(0), state(NotificationStatus::RISING), shape(NotificationShape::SQUARED), rect{0, 0, 0, 0}, y(0), travel_dist(0), code("") {}
|
: texture(nullptr), sprite(nullptr), texts(), rect{0, 0, 0, 0}, code("") {}
|
||||||
};
|
};
|
||||||
|
|
||||||
// --- Objetos y punteros ---
|
// --- Objetos y punteros ---
|
||||||
|
|||||||
@@ -28,7 +28,7 @@ std::vector<Difficulty> difficulties = {
|
|||||||
{DifficultyCode::HARD, "Hard"}};
|
{DifficultyCode::HARD, "Hard"}};
|
||||||
|
|
||||||
// Declaraciones
|
// Declaraciones
|
||||||
bool set(const std::string &var, const std::string &value);
|
auto set(const std::string &var, const std::string &value) -> bool;
|
||||||
|
|
||||||
// Inicializa las opciones del programa
|
// Inicializa las opciones del programa
|
||||||
void init() {
|
void init() {
|
||||||
@@ -49,7 +49,7 @@ void init() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Carga el fichero de configuración
|
// Carga el fichero de configuración
|
||||||
bool loadFromFile() {
|
auto loadFromFile() -> bool {
|
||||||
// Inicializa las opciones del programa
|
// Inicializa las opciones del programa
|
||||||
init();
|
init();
|
||||||
|
|
||||||
@@ -94,7 +94,7 @@ bool loadFromFile() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Guarda el fichero de configuración
|
// Guarda el fichero de configuración
|
||||||
bool saveToFile() {
|
auto saveToFile() -> bool {
|
||||||
std::ofstream file(settings.config_file);
|
std::ofstream file(settings.config_file);
|
||||||
|
|
||||||
if (!file.good()) {
|
if (!file.good()) {
|
||||||
@@ -167,7 +167,7 @@ bool saveToFile() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Asigna variables a partir de dos cadenas
|
// Asigna variables a partir de dos cadenas
|
||||||
bool set(const std::string &var, const std::string &value) {
|
auto set(const std::string &var, const std::string &value) -> bool {
|
||||||
// Indicador de éxito en la asignación
|
// Indicador de éxito en la asignación
|
||||||
auto success = true;
|
auto success = true;
|
||||||
|
|
||||||
@@ -281,7 +281,7 @@ void swapControllers() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Averigua quien está usando el teclado
|
// Averigua quien está usando el teclado
|
||||||
int getPlayerWhoUsesKeyboard() {
|
auto getPlayerWhoUsesKeyboard() -> int {
|
||||||
for (const auto &controller : controllers) {
|
for (const auto &controller : controllers) {
|
||||||
if (controller.type == InputDevice::ANY) {
|
if (controller.type == InputDevice::ANY) {
|
||||||
return controller.player_id;
|
return controller.player_id;
|
||||||
@@ -308,7 +308,7 @@ void checkPendingChanges() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
DifficultyCode getDifficultyCodeFromName(const std::string &name) {
|
auto getDifficultyCodeFromName(const std::string &name) -> DifficultyCode {
|
||||||
for (const auto &difficulty : difficulties) {
|
for (const auto &difficulty : difficulties) {
|
||||||
if (difficulty.name == name)
|
if (difficulty.name == name)
|
||||||
return difficulty.code;
|
return difficulty.code;
|
||||||
@@ -317,7 +317,7 @@ DifficultyCode getDifficultyCodeFromName(const std::string &name) {
|
|||||||
return difficulties[0].code;
|
return difficulties[0].code;
|
||||||
}
|
}
|
||||||
|
|
||||||
std::string getDifficultyNameFromCode(DifficultyCode code) {
|
auto getDifficultyNameFromCode(DifficultyCode code) -> std::string {
|
||||||
for (const auto &difficulty : difficulties) {
|
for (const auto &difficulty : difficulties) {
|
||||||
if (difficulty.code == code)
|
if (difficulty.code == code)
|
||||||
return difficulty.name;
|
return difficulty.name;
|
||||||
|
|||||||
@@ -3,6 +3,7 @@
|
|||||||
#include <SDL3/SDL.h> // Para SDL_GamepadButton, SDL_ScaleMode
|
#include <SDL3/SDL.h> // Para SDL_GamepadButton, SDL_ScaleMode
|
||||||
|
|
||||||
#include <string> // Para string, basic_string
|
#include <string> // Para string, basic_string
|
||||||
|
#include <utility>
|
||||||
#include <vector> // Para vector
|
#include <vector> // Para vector
|
||||||
|
|
||||||
#include "input.h" // Para InputAction, InputDevice
|
#include "input.h" // Para InputAction, InputDevice
|
||||||
@@ -24,96 +25,83 @@ struct Difficulty {
|
|||||||
DifficultyCode code; // Código que identifica la dificultad
|
DifficultyCode code; // Código que identifica la dificultad
|
||||||
std::string name; // Nombre que identifica la dificultad
|
std::string name; // Nombre que identifica la dificultad
|
||||||
|
|
||||||
Difficulty(DifficultyCode c, const std::string &n)
|
Difficulty(DifficultyCode c, std::string n)
|
||||||
: code(c), name(n) {}
|
: code(c), name(std::move(n)) {}
|
||||||
};
|
};
|
||||||
|
|
||||||
// --- Opciones de ventana ---
|
// --- Opciones de ventana ---
|
||||||
struct WindowOptions {
|
struct WindowOptions {
|
||||||
std::string caption; // Texto que aparece en la barra de título de la ventana
|
std::string caption; // Texto que aparece en la barra de título de la ventana
|
||||||
int size; // Valor por el que se multiplica el tamaño de la ventana
|
int size{2}; // Valor por el que se multiplica el tamaño de la ventana
|
||||||
int max_size; // Tamaño máximo para que la ventana no sea mayor que la pantalla
|
int max_size{2}; // Tamaño máximo para que la ventana no sea mayor que la pantalla
|
||||||
|
|
||||||
// Constructor por defecto con valores iniciales
|
// Constructor por defecto con valores iniciales
|
||||||
WindowOptions()
|
WindowOptions()
|
||||||
: caption("Coffee Crisis Arcade Edition"),
|
: caption("Coffee Crisis Arcade Edition") {}
|
||||||
size(2),
|
|
||||||
max_size(2) {}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
// --- Opciones de vídeo ---
|
// --- Opciones de vídeo ---
|
||||||
struct VideoOptions {
|
struct VideoOptions {
|
||||||
SDL_ScaleMode scale_mode; // Filtro usado para el escalado de la imagen
|
SDL_ScaleMode scale_mode{SDL_ScaleMode::SDL_SCALEMODE_NEAREST}; // Filtro usado para el escalado de la imagen
|
||||||
bool fullscreen; // Indica si se usa pantalla completa
|
bool fullscreen{false}; // Indica si se usa pantalla completa
|
||||||
bool v_sync; // Indica si se usa vsync
|
bool v_sync{true}; // Indica si se usa vsync
|
||||||
bool integer_scale; // Indica si se usa escalado entero
|
bool integer_scale{true}; // Indica si se usa escalado entero
|
||||||
bool shaders; // Indica si se usan shaders para los filtros de vídeo
|
bool shaders{false}; // Indica si se usan shaders para los filtros de vídeo
|
||||||
std::string info; // Información sobre el modo de vídeo
|
std::string info; // Información sobre el modo de vídeo
|
||||||
|
|
||||||
// Constructor por defecto con valores iniciales
|
// Constructor por defecto con valores iniciales
|
||||||
VideoOptions()
|
VideoOptions()
|
||||||
: scale_mode(SDL_ScaleMode::SDL_SCALEMODE_NEAREST),
|
: info() {}
|
||||||
fullscreen(false),
|
|
||||||
v_sync(true),
|
|
||||||
integer_scale(true),
|
|
||||||
shaders(false),
|
|
||||||
info() {}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
// --- Opciones de música ---
|
// --- Opciones de música ---
|
||||||
struct MusicOptions {
|
struct MusicOptions {
|
||||||
bool enabled; // Indica si la música suena o no
|
bool enabled{true}; // Indica si la música suena o no
|
||||||
int volume; // Volumen de la música
|
int volume{100}; // Volumen de la música
|
||||||
|
|
||||||
// Constructor por defecto
|
// Constructor por defecto
|
||||||
MusicOptions()
|
MusicOptions()
|
||||||
: enabled(true),
|
|
||||||
volume(100) {}
|
{}
|
||||||
};
|
};
|
||||||
|
|
||||||
// --- Opciones de sonido ---
|
// --- Opciones de sonido ---
|
||||||
struct SoundOptions {
|
struct SoundOptions {
|
||||||
bool enabled; // Indica si los sonidos suenan o no
|
bool enabled{true}; // Indica si los sonidos suenan o no
|
||||||
int volume; // Volumen de los sonidos
|
int volume{100}; // Volumen de los sonidos
|
||||||
|
|
||||||
// Constructor por defecto
|
// Constructor por defecto
|
||||||
SoundOptions()
|
SoundOptions()
|
||||||
: enabled(true),
|
|
||||||
volume(100) {}
|
{}
|
||||||
};
|
};
|
||||||
|
|
||||||
// --- Opciones de audio ---
|
// --- Opciones de audio ---
|
||||||
struct AudioOptions {
|
struct AudioOptions {
|
||||||
MusicOptions music; // Opciones para la música
|
MusicOptions music; // Opciones para la música
|
||||||
SoundOptions sound; // Opciones para los efectos de sonido
|
SoundOptions sound; // Opciones para los efectos de sonido
|
||||||
bool enabled; // Indica si el audio está activo o no
|
bool enabled{true}; // Indica si el audio está activo o no
|
||||||
int volume; // Volumen general del audio
|
int volume{100}; // Volumen general del audio
|
||||||
|
|
||||||
// Constructor por defecto
|
// Constructor por defecto
|
||||||
AudioOptions()
|
AudioOptions()
|
||||||
: music(),
|
: music(),
|
||||||
sound(),
|
sound() {}
|
||||||
enabled(true),
|
|
||||||
volume(100) {}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
// --- Opciones de configuración ---
|
// --- Opciones de configuración ---
|
||||||
struct SettingsOptions {
|
struct SettingsOptions {
|
||||||
DifficultyCode difficulty; // Dificultad del juego
|
DifficultyCode difficulty{DifficultyCode::NORMAL}; // Dificultad del juego
|
||||||
Lang::Code language; // Idioma usado en el juego
|
Lang::Code language{Lang::Code::VALENCIAN}; // Idioma usado en el juego
|
||||||
bool autofire; // Indicador de autofire
|
bool autofire{true}; // Indicador de autofire
|
||||||
bool shutdown_enabled; // Especifica si se puede apagar el sistema
|
bool shutdown_enabled{false}; // Especifica si se puede apagar el sistema
|
||||||
std::vector<HiScoreEntry> hi_score_table; // Tabla de mejores puntuaciones
|
std::vector<HiScoreEntry> hi_score_table; // Tabla de mejores puntuaciones
|
||||||
std::vector<int> last_hi_score_entry; // Últimas posiciones de entrada en la tabla
|
std::vector<int> last_hi_score_entry; // Últimas posiciones de entrada en la tabla
|
||||||
std::string config_file; // Ruta al fichero donde guardar la configuración y las opciones del juego
|
std::string config_file; // Ruta al fichero donde guardar la configuración y las opciones del juego
|
||||||
|
|
||||||
// Constructor por defecto con valores iniciales
|
// Constructor por defecto con valores iniciales
|
||||||
SettingsOptions()
|
SettingsOptions()
|
||||||
: difficulty(DifficultyCode::NORMAL),
|
: last_hi_score_entry({INVALID_INDEX, INVALID_INDEX}),
|
||||||
language(Lang::Code::VALENCIAN),
|
|
||||||
autofire(true),
|
|
||||||
shutdown_enabled(false),
|
|
||||||
last_hi_score_entry({INVALID_INDEX, INVALID_INDEX}),
|
|
||||||
config_file() {}
|
config_file() {}
|
||||||
|
|
||||||
// Reinicia las últimas entradas de puntuación
|
// Reinicia las últimas entradas de puntuación
|
||||||
@@ -127,9 +115,9 @@ struct SettingsOptions {
|
|||||||
struct GamepadOptions {
|
struct GamepadOptions {
|
||||||
int index; // Índice en el vector de mandos
|
int index; // Índice en el vector de mandos
|
||||||
int player_id; // Jugador asociado al mando
|
int player_id; // Jugador asociado al mando
|
||||||
InputDevice type; // Indica si se usará teclado, mando o ambos
|
InputDevice type{InputDevice::CONTROLLER}; // Indica si se usará teclado, mando o ambos
|
||||||
std::string name; // Nombre del dispositivo
|
std::string name; // Nombre del dispositivo
|
||||||
bool plugged; // Indica si el mando está conectado
|
bool plugged{false}; // Indica si el mando está conectado
|
||||||
std::vector<InputAction> inputs; // Listado de acciones asignadas
|
std::vector<InputAction> inputs; // Listado de acciones asignadas
|
||||||
std::vector<SDL_GamepadButton> buttons; // Listado de botones asignados a cada acción
|
std::vector<SDL_GamepadButton> buttons; // Listado de botones asignados a cada acción
|
||||||
|
|
||||||
@@ -137,9 +125,9 @@ struct GamepadOptions {
|
|||||||
GamepadOptions()
|
GamepadOptions()
|
||||||
: index(INVALID_INDEX),
|
: index(INVALID_INDEX),
|
||||||
player_id(INVALID_INDEX),
|
player_id(INVALID_INDEX),
|
||||||
type(InputDevice::CONTROLLER),
|
|
||||||
name(),
|
name(),
|
||||||
plugged(false),
|
|
||||||
inputs{
|
inputs{
|
||||||
InputAction::FIRE_LEFT,
|
InputAction::FIRE_LEFT,
|
||||||
InputAction::FIRE_CENTER,
|
InputAction::FIRE_CENTER,
|
||||||
@@ -156,15 +144,14 @@ struct GamepadOptions {
|
|||||||
|
|
||||||
// --- Opciones pendientes de aplicar ---
|
// --- Opciones pendientes de aplicar ---
|
||||||
struct PendingChanges {
|
struct PendingChanges {
|
||||||
Lang::Code new_language; // Idioma en espera de aplicar
|
Lang::Code new_language{Lang::Code::VALENCIAN}; // Idioma en espera de aplicar
|
||||||
DifficultyCode new_difficulty; // Dificultad en espera de aplicar
|
DifficultyCode new_difficulty{DifficultyCode::NORMAL}; // Dificultad en espera de aplicar
|
||||||
bool has_pending_changes; // Indica si hay cambios pendientes
|
bool has_pending_changes{false}; // Indica si hay cambios pendientes
|
||||||
|
|
||||||
// Constructor por defecto con valores iniciales
|
// Constructor por defecto con valores iniciales
|
||||||
PendingChanges()
|
PendingChanges()
|
||||||
: new_language(Lang::Code::VALENCIAN),
|
|
||||||
new_difficulty(DifficultyCode::NORMAL),
|
{}
|
||||||
has_pending_changes(false) {}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
// --- Variables globales ---
|
// --- Variables globales ---
|
||||||
@@ -178,14 +165,14 @@ extern std::vector<Difficulty> difficulties; // Lista de los diferentes tipo
|
|||||||
|
|
||||||
// --- Funciones de configuración ---
|
// --- Funciones de configuración ---
|
||||||
void init(); // Inicializa las opciones del programa
|
void init(); // Inicializa las opciones del programa
|
||||||
bool loadFromFile(); // Carga el fichero de configuración
|
auto loadFromFile() -> bool; // Carga el fichero de configuración
|
||||||
bool saveToFile(); // Guarda el fichero de configuración
|
auto saveToFile() -> bool; // Guarda el fichero de configuración
|
||||||
void setKeyboardToPlayer(int player_id); // Asigna el teclado al jugador
|
void setKeyboardToPlayer(int player_id); // Asigna el teclado al jugador
|
||||||
void swapKeyboard(); // Intercambia el teclado de jugador
|
void swapKeyboard(); // Intercambia el teclado de jugador
|
||||||
void swapControllers(); // Intercambia los jugadores asignados a los dos primeros mandos
|
void swapControllers(); // Intercambia los jugadores asignados a los dos primeros mandos
|
||||||
int getPlayerWhoUsesKeyboard(); // Averigua quién está usando el teclado
|
auto getPlayerWhoUsesKeyboard() -> int; // Averigua quién está usando el teclado
|
||||||
void applyPendingChanges(); // Aplica los cambios pendientes copiando los valores a sus variables
|
void applyPendingChanges(); // Aplica los cambios pendientes copiando los valores a sus variables
|
||||||
void checkPendingChanges(); // Verifica si hay cambios pendientes
|
void checkPendingChanges(); // Verifica si hay cambios pendientes
|
||||||
DifficultyCode getDifficultyCodeFromName(const std::string &name); // Obtiene el código de dificultad a partir del nombre
|
auto getDifficultyCodeFromName(const std::string &name) -> DifficultyCode; // Obtiene el código de dificultad a partir del nombre
|
||||||
std::string getDifficultyNameFromCode(DifficultyCode code); // Obtiene el nombre de la dificultad a partir del código
|
auto getDifficultyNameFromCode(DifficultyCode code) -> std::string; // Obtiene el nombre de la dificultad a partir del código
|
||||||
} // namespace Options
|
} // namespace Options
|
||||||
@@ -15,7 +15,7 @@ Param param;
|
|||||||
void precalculateZones();
|
void precalculateZones();
|
||||||
|
|
||||||
// Asigna variables a partir de dos cadenas
|
// Asigna variables a partir de dos cadenas
|
||||||
bool setParams(const std::string &var, const std::string &value);
|
auto setParams(const std::string &var, const std::string &value) -> bool;
|
||||||
|
|
||||||
// Establece valores por defecto a las variables
|
// Establece valores por defecto a las variables
|
||||||
void initParam() {
|
void initParam() {
|
||||||
@@ -127,7 +127,7 @@ void loadParamsFromFile(const std::string &file_path) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Asigna variables a partir de dos cadenas
|
// Asigna variables a partir de dos cadenas
|
||||||
bool setParams(const std::string &var, const std::string &value) {
|
auto setParams(const std::string &var, const std::string &value) -> bool {
|
||||||
// Indicador de éxito en la asignación
|
// Indicador de éxito en la asignación
|
||||||
auto success = true;
|
auto success = true;
|
||||||
|
|
||||||
|
|||||||
@@ -6,7 +6,7 @@
|
|||||||
#include <utility> // Para move
|
#include <utility> // Para move
|
||||||
|
|
||||||
// Devuelve un vector con los puntos que conforman la ruta
|
// Devuelve un vector con los puntos que conforman la ruta
|
||||||
std::vector<SDL_FPoint> createPath(float start, float end, PathType type, float fixed_pos, int steps, const std::function<double(double)> &easing_function) {
|
auto createPath(float start, float end, PathType type, float fixed_pos, int steps, const std::function<double(double)> &easing_function) -> std::vector<SDL_FPoint> {
|
||||||
std::vector<SDL_FPoint> v;
|
std::vector<SDL_FPoint> v;
|
||||||
v.reserve(steps);
|
v.reserve(steps);
|
||||||
|
|
||||||
@@ -141,4 +141,4 @@ void PathSprite::goToNextPathOrDie() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Indica si ha terminado todos los recorridos
|
// Indica si ha terminado todos los recorridos
|
||||||
bool PathSprite::hasFinished() { return has_finished_; }
|
auto PathSprite::hasFinished() -> bool { return has_finished_; }
|
||||||
@@ -37,7 +37,7 @@ struct Path {
|
|||||||
};
|
};
|
||||||
|
|
||||||
// Devuelve un vector con los puntos que conforman la ruta
|
// 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);
|
auto createPath(float start, float end, PathType type, float fixed_pos, int steps, const std::function<double(double)> &easing_function) -> std::vector<SDL_FPoint>;
|
||||||
|
|
||||||
// --- Clase PathSprite: Sprite que sigue uno o varios recorridos ---
|
// --- Clase PathSprite: Sprite que sigue uno o varios recorridos ---
|
||||||
class PathSprite : public Sprite {
|
class PathSprite : public Sprite {
|
||||||
@@ -54,16 +54,16 @@ class PathSprite : public Sprite {
|
|||||||
// --- Gestión de recorridos ---
|
// --- Gestión de recorridos ---
|
||||||
void addPath(Path path, bool centered = false); // Añade un recorrido (Path)
|
void addPath(Path path, bool centered = false); // Añade un recorrido (Path)
|
||||||
void addPath(std::vector<SDL_FPoint> spots, int waiting_counter = 0); // Añade un recorrido a partir de puntos
|
void addPath(std::vector<SDL_FPoint> spots, int waiting_counter = 0); // Añade un recorrido a partir de puntos
|
||||||
void addPath(int start, int end, PathType type, int fixed_pos, int steps, const std::function<double(double)> &easingFunction, int waiting_counter = 0); // Añade un recorrido generado
|
void addPath(int start, int end, PathType type, int fixed_pos, int steps, const std::function<double(double)> &easing_function, int waiting_counter = 0); // Añade un recorrido generado
|
||||||
|
|
||||||
// --- Estado y control ---
|
// --- Estado y control ---
|
||||||
void enable(); // Habilita el objeto
|
void enable(); // Habilita el objeto
|
||||||
bool hasFinished(); // Indica si ha terminado todos los recorridos
|
auto hasFinished() -> bool; // Indica si ha terminado todos los recorridos
|
||||||
|
|
||||||
// --- Getters ---
|
// --- Getters ---
|
||||||
int getCurrentPath() const { return current_path_; } // Devuelve el índice del recorrido actual
|
[[nodiscard]] auto getCurrentPath() const -> int { return current_path_; } // Devuelve el índice del recorrido actual
|
||||||
|
|
||||||
private:
|
private:
|
||||||
// --- Variables internas ---
|
// --- Variables internas ---
|
||||||
bool enabled_ = false; // Indica si el objeto está habilitado
|
bool enabled_ = false; // Indica si el objeto está habilitado
|
||||||
bool has_finished_ = false; // Indica si el objeto ha finalizado el recorrido
|
bool has_finished_ = false; // Indica si el objeto ha finalizado el recorrido
|
||||||
|
|||||||
@@ -1,9 +1,9 @@
|
|||||||
#include "player.h"
|
#include "player.h"
|
||||||
|
|
||||||
#include <SDL3/SDL.h> // Para SDL_GetTicks, SDL_FlipMode, SDL_FRect
|
#include <SDL3/SDL.h> // Para SDL_GetTicks, SDL_FlipMode, SDL_FRect
|
||||||
#include <stdlib.h> // Para rand
|
|
||||||
|
|
||||||
#include <algorithm> // Para clamp, max, min
|
#include <algorithm> // Para clamp, max, min
|
||||||
|
#include <cstdlib> // Para rand
|
||||||
|
|
||||||
#include "animated_sprite.h" // Para AnimatedSprite
|
#include "animated_sprite.h" // Para AnimatedSprite
|
||||||
#include "asset.h" // Para Asset
|
#include "asset.h" // Para Asset
|
||||||
@@ -46,7 +46,7 @@ void Player::init() {
|
|||||||
firing_state_ = PlayerState::FIRING_NONE;
|
firing_state_ = PlayerState::FIRING_NONE;
|
||||||
playing_state_ = PlayerState::WAITING;
|
playing_state_ = PlayerState::WAITING;
|
||||||
power_up_ = false;
|
power_up_ = false;
|
||||||
power_up_counter_ = POWERUP_COUNTER_;
|
power_up_counter_ = POWERUP_COUNTER;
|
||||||
extra_hit_ = false;
|
extra_hit_ = false;
|
||||||
coffees_ = 0;
|
coffees_ = 0;
|
||||||
continue_ticks_ = 0;
|
continue_ticks_ = 0;
|
||||||
@@ -91,12 +91,12 @@ void Player::setInput(InputAction input) {
|
|||||||
void Player::setInputPlaying(InputAction input) {
|
void Player::setInputPlaying(InputAction input) {
|
||||||
switch (input) {
|
switch (input) {
|
||||||
case InputAction::LEFT: {
|
case InputAction::LEFT: {
|
||||||
vel_x_ = -BASE_SPEED_;
|
vel_x_ = -BASE_SPEED;
|
||||||
setWalkingState(PlayerState::WALKING_LEFT);
|
setWalkingState(PlayerState::WALKING_LEFT);
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
case InputAction::RIGHT: {
|
case InputAction::RIGHT: {
|
||||||
vel_x_ = BASE_SPEED_;
|
vel_x_ = BASE_SPEED;
|
||||||
setWalkingState(PlayerState::WALKING_RIGHT);
|
setWalkingState(PlayerState::WALKING_RIGHT);
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
@@ -153,7 +153,7 @@ void Player::move() {
|
|||||||
|
|
||||||
// Si el jugador abandona el area de juego por los laterales, restaura su posición
|
// Si el jugador abandona el area de juego por los laterales, restaura su posición
|
||||||
const float MIN_X = play_area_.x - 5;
|
const float MIN_X = play_area_.x - 5;
|
||||||
const float MAX_X = play_area_.w + 5 - WIDTH_;
|
const float MAX_X = play_area_.w + 5 - WIDTH;
|
||||||
pos_x_ = std::clamp(pos_x_, MIN_X, MAX_X);
|
pos_x_ = std::clamp(pos_x_, MIN_X, MAX_X);
|
||||||
|
|
||||||
shiftSprite();
|
shiftSprite();
|
||||||
@@ -163,7 +163,7 @@ void Player::move() {
|
|||||||
// Si el jugador abandona el area de juego por los laterales lo hace rebotar
|
// Si el jugador abandona el area de juego por los laterales lo hace rebotar
|
||||||
const int X = player_sprite_->getPosX();
|
const int X = player_sprite_->getPosX();
|
||||||
const int MIN_X = play_area_.x;
|
const int MIN_X = play_area_.x;
|
||||||
const int MAX_X = play_area_.x + play_area_.w - WIDTH_;
|
const int MAX_X = play_area_.x + play_area_.w - WIDTH;
|
||||||
if ((X < MIN_X) || (X > MAX_X)) {
|
if ((X < MIN_X) || (X > MAX_X)) {
|
||||||
player_sprite_->setPosX(std::clamp(X, MIN_X, MAX_X));
|
player_sprite_->setPosX(std::clamp(X, MIN_X, MAX_X));
|
||||||
player_sprite_->setVelX(-player_sprite_->getVelX());
|
player_sprite_->setVelX(-player_sprite_->getVelX());
|
||||||
@@ -171,10 +171,10 @@ void Player::move() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Si el jugador toca el suelo rebota y si tiene poca velocidad, se detiene y cambia de estado
|
// Si el jugador toca el suelo rebota y si tiene poca velocidad, se detiene y cambia de estado
|
||||||
if (player_sprite_->getPosY() > play_area_.h - HEIGHT_) {
|
if (player_sprite_->getPosY() > play_area_.h - HEIGHT) {
|
||||||
if (player_sprite_->getVelY() < 2.0f) {
|
if (player_sprite_->getVelY() < 2.0f) {
|
||||||
// Si la velocidad de rebote es baja, lo detiene y cambia de estado
|
// Si la velocidad de rebote es baja, lo detiene y cambia de estado
|
||||||
const auto NEXT_PLAYER_STATUS = IsEligibleForHighScore() ? PlayerState::ENTERING_NAME : PlayerState::CONTINUE;
|
const auto NEXT_PLAYER_STATUS = isEligibleForHighScore() ? PlayerState::ENTERING_NAME : PlayerState::CONTINUE;
|
||||||
demo_ ? setPlayingState(PlayerState::LYING_ON_THE_FLOOR_FOREVER) : setPlayingState(NEXT_PLAYER_STATUS);
|
demo_ ? setPlayingState(PlayerState::LYING_ON_THE_FLOOR_FOREVER) : setPlayingState(NEXT_PLAYER_STATUS);
|
||||||
pos_x_ = player_sprite_->getPosX();
|
pos_x_ = player_sprite_->getPosX();
|
||||||
pos_y_ = default_pos_y_;
|
pos_y_ = default_pos_y_;
|
||||||
@@ -183,7 +183,7 @@ void Player::move() {
|
|||||||
playSound("jump.wav");
|
playSound("jump.wav");
|
||||||
} else {
|
} else {
|
||||||
// Decrementa las velocidades de rebote
|
// Decrementa las velocidades de rebote
|
||||||
player_sprite_->setPosY(play_area_.h - HEIGHT_);
|
player_sprite_->setPosY(play_area_.h - HEIGHT);
|
||||||
player_sprite_->setVelY(player_sprite_->getVelY() * -0.5f);
|
player_sprite_->setVelY(player_sprite_->getVelY() * -0.5f);
|
||||||
player_sprite_->setVelX(player_sprite_->getVelX() * 0.75f);
|
player_sprite_->setVelX(player_sprite_->getVelX() * 0.75f);
|
||||||
player_sprite_->setAnimationSpeed(player_sprite_->getAnimationSpeed() * 2);
|
player_sprite_->setAnimationSpeed(player_sprite_->getAnimationSpeed() * 2);
|
||||||
@@ -195,7 +195,7 @@ void Player::move() {
|
|||||||
case PlayerState::TITLE_ANIMATION: {
|
case PlayerState::TITLE_ANIMATION: {
|
||||||
// Si el jugador abandona el area de juego por los laterales lo detiene
|
// Si el jugador abandona el area de juego por los laterales lo detiene
|
||||||
/*const int X = player_sprite_->getPosX();
|
/*const int X = player_sprite_->getPosX();
|
||||||
const int MIN_X = play_area_.x - WIDTH_;
|
const int MIN_X = play_area_.x - WIDTH;
|
||||||
const int MAX_X = play_area_.x + play_area_.w;
|
const int MAX_X = play_area_.x + play_area_.w;
|
||||||
if ((X < MIN_X) || (X > MAX_X))
|
if ((X < MIN_X) || (X > MAX_X))
|
||||||
{
|
{
|
||||||
@@ -219,7 +219,7 @@ void Player::move() {
|
|||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
pos_x_ += vel_x_ * 2.0f;
|
pos_x_ += vel_x_ * 2.0f;
|
||||||
const float MIN_X = -WIDTH_;
|
const float MIN_X = -WIDTH;
|
||||||
const float MAX_X = play_area_.w;
|
const float MAX_X = play_area_.w;
|
||||||
pos_x_ = std::clamp(pos_x_, MIN_X, MAX_X);
|
pos_x_ = std::clamp(pos_x_, MIN_X, MAX_X);
|
||||||
shiftSprite();
|
shiftSprite();
|
||||||
@@ -253,7 +253,7 @@ void Player::move() {
|
|||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
pos_x_ += vel_x_;
|
pos_x_ += vel_x_;
|
||||||
const float MIN_X = -WIDTH_;
|
const float MIN_X = -WIDTH;
|
||||||
const float MAX_X = play_area_.w;
|
const float MAX_X = play_area_.w;
|
||||||
pos_x_ = std::clamp(pos_x_, MIN_X, MAX_X);
|
pos_x_ = std::clamp(pos_x_, MIN_X, MAX_X);
|
||||||
shiftSprite();
|
shiftSprite();
|
||||||
@@ -298,8 +298,8 @@ void Player::move() {
|
|||||||
pos_x_ += vel_x_ / 2.0f;
|
pos_x_ += vel_x_ / 2.0f;
|
||||||
if (vel_x_ > 0) {
|
if (vel_x_ > 0) {
|
||||||
// setInputPlaying(InputAction::RIGHT);
|
// setInputPlaying(InputAction::RIGHT);
|
||||||
if (pos_x_ > param.game.game_area.rect.w - WIDTH_) {
|
if (pos_x_ > param.game.game_area.rect.w - WIDTH) {
|
||||||
pos_x_ = param.game.game_area.rect.w - WIDTH_;
|
pos_x_ = param.game.game_area.rect.w - WIDTH;
|
||||||
vel_x_ *= -1;
|
vel_x_ *= -1;
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
@@ -310,7 +310,7 @@ void Player::move() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (pos_x_ > param.game.game_area.center_x - WIDTH_ / 2) {
|
if (pos_x_ > param.game.game_area.center_x - WIDTH / 2) {
|
||||||
setWalkingState(PlayerState::WALKING_LEFT);
|
setWalkingState(PlayerState::WALKING_LEFT);
|
||||||
} else {
|
} else {
|
||||||
setWalkingState(PlayerState::WALKING_RIGHT);
|
setWalkingState(PlayerState::WALKING_RIGHT);
|
||||||
@@ -326,7 +326,7 @@ void Player::move() {
|
|||||||
// Pinta el jugador en pantalla
|
// Pinta el jugador en pantalla
|
||||||
void Player::render() {
|
void Player::render() {
|
||||||
if (power_up_ && isPlaying()) {
|
if (power_up_ && isPlaying()) {
|
||||||
if (power_up_counter_ > (POWERUP_COUNTER_ / 4) || power_up_counter_ % 20 > 4) {
|
if (power_up_counter_ > (POWERUP_COUNTER / 4) || power_up_counter_ % 20 > 4) {
|
||||||
power_sprite_->render();
|
power_sprite_->render();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -406,7 +406,7 @@ void Player::setAnimation() {
|
|||||||
void Player::updateCooldown() {
|
void Player::updateCooldown() {
|
||||||
if (playing_state_ == PlayerState::PLAYING) {
|
if (playing_state_ == PlayerState::PLAYING) {
|
||||||
if (cant_fire_counter_ > 0) {
|
if (cant_fire_counter_ > 0) {
|
||||||
cooling_state_counter_ = COOLING_DURATION_;
|
cooling_state_counter_ = COOLING_DURATION;
|
||||||
|
|
||||||
// La mitad del tiempo que no puede disparar tiene el brazo arriba (PlayerState::FIRING)
|
// La mitad del tiempo que no puede disparar tiene el brazo arriba (PlayerState::FIRING)
|
||||||
// y la otra mitad en retroceso (PlayerState::RECOILING)
|
// y la otra mitad en retroceso (PlayerState::RECOILING)
|
||||||
@@ -434,8 +434,8 @@ void Player::updateCooldown() {
|
|||||||
if (recoiling_state_counter_ > 0) {
|
if (recoiling_state_counter_ > 0) {
|
||||||
--recoiling_state_counter_;
|
--recoiling_state_counter_;
|
||||||
} else {
|
} else {
|
||||||
if (cooling_state_counter_ > COOLING_COMPLETE_) {
|
if (cooling_state_counter_ > COOLING_COMPLETE) {
|
||||||
if (cooling_state_counter_ == COOLING_DURATION_) {
|
if (cooling_state_counter_ == COOLING_DURATION) {
|
||||||
switch (firing_state_) {
|
switch (firing_state_) {
|
||||||
case PlayerState::RECOILING_LEFT:
|
case PlayerState::RECOILING_LEFT:
|
||||||
setFiringState(PlayerState::COOLING_LEFT);
|
setFiringState(PlayerState::COOLING_LEFT);
|
||||||
@@ -454,7 +454,7 @@ void Player::updateCooldown() {
|
|||||||
--cooling_state_counter_;
|
--cooling_state_counter_;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (cooling_state_counter_ == COOLING_COMPLETE_) {
|
if (cooling_state_counter_ == COOLING_COMPLETE) {
|
||||||
setFiringState(PlayerState::FIRING_NONE);
|
setFiringState(PlayerState::FIRING_NONE);
|
||||||
cooling_state_counter_ = -1;
|
cooling_state_counter_ = -1;
|
||||||
}
|
}
|
||||||
@@ -608,7 +608,7 @@ void Player::setPlayingState(PlayerState state) {
|
|||||||
setScoreboardMode(ScoreboardMode::SCORE);
|
setScoreboardMode(ScoreboardMode::SCORE);
|
||||||
switch (id_) {
|
switch (id_) {
|
||||||
case 1:
|
case 1:
|
||||||
pos_x_ = param.game.game_area.rect.x - WIDTH_;
|
pos_x_ = param.game.game_area.rect.x - WIDTH;
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case 2:
|
case 2:
|
||||||
@@ -621,7 +621,7 @@ void Player::setPlayingState(PlayerState state) {
|
|||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
case PlayerState::CREDITS: {
|
case PlayerState::CREDITS: {
|
||||||
vel_x_ = (walking_state_ == PlayerState::WALKING_RIGHT) ? BASE_SPEED_ : -BASE_SPEED_;
|
vel_x_ = (walking_state_ == PlayerState::WALKING_RIGHT) ? BASE_SPEED : -BASE_SPEED;
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
default:
|
default:
|
||||||
@@ -644,7 +644,7 @@ void Player::decScoreMultiplier() {
|
|||||||
// Establece el valor del estado
|
// Establece el valor del estado
|
||||||
void Player::setInvulnerable(bool value) {
|
void Player::setInvulnerable(bool value) {
|
||||||
invulnerable_ = value;
|
invulnerable_ = value;
|
||||||
invulnerable_counter_ = invulnerable_ ? INVULNERABLE_COUNTER_ : 0;
|
invulnerable_counter_ = invulnerable_ ? INVULNERABLE_COUNTER : 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Monitoriza el estado
|
// Monitoriza el estado
|
||||||
@@ -664,7 +664,7 @@ void Player::updateInvulnerable() {
|
|||||||
// Establece el valor de la variable
|
// Establece el valor de la variable
|
||||||
void Player::setPowerUp() {
|
void Player::setPowerUp() {
|
||||||
power_up_ = true;
|
power_up_ = true;
|
||||||
power_up_counter_ = POWERUP_COUNTER_;
|
power_up_counter_ = POWERUP_COUNTER;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Actualiza el valor de la variable
|
// Actualiza el valor de la variable
|
||||||
@@ -698,8 +698,8 @@ void Player::removeExtraHit() {
|
|||||||
|
|
||||||
// Actualiza el circulo de colisión a la posición del jugador
|
// Actualiza el circulo de colisión a la posición del jugador
|
||||||
void Player::shiftColliders() {
|
void Player::shiftColliders() {
|
||||||
collider_.x = static_cast<int>(pos_x_ + (WIDTH_ / 2));
|
collider_.x = static_cast<int>(pos_x_ + (WIDTH / 2));
|
||||||
collider_.y = static_cast<int>(pos_y_ + (HEIGHT_ / 2));
|
collider_.y = static_cast<int>(pos_y_ + (HEIGHT / 2));
|
||||||
}
|
}
|
||||||
|
|
||||||
// Pone las texturas del jugador
|
// Pone las texturas del jugador
|
||||||
@@ -772,7 +772,7 @@ void Player::decNameEntryCounter() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Obtiene la posición que se está editando del nombre del jugador para la tabla de mejores puntuaciones
|
// Obtiene la posición que se está editando del nombre del jugador para la tabla de mejores puntuaciones
|
||||||
int Player::getRecordNamePos() const {
|
auto Player::getRecordNamePos() const -> int {
|
||||||
if (enter_name_) {
|
if (enter_name_) {
|
||||||
return enter_name_->getPosition();
|
return enter_name_->getPosition();
|
||||||
}
|
}
|
||||||
|
|||||||
100
source/player.h
100
source/player.h
@@ -101,50 +101,50 @@ class Player {
|
|||||||
void decContinueCounter(); // Decrementa el contador de continuar
|
void decContinueCounter(); // Decrementa el contador de continuar
|
||||||
|
|
||||||
// --- Getters y comprobaciones de estado ---
|
// --- Getters y comprobaciones de estado ---
|
||||||
int getRecordNamePos() const; // Obtiene la posición que se está editando del nombre del jugador para la tabla de mejores puntuaciones
|
[[nodiscard]] auto getRecordNamePos() const -> int; // Obtiene la posición que se está editando del nombre del jugador para la tabla de mejores puntuaciones
|
||||||
|
|
||||||
// Comprobación de playing_state
|
// Comprobación de playing_state
|
||||||
bool isLyingOnTheFloorForever() const { return playing_state_ == PlayerState::LYING_ON_THE_FLOOR_FOREVER; }
|
[[nodiscard]] auto isLyingOnTheFloorForever() const -> bool { return playing_state_ == PlayerState::LYING_ON_THE_FLOOR_FOREVER; }
|
||||||
bool isCelebrating() const { return playing_state_ == PlayerState::CELEBRATING; }
|
[[nodiscard]] auto isCelebrating() const -> bool { return playing_state_ == PlayerState::CELEBRATING; }
|
||||||
bool isContinue() const { return playing_state_ == PlayerState::CONTINUE; }
|
[[nodiscard]] auto isContinue() const -> bool { return playing_state_ == PlayerState::CONTINUE; }
|
||||||
bool isDying() const { return playing_state_ == PlayerState::ROLLING; }
|
[[nodiscard]] auto isDying() const -> bool { return playing_state_ == PlayerState::ROLLING; }
|
||||||
bool isEnteringName() const { return playing_state_ == PlayerState::ENTERING_NAME; }
|
[[nodiscard]] auto isEnteringName() const -> bool { return playing_state_ == PlayerState::ENTERING_NAME; }
|
||||||
bool isShowingName() const { return playing_state_ == PlayerState::SHOWING_NAME; }
|
[[nodiscard]] auto isShowingName() const -> bool { return playing_state_ == PlayerState::SHOWING_NAME; }
|
||||||
bool isEnteringNameGameCompleted() const { return playing_state_ == PlayerState::ENTERING_NAME_GAME_COMPLETED; }
|
[[nodiscard]] auto isEnteringNameGameCompleted() const -> bool { return playing_state_ == PlayerState::ENTERING_NAME_GAME_COMPLETED; }
|
||||||
bool isLeavingScreen() const { return playing_state_ == PlayerState::LEAVING_SCREEN; }
|
[[nodiscard]] auto isLeavingScreen() const -> bool { return playing_state_ == PlayerState::LEAVING_SCREEN; }
|
||||||
bool isGameOver() const { return playing_state_ == PlayerState::GAME_OVER; }
|
[[nodiscard]] auto isGameOver() const -> bool { return playing_state_ == PlayerState::GAME_OVER; }
|
||||||
bool isPlaying() const { return playing_state_ == PlayerState::PLAYING; }
|
[[nodiscard]] auto isPlaying() const -> bool { return playing_state_ == PlayerState::PLAYING; }
|
||||||
bool isWaiting() const { return playing_state_ == PlayerState::WAITING; }
|
[[nodiscard]] auto isWaiting() const -> bool { return playing_state_ == PlayerState::WAITING; }
|
||||||
bool isTitleHidden() const { return playing_state_ == PlayerState::TITLE_HIDDEN; }
|
[[nodiscard]] auto isTitleHidden() const -> bool { return playing_state_ == PlayerState::TITLE_HIDDEN; }
|
||||||
|
|
||||||
// Getters
|
// Getters
|
||||||
bool canFire() const { return cant_fire_counter_ <= 0; }
|
[[nodiscard]] auto canFire() const -> bool { return cant_fire_counter_ <= 0; }
|
||||||
bool hasExtraHit() const { return extra_hit_; }
|
[[nodiscard]] auto hasExtraHit() const -> bool { return extra_hit_; }
|
||||||
bool isCooling() const { return firing_state_ == PlayerState::COOLING_LEFT || firing_state_ == PlayerState::COOLING_UP || firing_state_ == PlayerState::COOLING_RIGHT; }
|
[[nodiscard]] auto isCooling() const -> bool { return firing_state_ == PlayerState::COOLING_LEFT || firing_state_ == PlayerState::COOLING_UP || firing_state_ == PlayerState::COOLING_RIGHT; }
|
||||||
bool isRecoiling() const { return firing_state_ == PlayerState::RECOILING_LEFT || firing_state_ == PlayerState::RECOILING_UP || firing_state_ == PlayerState::RECOILING_RIGHT; }
|
[[nodiscard]] auto isRecoiling() const -> bool { return firing_state_ == PlayerState::RECOILING_LEFT || firing_state_ == PlayerState::RECOILING_UP || firing_state_ == PlayerState::RECOILING_RIGHT; }
|
||||||
bool IsEligibleForHighScore() const { return score_ > Options::settings.hi_score_table.back().score; }
|
[[nodiscard]] auto isEligibleForHighScore() const -> bool { return score_ > Options::settings.hi_score_table.back().score; }
|
||||||
bool isInvulnerable() const { return invulnerable_; }
|
[[nodiscard]] auto isInvulnerable() const -> bool { return invulnerable_; }
|
||||||
bool isPowerUp() const { return power_up_; }
|
[[nodiscard]] auto isPowerUp() const -> bool { return power_up_; }
|
||||||
Circle &getCollider() { return collider_; }
|
auto getCollider() -> Circle & { return collider_; }
|
||||||
float getScoreMultiplier() const { return score_multiplier_; }
|
[[nodiscard]] auto getScoreMultiplier() const -> float { return score_multiplier_; }
|
||||||
int getCoffees() const { return coffees_; }
|
[[nodiscard]] auto getCoffees() const -> int { return coffees_; }
|
||||||
int getContinueCounter() const { return continue_counter_; }
|
[[nodiscard]] auto getContinueCounter() const -> int { return continue_counter_; }
|
||||||
int getController() const { return controller_index_; }
|
[[nodiscard]] auto getController() const -> int { return controller_index_; }
|
||||||
int getHeight() const { return HEIGHT_; }
|
[[nodiscard]] auto getHeight() const -> int { return HEIGHT; }
|
||||||
int getId() const { return id_; }
|
[[nodiscard]] auto getId() const -> int { return id_; }
|
||||||
int getInvulnerableCounter() const { return invulnerable_counter_; }
|
[[nodiscard]] auto getInvulnerableCounter() const -> int { return invulnerable_counter_; }
|
||||||
int getPosX() const { return static_cast<int>(pos_x_); }
|
[[nodiscard]] auto getPosX() const -> int { return static_cast<int>(pos_x_); }
|
||||||
int getPosY() const { return pos_y_; }
|
[[nodiscard]] auto getPosY() const -> int { return pos_y_; }
|
||||||
int getPowerUpCounter() const { return power_up_counter_; }
|
[[nodiscard]] auto getPowerUpCounter() const -> int { return power_up_counter_; }
|
||||||
std::string getRecordName() const { return enter_name_ ? enter_name_->getFinalName() : "xxx"; }
|
[[nodiscard]] auto getRecordName() const -> std::string { return enter_name_ ? enter_name_->getFinalName() : "xxx"; }
|
||||||
std::string getLastEnterName() const { return last_enter_name_; }
|
[[nodiscard]] auto getLastEnterName() const -> std::string { return last_enter_name_; }
|
||||||
int getScore() const { return score_; }
|
[[nodiscard]] auto getScore() const -> int { return score_; }
|
||||||
int getScoreBoardPanel() const { return scoreboard_panel_; }
|
[[nodiscard]] auto getScoreBoardPanel() const -> int { return scoreboard_panel_; }
|
||||||
int getWidth() const { return WIDTH_; }
|
[[nodiscard]] auto getWidth() const -> int { return WIDTH; }
|
||||||
PlayerState getPlayingState() const { return playing_state_; }
|
[[nodiscard]] auto getPlayingState() const -> PlayerState { return playing_state_; }
|
||||||
const std::string &getName() const { return name_; }
|
[[nodiscard]] auto getName() const -> const std::string & { return name_; }
|
||||||
bool get1CC() const { return game_completed_ && credits_used_ == 1; }
|
[[nodiscard]] auto get1CC() const -> bool { return game_completed_ && credits_used_ == 1; }
|
||||||
bool getEnterNamePositionOverflow() const { return enter_name_ ? enter_name_->getPositionOverflow() : false; }
|
[[nodiscard]] auto getEnterNamePositionOverflow() const -> bool { return enter_name_ ? enter_name_->getPositionOverflow() : false; }
|
||||||
|
|
||||||
// Setters inline
|
// Setters inline
|
||||||
void setController(int index) { controller_index_ = index; }
|
void setController(int index) { controller_index_ = index; }
|
||||||
@@ -161,13 +161,13 @@ class Player {
|
|||||||
|
|
||||||
private:
|
private:
|
||||||
// --- Constantes ---
|
// --- Constantes ---
|
||||||
static constexpr int POWERUP_COUNTER_ = 1500; // Duración del estado PowerUp
|
static constexpr int POWERUP_COUNTER = 1500; // Duración del estado PowerUp
|
||||||
static constexpr int INVULNERABLE_COUNTER_ = 200; // Duración del estado invulnerable
|
static constexpr int INVULNERABLE_COUNTER = 200; // Duración del estado invulnerable
|
||||||
static constexpr int WIDTH_ = 30; // Anchura
|
static constexpr int WIDTH = 30; // Anchura
|
||||||
static constexpr int HEIGHT_ = 30; // Altura
|
static constexpr int HEIGHT = 30; // Altura
|
||||||
static constexpr float BASE_SPEED_ = 1.5f; // Velocidad base del jugador
|
static constexpr float BASE_SPEED = 1.5f; // Velocidad base del jugador
|
||||||
static constexpr int COOLING_DURATION_ = 50;
|
static constexpr int COOLING_DURATION = 50;
|
||||||
static constexpr int COOLING_COMPLETE_ = 0;
|
static constexpr int COOLING_COMPLETE = 0;
|
||||||
|
|
||||||
// --- Objetos y punteros ---
|
// --- Objetos y punteros ---
|
||||||
std::unique_ptr<AnimatedSprite> player_sprite_; // Sprite para dibujar el jugador
|
std::unique_ptr<AnimatedSprite> player_sprite_; // Sprite para dibujar el jugador
|
||||||
@@ -193,11 +193,11 @@ class Player {
|
|||||||
PlayerState firing_state_ = PlayerState::FIRING_NONE; // Estado del jugador al disparar
|
PlayerState firing_state_ = PlayerState::FIRING_NONE; // Estado del jugador al disparar
|
||||||
PlayerState playing_state_ = PlayerState::WAITING; // Estado del jugador en el juego
|
PlayerState playing_state_ = PlayerState::WAITING; // Estado del jugador en el juego
|
||||||
bool invulnerable_ = true; // Indica si el jugador es invulnerable
|
bool invulnerable_ = true; // Indica si el jugador es invulnerable
|
||||||
int invulnerable_counter_ = INVULNERABLE_COUNTER_; // Contador para la invulnerabilidad
|
int invulnerable_counter_ = INVULNERABLE_COUNTER; // Contador para la invulnerabilidad
|
||||||
bool extra_hit_ = false; // Indica si el jugador tiene un toque extra
|
bool extra_hit_ = false; // Indica si el jugador tiene un toque extra
|
||||||
int coffees_ = 0; // Indica cuántos cafés lleva acumulados
|
int coffees_ = 0; // Indica cuántos cafés lleva acumulados
|
||||||
bool power_up_ = false; // Indica si el jugador tiene activo el modo PowerUp
|
bool power_up_ = false; // Indica si el jugador tiene activo el modo PowerUp
|
||||||
int power_up_counter_ = POWERUP_COUNTER_; // Temporizador para el modo PowerUp
|
int power_up_counter_ = POWERUP_COUNTER; // Temporizador para el modo PowerUp
|
||||||
int power_up_desp_x_ = 0; // Desplazamiento del sprite de PowerUp respecto al sprite del jugador
|
int power_up_desp_x_ = 0; // Desplazamiento del sprite de PowerUp respecto al sprite del jugador
|
||||||
Circle collider_ = Circle(0, 0, 9); // Círculo de colisión del jugador
|
Circle collider_ = Circle(0, 0, 9); // Círculo de colisión del jugador
|
||||||
int continue_counter_ = 10; // Contador para poder continuar
|
int continue_counter_ = 10; // Contador para poder continuar
|
||||||
@@ -226,6 +226,6 @@ class Player {
|
|||||||
void updateScoreboard(); // Actualiza el panel del marcador
|
void updateScoreboard(); // Actualiza el panel del marcador
|
||||||
void setScoreboardMode(ScoreboardMode mode); // Cambia el modo del marcador
|
void setScoreboardMode(ScoreboardMode mode); // Cambia el modo del marcador
|
||||||
void playSound(const std::string &name); // Hace sonar un sonido
|
void playSound(const std::string &name); // Hace sonar un sonido
|
||||||
bool isRenderable() const { return !isWaiting() && !isGameOver() && !isTitleHidden(); }
|
[[nodiscard]] auto isRenderable() const -> bool { return !isWaiting() && !isGameOver() && !isTitleHidden(); }
|
||||||
void addScoreToScoreBoard(); // Añade una puntuación a la tabla de records
|
void addScoreToScoreBoard(); // Añade una puntuación a la tabla de records
|
||||||
};
|
};
|
||||||
@@ -1,11 +1,12 @@
|
|||||||
#include "resource.h"
|
#include "resource.h"
|
||||||
|
|
||||||
#include <SDL3/SDL.h> // Para SDL_LogInfo, SDL_LogCategory, SDL_L...
|
#include <SDL3/SDL.h> // Para SDL_LogInfo, SDL_LogCategory, SDL_L...
|
||||||
#include <stdlib.h> // Para exit
|
|
||||||
|
|
||||||
#include <algorithm> // Para find_if
|
#include <algorithm> // Para find_if
|
||||||
#include <array> // Para array
|
#include <array> // Para array
|
||||||
|
#include <cstdlib> // Para exit
|
||||||
#include <stdexcept> // Para runtime_error
|
#include <stdexcept> // Para runtime_error
|
||||||
|
#include <utility>
|
||||||
|
|
||||||
#include "asset.h" // Para Asset, AssetType
|
#include "asset.h" // Para Asset, AssetType
|
||||||
#include "external/jail_audio.h" // Para JA_DeleteMusic, JA_DeleteSound, JA_...
|
#include "external/jail_audio.h" // Para JA_DeleteMusic, JA_DeleteSound, JA_...
|
||||||
@@ -18,16 +19,16 @@ struct JA_Music_t; // lines 11-11
|
|||||||
struct JA_Sound_t; // lines 12-12
|
struct JA_Sound_t; // lines 12-12
|
||||||
|
|
||||||
// Singleton
|
// Singleton
|
||||||
Resource *Resource::instance_ = nullptr;
|
Resource *Resource::instance = nullptr;
|
||||||
|
|
||||||
// Inicializa la instancia única del singleton
|
// Inicializa la instancia única del singleton
|
||||||
void Resource::init() { Resource::instance_ = new Resource(); }
|
void Resource::init() { Resource::instance = new Resource(); }
|
||||||
|
|
||||||
// Libera la instancia
|
// Libera la instancia
|
||||||
void Resource::destroy() { delete Resource::instance_; }
|
void Resource::destroy() { delete Resource::instance; }
|
||||||
|
|
||||||
// Obtiene la instancia
|
// Obtiene la instancia
|
||||||
Resource *Resource::get() { return Resource::instance_; }
|
auto Resource::get() -> Resource * { return Resource::instance; }
|
||||||
|
|
||||||
// Constructor
|
// Constructor
|
||||||
Resource::Resource() : loading_text_(Screen::get()->getText()) { load(); }
|
Resource::Resource() : loading_text_(Screen::get()->getText()) { load(); }
|
||||||
@@ -87,7 +88,7 @@ void Resource::reloadTextures() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Obtiene el sonido a partir de un nombre. Lanza excepción si no existe.
|
// Obtiene el sonido a partir de un nombre. Lanza excepción si no existe.
|
||||||
JA_Sound_t *Resource::getSound(const std::string &name) {
|
auto Resource::getSound(const std::string &name) -> JA_Sound_t * {
|
||||||
auto it = std::find_if(sounds_.begin(), sounds_.end(), [&name](const auto &s) { return s.name == name; });
|
auto it = std::find_if(sounds_.begin(), sounds_.end(), [&name](const auto &s) { return s.name == name; });
|
||||||
|
|
||||||
if (it != sounds_.end()) {
|
if (it != sounds_.end()) {
|
||||||
@@ -99,7 +100,7 @@ JA_Sound_t *Resource::getSound(const std::string &name) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Obtiene la música a partir de un nombre. Lanza excepción si no existe.
|
// Obtiene la música a partir de un nombre. Lanza excepción si no existe.
|
||||||
JA_Music_t *Resource::getMusic(const std::string &name) {
|
auto Resource::getMusic(const std::string &name) -> JA_Music_t * {
|
||||||
auto it = std::find_if(musics_.begin(), musics_.end(), [&name](const auto &m) { return m.name == name; });
|
auto it = std::find_if(musics_.begin(), musics_.end(), [&name](const auto &m) { return m.name == name; });
|
||||||
|
|
||||||
if (it != musics_.end()) {
|
if (it != musics_.end()) {
|
||||||
@@ -111,7 +112,7 @@ JA_Music_t *Resource::getMusic(const std::string &name) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Obtiene la textura a partir de un nombre. Lanza excepción si no existe.
|
// Obtiene la textura a partir de un nombre. Lanza excepción si no existe.
|
||||||
std::shared_ptr<Texture> Resource::getTexture(const std::string &name) {
|
auto Resource::getTexture(const std::string &name) -> std::shared_ptr<Texture> {
|
||||||
auto it = std::find_if(textures_.begin(), textures_.end(), [&name](const auto &t) { return t.name == name; });
|
auto it = std::find_if(textures_.begin(), textures_.end(), [&name](const auto &t) { return t.name == name; });
|
||||||
|
|
||||||
if (it != textures_.end()) {
|
if (it != textures_.end()) {
|
||||||
@@ -123,7 +124,7 @@ std::shared_ptr<Texture> Resource::getTexture(const std::string &name) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Obtiene el fichero de texto a partir de un nombre. Lanza excepción si no existe.
|
// Obtiene el fichero de texto a partir de un nombre. Lanza excepción si no existe.
|
||||||
std::shared_ptr<TextFile> Resource::getTextFile(const std::string &name) {
|
auto Resource::getTextFile(const std::string &name) -> std::shared_ptr<TextFile> {
|
||||||
auto it = std::find_if(text_files_.begin(), text_files_.end(), [&name](const auto &t) { return t.name == name; });
|
auto it = std::find_if(text_files_.begin(), text_files_.end(), [&name](const auto &t) { return t.name == name; });
|
||||||
|
|
||||||
if (it != text_files_.end()) {
|
if (it != text_files_.end()) {
|
||||||
@@ -135,7 +136,7 @@ std::shared_ptr<TextFile> Resource::getTextFile(const std::string &name) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Obtiene el objeto de texto a partir de un nombre. Lanza excepción si no existe.
|
// Obtiene el objeto de texto a partir de un nombre. Lanza excepción si no existe.
|
||||||
std::shared_ptr<Text> Resource::getText(const std::string &name) {
|
auto Resource::getText(const std::string &name) -> std::shared_ptr<Text> {
|
||||||
auto it = std::find_if(texts_.begin(), texts_.end(), [&name](const auto &t) { return t.name == name; });
|
auto it = std::find_if(texts_.begin(), texts_.end(), [&name](const auto &t) { return t.name == name; });
|
||||||
|
|
||||||
if (it != texts_.end()) {
|
if (it != texts_.end()) {
|
||||||
@@ -147,7 +148,7 @@ std::shared_ptr<Text> Resource::getText(const std::string &name) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Obtiene la animación a partir de un nombre. Lanza excepción si no existe.
|
// Obtiene la animación a partir de un nombre. Lanza excepción si no existe.
|
||||||
AnimationsFileBuffer &Resource::getAnimation(const std::string &name) {
|
auto Resource::getAnimation(const std::string &name) -> AnimationsFileBuffer & {
|
||||||
auto it = std::find_if(animations_.begin(), animations_.end(), [&name](const auto &a) { return a.name == name; });
|
auto it = std::find_if(animations_.begin(), animations_.end(), [&name](const auto &a) { return a.name == name; });
|
||||||
|
|
||||||
if (it != animations_.end()) {
|
if (it != animations_.end()) {
|
||||||
@@ -159,7 +160,7 @@ AnimationsFileBuffer &Resource::getAnimation(const std::string &name) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Obtiene el fichero con los datos para el modo demostración a partir de un índice
|
// Obtiene el fichero con los datos para el modo demostración a partir de un índice
|
||||||
DemoData &Resource::getDemoData(int index) {
|
auto Resource::getDemoData(int index) -> DemoData & {
|
||||||
return demos_.at(index);
|
return demos_.at(index);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -172,7 +173,7 @@ void Resource::loadSounds() {
|
|||||||
for (const auto &l : list) {
|
for (const auto &l : list) {
|
||||||
auto name = getFileName(l);
|
auto name = getFileName(l);
|
||||||
updateLoadingProgress(name);
|
updateLoadingProgress(name);
|
||||||
sounds_.emplace_back(Resource::ResourceSound(name, JA_LoadSound(l.c_str())));
|
sounds_.emplace_back(name, JA_LoadSound(l.c_str()));
|
||||||
printWithDots("Sound : ", name, "[ LOADED ]");
|
printWithDots("Sound : ", name, "[ LOADED ]");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -186,7 +187,7 @@ void Resource::loadMusics() {
|
|||||||
for (const auto &l : list) {
|
for (const auto &l : list) {
|
||||||
auto name = getFileName(l);
|
auto name = getFileName(l);
|
||||||
updateLoadingProgress(name);
|
updateLoadingProgress(name);
|
||||||
musics_.emplace_back(Resource::ResourceMusic(name, JA_LoadMusic(l.c_str())));
|
musics_.emplace_back(name, JA_LoadMusic(l.c_str()));
|
||||||
printWithDots("Music : ", name, "[ LOADED ]");
|
printWithDots("Music : ", name, "[ LOADED ]");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -200,7 +201,7 @@ void Resource::loadTextures() {
|
|||||||
for (const auto &l : list) {
|
for (const auto &l : list) {
|
||||||
auto name = getFileName(l);
|
auto name = getFileName(l);
|
||||||
updateLoadingProgress(name);
|
updateLoadingProgress(name);
|
||||||
textures_.emplace_back(Resource::ResourceTexture(name, std::make_shared<Texture>(Screen::get()->getRenderer(), l)));
|
textures_.emplace_back(name, std::make_shared<Texture>(Screen::get()->getRenderer(), l));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -213,7 +214,7 @@ void Resource::loadTextFiles() {
|
|||||||
for (const auto &l : list) {
|
for (const auto &l : list) {
|
||||||
auto name = getFileName(l);
|
auto name = getFileName(l);
|
||||||
updateLoadingProgress(name);
|
updateLoadingProgress(name);
|
||||||
text_files_.emplace_back(Resource::ResourceTextFile(name, loadTextFile(l)));
|
text_files_.emplace_back(name, loadTextFile(l));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -226,7 +227,7 @@ void Resource::loadAnimations() {
|
|||||||
for (const auto &l : list) {
|
for (const auto &l : list) {
|
||||||
auto name = getFileName(l);
|
auto name = getFileName(l);
|
||||||
updateLoadingProgress(name);
|
updateLoadingProgress(name);
|
||||||
animations_.emplace_back(Resource::ResourceAnimation(name, loadAnimationsFromFile(l)));
|
animations_.emplace_back(name, loadAnimationsFromFile(l));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -263,8 +264,8 @@ void Resource::createTextures() {
|
|||||||
std::string name;
|
std::string name;
|
||||||
std::string text;
|
std::string text;
|
||||||
|
|
||||||
NameAndText(const std::string &name_init, const std::string &text_init)
|
NameAndText(std::string name_init, std::string text_init)
|
||||||
: name(name_init), text(text_init) {}
|
: name(std::move(name_init)), text(std::move(text_init)) {}
|
||||||
};
|
};
|
||||||
|
|
||||||
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "\n>> CREATING TEXTURES");
|
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "\n>> CREATING TEXTURES");
|
||||||
@@ -281,7 +282,7 @@ void Resource::createTextures() {
|
|||||||
|
|
||||||
auto text = getText("04b_25");
|
auto text = getText("04b_25");
|
||||||
for (const auto &s : strings) {
|
for (const auto &s : strings) {
|
||||||
textures_.emplace_back(Resource::ResourceTexture(s.name, text->writeToTexture(s.text, 1, -2)));
|
textures_.emplace_back(s.name, text->writeToTexture(s.text, 1, -2));
|
||||||
printWithDots("Texture : ", s.name, "[ DONE ]");
|
printWithDots("Texture : ", s.name, "[ DONE ]");
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -295,7 +296,7 @@ void Resource::createTextures() {
|
|||||||
|
|
||||||
auto text2 = getText("04b_25_2x");
|
auto text2 = getText("04b_25_2x");
|
||||||
for (const auto &s : strings2_x) {
|
for (const auto &s : strings2_x) {
|
||||||
textures_.emplace_back(Resource::ResourceTexture(s.name, text2->writeToTexture(s.text, 1, -4)));
|
textures_.emplace_back(s.name, text2->writeToTexture(s.text, 1, -4));
|
||||||
printWithDots("Texture : ", s.name, "[ DONE ]");
|
printWithDots("Texture : ", s.name, "[ DONE ]");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -307,8 +308,8 @@ void Resource::createText() {
|
|||||||
std::string texture_file;
|
std::string texture_file;
|
||||||
std::string text_file;
|
std::string text_file;
|
||||||
|
|
||||||
ResourceInfo(const std::string &k, const std::string &t_file, const std::string &txt_file)
|
ResourceInfo(std::string k, std::string t_file, std::string txt_file)
|
||||||
: key(k), texture_file(t_file), text_file(txt_file) {}
|
: key(std::move(k)), texture_file(std::move(t_file)), text_file(std::move(txt_file)) {}
|
||||||
};
|
};
|
||||||
|
|
||||||
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "\n>> CREATING TEXT OBJECTS");
|
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "\n>> CREATING TEXT OBJECTS");
|
||||||
@@ -328,7 +329,7 @@ void Resource::createText() {
|
|||||||
{"smb2_grad", "smb2_grad.png", "smb2.txt"}};
|
{"smb2_grad", "smb2_grad.png", "smb2.txt"}};
|
||||||
|
|
||||||
for (const auto &resource : resources) {
|
for (const auto &resource : resources) {
|
||||||
texts_.emplace_back(Resource::ResourceText(resource.key, std::make_shared<Text>(getTexture(resource.texture_file), getTextFile(resource.text_file))));
|
texts_.emplace_back(resource.key, std::make_shared<Text>(getTexture(resource.texture_file), getTextFile(resource.text_file)));
|
||||||
printWithDots("Text : ", resource.key, "[ DONE ]");
|
printWithDots("Text : ", resource.key, "[ DONE ]");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
#include <SDL3/SDL.h> // Para SDL_FRect
|
#include <SDL3/SDL.h> // Para SDL_FRect
|
||||||
#include <stddef.h> // Para size_t
|
|
||||||
|
|
||||||
|
#include <cstddef> // Para size_t
|
||||||
#include <memory> // Para shared_ptr
|
#include <memory> // Para shared_ptr
|
||||||
#include <string> // Para basic_string, string
|
#include <string> // Para basic_string, string
|
||||||
#include <utility>
|
#include <utility>
|
||||||
@@ -146,5 +146,5 @@ class Resource {
|
|||||||
~Resource(); // Destructor privado
|
~Resource(); // Destructor privado
|
||||||
|
|
||||||
// --- Instancia singleton ---
|
// --- Instancia singleton ---
|
||||||
static Resource *instance_; // Instancia única de Resource
|
static Resource *instance; // Instancia única de Resource
|
||||||
};
|
};
|
||||||
@@ -1,8 +1,8 @@
|
|||||||
#include "scoreboard.h"
|
#include "scoreboard.h"
|
||||||
|
|
||||||
#include <SDL3/SDL.h> // Para SDL_DestroyTexture, SDL_SetRenderDrawColor
|
#include <SDL3/SDL.h> // Para SDL_DestroyTexture, SDL_SetRenderDrawColor
|
||||||
#include <math.h> // Para roundf
|
|
||||||
|
|
||||||
|
#include <cmath> // Para roundf
|
||||||
#include <iomanip> // Para operator<<, setfill, setw
|
#include <iomanip> // Para operator<<, setfill, setw
|
||||||
#include <sstream> // Para basic_ostringstream, basic_ostream, basic_os...
|
#include <sstream> // Para basic_ostringstream, basic_ostream, basic_os...
|
||||||
|
|
||||||
@@ -16,21 +16,21 @@
|
|||||||
#include "texture.h" // Para Texture
|
#include "texture.h" // Para Texture
|
||||||
|
|
||||||
// [SINGLETON] Hay que definir las variables estáticas, desde el .h sólo la hemos declarado
|
// [SINGLETON] Hay que definir las variables estáticas, desde el .h sólo la hemos declarado
|
||||||
Scoreboard *Scoreboard::scoreboard_ = nullptr;
|
Scoreboard *Scoreboard::instance = nullptr;
|
||||||
|
|
||||||
// [SINGLETON] Crearemos el objeto score_board con esta función estática
|
// [SINGLETON] Crearemos el objeto score_board con esta función estática
|
||||||
void Scoreboard::init() {
|
void Scoreboard::init() {
|
||||||
Scoreboard::scoreboard_ = new Scoreboard();
|
Scoreboard::instance = new Scoreboard();
|
||||||
}
|
}
|
||||||
|
|
||||||
// [SINGLETON] Destruiremos el objeto score_board con esta función estática
|
// [SINGLETON] Destruiremos el objeto score_board con esta función estática
|
||||||
void Scoreboard::destroy() {
|
void Scoreboard::destroy() {
|
||||||
delete Scoreboard::scoreboard_;
|
delete Scoreboard::instance;
|
||||||
}
|
}
|
||||||
|
|
||||||
// [SINGLETON] Con este método obtenemos el objeto score_board y podemos trabajar con él
|
// [SINGLETON] Con este método obtenemos el objeto score_board y podemos trabajar con él
|
||||||
Scoreboard *Scoreboard::get() {
|
auto Scoreboard::get() -> Scoreboard * {
|
||||||
return Scoreboard::scoreboard_;
|
return Scoreboard::instance;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Constructor
|
// Constructor
|
||||||
@@ -88,7 +88,7 @@ Scoreboard::~Scoreboard() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Transforma un valor numérico en una cadena de 7 cifras
|
// Transforma un valor numérico en una cadena de 7 cifras
|
||||||
std::string Scoreboard::updateScoreText(int num) {
|
auto Scoreboard::updateScoreText(int num) -> std::string {
|
||||||
std::ostringstream oss;
|
std::ostringstream oss;
|
||||||
oss << std::setw(7) << std::setfill('0') << num;
|
oss << std::setw(7) << std::setfill('0') << num;
|
||||||
return oss.str();
|
return oss.str();
|
||||||
@@ -385,8 +385,8 @@ void Scoreboard::createPanelTextures() {
|
|||||||
panel_texture_.clear();
|
panel_texture_.clear();
|
||||||
|
|
||||||
// Crea las texturas para cada panel_
|
// Crea las texturas para cada panel_
|
||||||
for (int i = 0; i < SCOREBOARD_MAX_PANELS; ++i) {
|
for (auto &i : panel_) {
|
||||||
SDL_Texture *tex = SDL_CreateTexture(renderer_, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, panel_[i].pos.w, panel_[i].pos.h);
|
SDL_Texture *tex = SDL_CreateTexture(renderer_, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, i.pos.w, i.pos.h);
|
||||||
SDL_SetTextureBlendMode(tex, SDL_BLENDMODE_BLEND);
|
SDL_SetTextureBlendMode(tex, SDL_BLENDMODE_BLEND);
|
||||||
panel_texture_.push_back(tex);
|
panel_texture_.push_back(tex);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
#include <SDL3/SDL.h> // Para SDL_FPoint, SDL_GetTicks, SDL_FRect, SDL_Texture, SDL_Renderer, Uint64
|
#include <SDL3/SDL.h> // Para SDL_FPoint, SDL_GetTicks, SDL_FRect, SDL_Texture, SDL_Renderer, Uint64
|
||||||
#include <stddef.h> // Para size_t
|
|
||||||
|
|
||||||
|
#include <cstddef> // Para size_t
|
||||||
#include <memory> // Para shared_ptr, unique_ptr
|
#include <memory> // Para shared_ptr, unique_ptr
|
||||||
#include <string> // Para basic_string, string
|
#include <string> // Para basic_string, string
|
||||||
#include <vector> // Para vector
|
#include <vector> // Para vector
|
||||||
@@ -45,7 +45,7 @@ class Scoreboard {
|
|||||||
// --- Métodos de singleton ---
|
// --- Métodos de singleton ---
|
||||||
static void init(); // Crea el objeto Scoreboard
|
static void init(); // Crea el objeto Scoreboard
|
||||||
static void destroy(); // Libera el objeto Scoreboard
|
static void destroy(); // Libera el objeto Scoreboard
|
||||||
static Scoreboard *get(); // Obtiene el puntero al objeto Scoreboard
|
static auto get() -> Scoreboard *; // Obtiene el puntero al objeto Scoreboard
|
||||||
|
|
||||||
// --- Métodos principales ---
|
// --- Métodos principales ---
|
||||||
void update(); // Actualiza la lógica del marcador
|
void update(); // Actualiza la lógica del marcador
|
||||||
@@ -67,9 +67,6 @@ class Scoreboard {
|
|||||||
void setStage(int stage) { stage_ = stage; }
|
void setStage(int stage) { stage_ = stage; }
|
||||||
|
|
||||||
private:
|
private:
|
||||||
// --- Singleton ---
|
|
||||||
static Scoreboard *scoreboard_;
|
|
||||||
|
|
||||||
// --- Objetos y punteros ---
|
// --- Objetos y punteros ---
|
||||||
SDL_Renderer *renderer_; // El renderizador de la ventana
|
SDL_Renderer *renderer_; // El renderizador de la ventana
|
||||||
std::shared_ptr<Texture> game_power_meter_texture_; // Textura con el marcador de poder de la fase
|
std::shared_ptr<Texture> game_power_meter_texture_; // Textura con el marcador de poder de la fase
|
||||||
@@ -106,7 +103,7 @@ class Scoreboard {
|
|||||||
|
|
||||||
// --- Métodos internos ---
|
// --- Métodos internos ---
|
||||||
void recalculateAnchors(); // Recalcula las anclas de los elementos
|
void recalculateAnchors(); // Recalcula las anclas de los elementos
|
||||||
std::string updateScoreText(int num); // Transforma un valor numérico en una cadena de 7 cifras
|
auto updateScoreText(int num) -> std::string; // Transforma un valor numérico en una cadena de 7 cifras
|
||||||
void createBackgroundTexture(); // Crea la textura de fondo
|
void createBackgroundTexture(); // Crea la textura de fondo
|
||||||
void createPanelTextures(); // Crea las texturas de los paneles
|
void createPanelTextures(); // Crea las texturas de los paneles
|
||||||
void fillPanelTextures(); // Rellena los diferentes paneles del marcador
|
void fillPanelTextures(); // Rellena los diferentes paneles del marcador
|
||||||
@@ -118,4 +115,7 @@ class Scoreboard {
|
|||||||
// --- Constructor y destructor privados (singleton) ---
|
// --- Constructor y destructor privados (singleton) ---
|
||||||
Scoreboard();
|
Scoreboard();
|
||||||
~Scoreboard();
|
~Scoreboard();
|
||||||
|
|
||||||
|
// --- Singleton ---
|
||||||
|
static Scoreboard *instance;
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -19,16 +19,16 @@
|
|||||||
#include "ui/service_menu.h" // Para ServiceMenu
|
#include "ui/service_menu.h" // Para ServiceMenu
|
||||||
|
|
||||||
// Singleton
|
// Singleton
|
||||||
Screen *Screen::instance_ = nullptr;
|
Screen *Screen::instance = nullptr;
|
||||||
|
|
||||||
// Inicializa la instancia única del singleton
|
// Inicializa la instancia única del singleton
|
||||||
void Screen::init() { Screen::instance_ = new Screen(); }
|
void Screen::init() { Screen::instance = new Screen(); }
|
||||||
|
|
||||||
// Libera la instancia
|
// Libera la instancia
|
||||||
void Screen::destroy() { delete Screen::instance_; }
|
void Screen::destroy() { delete Screen::instance; }
|
||||||
|
|
||||||
// Obtiene la instancia
|
// Obtiene la instancia
|
||||||
auto Screen::get() -> Screen * { return Screen::instance_; }
|
auto Screen::get() -> Screen * { return Screen::instance; }
|
||||||
|
|
||||||
// Constructor
|
// Constructor
|
||||||
Screen::Screen()
|
Screen::Screen()
|
||||||
@@ -214,7 +214,7 @@ void Screen::renderInfo() {
|
|||||||
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
|
// FPS
|
||||||
const std::string FPS_TEXT = std::to_string(fps_.lastValue) + " FPS";
|
const std::string FPS_TEXT = std::to_string(fps_.last_value) + " 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));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -254,7 +254,7 @@ void Screen::adjustWindowSize() {
|
|||||||
const int NEW_POS_X = old_pos_x + ((old_width - WIDTH) / 2);
|
const int NEW_POS_X = old_pos_x + ((old_width - WIDTH) / 2);
|
||||||
const int NEW_POS_Y = old_pos_y + ((old_height - HEIGHT) / 2);
|
const int NEW_POS_Y = old_pos_y + ((old_height - HEIGHT) / 2);
|
||||||
|
|
||||||
SDL_SetWindowPosition(window_, std::max(NEW_POS_X, WINDOWS_DECORATIONS_), std::max(NEW_POS_Y, 0));
|
SDL_SetWindowPosition(window_, std::max(NEW_POS_X, WINDOWS_DECORATIONS), std::max(NEW_POS_Y, 0));
|
||||||
SDL_SetWindowSize(window_, WIDTH, HEIGHT);
|
SDL_SetWindowSize(window_, WIDTH, HEIGHT);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -370,7 +370,7 @@ void Screen::getDisplayInfo() {
|
|||||||
std::to_string(static_cast<int>(dm->refresh_rate)) + " Hz";
|
std::to_string(static_cast<int>(dm->refresh_rate)) + " Hz";
|
||||||
|
|
||||||
// Calcula el máximo factor de zoom que se puede aplicar a la pantalla
|
// Calcula el máximo factor de zoom que se puede aplicar a la pantalla
|
||||||
const int MAX_ZOOM = std::min(dm->w / param.game.width, (dm->h - WINDOWS_DECORATIONS_) / param.game.height);
|
const int MAX_ZOOM = std::min(dm->w / param.game.width, (dm->h - WINDOWS_DECORATIONS) / param.game.height);
|
||||||
|
|
||||||
// Normaliza los valores de zoom
|
// Normaliza los valores de zoom
|
||||||
Options::window.size = std::min(Options::window.size, MAX_ZOOM);
|
Options::window.size = std::min(Options::window.size, MAX_ZOOM);
|
||||||
|
|||||||
@@ -18,7 +18,7 @@ class Screen {
|
|||||||
// --- Métodos de singleton ---
|
// --- Métodos de singleton ---
|
||||||
static void init(); // Inicializa el objeto Screen
|
static void init(); // Inicializa el objeto Screen
|
||||||
static void destroy(); // Libera el objeto Screen
|
static void destroy(); // Libera el objeto Screen
|
||||||
static Screen *get(); // Obtiene el puntero al objeto Screen
|
static auto get() -> Screen *; // Obtiene el puntero al objeto Screen
|
||||||
|
|
||||||
// --- Métodos principales ---
|
// --- Métodos principales ---
|
||||||
void update(); // Actualiza la lógica de la clase
|
void update(); // Actualiza la lógica de la clase
|
||||||
@@ -32,8 +32,8 @@ class Screen {
|
|||||||
void setFullscreenMode(); // Establece el modo de pantalla completa
|
void setFullscreenMode(); // Establece el modo de pantalla completa
|
||||||
void toggleFullscreen(); // Cambia entre pantalla completa y ventana
|
void toggleFullscreen(); // Cambia entre pantalla completa y ventana
|
||||||
void setWindowZoom(int size); // Cambia el tamaño de la ventana
|
void setWindowZoom(int size); // Cambia el tamaño de la ventana
|
||||||
bool decWindowSize(); // Reduce el tamaño de la ventana
|
auto decWindowSize() -> bool; // Reduce el tamaño de la ventana
|
||||||
bool incWindowSize(); // Aumenta el tamaño de la ventana
|
auto incWindowSize() -> bool; // Aumenta el tamaño de la ventana
|
||||||
void applySettings(); // Aplica los valores de las opciones
|
void applySettings(); // Aplica los valores de las opciones
|
||||||
void initShaders(); // Inicializa los shaders
|
void initShaders(); // Inicializa los shaders
|
||||||
|
|
||||||
@@ -47,12 +47,12 @@ class Screen {
|
|||||||
void attenuate(bool value) { attenuate_effect_ = value; } // Atenúa la pantalla
|
void attenuate(bool value) { attenuate_effect_ = value; } // Atenúa la pantalla
|
||||||
|
|
||||||
// --- Getters ---
|
// --- Getters ---
|
||||||
SDL_Renderer *getRenderer() { return renderer_; } // Obtiene el renderizador
|
auto getRenderer() -> SDL_Renderer * { return renderer_; } // Obtiene el renderizador
|
||||||
void show() { SDL_ShowWindow(window_); } // Muestra la ventana
|
void show() { SDL_ShowWindow(window_); } // Muestra la ventana
|
||||||
void hide() { SDL_HideWindow(window_); } // Oculta la ventana
|
void hide() { SDL_HideWindow(window_); } // Oculta la ventana
|
||||||
void getSingletons(); // Obtiene los punteros a los singletones
|
void getSingletons(); // Obtiene los punteros a los singletones
|
||||||
bool getVSync() const { return Options::video.v_sync; } // Obtiene el valor de V-Sync
|
[[nodiscard]] auto getVSync() const -> bool { return Options::video.v_sync; } // Obtiene el valor de V-Sync
|
||||||
std::shared_ptr<Text> getText() const { return text_; } // Obtiene el puntero al texto de Screen
|
[[nodiscard]] auto getText() const -> std::shared_ptr<Text> { return text_; } // Obtiene el puntero al texto de Screen
|
||||||
|
|
||||||
#ifdef DEBUG
|
#ifdef DEBUG
|
||||||
// --- Debug ---
|
// --- Debug ---
|
||||||
@@ -62,23 +62,23 @@ class Screen {
|
|||||||
|
|
||||||
private:
|
private:
|
||||||
// --- Constantes ---
|
// --- Constantes ---
|
||||||
static constexpr int WINDOWS_DECORATIONS_ = 35;
|
static constexpr int WINDOWS_DECORATIONS = 35;
|
||||||
|
|
||||||
// --- Estructuras internas ---
|
// --- Estructuras internas ---
|
||||||
struct FPS {
|
struct FPS {
|
||||||
Uint32 ticks; // Tiempo en milisegundos desde que se comenzó a contar.
|
Uint32 ticks{0}; // Tiempo en milisegundos desde que se comenzó a contar.
|
||||||
int frameCount; // Número acumulado de frames en el intervalo.
|
int frame_count{0}; // Número acumulado de frames en el intervalo.
|
||||||
int lastValue; // Número de frames calculado en el último segundo.
|
int last_value{0}; // Número de frames calculado en el último segundo.
|
||||||
|
|
||||||
FPS() : ticks(0), frameCount(0), lastValue(0) {}
|
FPS() {}
|
||||||
void increment() { frameCount++; }
|
void increment() { frame_count++; }
|
||||||
int calculate(Uint32 currentTicks) {
|
auto calculate(Uint32 current_ticks) -> int {
|
||||||
if (currentTicks - ticks >= 1000) {
|
if (current_ticks - ticks >= 1000) {
|
||||||
lastValue = frameCount;
|
last_value = frame_count;
|
||||||
frameCount = 0;
|
frame_count = 0;
|
||||||
ticks = currentTicks;
|
ticks = current_ticks;
|
||||||
}
|
}
|
||||||
return lastValue;
|
return last_value;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -94,7 +94,7 @@ class Screen {
|
|||||||
: enabled(enabled), lenght(lenght), delay(delay), counter(lenght), color(color) {}
|
: enabled(enabled), lenght(lenght), delay(delay), counter(lenght), color(color) {}
|
||||||
|
|
||||||
void update() { (enabled && counter > 0) ? counter-- : enabled = false; }
|
void update() { (enabled && counter > 0) ? counter-- : enabled = false; }
|
||||||
bool isRendarable() { return enabled && counter < lenght - delay; }
|
auto isRendarable() -> bool { return enabled && counter < lenght - delay; }
|
||||||
};
|
};
|
||||||
|
|
||||||
// Efecto de sacudida/agitación de pantalla: mueve la imagen para simular un temblor
|
// Efecto de sacudida/agitación de pantalla: mueve la imagen para simular un temblor
|
||||||
@@ -108,8 +108,8 @@ class Screen {
|
|||||||
int original_width; // Ancho original de la imagen
|
int original_width; // Ancho original de la imagen
|
||||||
bool enabled; // Indica si el efecto está activo
|
bool enabled; // Indica si el efecto está activo
|
||||||
|
|
||||||
explicit ShakeEffect(bool en = false, int dp = 2, int dl = 3, int cnt = 0, int len = 8, int rem = 0, int origPos = 0, int origWidth = 800)
|
explicit ShakeEffect(bool en = false, int dp = 2, int dl = 3, int cnt = 0, int len = 8, int rem = 0, int orig_pos = 0, int orig_width = 800)
|
||||||
: desp(dp), delay(dl), counter(cnt), lenght(len), remaining(rem), original_pos(origPos), original_width(origWidth), enabled(en) {}
|
: desp(dp), delay(dl), counter(cnt), lenght(len), remaining(rem), original_pos(orig_pos), original_width(orig_width), enabled(en) {}
|
||||||
|
|
||||||
// Activa el efecto de sacudida y guarda la posición y tamaño originales
|
// Activa el efecto de sacudida y guarda la posición y tamaño originales
|
||||||
void enable(SDL_FRect &src_rect, SDL_FRect &dst_rect, int new_desp = -1, int new_delay = -1, int new_lenght = -1) {
|
void enable(SDL_FRect &src_rect, SDL_FRect &dst_rect, int new_desp = -1, int new_delay = -1, int new_lenght = -1) {
|
||||||
@@ -156,7 +156,7 @@ class Screen {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
bool isEnabled() const { return enabled; }
|
[[nodiscard]] auto isEnabled() const -> bool { return enabled; }
|
||||||
};
|
};
|
||||||
|
|
||||||
#ifdef DEBUG
|
#ifdef DEBUG
|
||||||
@@ -168,7 +168,7 @@ class Screen {
|
|||||||
#endif
|
#endif
|
||||||
|
|
||||||
// --- Singleton ---
|
// --- Singleton ---
|
||||||
static Screen *instance_;
|
static Screen *instance;
|
||||||
|
|
||||||
// --- Objetos y punteros ---
|
// --- Objetos y punteros ---
|
||||||
SDL_Window *window_; // Ventana de la aplicación
|
SDL_Window *window_; // Ventana de la aplicación
|
||||||
@@ -193,7 +193,7 @@ class Screen {
|
|||||||
std::shared_ptr<Text> text_; // Objeto para escribir texto en pantalla
|
std::shared_ptr<Text> text_; // Objeto para escribir texto en pantalla
|
||||||
|
|
||||||
// --- Métodos internos ---
|
// --- Métodos internos ---
|
||||||
bool initSDLVideo(); // Arranca SDL VIDEO y crea la ventana
|
auto initSDLVideo() -> bool; // Arranca SDL VIDEO y crea la ventana
|
||||||
void renderFlash(); // Dibuja el efecto de flash en la pantalla
|
void renderFlash(); // Dibuja el efecto de flash en la pantalla
|
||||||
void renderShake(); // Aplica el efecto de agitar la pantalla
|
void renderShake(); // Aplica el efecto de agitar la pantalla
|
||||||
void renderInfo(); // Muestra información por pantalla
|
void renderInfo(); // Muestra información por pantalla
|
||||||
|
|||||||
@@ -170,9 +170,8 @@ void Credits::fillTextTexture() {
|
|||||||
const int TEXTS_HEIGHT = 1 * text->getCharacterSize() + 8 * SPACE_POST_TITLE + 3 * SPACE_PRE_TITLE;
|
const int TEXTS_HEIGHT = 1 * text->getCharacterSize() + 8 * SPACE_POST_TITLE + 3 * SPACE_PRE_TITLE;
|
||||||
credits_rect_dst_.h = credits_rect_src_.h = TEXTS_HEIGHT;
|
credits_rect_dst_.h = credits_rect_src_.h = TEXTS_HEIGHT;
|
||||||
|
|
||||||
int y = (param.game.height - TEXTS_HEIGHT) / 2;
|
|
||||||
// PROGRAMMED_AND_DESIGNED_BY
|
// PROGRAMMED_AND_DESIGNED_BY
|
||||||
y = 0;
|
int y = 0;
|
||||||
text_grad->writeDX(TEXT_CENTER | TEXT_SHADOW, param.game.game_area.center_x, y, TEXTS.at(0), 1, NO_TEXT_COLOR, 1, SHADOW_TEXT_COLOR);
|
text_grad->writeDX(TEXT_CENTER | TEXT_SHADOW, param.game.game_area.center_x, y, TEXTS.at(0), 1, NO_TEXT_COLOR, 1, SHADOW_TEXT_COLOR);
|
||||||
|
|
||||||
y += SPACE_POST_TITLE;
|
y += SPACE_POST_TITLE;
|
||||||
@@ -259,7 +258,7 @@ void Credits::fillCanvas() {
|
|||||||
// SDL_SetRenderDrawColor(Screen::get()->getRenderer(), 0xFF, 0, 0, 0xFF);
|
// SDL_SetRenderDrawColor(Screen::get()->getRenderer(), 0xFF, 0, 0, 0xFF);
|
||||||
const Color COLOR = color_.LIGHTEN();
|
const Color COLOR = color_.LIGHTEN();
|
||||||
SDL_SetRenderDrawColor(Screen::get()->getRenderer(), COLOR.r, COLOR.g, COLOR.b, 0xFF);
|
SDL_SetRenderDrawColor(Screen::get()->getRenderer(), COLOR.r, COLOR.g, COLOR.b, 0xFF);
|
||||||
SDL_RenderRect(Screen::get()->getRenderer(), &red_rect);
|
SDL_RenderRect(Screen::get()->getRenderer(), &border_rect_);
|
||||||
|
|
||||||
// Si el mini_logo está en su destino, lo dibuja encima de lo anterior
|
// Si el mini_logo está en su destino, lo dibuja encima de lo anterior
|
||||||
if (mini_logo_on_position_) {
|
if (mini_logo_on_position_) {
|
||||||
@@ -408,10 +407,10 @@ void Credits::updateBlackRects() {
|
|||||||
|
|
||||||
// Actualiza el rectangulo rojo
|
// Actualiza el rectangulo rojo
|
||||||
void Credits::updateRedRect() {
|
void Credits::updateRedRect() {
|
||||||
red_rect.x = left_black_rect_.x + left_black_rect_.w;
|
border_rect_.x = left_black_rect_.x + left_black_rect_.w;
|
||||||
red_rect.y = top_black_rect_.y + top_black_rect_.h - 1;
|
border_rect_.y = top_black_rect_.y + top_black_rect_.h - 1;
|
||||||
red_rect.w = right_black_rect_.x - red_rect.x;
|
border_rect_.w = right_black_rect_.x - border_rect_.x;
|
||||||
red_rect.h = bottom_black_rect_.y - red_rect.y + 1;
|
border_rect_.h = bottom_black_rect_.y - border_rect_.y + 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Actualiza el estado de fade
|
// Actualiza el estado de fade
|
||||||
@@ -452,9 +451,9 @@ void Credits::cycleColors() {
|
|||||||
constexpr int UPPER_LIMIT = 140; // Límite superior
|
constexpr int UPPER_LIMIT = 140; // Límite superior
|
||||||
constexpr int LOWER_LIMIT = 30; // Límite inferior
|
constexpr int LOWER_LIMIT = 30; // Límite inferior
|
||||||
|
|
||||||
static float r_ = static_cast<float>(UPPER_LIMIT);
|
static auto r_ = static_cast<float>(UPPER_LIMIT);
|
||||||
static float g_ = static_cast<float>(LOWER_LIMIT);
|
static auto g_ = static_cast<float>(LOWER_LIMIT);
|
||||||
static float b_ = static_cast<float>(LOWER_LIMIT);
|
static auto b_ = static_cast<float>(LOWER_LIMIT);
|
||||||
static float step_r_ = -0.5f; // Paso flotante para transiciones suaves
|
static float step_r_ = -0.5f; // Paso flotante para transiciones suaves
|
||||||
static float step_g_ = 0.3f;
|
static float step_g_ = 0.3f;
|
||||||
static float step_b_ = 0.1f;
|
static float step_b_ = 0.1f;
|
||||||
|
|||||||
@@ -98,7 +98,7 @@ class Credits {
|
|||||||
2};
|
2};
|
||||||
|
|
||||||
// Borde para la ventana
|
// Borde para la ventana
|
||||||
SDL_FRect red_rect = play_area_; // Delimitador de ventana
|
SDL_FRect border_rect_ = play_area_; // Delimitador de ventana
|
||||||
|
|
||||||
// --- Métodos del bucle principal ---
|
// --- Métodos del bucle principal ---
|
||||||
void update(); // Actualización principal de la lógica
|
void update(); // Actualización principal de la lógica
|
||||||
|
|||||||
@@ -1,9 +1,9 @@
|
|||||||
#include "game.h"
|
#include "game.h"
|
||||||
|
|
||||||
#include <SDL3/SDL.h> // Para SDL_GetTicks, SDL_SetRenderTarget
|
#include <SDL3/SDL.h> // Para SDL_GetTicks, SDL_SetRenderTarget
|
||||||
#include <stdlib.h> // Para rand, size_t
|
|
||||||
|
|
||||||
#include <algorithm> // Para find_if, clamp, find, min
|
#include <algorithm> // Para find_if, clamp, find, min
|
||||||
|
#include <cstdlib> // Para rand, size_t
|
||||||
#include <functional> // Para function
|
#include <functional> // Para function
|
||||||
#include <iterator> // Para distance, size
|
#include <iterator> // Para distance, size
|
||||||
|
|
||||||
@@ -283,7 +283,7 @@ void Game::updateGameStateGameOver() {
|
|||||||
cleanVectors();
|
cleanVectors();
|
||||||
|
|
||||||
if (game_over_counter_ > 0) {
|
if (game_over_counter_ > 0) {
|
||||||
if (game_over_counter_ == GAME_OVER_COUNTER_) {
|
if (game_over_counter_ == GAME_OVER_COUNTER) {
|
||||||
createMessage({paths_.at(2), paths_.at(3)}, Resource::get()->getTexture("game_text_game_over"));
|
createMessage({paths_.at(2), paths_.at(3)}, Resource::get()->getTexture("game_text_game_over"));
|
||||||
Audio::get()->fadeOutMusic(1000);
|
Audio::get()->fadeOutMusic(1000);
|
||||||
balloon_manager_->setBouncingSounds(true);
|
balloon_manager_->setBouncingSounds(true);
|
||||||
@@ -367,7 +367,7 @@ void Game::updateGameStateCompleted() {
|
|||||||
if (game_completed_counter_ == END_CELEBRATIONS) {
|
if (game_completed_counter_ == END_CELEBRATIONS) {
|
||||||
for (auto &player : players_) {
|
for (auto &player : players_) {
|
||||||
if (player->isCelebrating()) {
|
if (player->isCelebrating()) {
|
||||||
player->setPlayingState(player->IsEligibleForHighScore() ? PlayerState::ENTERING_NAME_GAME_COMPLETED : PlayerState::LEAVING_SCREEN);
|
player->setPlayingState(player->isEligibleForHighScore() ? PlayerState::ENTERING_NAME_GAME_COMPLETED : PlayerState::LEAVING_SCREEN);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -399,7 +399,7 @@ void Game::destroyAllItems() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Comprueba la colisión entre el jugador y los globos activos
|
// Comprueba la colisión entre el jugador y los globos activos
|
||||||
std::shared_ptr<Balloon> Game::checkPlayerBalloonCollision(std::shared_ptr<Player> &player) {
|
auto Game::checkPlayerBalloonCollision(std::shared_ptr<Player> &player) -> std::shared_ptr<Balloon> {
|
||||||
for (auto &balloon : balloon_manager_->getBalloons()) {
|
for (auto &balloon : balloon_manager_->getBalloons()) {
|
||||||
if (!balloon->isInvulnerable() && !balloon->isPowerBall()) {
|
if (!balloon->isInvulnerable() && !balloon->isPowerBall()) {
|
||||||
if (checkCollision(player->getCollider(), balloon->getCollider())) {
|
if (checkCollision(player->getCollider(), balloon->getCollider())) {
|
||||||
@@ -594,7 +594,7 @@ void Game::renderItems() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Devuelve un item al azar y luego segun sus probabilidades
|
// Devuelve un item al azar y luego segun sus probabilidades
|
||||||
ItemType Game::dropItem() {
|
auto Game::dropItem() -> ItemType {
|
||||||
const auto LUCKY_NUMBER = rand() % 100;
|
const auto LUCKY_NUMBER = rand() % 100;
|
||||||
const auto ITEM = rand() % 6;
|
const auto ITEM = rand() % 6;
|
||||||
|
|
||||||
@@ -621,7 +621,7 @@ ItemType Game::dropItem() {
|
|||||||
break;
|
break;
|
||||||
case 4:
|
case 4:
|
||||||
if (LUCKY_NUMBER < helper_.item_coffee_odds) {
|
if (LUCKY_NUMBER < helper_.item_coffee_odds) {
|
||||||
helper_.item_coffee_odds = ITEM_COFFEE_ODDS_;
|
helper_.item_coffee_odds = ITEM_COFFEE_ODDS;
|
||||||
return ItemType::COFFEE;
|
return ItemType::COFFEE;
|
||||||
} else {
|
} else {
|
||||||
if (helper_.need_coffee) {
|
if (helper_.need_coffee) {
|
||||||
@@ -631,7 +631,7 @@ ItemType Game::dropItem() {
|
|||||||
break;
|
break;
|
||||||
case 5:
|
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_;
|
helper_.item_coffee_machine_odds = ITEM_COFFEE_MACHINE_ODDS;
|
||||||
if (!coffee_machine_enabled_ && helper_.need_coffee_machine) {
|
if (!coffee_machine_enabled_ && helper_.need_coffee_machine) {
|
||||||
return ItemType::COFFEE_MACHINE;
|
return ItemType::COFFEE_MACHINE;
|
||||||
}
|
}
|
||||||
@@ -786,7 +786,7 @@ void Game::handlePlayerCollision(std::shared_ptr<Player> &player) {
|
|||||||
screen_->shake();
|
screen_->shake();
|
||||||
playSound("voice_no.wav");
|
playSound("voice_no.wav");
|
||||||
player->setPlayingState(PlayerState::ROLLING);
|
player->setPlayingState(PlayerState::ROLLING);
|
||||||
players_to_reorder.push_back(player);
|
players_to_reorder_.push_back(player);
|
||||||
if (allPlayersAreNotPlaying()) {
|
if (allPlayersAreNotPlaying()) {
|
||||||
// No se puede subir poder de fase si no hay nadie jugando
|
// No se puede subir poder de fase si no hay nadie jugando
|
||||||
Stage::power_can_be_added = false;
|
Stage::power_can_be_added = false;
|
||||||
@@ -928,7 +928,7 @@ void Game::render() {
|
|||||||
void Game::enableTimeStopItem() {
|
void Game::enableTimeStopItem() {
|
||||||
balloon_manager_->stopAllBalloons();
|
balloon_manager_->stopAllBalloons();
|
||||||
balloon_manager_->reverseColorsToAllBalloons();
|
balloon_manager_->reverseColorsToAllBalloons();
|
||||||
time_stopped_counter_ = TIME_STOPPED_COUNTER_;
|
time_stopped_counter_ = TIME_STOPPED_COUNTER;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Deshabilita el efecto del item de detener el tiempo
|
// Deshabilita el efecto del item de detener el tiempo
|
||||||
@@ -960,8 +960,8 @@ void Game::initPaths() {
|
|||||||
const int X1 = param.game.play_area.center_x - W / 2;
|
const int X1 = param.game.play_area.center_x - W / 2;
|
||||||
const int X2 = param.game.play_area.rect.w;
|
const int X2 = param.game.play_area.rect.w;
|
||||||
const int Y = param.game.play_area.center_y;
|
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(createPath(X0, X1, PathType::HORIZONTAL, Y, 80, easeOutQuint), 20);
|
||||||
paths_.emplace_back(Path(createPath(X1, X2, PathType::HORIZONTAL, Y, 80, easeInQuint), 0));
|
paths_.emplace_back(createPath(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)
|
// Recorrido para el texto de "Last Stage!" o de "X stages left" o "Game Over" (2,3)
|
||||||
@@ -972,8 +972,8 @@ void Game::initPaths() {
|
|||||||
const int Y1 = param.game.play_area.center_y - H / 2;
|
const int Y1 = param.game.play_area.center_y - H / 2;
|
||||||
const int Y2 = -H;
|
const int Y2 = -H;
|
||||||
const int X = param.game.play_area.center_x;
|
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(createPath(Y0, Y1, PathType::VERTICAL, X, 80, easeOutQuint), 20);
|
||||||
paths_.emplace_back(Path(createPath(Y1, Y2, PathType::VERTICAL, X, 80, easeInQuint), 0));
|
paths_.emplace_back(createPath(Y1, Y2, PathType::VERTICAL, X, 80, easeInQuint), 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Recorrido para el texto de "Congratulations!!" (3,4)
|
// Recorrido para el texto de "Congratulations!!" (3,4)
|
||||||
@@ -985,8 +985,8 @@ void Game::initPaths() {
|
|||||||
const int X1 = param.game.play_area.center_x - W / 2;
|
const int X1 = param.game.play_area.center_x - W / 2;
|
||||||
const int X2 = param.game.play_area.rect.w;
|
const int X2 = param.game.play_area.rect.w;
|
||||||
const int Y = param.game.play_area.center_y - H / 2 - 20;
|
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(createPath(X0, X1, PathType::HORIZONTAL, Y, 80, easeOutQuint), 400);
|
||||||
paths_.emplace_back(Path(createPath(X1, X2, PathType::HORIZONTAL, Y, 80, easeInQuint), 0));
|
paths_.emplace_back(createPath(X1, X2, PathType::HORIZONTAL, Y, 80, easeInQuint), 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Recorrido para el texto de "1.000.000 points!" (5,6)
|
// Recorrido para el texto de "1.000.000 points!" (5,6)
|
||||||
@@ -998,8 +998,8 @@ void Game::initPaths() {
|
|||||||
const int X1 = param.game.play_area.center_x - W / 2;
|
const int X1 = param.game.play_area.center_x - W / 2;
|
||||||
const int X2 = -W;
|
const int X2 = -W;
|
||||||
const int Y = param.game.play_area.center_y + H / 2 - 20;
|
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(createPath(X0, X1, PathType::HORIZONTAL, Y, 80, easeOutQuint), 400);
|
||||||
paths_.emplace_back(Path(createPath(X1, X2, PathType::HORIZONTAL, Y, 80, easeInQuint), 0));
|
paths_.emplace_back(createPath(X1, X2, PathType::HORIZONTAL, Y, 80, easeInQuint), 0);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1021,7 +1021,7 @@ void Game::updateHelper() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Comprueba si todos los jugadores han terminado de jugar
|
// Comprueba si todos los jugadores han terminado de jugar
|
||||||
bool Game::allPlayersAreWaitingOrGameOver() {
|
auto Game::allPlayersAreWaitingOrGameOver() -> bool {
|
||||||
auto success = true;
|
auto success = true;
|
||||||
for (const auto &player : players_)
|
for (const auto &player : players_)
|
||||||
success &= player->isWaiting() || player->isGameOver();
|
success &= player->isWaiting() || player->isGameOver();
|
||||||
@@ -1030,7 +1030,7 @@ bool Game::allPlayersAreWaitingOrGameOver() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Comprueba si todos los jugadores han terminado de jugar
|
// Comprueba si todos los jugadores han terminado de jugar
|
||||||
bool Game::allPlayersAreGameOver() {
|
auto Game::allPlayersAreGameOver() -> bool {
|
||||||
auto success = true;
|
auto success = true;
|
||||||
for (const auto &player : players_)
|
for (const auto &player : players_)
|
||||||
success &= player->isGameOver();
|
success &= player->isGameOver();
|
||||||
@@ -1039,7 +1039,7 @@ bool Game::allPlayersAreGameOver() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Comprueba si todos los jugadores han terminado de jugar
|
// Comprueba si todos los jugadores han terminado de jugar
|
||||||
bool Game::allPlayersAreNotPlaying() {
|
auto Game::allPlayersAreNotPlaying() -> bool {
|
||||||
auto success = true;
|
auto success = true;
|
||||||
for (const auto &player : players_)
|
for (const auto &player : players_)
|
||||||
success &= !player->isPlaying();
|
success &= !player->isPlaying();
|
||||||
@@ -1131,7 +1131,7 @@ void Game::checkPlayersStatusPlaying() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Obtiene un jugador a partir de su "id"
|
// Obtiene un jugador a partir de su "id"
|
||||||
std::shared_ptr<Player> Game::getPlayer(int id) {
|
auto Game::getPlayer(int id) -> std::shared_ptr<Player> {
|
||||||
auto it = std::find_if(players_.begin(), players_.end(), [id](const auto &player) { return player->getId() == id; });
|
auto it = std::find_if(players_.begin(), players_.end(), [id](const auto &player) { return player->getId() == id; });
|
||||||
|
|
||||||
if (it != players_.end()) {
|
if (it != players_.end()) {
|
||||||
@@ -1141,7 +1141,7 @@ std::shared_ptr<Player> Game::getPlayer(int id) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Obtiene un controlador a partir del "id" del jugador
|
// Obtiene un controlador a partir del "id" del jugador
|
||||||
int Game::getController(int player_id) {
|
auto Game::getController(int player_id) -> int {
|
||||||
auto it = std::find_if(Options::controllers.begin(), Options::controllers.end(), [player_id](const auto &controller) { return controller.player_id == player_id; });
|
auto it = std::find_if(Options::controllers.begin(), Options::controllers.end(), [player_id](const auto &controller) { return controller.player_id == player_id; });
|
||||||
|
|
||||||
if (it != Options::controllers.end()) {
|
if (it != Options::controllers.end()) {
|
||||||
@@ -1158,12 +1158,12 @@ void Game::checkInput() {
|
|||||||
// Comprueba las entradas si no está el menú de servicio activo
|
// Comprueba las entradas si no está el menú de servicio activo
|
||||||
if (!ServiceMenu::get()->isEnabled()) {
|
if (!ServiceMenu::get()->isEnabled()) {
|
||||||
checkPauseInput();
|
checkPauseInput();
|
||||||
demo_.enabled ? DEMO_handlePassInput() : handlePlayersInput();
|
demo_.enabled ? demoHandlePassInput() : handlePlayersInput();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Mueve los jugadores en el modo demo
|
// Mueve los jugadores en el modo demo
|
||||||
if (demo_.enabled) {
|
if (demo_.enabled) {
|
||||||
DEMO_handleInput();
|
demoHandleInput();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Verifica los inputs globales.
|
// Verifica los inputs globales.
|
||||||
@@ -1188,7 +1188,7 @@ void Game::checkPauseInput() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Gestiona las entradas de los jugadores en el modo demo para saltarse la demo.
|
// Gestiona las entradas de los jugadores en el modo demo para saltarse la demo.
|
||||||
void Game::DEMO_handlePassInput() {
|
void Game::demoHandlePassInput() {
|
||||||
if (input_->checkAnyButton()) {
|
if (input_->checkAnyButton()) {
|
||||||
Section::name = Section::Name::TITLE; // Salir del modo demo y regresar al menú principal.
|
Section::name = Section::Name::TITLE; // Salir del modo demo y regresar al menú principal.
|
||||||
Section::attract_mode = Section::AttractMode::TITLE_TO_DEMO; // El juego volverá a mostrar la demo
|
Section::attract_mode = Section::AttractMode::TITLE_TO_DEMO; // El juego volverá a mostrar la demo
|
||||||
@@ -1197,19 +1197,19 @@ void Game::DEMO_handlePassInput() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Gestiona las entradas de los jugadores en el modo demo, incluyendo movimientos y disparos automáticos.
|
// Gestiona las entradas de los jugadores en el modo demo, incluyendo movimientos y disparos automáticos.
|
||||||
void Game::DEMO_handleInput() {
|
void Game::demoHandleInput() {
|
||||||
int index = 0;
|
int index = 0;
|
||||||
for (const auto &player : players_) {
|
for (const auto &player : players_) {
|
||||||
if (player->isPlaying()) {
|
if (player->isPlaying()) {
|
||||||
// Maneja el input específico del jugador en modo demo.
|
// Maneja el input específico del jugador en modo demo.
|
||||||
DEMO_handlePlayerInput(player, index);
|
demoHandlePlayerInput(player, index);
|
||||||
}
|
}
|
||||||
++index;
|
++index;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Procesa las entradas para un jugador específico durante el modo demo.
|
// Procesa las entradas para un jugador específico durante el modo demo.
|
||||||
void Game::DEMO_handlePlayerInput(const std::shared_ptr<Player> &player, int index) {
|
void Game::demoHandlePlayerInput(const std::shared_ptr<Player> &player, int index) {
|
||||||
const auto &demo_data = demo_.data[index][demo_.counter];
|
const auto &demo_data = demo_.data[index][demo_.counter];
|
||||||
|
|
||||||
if (demo_data.left == 1) {
|
if (demo_data.left == 1) {
|
||||||
@@ -1721,10 +1721,10 @@ void Game::playSound(const std::string &name) {
|
|||||||
|
|
||||||
// Organiza los jugadores para que los vivos se pinten sobre los muertos
|
// Organiza los jugadores para que los vivos se pinten sobre los muertos
|
||||||
void Game::movePlayersToFront() {
|
void Game::movePlayersToFront() {
|
||||||
if (players_to_reorder.empty())
|
if (players_to_reorder_.empty())
|
||||||
return;
|
return;
|
||||||
|
|
||||||
for (auto &player : players_to_reorder) {
|
for (auto &player : players_to_reorder_) {
|
||||||
auto it = std::find(players_.begin(), players_.end(), player);
|
auto it = std::find(players_.begin(), players_.end(), player);
|
||||||
if (it != players_.end() && it != players_.begin()) {
|
if (it != players_.end() && it != players_.begin()) {
|
||||||
std::shared_ptr<Player> dying_player = *it;
|
std::shared_ptr<Player> dying_player = *it;
|
||||||
@@ -1732,7 +1732,7 @@ void Game::movePlayersToFront() {
|
|||||||
players_.insert(players_.begin(), dying_player);
|
players_.insert(players_.begin(), dying_player);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
players_to_reorder.clear();
|
players_to_reorder_.clear();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Comprueba si está activo el menu de servicio para poner el juego en pausa
|
// Comprueba si está activo el menu de servicio para poner el juego en pausa
|
||||||
|
|||||||
@@ -39,7 +39,7 @@ constexpr int TOTAL_SCORE_DATA = 3;
|
|||||||
class Game {
|
class Game {
|
||||||
public:
|
public:
|
||||||
// Constructor
|
// Constructor
|
||||||
Game(int playerID, int current_stage, bool demo);
|
Game(int player_id, int current_stage, bool demo);
|
||||||
|
|
||||||
// Destructor
|
// Destructor
|
||||||
~Game();
|
~Game();
|
||||||
@@ -59,24 +59,24 @@ class Game {
|
|||||||
};
|
};
|
||||||
|
|
||||||
// --- Constantes internas ---
|
// --- Constantes internas ---
|
||||||
static constexpr int HELP_COUNTER_ = 1000;
|
static constexpr int HELP_COUNTER = 1000;
|
||||||
static constexpr int GAME_COMPLETED_START_FADE_ = 500;
|
static constexpr int GAME_COMPLETED_START_FADE = 500;
|
||||||
static constexpr int GAME_COMPLETED_END_ = 700;
|
static constexpr int GAME_COMPLETED_END = 700;
|
||||||
static constexpr int GAME_OVER_COUNTER_ = 350;
|
static constexpr int GAME_OVER_COUNTER = 350;
|
||||||
static constexpr int TIME_STOPPED_COUNTER_ = 360;
|
static constexpr int TIME_STOPPED_COUNTER = 360;
|
||||||
static constexpr int ITEM_POINTS_1_DISK_ODDS_ = 10;
|
static constexpr int ITEM_POINTS_1_DISK_ODDS = 10;
|
||||||
static constexpr int ITEM_POINTS_2_GAVINA_ODDS_ = 6;
|
static constexpr int ITEM_POINTS_2_GAVINA_ODDS = 6;
|
||||||
static constexpr int ITEM_POINTS_3_PACMAR_ODDS_ = 3;
|
static constexpr int ITEM_POINTS_3_PACMAR_ODDS = 3;
|
||||||
static constexpr int ITEM_CLOCK_ODDS_ = 5;
|
static constexpr int ITEM_CLOCK_ODDS = 5;
|
||||||
static constexpr int ITEM_COFFEE_ODDS_ = 5;
|
static constexpr int ITEM_COFFEE_ODDS = 5;
|
||||||
static constexpr int ITEM_POWER_BALL_ODDS_ = 0;
|
static constexpr int ITEM_POWER_BALL_ODDS = 0;
|
||||||
static constexpr int ITEM_COFFEE_MACHINE_ODDS_ = 4;
|
static constexpr int ITEM_COFFEE_MACHINE_ODDS = 4;
|
||||||
|
|
||||||
// --- Estructuras ---
|
// --- Estructuras ---
|
||||||
struct Helper {
|
struct Helper {
|
||||||
bool need_coffee; // Indica si se necesitan cafes
|
bool need_coffee{false}; // Indica si se necesitan cafes
|
||||||
bool need_coffee_machine; // Indica si se necesita PowerUp
|
bool need_coffee_machine{false}; // Indica si se necesita PowerUp
|
||||||
bool need_power_ball; // Indica si se necesita una PowerBall
|
bool need_power_ball{false}; // Indica si se necesita una PowerBall
|
||||||
int counter; // Contador para no dar ayudas consecutivas
|
int counter; // Contador para no dar ayudas consecutivas
|
||||||
int item_disk_odds; // Probabilidad de aparición del objeto
|
int item_disk_odds; // Probabilidad de aparición del objeto
|
||||||
int item_gavina_odds; // Probabilidad de aparición del objeto
|
int item_gavina_odds; // Probabilidad de aparición del objeto
|
||||||
@@ -86,16 +86,13 @@ class Game {
|
|||||||
int item_coffee_machine_odds; // Probabilidad de aparición del objeto
|
int item_coffee_machine_odds; // Probabilidad de aparición del objeto
|
||||||
|
|
||||||
Helper()
|
Helper()
|
||||||
: need_coffee(false),
|
: counter(HELP_COUNTER),
|
||||||
need_coffee_machine(false),
|
item_disk_odds(ITEM_POINTS_1_DISK_ODDS),
|
||||||
need_power_ball(false),
|
item_gavina_odds(ITEM_POINTS_2_GAVINA_ODDS),
|
||||||
counter(HELP_COUNTER_),
|
item_pacmar_odds(ITEM_POINTS_3_PACMAR_ODDS),
|
||||||
item_disk_odds(ITEM_POINTS_1_DISK_ODDS_),
|
item_clock_odds(ITEM_CLOCK_ODDS),
|
||||||
item_gavina_odds(ITEM_POINTS_2_GAVINA_ODDS_),
|
item_coffee_odds(ITEM_COFFEE_ODDS),
|
||||||
item_pacmar_odds(ITEM_POINTS_3_PACMAR_ODDS_),
|
item_coffee_machine_odds(ITEM_COFFEE_MACHINE_ODDS) {}
|
||||||
item_clock_odds(ITEM_CLOCK_ODDS_),
|
|
||||||
item_coffee_odds(ITEM_COFFEE_ODDS_),
|
|
||||||
item_coffee_machine_odds(ITEM_COFFEE_MACHINE_ODDS_) {}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
// --- Objetos y punteros ---
|
// --- Objetos y punteros ---
|
||||||
@@ -144,13 +141,13 @@ class Game {
|
|||||||
float difficulty_score_multiplier_; // Multiplicador de puntos en función de la dificultad
|
float difficulty_score_multiplier_; // Multiplicador de puntos en función de la dificultad
|
||||||
int counter_ = 0; // Contador para el juego
|
int counter_ = 0; // Contador para el juego
|
||||||
int game_completed_counter_ = 0; // Contador para el tramo final, cuando se ha completado la partida y ya no aparecen más enemigos
|
int game_completed_counter_ = 0; // Contador para el tramo final, cuando se ha completado la partida y ya no aparecen más enemigos
|
||||||
int game_over_counter_ = GAME_OVER_COUNTER_; // Contador para el estado de fin de partida
|
int game_over_counter_ = GAME_OVER_COUNTER; // Contador para el estado de fin de partida
|
||||||
int time_stopped_counter_ = 0; // Temporizador para llevar la cuenta del tiempo detenido
|
int time_stopped_counter_ = 0; // Temporizador para llevar la cuenta del tiempo detenido
|
||||||
int total_power_to_complete_game_; // La suma del poder necesario para completar todas las fases
|
int total_power_to_complete_game_; // La suma del poder necesario para completar todas las fases
|
||||||
int menace_current_ = 0; // Nivel de amenaza actual
|
int menace_current_ = 0; // Nivel de amenaza actual
|
||||||
int menace_threshold_ = 0; // Umbral del nivel de amenaza. Si el nivel de amenaza cae por debajo del umbral, se generan más globos. Si el umbral aumenta, aumenta el número de globos
|
int menace_threshold_ = 0; // Umbral del nivel de amenaza. Si el nivel de amenaza cae por debajo del umbral, se generan más globos. Si el umbral aumenta, aumenta el número de globos
|
||||||
GameState state_ = GameState::FADE_IN; // Estado
|
GameState state_ = GameState::FADE_IN; // Estado
|
||||||
std::vector<std::shared_ptr<Player>> players_to_reorder;
|
std::vector<std::shared_ptr<Player>> players_to_reorder_;
|
||||||
|
|
||||||
#ifdef DEBUG
|
#ifdef DEBUG
|
||||||
bool auto_pop_balloons_ = false; // Si es true, incrementa automaticamente los globos explotados
|
bool auto_pop_balloons_ = false; // Si es true, incrementa automaticamente los globos explotados
|
||||||
@@ -170,7 +167,7 @@ class Game {
|
|||||||
void updateStage(); // Comprueba si hay cambio de fase y actualiza las variables
|
void updateStage(); // Comprueba si hay cambio de fase y actualiza las variables
|
||||||
void updateGameStateGameOver(); // Actualiza el estado de fin de la partida
|
void updateGameStateGameOver(); // Actualiza el estado de fin de la partida
|
||||||
void destroyAllItems(); // Destruye todos los items
|
void destroyAllItems(); // Destruye todos los items
|
||||||
std::shared_ptr<Balloon> checkPlayerBalloonCollision(std::shared_ptr<Player> &player); // Comprueba la colisión entre el jugador y los globos activos
|
auto checkPlayerBalloonCollision(std::shared_ptr<Player> &player) -> std::shared_ptr<Balloon>; // Comprueba la colisión entre el jugador y los globos activos
|
||||||
void checkPlayerItemCollision(std::shared_ptr<Player> &player); // Comprueba la colisión entre el jugador y los items
|
void checkPlayerItemCollision(std::shared_ptr<Player> &player); // Comprueba la colisión entre el jugador y los items
|
||||||
void checkBulletCollision(); // Comprueba y procesa la colisión de las balas
|
void checkBulletCollision(); // Comprueba y procesa la colisión de las balas
|
||||||
void updateBullets(); // Mueve las balas activas
|
void updateBullets(); // Mueve las balas activas
|
||||||
@@ -179,7 +176,7 @@ class Game {
|
|||||||
void freeBullets(); // Vacia el vector de balas
|
void freeBullets(); // Vacia el vector de balas
|
||||||
void updateItems(); // Actualiza los items
|
void updateItems(); // Actualiza los items
|
||||||
void renderItems(); // Pinta los items activos
|
void renderItems(); // Pinta los items activos
|
||||||
ItemType dropItem(); // Devuelve un item en función del azar
|
auto dropItem() -> ItemType; // Devuelve un item en función del azar
|
||||||
void createItem(ItemType type, float x, float y); // Crea un objeto item
|
void createItem(ItemType type, float x, float y); // Crea un objeto item
|
||||||
void freeItems(); // Vacia el vector de items
|
void freeItems(); // Vacia el vector de items
|
||||||
void createItemText(int x, std::shared_ptr<Texture> texture); // Crea un objeto PathSprite
|
void createItemText(int x, std::shared_ptr<Texture> texture); // Crea un objeto PathSprite
|
||||||
@@ -198,26 +195,26 @@ class Game {
|
|||||||
void enableTimeStopItem(); // Habilita el efecto del item de detener el tiempo
|
void enableTimeStopItem(); // Habilita el efecto del item de detener el tiempo
|
||||||
void disableTimeStopItem(); // Deshabilita el efecto del item de detener el tiempo
|
void disableTimeStopItem(); // Deshabilita el efecto del item de detener el tiempo
|
||||||
void updateHelper(); // Actualiza las variables de ayuda
|
void updateHelper(); // Actualiza las variables de ayuda
|
||||||
bool allPlayersAreWaitingOrGameOver(); // Comprueba si todos los jugadores han terminado de jugar
|
auto allPlayersAreWaitingOrGameOver() -> bool; // Comprueba si todos los jugadores han terminado de jugar
|
||||||
bool allPlayersAreGameOver(); // Comprueba si todos los jugadores han terminado de jugar
|
auto allPlayersAreGameOver() -> bool; // Comprueba si todos los jugadores han terminado de jugar
|
||||||
bool allPlayersAreNotPlaying(); // Comprueba si todos los jugadores han terminado de jugar
|
auto allPlayersAreNotPlaying() -> bool; // Comprueba si todos los jugadores han terminado de jugar
|
||||||
void updateScoreboard(); // Actualiza el marcador
|
void updateScoreboard(); // Actualiza el marcador
|
||||||
void fillCanvas(); // Dibuja los elementos de la zona de juego en su textura
|
void fillCanvas(); // Dibuja los elementos de la zona de juego en su textura
|
||||||
void pause(bool value); // Pausa el juego
|
void pause(bool value); // Pausa el juego
|
||||||
void addScoreToScoreBoard(const std::shared_ptr<Player> &player); // Añade una puntuación a la tabla de records
|
void addScoreToScoreBoard(const std::shared_ptr<Player> &player); // Añade una puntuación a la tabla de records
|
||||||
void checkAndUpdatePlayerStatus(int active_player_index, int inactive_player_index); // Saca del estado de GAME OVER al jugador si el otro está activo
|
void checkAndUpdatePlayerStatus(int active_player_index, int inactive_player_index); // Saca del estado de GAME OVER al jugador si el otro está activo
|
||||||
void checkPlayersStatusPlaying(); // Comprueba el estado de juego de los jugadores
|
void checkPlayersStatusPlaying(); // Comprueba el estado de juego de los jugadores
|
||||||
std::shared_ptr<Player> getPlayer(int id); // Obtiene un jugador a partir de su "id"
|
auto getPlayer(int id) -> std::shared_ptr<Player>; // Obtiene un jugador a partir de su "id"
|
||||||
int getController(int playerId); // Obtiene un controlador a partir del "id" del jugador
|
auto getController(int player_id) -> int; // Obtiene un controlador a partir del "id" del jugador
|
||||||
void checkInput(); // Gestiona la entrada durante el juego
|
void checkInput(); // Gestiona la entrada durante el juego
|
||||||
void checkPauseInput(); // Verifica si alguno de los controladores ha solicitado una pausa y actualiza el estado de pausa del juego.
|
void checkPauseInput(); // Verifica si alguno de los controladores ha solicitado una pausa y actualiza el estado de pausa del juego.
|
||||||
void DEMO_handleInput(); // Gestiona las entradas de los jugadores en el modo demo, incluyendo movimientos y disparos automáticos.
|
void demoHandleInput(); // Gestiona las entradas de los jugadores en el modo demo, incluyendo movimientos y disparos automáticos.
|
||||||
void DEMO_handlePassInput(); // Gestiona las entradas de los jugadores en el modo demo para saltarse la demo.
|
void demoHandlePassInput(); // Gestiona las entradas de los jugadores en el modo demo para saltarse la demo.
|
||||||
void DEMO_handlePlayerInput(const std::shared_ptr<Player> &player, int index); // Procesa las entradas para un jugador específico durante el modo demo.
|
void demoHandlePlayerInput(const std::shared_ptr<Player> &player, int index); // Procesa las entradas para un jugador específico durante el modo demo.
|
||||||
void handleFireInput(const std::shared_ptr<Player> &player, BulletType bulletType); // Maneja el disparo de un jugador, incluyendo la creación de balas y la gestión del tiempo de espera entre disparos.
|
void handleFireInput(const std::shared_ptr<Player> &player, BulletType bullet_type); // Maneja el disparo de un jugador, incluyendo la creación de balas y la gestión del tiempo de espera entre disparos.
|
||||||
void handlePlayersInput(); // Gestiona las entradas de todos los jugadores en el modo normal (fuera del modo demo).
|
void handlePlayersInput(); // Gestiona las entradas de todos los jugadores en el modo normal (fuera del modo demo).
|
||||||
void handleNormalPlayerInput(const std::shared_ptr<Player> &player); // Maneja las entradas de movimiento y disparo para un jugador en modo normal.
|
void handleNormalPlayerInput(const std::shared_ptr<Player> &player); // Maneja las entradas de movimiento y disparo para un jugador en modo normal.
|
||||||
void handleFireInputs(const std::shared_ptr<Player> &player, bool autofire, int controllerIndex); // Procesa las entradas de disparo del jugador, permitiendo disparos automáticos si está habilitado.
|
void handleFireInputs(const std::shared_ptr<Player> &player, bool autofire, int controller_index); // Procesa las entradas de disparo del jugador, permitiendo disparos automáticos si está habilitado.
|
||||||
void handlePlayerContinue(const std::shared_ptr<Player> &player); // Maneja la continuación del jugador cuando no está jugando, permitiendo que continúe si se pulsa el botón de inicio.
|
void handlePlayerContinue(const std::shared_ptr<Player> &player); // Maneja la continuación del jugador cuando no está jugando, permitiendo que continúe si se pulsa el botón de inicio.
|
||||||
void handleNameInput(const std::shared_ptr<Player> &player); // Procesa las entradas para la introducción del nombre del jugador.
|
void handleNameInput(const std::shared_ptr<Player> &player); // Procesa las entradas para la introducción del nombre del jugador.
|
||||||
void initDemo(int player_id); // Inicializa las variables para el modo DEMO
|
void initDemo(int player_id); // Inicializa las variables para el modo DEMO
|
||||||
|
|||||||
@@ -1,9 +1,9 @@
|
|||||||
#include "hiscore_table.h"
|
#include "hiscore_table.h"
|
||||||
|
|
||||||
#include <SDL3/SDL.h> // Para SDL_GetTicks, SDL_SetRenderTarget
|
#include <SDL3/SDL.h> // Para SDL_GetTicks, SDL_SetRenderTarget
|
||||||
#include <stdlib.h> // Para rand, size_t
|
|
||||||
|
|
||||||
#include <algorithm> // Para max
|
#include <algorithm> // Para max
|
||||||
|
#include <cstdlib> // Para rand, size_t
|
||||||
#include <functional> // Para function
|
#include <functional> // Para function
|
||||||
#include <vector> // Para vector
|
#include <vector> // Para vector
|
||||||
|
|
||||||
@@ -32,7 +32,7 @@ HiScoreTable::HiScoreTable()
|
|||||||
backbuffer_(SDL_CreateTexture(renderer_, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, param.game.width, param.game.height)),
|
backbuffer_(SDL_CreateTexture(renderer_, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, param.game.width, param.game.height)),
|
||||||
fade_(std::make_unique<Fade>()),
|
fade_(std::make_unique<Fade>()),
|
||||||
background_(std::make_unique<Background>()),
|
background_(std::make_unique<Background>()),
|
||||||
counter_(0),
|
|
||||||
ticks_(0),
|
ticks_(0),
|
||||||
view_area_(SDL_FRect{0, 0, static_cast<float>(param.game.width), static_cast<float>(param.game.height)}),
|
view_area_(SDL_FRect{0, 0, static_cast<float>(param.game.width), static_cast<float>(param.game.height)}),
|
||||||
fade_mode_(FadeMode::IN),
|
fade_mode_(FadeMode::IN),
|
||||||
@@ -168,7 +168,7 @@ void HiScoreTable::updateFade() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Convierte un entero a un string con separadores de miles
|
// Convierte un entero a un string con separadores de miles
|
||||||
std::string HiScoreTable::format(int number) {
|
auto HiScoreTable::format(int number) -> std::string {
|
||||||
const std::string SEPARATOR = ".";
|
const std::string SEPARATOR = ".";
|
||||||
const std::string SCORE = std::to_string(number);
|
const std::string SCORE = std::to_string(number);
|
||||||
|
|
||||||
@@ -341,7 +341,7 @@ void HiScoreTable::initBackground() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Obtiene un color del vector de colores de entradas
|
// Obtiene un color del vector de colores de entradas
|
||||||
Color HiScoreTable::getEntryColor(int counter) {
|
auto HiScoreTable::getEntryColor(int counter) -> Color {
|
||||||
int cycle_length = entry_colors_.size() * 2 - 2;
|
int cycle_length = entry_colors_.size() * 2 - 2;
|
||||||
size_t n = counter % cycle_length;
|
size_t n = counter % cycle_length;
|
||||||
|
|
||||||
@@ -383,7 +383,7 @@ void HiScoreTable::updateCounter() {
|
|||||||
background_->setAlpha(96);
|
background_->setAlpha(96);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (counter_ == COUNTER_END_) {
|
if (counter_ == COUNTER_END) {
|
||||||
fade_->activate();
|
fade_->activate();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -39,7 +39,7 @@ class HiScoreTable {
|
|||||||
|
|
||||||
private:
|
private:
|
||||||
// --- Constantes ---
|
// --- Constantes ---
|
||||||
static constexpr Uint16 COUNTER_END_ = 800; // Valor final para el contador
|
static constexpr Uint16 COUNTER_END = 800; // Valor final para el contador
|
||||||
|
|
||||||
// --- Objetos y punteros ---
|
// --- Objetos y punteros ---
|
||||||
SDL_Renderer *renderer_; // El renderizador de la ventana
|
SDL_Renderer *renderer_; // El renderizador de la ventana
|
||||||
@@ -64,14 +64,14 @@ class HiScoreTable {
|
|||||||
void render(); // Pinta en pantalla
|
void render(); // Pinta en pantalla
|
||||||
void checkEvents(); // Comprueba los eventos
|
void checkEvents(); // Comprueba los eventos
|
||||||
void checkInput(); // Comprueba las entradas
|
void checkInput(); // Comprueba las entradas
|
||||||
std::string format(int number); // Convierte un entero a un string con separadores de miles
|
auto format(int number) -> std::string; // Convierte un entero a un string con separadores de miles
|
||||||
void fillTexture(); // Dibuja los sprites en la textura
|
void fillTexture(); // Dibuja los sprites en la textura
|
||||||
void updateFade(); // Gestiona el fade
|
void updateFade(); // Gestiona el fade
|
||||||
void createSprites(); // Crea los sprites con los textos
|
void createSprites(); // Crea los sprites con los textos
|
||||||
void updateSprites(); // Actualiza las posiciones de los sprites de texto
|
void updateSprites(); // Actualiza las posiciones de los sprites de texto
|
||||||
void initFade(); // Inicializa el fade
|
void initFade(); // Inicializa el fade
|
||||||
void initBackground(); // Inicializa el fondo
|
void initBackground(); // Inicializa el fondo
|
||||||
Color getEntryColor(int counter_); // Obtiene un color del vector de colores de entradas
|
auto getEntryColor(int counter) -> Color; // Obtiene un color del vector de colores de entradas
|
||||||
void iniEntryColors(); // Inicializa los colores de las entradas
|
void iniEntryColors(); // Inicializa los colores de las entradas
|
||||||
void glowEntryNames(); // Hace brillar los nombres de la tabla de records
|
void glowEntryNames(); // Hace brillar los nombres de la tabla de records
|
||||||
void updateCounter(); // Gestiona el contador
|
void updateCounter(); // Gestiona el contador
|
||||||
|
|||||||
@@ -279,7 +279,7 @@ void Instructions::run() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Método para inicializar las líneas
|
// Método para inicializar las líneas
|
||||||
std::vector<Line> Instructions::initializeLines(int height) {
|
auto Instructions::initializeLines(int height) -> std::vector<Line> {
|
||||||
std::vector<Line> lines;
|
std::vector<Line> lines;
|
||||||
for (int y = 0; y < height; y++) {
|
for (int y = 0; y < height; y++) {
|
||||||
int direction = (y % 2 == 0) ? -1 : 1; // Pares a la izquierda, impares a la derecha
|
int direction = (y % 2 == 0) ? -1 : 1; // Pares a la izquierda, impares a la derecha
|
||||||
@@ -289,17 +289,17 @@ std::vector<Line> Instructions::initializeLines(int height) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Método para mover las líneas con suavizado
|
// Método para mover las líneas con suavizado
|
||||||
bool Instructions::moveLines(std::vector<Line> &lines, int width, float duration, Uint32 start_delay) {
|
auto Instructions::moveLines(std::vector<Line> &lines, int width, float duration, Uint32 start_delay) -> bool {
|
||||||
Uint32 current_time = SDL_GetTicks();
|
Uint32 current_time = SDL_GetTicks();
|
||||||
bool all_lines_off_screen = true;
|
bool all_lines_off_screen = true;
|
||||||
|
|
||||||
for (auto &line : lines) {
|
for (auto &line : lines) {
|
||||||
// Establecer startTime en el primer cuadro de animación
|
// Establecer start_time en el primer cuadro de animación
|
||||||
if (line.startTime == 0) {
|
if (line.start_time == 0) {
|
||||||
line.startTime = current_time + line.y * start_delay;
|
line.start_time = current_time + line.y * start_delay;
|
||||||
}
|
}
|
||||||
|
|
||||||
float elapsed_time = (current_time - line.startTime) / 1000.0f; // Convertir a segundos
|
float elapsed_time = (current_time - line.start_time) / 1000.0f; // Convertir a segundos
|
||||||
if (elapsed_time < 0) {
|
if (elapsed_time < 0) {
|
||||||
all_lines_off_screen = false; // Si aún no se debe mover esta línea, no están todas fuera de pantalla
|
all_lines_off_screen = false; // Si aún no se debe mover esta línea, no están todas fuera de pantalla
|
||||||
continue;
|
continue;
|
||||||
|
|||||||
@@ -29,11 +29,11 @@ struct Line {
|
|||||||
int y; // Coordenada Y de la línea
|
int y; // Coordenada Y de la línea
|
||||||
float x; // Coordenada X inicial (usamos float para mayor precisión en el suavizado)
|
float x; // Coordenada X inicial (usamos float para mayor precisión en el suavizado)
|
||||||
int direction; // Dirección de movimiento: -1 para izquierda, 1 para derecha
|
int direction; // Dirección de movimiento: -1 para izquierda, 1 para derecha
|
||||||
Uint32 startTime; // Tiempo de inicio del movimiento
|
Uint32 start_time{0}; // Tiempo de inicio del movimiento
|
||||||
|
|
||||||
// Constructor de Line
|
// Constructor de Line
|
||||||
Line(int y, float x, int direction)
|
Line(int y, float x, int direction)
|
||||||
: y(y), x(x), direction(direction), startTime(0) {}
|
: y(y), x(x), direction(direction) {}
|
||||||
};
|
};
|
||||||
|
|
||||||
// Clase Instructions
|
// Clase Instructions
|
||||||
@@ -80,8 +80,8 @@ class Instructions {
|
|||||||
void fillBackbuffer(); // Rellena el backbuffer
|
void fillBackbuffer(); // Rellena el backbuffer
|
||||||
void iniSprites(); // Inicializa los sprites de los items
|
void iniSprites(); // Inicializa los sprites de los items
|
||||||
void updateSprites(); // Actualiza los sprites
|
void updateSprites(); // Actualiza los sprites
|
||||||
std::vector<Line> initializeLines(int height); // Inicializa las líneas animadas
|
auto initializeLines(int height) -> std::vector<Line>; // Inicializa las líneas animadas
|
||||||
bool moveLines(std::vector<Line> &lines, int width, float duration, Uint32 startDelay); // Mueve las líneas
|
auto moveLines(std::vector<Line> &lines, int width, float duration, Uint32 start_delay) -> bool; // Mueve las líneas
|
||||||
void renderLines(SDL_Renderer *renderer, SDL_Texture *texture, const std::vector<Line> &lines); // Renderiza las líneas
|
void renderLines(SDL_Renderer *renderer, SDL_Texture *texture, const std::vector<Line> &lines); // Renderiza las líneas
|
||||||
void updateBackbuffer(); // Gestiona la textura con los gráficos
|
void updateBackbuffer(); // Gestiona la textura con los gráficos
|
||||||
};
|
};
|
||||||
@@ -46,14 +46,14 @@ Logo::Logo()
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Inicializa el vector de colores
|
// Inicializa el vector de colores
|
||||||
color_.push_back(Color(0x00, 0x00, 0x00)); // Black
|
color_.emplace_back(0x00, 0x00, 0x00); // Black
|
||||||
color_.push_back(Color(0x00, 0x00, 0xd8)); // Blue
|
color_.emplace_back(0x00, 0x00, 0xd8); // Blue
|
||||||
color_.push_back(Color(0xd8, 0x00, 0x00)); // Red
|
color_.emplace_back(0xd8, 0x00, 0x00); // Red
|
||||||
color_.push_back(Color(0xd8, 0x00, 0xd8)); // Magenta
|
color_.emplace_back(0xd8, 0x00, 0xd8); // Magenta
|
||||||
color_.push_back(Color(0x00, 0xd8, 0x00)); // Green
|
color_.emplace_back(0x00, 0xd8, 0x00); // Green
|
||||||
color_.push_back(Color(0x00, 0xd8, 0xd8)); // Cyan
|
color_.emplace_back(0x00, 0xd8, 0xd8); // Cyan
|
||||||
color_.push_back(Color(0xd8, 0xd8, 0x00)); // Yellow
|
color_.emplace_back(0xd8, 0xd8, 0x00); // Yellow
|
||||||
color_.push_back(Color(0xFF, 0xFF, 0xFF)); // Bright white
|
color_.emplace_back(0xFF, 0xFF, 0xFF); // Bright white
|
||||||
}
|
}
|
||||||
|
|
||||||
// Destructor
|
// Destructor
|
||||||
|
|||||||
@@ -1,9 +1,9 @@
|
|||||||
#include "title.h"
|
#include "title.h"
|
||||||
|
|
||||||
#include <SDL3/SDL.h> // Para SDL_GetTicks, Uint32, SDL_EventType
|
#include <SDL3/SDL.h> // Para SDL_GetTicks, Uint32, SDL_EventType
|
||||||
#include <stddef.h> // Para size_t
|
|
||||||
|
|
||||||
#include <algorithm> // Para find_if
|
#include <algorithm> // Para find_if
|
||||||
|
#include <cstddef> // Para size_t
|
||||||
#include <iostream> // Para basic_ostream, basic_ostream::operator<<
|
#include <iostream> // Para basic_ostream, basic_ostream::operator<<
|
||||||
#include <string> // Para basic_string, char_traits, operator+
|
#include <string> // Para basic_string, char_traits, operator+
|
||||||
#include <vector> // Para vector
|
#include <vector> // Para vector
|
||||||
@@ -408,11 +408,11 @@ void Title::updateStartPrompt() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
should_render_start_prompt = condition_met;
|
should_render_start_prompt_ = condition_met;
|
||||||
}
|
}
|
||||||
|
|
||||||
void Title::renderStartPrompt() {
|
void Title::renderStartPrompt() {
|
||||||
if (should_render_start_prompt) {
|
if (should_render_start_prompt_) {
|
||||||
text_->writeDX(TEXT_CENTER | TEXT_SHADOW,
|
text_->writeDX(TEXT_CENTER | TEXT_SHADOW,
|
||||||
param.game.game_area.center_x,
|
param.game.game_area.center_x,
|
||||||
param.title.press_start_position,
|
param.title.press_start_position,
|
||||||
@@ -513,7 +513,7 @@ void Title::renderPlayers() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Obtiene un jugador a partir de su "id"
|
// Obtiene un jugador a partir de su "id"
|
||||||
std::shared_ptr<Player> Title::getPlayer(int id) {
|
auto Title::getPlayer(int id) -> std::shared_ptr<Player> {
|
||||||
auto it = std::find_if(players_.begin(), players_.end(), [id](const auto &player) { return player->getId() == id; });
|
auto it = std::find_if(players_.begin(), players_.end(), [id](const auto &player) { return player->getId() == id; });
|
||||||
|
|
||||||
if (it != players_.end()) {
|
if (it != players_.end()) {
|
||||||
|
|||||||
@@ -67,7 +67,7 @@ class Title {
|
|||||||
Section::Options selection_ = Section::Options::TITLE_TIME_OUT; // Opción elegida en el título
|
Section::Options selection_ = Section::Options::TITLE_TIME_OUT; // Opción elegida en el título
|
||||||
int num_controllers_; // Número de mandos conectados
|
int num_controllers_; // Número de mandos conectados
|
||||||
TitleState state_; // Estado actual de la sección
|
TitleState state_; // Estado actual de la sección
|
||||||
bool should_render_start_prompt = false; // Indica si se muestra o no el texto de PRESS START BUTTON TO PLAY
|
bool should_render_start_prompt_ = false; // Indica si se muestra o no el texto de PRESS START BUTTON TO PLAY
|
||||||
bool player1_start_pressed_ = false; // Indica si se ha pulsdo el boton de empezar a jugar para el jugador 1
|
bool player1_start_pressed_ = false; // Indica si se ha pulsdo el boton de empezar a jugar para el jugador 1
|
||||||
bool player2_start_pressed_ = false; // Indica si se ha pulsdo el boton de empezar a jugar para el jugador 2
|
bool player2_start_pressed_ = false; // Indica si se ha pulsdo el boton de empezar a jugar para el jugador 2
|
||||||
|
|
||||||
@@ -92,5 +92,5 @@ class Title {
|
|||||||
void initPlayers(); // Inicializa los jugadores
|
void initPlayers(); // Inicializa los jugadores
|
||||||
void renderPlayers(); // Renderiza los jugadores
|
void renderPlayers(); // Renderiza los jugadores
|
||||||
void updatePlayers(); // Actualza los jugadores
|
void updatePlayers(); // Actualza los jugadores
|
||||||
std::shared_ptr<Player> getPlayer(int id); // Obtiene un jugador a partir de su "id"
|
auto getPlayer(int id) -> std::shared_ptr<Player>; // Obtiene un jugador a partir de su "id"
|
||||||
};
|
};
|
||||||
@@ -19,10 +19,10 @@ class SmartSprite : public AnimatedSprite {
|
|||||||
void render() override; // Dibuja el sprite
|
void render() override; // Dibuja el sprite
|
||||||
|
|
||||||
// --- Getters ---
|
// --- Getters ---
|
||||||
int getDestX() const { return dest_x_; } // Obtiene la posición de destino en X
|
auto getDestX() const -> int { return dest_x_; } // Obtiene la posición de destino en X
|
||||||
int getDestY() const { return dest_y_; } // Obtiene la posición de destino en Y
|
auto getDestY() const -> int { return dest_y_; } // Obtiene la posición de destino en Y
|
||||||
bool isOnDestination() const { return on_destination_; } // Indica si está en el destino
|
auto isOnDestination() const -> bool { return on_destination_; } // Indica si está en el destino
|
||||||
bool hasFinished() const { return finished_; } // Indica si ya ha terminado
|
auto hasFinished() const -> bool { return finished_; } // Indica si ya ha terminado
|
||||||
|
|
||||||
// --- Setters ---
|
// --- Setters ---
|
||||||
void setFinishedCounter(int value) { finished_counter_ = value; } // Establece el contador para deshabilitarlo
|
void setFinishedCounter(int value) { finished_counter_ = value; } // Establece el contador para deshabilitarlo
|
||||||
|
|||||||
@@ -1,20 +1,22 @@
|
|||||||
#include "sprite.h"
|
#include "sprite.h"
|
||||||
|
|
||||||
|
#include <utility>
|
||||||
|
|
||||||
#include "texture.h" // Para Texture
|
#include "texture.h" // Para Texture
|
||||||
|
|
||||||
// Constructor
|
// Constructor
|
||||||
Sprite::Sprite(std::shared_ptr<Texture> texture, float pos_x, float pos_y, float width, float height)
|
Sprite::Sprite(std::shared_ptr<Texture> texture, float pos_x, float pos_y, float width, float height)
|
||||||
: texture_(texture),
|
: texture_(std::move(texture)),
|
||||||
pos_((SDL_FRect){pos_x, pos_y, width, height}),
|
pos_((SDL_FRect){pos_x, pos_y, width, height}),
|
||||||
sprite_clip_((SDL_FRect){0, 0, pos_.w, pos_.h}) {}
|
sprite_clip_((SDL_FRect){0, 0, pos_.w, pos_.h}) {}
|
||||||
|
|
||||||
Sprite::Sprite(std::shared_ptr<Texture> texture, SDL_FRect rect)
|
Sprite::Sprite(std::shared_ptr<Texture> texture, SDL_FRect rect)
|
||||||
: texture_(texture),
|
: texture_(std::move(texture)),
|
||||||
pos_(rect),
|
pos_(rect),
|
||||||
sprite_clip_((SDL_FRect){0, 0, pos_.w, pos_.h}) {}
|
sprite_clip_((SDL_FRect){0, 0, pos_.w, pos_.h}) {}
|
||||||
|
|
||||||
Sprite::Sprite(std::shared_ptr<Texture> texture)
|
Sprite::Sprite(std::shared_ptr<Texture> texture)
|
||||||
: texture_(texture),
|
: texture_(std::move(texture)),
|
||||||
pos_(SDL_FRect{0, 0, static_cast<float>(texture_->getWidth()), static_cast<float>(texture_->getHeight())}),
|
pos_(SDL_FRect{0, 0, static_cast<float>(texture_->getWidth()), static_cast<float>(texture_->getHeight())}),
|
||||||
sprite_clip_(pos_) {}
|
sprite_clip_(pos_) {}
|
||||||
|
|
||||||
|
|||||||
@@ -12,21 +12,21 @@ int number = 0; // Fase actual
|
|||||||
bool power_can_be_added = true; // Habilita la recolecta de poder
|
bool power_can_be_added = true; // Habilita la recolecta de poder
|
||||||
|
|
||||||
// Devuelve una fase
|
// Devuelve una fase
|
||||||
Stage get(int index) { return stages.at(std::min(9, index)); }
|
auto get(int index) -> Stage { return stages.at(std::min(9, index)); }
|
||||||
|
|
||||||
// Inicializa las variables del namespace Stage
|
// Inicializa las variables del namespace Stage
|
||||||
void init() {
|
void init() {
|
||||||
stages.clear();
|
stages.clear();
|
||||||
stages.emplace_back(Stage(200, 7 + (4 * 1), 7 + (4 * 3)));
|
stages.emplace_back(200, 7 + (4 * 1), 7 + (4 * 3));
|
||||||
stages.emplace_back(Stage(300, 7 + (4 * 2), 7 + (4 * 4)));
|
stages.emplace_back(300, 7 + (4 * 2), 7 + (4 * 4));
|
||||||
stages.emplace_back(Stage(600, 7 + (4 * 3), 7 + (4 * 5)));
|
stages.emplace_back(600, 7 + (4 * 3), 7 + (4 * 5));
|
||||||
stages.emplace_back(Stage(600, 7 + (4 * 3), 7 + (4 * 5)));
|
stages.emplace_back(600, 7 + (4 * 3), 7 + (4 * 5));
|
||||||
stages.emplace_back(Stage(600, 7 + (4 * 4), 7 + (4 * 6)));
|
stages.emplace_back(600, 7 + (4 * 4), 7 + (4 * 6));
|
||||||
stages.emplace_back(Stage(600, 7 + (4 * 4), 7 + (4 * 6)));
|
stages.emplace_back(600, 7 + (4 * 4), 7 + (4 * 6));
|
||||||
stages.emplace_back(Stage(650, 7 + (4 * 5), 7 + (4 * 7)));
|
stages.emplace_back(650, 7 + (4 * 5), 7 + (4 * 7));
|
||||||
stages.emplace_back(Stage(750, 7 + (4 * 5), 7 + (4 * 7)));
|
stages.emplace_back(750, 7 + (4 * 5), 7 + (4 * 7));
|
||||||
stages.emplace_back(Stage(850, 7 + (4 * 6), 7 + (4 * 8)));
|
stages.emplace_back(850, 7 + (4 * 6), 7 + (4 * 8));
|
||||||
stages.emplace_back(Stage(950, 7 + (4 * 7), 7 + (4 * 10)));
|
stages.emplace_back(950, 7 + (4 * 7), 7 + (4 * 10));
|
||||||
|
|
||||||
power = 0;
|
power = 0;
|
||||||
total_power = 0;
|
total_power = 0;
|
||||||
|
|||||||
@@ -27,7 +27,7 @@ extern int number; // Índice de la fase actual
|
|||||||
extern bool power_can_be_added; // Indica si se puede añadir poder a la fase
|
extern bool power_can_be_added; // Indica si se puede añadir poder a la fase
|
||||||
|
|
||||||
// --- Funciones principales ---
|
// --- Funciones principales ---
|
||||||
Stage get(int index); // Devuelve una fase por índice
|
auto get(int index) -> Stage; // Devuelve una fase por índice
|
||||||
void init(); // Inicializa las variables del namespace Stage
|
void init(); // Inicializa las variables del namespace Stage
|
||||||
void addPower(int amount); // Añade poder a la fase actual
|
void addPower(int amount); // Añade poder a la fase actual
|
||||||
} // namespace Stage
|
} // namespace Stage
|
||||||
@@ -1,8 +1,8 @@
|
|||||||
#include "text.h"
|
#include "text.h"
|
||||||
|
|
||||||
#include <SDL3/SDL.h> // Para SDL_SetRenderTarget, SDL_GetRenderTarget, Uint8
|
#include <SDL3/SDL.h> // Para SDL_SetRenderTarget, SDL_GetRenderTarget, Uint8
|
||||||
#include <stddef.h> // Para size_t
|
|
||||||
|
|
||||||
|
#include <cstddef> // Para size_t
|
||||||
#include <fstream> // Para basic_ifstream, basic_istream, basic_ostream
|
#include <fstream> // Para basic_ifstream, basic_istream, basic_ostream
|
||||||
#include <iostream> // Para cerr
|
#include <iostream> // Para cerr
|
||||||
#include <stdexcept> // Para runtime_error
|
#include <stdexcept> // Para runtime_error
|
||||||
@@ -13,14 +13,14 @@
|
|||||||
#include "utils.h" // Para Color, getFileName, printWithDots
|
#include "utils.h" // Para Color, getFileName, printWithDots
|
||||||
|
|
||||||
// Llena una estructuta TextFile desde un fichero
|
// Llena una estructuta TextFile desde un fichero
|
||||||
std::shared_ptr<TextFile> loadTextFile(const std::string &file_path) {
|
auto loadTextFile(const std::string &file_path) -> std::shared_ptr<TextFile> {
|
||||||
auto tf = std::make_shared<TextFile>();
|
auto tf = std::make_shared<TextFile>();
|
||||||
|
|
||||||
// Inicializa a cero el vector con las coordenadas
|
// Inicializa a cero el vector con las coordenadas
|
||||||
for (int i = 0; i < 128; ++i) {
|
for (auto &i : tf->offset) {
|
||||||
tf->offset[i].x = 0;
|
i.x = 0;
|
||||||
tf->offset[i].y = 0;
|
i.y = 0;
|
||||||
tf->offset[i].w = 0;
|
i.w = 0;
|
||||||
tf->box_width = 0;
|
tf->box_width = 0;
|
||||||
tf->box_height = 0;
|
tf->box_height = 0;
|
||||||
}
|
}
|
||||||
@@ -141,7 +141,7 @@ void Text::write2X(int x, int y, const std::string &text, int kerning) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Escribe el texto en una textura
|
// Escribe el texto en una textura
|
||||||
std::shared_ptr<Texture> Text::writeToTexture(const std::string &text, int zoom, int kerning) {
|
auto Text::writeToTexture(const std::string &text, int zoom, int kerning) -> std::shared_ptr<Texture> {
|
||||||
auto renderer = Screen::get()->getRenderer();
|
auto renderer = Screen::get()->getRenderer();
|
||||||
auto texture = std::make_shared<Texture>(renderer);
|
auto texture = std::make_shared<Texture>(renderer);
|
||||||
auto width = lenght(text, kerning) * zoom;
|
auto width = lenght(text, kerning) * zoom;
|
||||||
@@ -159,7 +159,7 @@ std::shared_ptr<Texture> Text::writeToTexture(const std::string &text, int zoom,
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Escribe el texto con extras en una textura
|
// Escribe el texto con extras en una textura
|
||||||
std::shared_ptr<Texture> Text::writeDXToTexture(Uint8 flags, const std::string &text, int kerning, Color text_color, Uint8 shadow_distance, Color shadow_color, int lenght) {
|
auto Text::writeDXToTexture(Uint8 flags, const std::string &text, int kerning, Color text_color, Uint8 shadow_distance, Color shadow_color, int lenght) -> std::shared_ptr<Texture> {
|
||||||
auto renderer = Screen::get()->getRenderer();
|
auto renderer = Screen::get()->getRenderer();
|
||||||
auto texture = std::make_shared<Texture>(renderer);
|
auto texture = std::make_shared<Texture>(renderer);
|
||||||
auto width = Text::lenght(text, kerning) + shadow_distance;
|
auto width = Text::lenght(text, kerning) + shadow_distance;
|
||||||
@@ -230,7 +230,7 @@ void Text::writeDX(Uint8 flags, int x, int y, const std::string &text, int kerni
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Obtiene la longitud en pixels de una cadena
|
// Obtiene la longitud en pixels de una cadena
|
||||||
int Text::lenght(const std::string &text, int kerning) const {
|
auto Text::lenght(const std::string &text, int kerning) const -> int {
|
||||||
int shift = 0;
|
int shift = 0;
|
||||||
for (size_t i = 0; i < text.length(); ++i)
|
for (size_t i = 0; i < text.length(); ++i)
|
||||||
shift += (offset_[static_cast<int>(text[i])].w + kerning);
|
shift += (offset_[static_cast<int>(text[i])].w + kerning);
|
||||||
@@ -240,7 +240,7 @@ int Text::lenght(const std::string &text, int kerning) const {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Devuelve el valor de la variable
|
// Devuelve el valor de la variable
|
||||||
int Text::getCharacterSize() const {
|
auto Text::getCharacterSize() const -> int {
|
||||||
return box_width_;
|
return box_width_;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -2,13 +2,14 @@
|
|||||||
#include "texture.h"
|
#include "texture.h"
|
||||||
|
|
||||||
#include <SDL3/SDL.h> // Para SDL_LogError, SDL_LogCategory, Uint8, SDL_...
|
#include <SDL3/SDL.h> // Para SDL_LogError, SDL_LogCategory, Uint8, SDL_...
|
||||||
#include <stdint.h> // Para uint32_t
|
|
||||||
|
|
||||||
|
#include <cstdint> // Para uint32_t
|
||||||
#include <cstring> // Para memcpy
|
#include <cstring> // Para memcpy
|
||||||
#include <fstream> // Para basic_ifstream, basic_istream, basic_ios
|
#include <fstream> // Para basic_ifstream, basic_istream, basic_ios
|
||||||
#include <sstream> // Para basic_istringstream
|
#include <sstream> // Para basic_istringstream
|
||||||
#include <stdexcept> // Para runtime_error
|
#include <stdexcept> // Para runtime_error
|
||||||
#include <string> // Para basic_string, char_traits, operator+, string
|
#include <string> // Para basic_string, char_traits, operator+, string
|
||||||
|
#include <utility>
|
||||||
#include <vector> // Para vector
|
#include <vector> // Para vector
|
||||||
|
|
||||||
#include "external/gif.h" // Para Gif
|
#include "external/gif.h" // Para Gif
|
||||||
@@ -16,9 +17,9 @@
|
|||||||
#include "utils.h" // Para getFileName, Color, printWithDots
|
#include "utils.h" // Para getFileName, Color, printWithDots
|
||||||
|
|
||||||
// Constructor
|
// Constructor
|
||||||
Texture::Texture(SDL_Renderer *renderer, const std::string &path)
|
Texture::Texture(SDL_Renderer *renderer, std::string path)
|
||||||
: renderer_(renderer),
|
: renderer_(renderer),
|
||||||
path_(path) {
|
path_(std::move(path)) {
|
||||||
// Carga el fichero en la textura
|
// Carga el fichero en la textura
|
||||||
if (!path_.empty()) {
|
if (!path_.empty()) {
|
||||||
// Obtiene la extensión
|
// Obtiene la extensión
|
||||||
@@ -53,7 +54,7 @@ Texture::~Texture() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Carga una imagen desde un fichero
|
// Carga una imagen desde un fichero
|
||||||
bool Texture::loadFromFile(const std::string &file_path) {
|
auto Texture::loadFromFile(const std::string &file_path) -> bool {
|
||||||
if (file_path.empty())
|
if (file_path.empty())
|
||||||
return false;
|
return false;
|
||||||
|
|
||||||
@@ -106,7 +107,7 @@ bool Texture::loadFromFile(const std::string &file_path) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Crea una textura en blanco
|
// Crea una textura en blanco
|
||||||
bool Texture::createBlank(int width, int height, SDL_PixelFormat format, SDL_TextureAccess access) {
|
auto Texture::createBlank(int width, int height, SDL_PixelFormat format, SDL_TextureAccess access) -> bool {
|
||||||
// Crea una textura sin inicializar
|
// Crea una textura sin inicializar
|
||||||
texture_ = SDL_CreateTexture(renderer_, format, access, width, height);
|
texture_ = SDL_CreateTexture(renderer_, format, access, width, height);
|
||||||
if (!texture_) {
|
if (!texture_) {
|
||||||
@@ -179,22 +180,22 @@ void Texture::setAsRenderTarget(SDL_Renderer *renderer) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Obtiene el ancho de la imagen
|
// Obtiene el ancho de la imagen
|
||||||
int Texture::getWidth() {
|
auto Texture::getWidth() -> int {
|
||||||
return width_;
|
return width_;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Obtiene el alto de la imagen
|
// Obtiene el alto de la imagen
|
||||||
int Texture::getHeight() {
|
auto Texture::getHeight() -> int {
|
||||||
return height_;
|
return height_;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Recarga la textura
|
// Recarga la textura
|
||||||
bool Texture::reLoad() {
|
auto Texture::reLoad() -> bool {
|
||||||
return loadFromFile(path_);
|
return loadFromFile(path_);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Obtiene la textura
|
// Obtiene la textura
|
||||||
SDL_Texture *Texture::getSDLTexture() {
|
auto Texture::getSDLTexture() -> SDL_Texture * {
|
||||||
return texture_;
|
return texture_;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -206,7 +207,7 @@ void Texture::unloadSurface() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Crea una surface desde un fichero .gif
|
// Crea una surface desde un fichero .gif
|
||||||
std::shared_ptr<Surface> Texture::loadSurface(const std::string &file_path) {
|
auto Texture::loadSurface(const std::string &file_path) -> std::shared_ptr<Surface> {
|
||||||
// Libera la superficie actual
|
// Libera la superficie actual
|
||||||
unloadSurface();
|
unloadSurface();
|
||||||
|
|
||||||
@@ -277,7 +278,7 @@ void Texture::setPaletteColor(int palette, int index, Uint32 color) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Carga una paleta desde un fichero
|
// Carga una paleta desde un fichero
|
||||||
Palette Texture::loadPaletteFromFile(const std::string &file_path) {
|
auto Texture::loadPaletteFromFile(const std::string &file_path) -> Palette {
|
||||||
Palette palette;
|
Palette palette;
|
||||||
|
|
||||||
// Abrir el archivo GIF
|
// Abrir el archivo GIF
|
||||||
@@ -337,10 +338,10 @@ void Texture::setPalette(size_t palette) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Obtiene el renderizador
|
// Obtiene el renderizador
|
||||||
SDL_Renderer *Texture::getRenderer() { return renderer_; }
|
auto Texture::getRenderer() -> SDL_Renderer * { return renderer_; }
|
||||||
|
|
||||||
// Carga una paleta desde un archivo .pal
|
// Carga una paleta desde un archivo .pal
|
||||||
Palette Texture::readPalFile(const std::string &file_path) {
|
auto Texture::readPalFile(const std::string &file_path) -> Palette {
|
||||||
Palette palette{};
|
Palette palette{};
|
||||||
palette.fill(0); // Inicializar todo con 0 (transparente por defecto)
|
palette.fill(0); // Inicializar todo con 0 (transparente por defecto)
|
||||||
|
|
||||||
|
|||||||
@@ -1,9 +1,9 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
#include <SDL3/SDL.h> // Para Uint8, SDL_Renderer, Uint16, SDL_FlipMode, SDL_PixelFormat, SDL_TextureAccess, SDL_Texture, Uint32, SDL_BlendMode, SDL_FPoint, SDL_FRect
|
#include <SDL3/SDL.h> // Para Uint8, SDL_Renderer, Uint16, SDL_FlipMode, SDL_PixelFormat, SDL_TextureAccess, SDL_Texture, Uint32, SDL_BlendMode, SDL_FPoint, SDL_FRect
|
||||||
#include <stddef.h> // Para size_t
|
|
||||||
|
|
||||||
#include <array> // Para array
|
#include <array> // Para array
|
||||||
|
#include <cstddef> // Para size_t
|
||||||
#include <memory> // Para shared_ptr
|
#include <memory> // Para shared_ptr
|
||||||
#include <string> // Para string, basic_string
|
#include <string> // Para string, basic_string
|
||||||
#include <utility>
|
#include <utility>
|
||||||
@@ -28,7 +28,7 @@ struct Surface {
|
|||||||
class Texture {
|
class Texture {
|
||||||
public:
|
public:
|
||||||
// --- Constructores y destructor ---
|
// --- Constructores y destructor ---
|
||||||
explicit Texture(SDL_Renderer *renderer, const std::string &path = std::string());
|
explicit Texture(SDL_Renderer *renderer, std::string path = std::string());
|
||||||
~Texture();
|
~Texture();
|
||||||
|
|
||||||
// --- Carga y creación ---
|
// --- Carga y creación ---
|
||||||
|
|||||||
@@ -1,10 +1,11 @@
|
|||||||
#include "tiled_bg.h"
|
#include "tiled_bg.h"
|
||||||
|
|
||||||
#include <SDL3/SDL.h> // Para SDL_SetRenderTarget, SDL_CreateTexture, SDL_De...
|
#include <SDL3/SDL.h> // Para SDL_SetRenderTarget, SDL_CreateTexture, SDL_De...
|
||||||
#include <stdlib.h> // Para rand
|
|
||||||
|
|
||||||
#include <cmath> // Para sin
|
#include <cmath> // Para sin
|
||||||
|
#include <cstdlib> // Para rand
|
||||||
#include <memory> // Para unique_ptr, make_unique
|
#include <memory> // Para unique_ptr, make_unique
|
||||||
|
#include <numbers>
|
||||||
#include <string> // Para basic_string
|
#include <string> // Para basic_string
|
||||||
|
|
||||||
#include "resource.h" // Para Resource
|
#include "resource.h" // Para Resource
|
||||||
@@ -41,7 +42,7 @@ TiledBG::TiledBG(SDL_FRect pos, TiledBGMode mode)
|
|||||||
|
|
||||||
// Inicializa los valores del vector con los valores del seno
|
// Inicializa los valores del vector con los valores del seno
|
||||||
for (int i = 0; i < 360; ++i) {
|
for (int i = 0; i < 360; ++i) {
|
||||||
sin_[i] = std::sin(i * 3.14159 / 180.0); // Convierte grados a radianes y calcula el seno
|
sin_[i] = std::sin(i * std::numbers::pi / 180.0); // Convierte grados a radianes y calcula el seno
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -53,20 +54,20 @@ TiledBG::~TiledBG() {
|
|||||||
// Rellena la textura con el contenido
|
// Rellena la textura con el contenido
|
||||||
void TiledBG::fillTexture() {
|
void TiledBG::fillTexture() {
|
||||||
// Crea los objetos para pintar en la textura de fondo
|
// Crea los objetos para pintar en la textura de fondo
|
||||||
auto tile = std::make_unique<Sprite>(Resource::get()->getTexture("title_bg_tile.png"), (SDL_FRect){0, 0, TILE_WIDTH_, TILE_HEIGHT_});
|
auto tile = std::make_unique<Sprite>(Resource::get()->getTexture("title_bg_tile.png"), (SDL_FRect){0, 0, TILE_WIDTH, TILE_HEIGHT});
|
||||||
|
|
||||||
// Prepara para dibujar sobre la textura
|
// Prepara para dibujar sobre la textura
|
||||||
auto temp = SDL_GetRenderTarget(renderer_);
|
auto temp = SDL_GetRenderTarget(renderer_);
|
||||||
SDL_SetRenderTarget(renderer_, canvas_);
|
SDL_SetRenderTarget(renderer_, canvas_);
|
||||||
|
|
||||||
// Rellena la textura con el tile
|
// Rellena la textura con el tile
|
||||||
const auto I_MAX = pos_.w * 2 / TILE_WIDTH_;
|
const auto I_MAX = pos_.w * 2 / TILE_WIDTH;
|
||||||
const auto J_MAX = pos_.h * 2 / TILE_HEIGHT_;
|
const auto J_MAX = pos_.h * 2 / TILE_HEIGHT;
|
||||||
tile->setSpriteClip(0, 0, TILE_WIDTH_, TILE_HEIGHT_);
|
tile->setSpriteClip(0, 0, TILE_WIDTH, TILE_HEIGHT);
|
||||||
for (int i = 0; i < I_MAX; ++i) {
|
for (int i = 0; i < I_MAX; ++i) {
|
||||||
for (int j = 0; j < J_MAX; ++j) {
|
for (int j = 0; j < J_MAX; ++j) {
|
||||||
tile->setX(i * TILE_WIDTH_);
|
tile->setX(i * TILE_WIDTH);
|
||||||
tile->setY(j * TILE_HEIGHT_);
|
tile->setY(j * TILE_HEIGHT);
|
||||||
tile->render();
|
tile->render();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -88,8 +89,8 @@ void TiledBG::update() {
|
|||||||
switch (mode_) {
|
switch (mode_) {
|
||||||
case TiledBGMode::DIAGONAL: {
|
case TiledBGMode::DIAGONAL: {
|
||||||
// El tileado de fondo se desplaza en diagonal
|
// El tileado de fondo se desplaza en diagonal
|
||||||
window_.x = static_cast<int>(desp_) % TILE_WIDTH_;
|
window_.x = static_cast<int>(desp_) % TILE_WIDTH;
|
||||||
window_.y = static_cast<int>(desp_) % TILE_HEIGHT_;
|
window_.y = static_cast<int>(desp_) % TILE_HEIGHT;
|
||||||
|
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
@@ -112,7 +113,7 @@ void TiledBG::updateStop() {
|
|||||||
const int UMBRAL = 20 * speed_; // Ajusta este valor según la precisión deseada
|
const int UMBRAL = 20 * speed_; // Ajusta este valor según la precisión deseada
|
||||||
|
|
||||||
// Desacelerar si estamos cerca de completar el ciclo (ventana a punto de regresar a 0)
|
// Desacelerar si estamos cerca de completar el ciclo (ventana a punto de regresar a 0)
|
||||||
if (window_.x >= TILE_WIDTH_ - UMBRAL) {
|
if (window_.x >= TILE_WIDTH - UMBRAL) {
|
||||||
speed_ /= 1.05f; // Reduce gradualmente la velocidad
|
speed_ /= 1.05f; // Reduce gradualmente la velocidad
|
||||||
|
|
||||||
// Asegura que no baje demasiado
|
// Asegura que no baje demasiado
|
||||||
|
|||||||
@@ -35,12 +35,12 @@ class TiledBG {
|
|||||||
void setColor(Color color) { SDL_SetTextureColorMod(canvas_, color.r, color.g, color.b); } // Cambia el color de la textura
|
void setColor(Color color) { SDL_SetTextureColorMod(canvas_, color.r, color.g, color.b); } // Cambia el color de la textura
|
||||||
|
|
||||||
// --- Getters ---
|
// --- Getters ---
|
||||||
bool isStopped() const { return speed_ == 0.0f; } // Indica si está parado
|
[[nodiscard]] auto isStopped() const -> bool { return speed_ == 0.0f; } // Indica si está parado
|
||||||
|
|
||||||
private:
|
private:
|
||||||
// --- Constantes ---
|
// --- Constantes ---
|
||||||
static constexpr int TILE_WIDTH_ = 64; // Ancho del tile
|
static constexpr int TILE_WIDTH = 64; // Ancho del tile
|
||||||
static constexpr int TILE_HEIGHT_ = 64; // Alto del tile
|
static constexpr int TILE_HEIGHT = 64; // Alto del tile
|
||||||
|
|
||||||
// --- Objetos y punteros ---
|
// --- Objetos y punteros ---
|
||||||
SDL_Renderer *renderer_; // El renderizador de la ventana
|
SDL_Renderer *renderer_; // El renderizador de la ventana
|
||||||
|
|||||||
@@ -26,21 +26,21 @@ class MenuOption {
|
|||||||
|
|
||||||
virtual ~MenuOption() = default;
|
virtual ~MenuOption() = default;
|
||||||
|
|
||||||
const std::string &getCaption() const { return caption_; }
|
[[nodiscard]] auto getCaption() const -> const std::string & { return caption_; }
|
||||||
ServiceMenu::SettingsGroup getGroup() const { return group_; }
|
[[nodiscard]] auto getGroup() const -> ServiceMenu::SettingsGroup { return group_; }
|
||||||
bool isHidden() const { return hidden_; }
|
[[nodiscard]] auto isHidden() const -> bool { return hidden_; }
|
||||||
void setHidden(bool hidden) { hidden_ = hidden; }
|
void setHidden(bool hidden) { hidden_ = hidden; }
|
||||||
|
|
||||||
virtual Behavior getBehavior() const = 0;
|
[[nodiscard]] virtual auto getBehavior() const -> Behavior = 0;
|
||||||
virtual std::string getValueAsString() const { return ""; }
|
[[nodiscard]] virtual auto getValueAsString() const -> std::string { return ""; }
|
||||||
virtual void adjustValue(bool adjust_up) {}
|
virtual void adjustValue(bool adjust_up) {}
|
||||||
virtual ServiceMenu::SettingsGroup getTargetGroup() const { return ServiceMenu::SettingsGroup::MAIN; }
|
[[nodiscard]] virtual auto getTargetGroup() const -> ServiceMenu::SettingsGroup { return ServiceMenu::SettingsGroup::MAIN; }
|
||||||
virtual void executeAction() {}
|
virtual void executeAction() {}
|
||||||
|
|
||||||
// Método virtual para que cada opción calcule el ancho de su valor más largo.
|
// Método virtual para que cada opción calcule el ancho de su valor más largo.
|
||||||
virtual int getMaxValueWidth(Text *text_renderer) const { return 0; }
|
virtual auto getMaxValueWidth(Text *text_renderer) const -> int { return 0; }
|
||||||
|
|
||||||
protected:
|
protected:
|
||||||
std::string caption_;
|
std::string caption_;
|
||||||
ServiceMenu::SettingsGroup group_;
|
ServiceMenu::SettingsGroup group_;
|
||||||
bool hidden_;
|
bool hidden_;
|
||||||
@@ -53,14 +53,14 @@ class BoolOption : public MenuOption {
|
|||||||
BoolOption(const std::string &cap, ServiceMenu::SettingsGroup grp, bool *var)
|
BoolOption(const std::string &cap, ServiceMenu::SettingsGroup grp, bool *var)
|
||||||
: MenuOption(cap, grp), linked_variable_(var) {}
|
: MenuOption(cap, grp), linked_variable_(var) {}
|
||||||
|
|
||||||
Behavior getBehavior() const override { return Behavior::ADJUST; }
|
[[nodiscard]] auto getBehavior() const -> Behavior override { return Behavior::ADJUST; }
|
||||||
std::string getValueAsString() const override {
|
[[nodiscard]] auto getValueAsString() const -> std::string override {
|
||||||
return *linked_variable_ ? Lang::getText("[SERVICE_MENU] ON") : Lang::getText("[SERVICE_MENU] OFF");
|
return *linked_variable_ ? Lang::getText("[SERVICE_MENU] ON") : Lang::getText("[SERVICE_MENU] OFF");
|
||||||
}
|
}
|
||||||
void adjustValue(bool /*adjust_up*/) override {
|
void adjustValue(bool /*adjust_up*/) override {
|
||||||
*linked_variable_ = !*linked_variable_;
|
*linked_variable_ = !*linked_variable_;
|
||||||
}
|
}
|
||||||
int getMaxValueWidth(Text *text_renderer) const override {
|
auto getMaxValueWidth(Text *text_renderer) const -> int override {
|
||||||
return std::max(
|
return std::max(
|
||||||
text_renderer->lenght(Lang::getText("[SERVICE_MENU] ON"), -2),
|
text_renderer->lenght(Lang::getText("[SERVICE_MENU] ON"), -2),
|
||||||
text_renderer->lenght(Lang::getText("[SERVICE_MENU] OFF"), -2));
|
text_renderer->lenght(Lang::getText("[SERVICE_MENU] OFF"), -2));
|
||||||
@@ -75,13 +75,13 @@ class IntOption : public MenuOption {
|
|||||||
IntOption(const std::string &cap, ServiceMenu::SettingsGroup grp, int *var, int min, int max, int step)
|
IntOption(const std::string &cap, ServiceMenu::SettingsGroup grp, int *var, int min, int max, int step)
|
||||||
: MenuOption(cap, grp), linked_variable_(var), min_value_(min), max_value_(max), step_value_(step) {}
|
: MenuOption(cap, grp), linked_variable_(var), min_value_(min), max_value_(max), step_value_(step) {}
|
||||||
|
|
||||||
Behavior getBehavior() const override { return Behavior::ADJUST; }
|
[[nodiscard]] auto getBehavior() const -> Behavior override { return Behavior::ADJUST; }
|
||||||
std::string getValueAsString() const override { return std::to_string(*linked_variable_); }
|
[[nodiscard]] auto getValueAsString() const -> std::string override { return std::to_string(*linked_variable_); }
|
||||||
void adjustValue(bool adjust_up) override {
|
void adjustValue(bool adjust_up) override {
|
||||||
int newValue = *linked_variable_ + (adjust_up ? step_value_ : -step_value_);
|
int new_value = *linked_variable_ + (adjust_up ? step_value_ : -step_value_);
|
||||||
*linked_variable_ = std::clamp(newValue, min_value_, max_value_);
|
*linked_variable_ = std::clamp(new_value, min_value_, max_value_);
|
||||||
}
|
}
|
||||||
int getMaxValueWidth(Text *text_renderer) const override {
|
auto getMaxValueWidth(Text *text_renderer) const -> int override {
|
||||||
int max_width = 0;
|
int max_width = 0;
|
||||||
|
|
||||||
// Iterar por todos los valores posibles en el rango
|
// Iterar por todos los valores posibles en el rango
|
||||||
@@ -104,8 +104,7 @@ class ListOption : public MenuOption {
|
|||||||
: MenuOption(cap, grp),
|
: MenuOption(cap, grp),
|
||||||
value_list_(std::move(values)),
|
value_list_(std::move(values)),
|
||||||
getter_(std::move(current_value_getter)),
|
getter_(std::move(current_value_getter)),
|
||||||
setter_(std::move(new_value_setter)),
|
setter_(std::move(new_value_setter)) {
|
||||||
list_index_(0) {
|
|
||||||
sync();
|
sync();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -119,8 +118,8 @@ class ListOption : public MenuOption {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
Behavior getBehavior() const override { return Behavior::ADJUST; }
|
[[nodiscard]] auto getBehavior() const -> Behavior override { return Behavior::ADJUST; }
|
||||||
std::string getValueAsString() const override {
|
[[nodiscard]] auto getValueAsString() const -> std::string override {
|
||||||
return value_list_.empty() ? "" : value_list_[list_index_];
|
return value_list_.empty() ? "" : value_list_[list_index_];
|
||||||
}
|
}
|
||||||
void adjustValue(bool adjust_up) override {
|
void adjustValue(bool adjust_up) override {
|
||||||
@@ -131,7 +130,7 @@ class ListOption : public MenuOption {
|
|||||||
: (list_index_ + size - 1) % size;
|
: (list_index_ + size - 1) % size;
|
||||||
setter_(value_list_[list_index_]);
|
setter_(value_list_[list_index_]);
|
||||||
}
|
}
|
||||||
int getMaxValueWidth(Text *text_renderer) const override {
|
auto getMaxValueWidth(Text *text_renderer) const -> int override {
|
||||||
int max_w = 0;
|
int max_w = 0;
|
||||||
for (const auto &val : value_list_) {
|
for (const auto &val : value_list_) {
|
||||||
max_w = std::max(max_w, text_renderer->lenght(val, -2));
|
max_w = std::max(max_w, text_renderer->lenght(val, -2));
|
||||||
@@ -143,7 +142,7 @@ class ListOption : public MenuOption {
|
|||||||
std::vector<std::string> value_list_;
|
std::vector<std::string> value_list_;
|
||||||
std::function<std::string()> getter_;
|
std::function<std::string()> getter_;
|
||||||
std::function<void(const std::string &)> setter_;
|
std::function<void(const std::string &)> setter_;
|
||||||
size_t list_index_;
|
size_t list_index_{0};
|
||||||
};
|
};
|
||||||
|
|
||||||
class FolderOption : public MenuOption {
|
class FolderOption : public MenuOption {
|
||||||
@@ -151,10 +150,10 @@ class FolderOption : public MenuOption {
|
|||||||
FolderOption(const std::string &cap, ServiceMenu::SettingsGroup grp, ServiceMenu::SettingsGroup target)
|
FolderOption(const std::string &cap, ServiceMenu::SettingsGroup grp, ServiceMenu::SettingsGroup target)
|
||||||
: MenuOption(cap, grp), target_group_(target) {}
|
: MenuOption(cap, grp), target_group_(target) {}
|
||||||
|
|
||||||
Behavior getBehavior() const override { return Behavior::SELECT; }
|
[[nodiscard]] auto getBehavior() const -> Behavior override { return Behavior::SELECT; }
|
||||||
ServiceMenu::SettingsGroup getTargetGroup() const override { return target_group_; }
|
[[nodiscard]] auto getTargetGroup() const -> ServiceMenu::SettingsGroup override { return target_group_; }
|
||||||
|
|
||||||
private:
|
private:
|
||||||
ServiceMenu::SettingsGroup target_group_;
|
ServiceMenu::SettingsGroup target_group_;
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -163,7 +162,7 @@ class ActionOption : public MenuOption {
|
|||||||
ActionOption(const std::string &cap, ServiceMenu::SettingsGroup grp, std::function<void()> action, bool hidden = false)
|
ActionOption(const std::string &cap, ServiceMenu::SettingsGroup grp, std::function<void()> action, bool hidden = false)
|
||||||
: MenuOption(cap, grp, hidden), action_(std::move(action)) {}
|
: MenuOption(cap, grp, hidden), action_(std::move(action)) {}
|
||||||
|
|
||||||
Behavior getBehavior() const override { return Behavior::SELECT; }
|
[[nodiscard]] auto getBehavior() const -> Behavior override { return Behavior::SELECT; }
|
||||||
void executeAction() override {
|
void executeAction() override {
|
||||||
if (action_)
|
if (action_)
|
||||||
action_();
|
action_();
|
||||||
|
|||||||
@@ -37,7 +37,7 @@ void MenuRenderer::render(const ServiceMenu *menu_state) {
|
|||||||
// Dibuja la línea separadora
|
// Dibuja la línea separadora
|
||||||
y = rect_.y + upper_height_;
|
y = rect_.y + upper_height_;
|
||||||
SDL_SetRenderDrawColor(Screen::get()->getRenderer(), BORDER_COLOR.r, BORDER_COLOR.g, BORDER_COLOR.b, 255);
|
SDL_SetRenderDrawColor(Screen::get()->getRenderer(), BORDER_COLOR.r, BORDER_COLOR.g, BORDER_COLOR.b, 255);
|
||||||
SDL_RenderLine(Screen::get()->getRenderer(), rect_.x + ServiceMenu::OPTIONS_HORIZONTAL_PADDING_, y, rect_.x + rect_.w - ServiceMenu::OPTIONS_HORIZONTAL_PADDING_, y);
|
SDL_RenderLine(Screen::get()->getRenderer(), rect_.x + ServiceMenu::OPTIONS_HORIZONTAL_PADDING, y, rect_.x + rect_.w - ServiceMenu::OPTIONS_HORIZONTAL_PADDING, y);
|
||||||
|
|
||||||
// Dibuja las opciones
|
// Dibuja las opciones
|
||||||
y = options_y_;
|
y = options_y_;
|
||||||
@@ -47,8 +47,8 @@ void MenuRenderer::render(const ServiceMenu *menu_state) {
|
|||||||
const Color ¤t_color = IS_SELECTED ? param.service_menu.selected_color : param.service_menu.text_color;
|
const Color ¤t_color = IS_SELECTED ? param.service_menu.selected_color : param.service_menu.text_color;
|
||||||
|
|
||||||
if (menu_state->getCurrentGroupAlignment() == ServiceMenu::GroupAlignment::LEFT) {
|
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);
|
element_text_->writeColored(rect_.x + ServiceMenu::OPTIONS_HORIZONTAL_PADDING, y, option_pairs.at(i).first, current_color, -2);
|
||||||
const int X = rect_.x + rect_.w - ServiceMenu::OPTIONS_HORIZONTAL_PADDING_ - element_text_->lenght(option_pairs.at(i).second, -2);
|
const int X = rect_.x + rect_.w - ServiceMenu::OPTIONS_HORIZONTAL_PADDING - element_text_->lenght(option_pairs.at(i).second, -2);
|
||||||
element_text_->writeColored(X, y, option_pairs.at(i).second, current_color, -2);
|
element_text_->writeColored(X, y, option_pairs.at(i).second, current_color, -2);
|
||||||
} else {
|
} else {
|
||||||
element_text_->writeDX(TEXT_CENTER | TEXT_COLOR, rect_.x + rect_.w / 2, y, option_pairs.at(i).first, -2, current_color);
|
element_text_->writeDX(TEXT_CENTER | TEXT_COLOR, rect_.x + rect_.w / 2, y, option_pairs.at(i).first, -2, current_color);
|
||||||
@@ -96,11 +96,11 @@ void MenuRenderer::setAnchors(const ServiceMenu *menu_state) {
|
|||||||
lower_padding_ = (options_padding_ * 3);
|
lower_padding_ = (options_padding_ * 3);
|
||||||
lower_height_ = ((max_entries > 0 ? max_entries - 1 : 0) * (options_height_ + options_padding_)) + options_height_ + (lower_padding_ * 2);
|
lower_height_ = ((max_entries > 0 ? max_entries - 1 : 0) * (options_height_ + options_padding_)) + options_height_ + (lower_padding_ * 2);
|
||||||
|
|
||||||
width_ = ServiceMenu::MIN_WIDTH_;
|
width_ = ServiceMenu::MIN_WIDTH;
|
||||||
height_ = upper_height_ + lower_height_;
|
height_ = upper_height_ + lower_height_;
|
||||||
}
|
}
|
||||||
|
|
||||||
SDL_FRect MenuRenderer::calculateNewRect(const ServiceMenu *menu_state) {
|
auto MenuRenderer::calculateNewRect(const ServiceMenu *menu_state) -> SDL_FRect {
|
||||||
width_ = getMenuWidthForGroup(menu_state->getCurrentGroup());
|
width_ = getMenuWidthForGroup(menu_state->getCurrentGroup());
|
||||||
const auto &display_options = menu_state->getDisplayOptions();
|
const auto &display_options = menu_state->getDisplayOptions();
|
||||||
lower_height_ = ((display_options.size() > 0 ? display_options.size() - 1 : 0) * (options_height_ + options_padding_)) + options_height_ + (lower_padding_ * 2);
|
lower_height_ = ((display_options.size() > 0 ? display_options.size() - 1 : 0) * (options_height_ + options_padding_)) + options_height_ + (lower_padding_ * 2);
|
||||||
@@ -151,7 +151,7 @@ void MenuRenderer::updateResizeAnimation() {
|
|||||||
|
|
||||||
void MenuRenderer::precalculateMenuWidths(const std::vector<std::unique_ptr<MenuOption>> &all_options, const ServiceMenu *menu_state) {
|
void MenuRenderer::precalculateMenuWidths(const std::vector<std::unique_ptr<MenuOption>> &all_options, const ServiceMenu *menu_state) {
|
||||||
for (int &w : group_menu_widths_)
|
for (int &w : group_menu_widths_)
|
||||||
w = ServiceMenu::MIN_WIDTH_;
|
w = ServiceMenu::MIN_WIDTH;
|
||||||
for (int group = 0; group < 5; ++group) {
|
for (int group = 0; group < 5; ++group) {
|
||||||
auto sg = static_cast<ServiceMenu::SettingsGroup>(group);
|
auto sg = static_cast<ServiceMenu::SettingsGroup>(group);
|
||||||
int max_option_width = 0;
|
int max_option_width = 0;
|
||||||
@@ -164,15 +164,15 @@ void MenuRenderer::precalculateMenuWidths(const std::vector<std::unique_ptr<Menu
|
|||||||
max_value_width = std::max(max_value_width, option->getMaxValueWidth(element_text_.get()));
|
max_value_width = std::max(max_value_width, option->getMaxValueWidth(element_text_.get()));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
size_t total_width = max_option_width + (ServiceMenu::OPTIONS_HORIZONTAL_PADDING_ * 2);
|
size_t total_width = max_option_width + (ServiceMenu::OPTIONS_HORIZONTAL_PADDING * 2);
|
||||||
if (menu_state->getCurrentGroupAlignment() == ServiceMenu::GroupAlignment::LEFT) {
|
if (menu_state->getCurrentGroupAlignment() == ServiceMenu::GroupAlignment::LEFT) {
|
||||||
total_width += ServiceMenu::MIN_GAP_OPTION_VALUE_ + max_value_width;
|
total_width += ServiceMenu::MIN_GAP_OPTION_VALUE + max_value_width;
|
||||||
}
|
}
|
||||||
group_menu_widths_[group] = std::max((int)ServiceMenu::MIN_WIDTH_, (int)total_width);
|
group_menu_widths_[group] = std::max((int)ServiceMenu::MIN_WIDTH, (int)total_width);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
int MenuRenderer::getMenuWidthForGroup(ServiceMenu::SettingsGroup group) const {
|
auto MenuRenderer::getMenuWidthForGroup(ServiceMenu::SettingsGroup group) const -> int {
|
||||||
return group_menu_widths_[static_cast<int>(group)];
|
return group_menu_widths_[static_cast<int>(group)];
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -185,12 +185,12 @@ void MenuRenderer::updateColorCounter() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
Color MenuRenderer::getAnimatedSelectedColor() {
|
auto MenuRenderer::getAnimatedSelectedColor() -> Color {
|
||||||
static auto color_cycle_ = generateMirroredCycle(param.service_menu.selected_color, ColorCycleStyle::HUE_WAVE);
|
static auto color_cycle_ = generateMirroredCycle(param.service_menu.selected_color, ColorCycleStyle::HUE_WAVE);
|
||||||
return color_cycle_.at(color_counter_ % color_cycle_.size());
|
return color_cycle_.at(color_counter_ % color_cycle_.size());
|
||||||
}
|
}
|
||||||
|
|
||||||
SDL_FRect MenuRenderer::setRect(SDL_FRect rect) {
|
auto MenuRenderer::setRect(SDL_FRect rect) -> SDL_FRect {
|
||||||
border_rect_ = {rect.x - 1, rect.y + 1, rect.w + 2, rect.h - 2};
|
border_rect_ = {rect.x - 1, rect.y + 1, rect.w + 2, rect.h - 2};
|
||||||
return rect;
|
return rect;
|
||||||
}
|
}
|
||||||
@@ -1,8 +1,8 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
#include <SDL3/SDL.h> // Para SDL_FRect, Uint32
|
#include <SDL3/SDL.h> // Para SDL_FRect, Uint32
|
||||||
#include <stddef.h> // Para size_t
|
|
||||||
|
|
||||||
|
#include <cstddef> // Para size_t
|
||||||
#include <memory> // Para shared_ptr, unique_ptr
|
#include <memory> // Para shared_ptr, unique_ptr
|
||||||
#include <vector> // Para vector
|
#include <vector> // Para vector
|
||||||
|
|
||||||
@@ -26,9 +26,9 @@ class MenuRenderer {
|
|||||||
void setLayout(const ServiceMenu *menu_state);
|
void setLayout(const ServiceMenu *menu_state);
|
||||||
|
|
||||||
// Getters
|
// Getters
|
||||||
const SDL_FRect &getRect() const { return rect_; }
|
[[nodiscard]] auto getRect() const -> const SDL_FRect & { return rect_; }
|
||||||
|
|
||||||
private:
|
private:
|
||||||
// --- Referencias a los renderizadores de texto ---
|
// --- Referencias a los renderizadores de texto ---
|
||||||
std::shared_ptr<Text> element_text_;
|
std::shared_ptr<Text> element_text_;
|
||||||
std::shared_ptr<Text> title_text_;
|
std::shared_ptr<Text> title_text_;
|
||||||
@@ -60,13 +60,13 @@ class MenuRenderer {
|
|||||||
|
|
||||||
// --- Métodos privados de la vista ---
|
// --- Métodos privados de la vista ---
|
||||||
void setAnchors(const ServiceMenu *menu_state);
|
void setAnchors(const ServiceMenu *menu_state);
|
||||||
SDL_FRect calculateNewRect(const ServiceMenu *menu_state);
|
auto calculateNewRect(const ServiceMenu *menu_state) -> SDL_FRect;
|
||||||
void resize(const ServiceMenu *menu_state);
|
void resize(const ServiceMenu *menu_state);
|
||||||
void setSize(const ServiceMenu *menu_state);
|
void setSize(const ServiceMenu *menu_state);
|
||||||
void updateResizeAnimation();
|
void updateResizeAnimation();
|
||||||
void precalculateMenuWidths(const std::vector<std::unique_ptr<MenuOption>> &all_options, const ServiceMenu *menu_state);
|
void precalculateMenuWidths(const std::vector<std::unique_ptr<MenuOption>> &all_options, const ServiceMenu *menu_state);
|
||||||
int getMenuWidthForGroup(ServiceMenu::SettingsGroup group) const;
|
[[nodiscard]] auto getMenuWidthForGroup(ServiceMenu::SettingsGroup group) const -> int;
|
||||||
Color getAnimatedSelectedColor();
|
auto getAnimatedSelectedColor() -> Color;
|
||||||
void updateColorCounter();
|
void updateColorCounter();
|
||||||
SDL_FRect setRect(SDL_FRect rect);
|
auto setRect(SDL_FRect rect) -> SDL_FRect;
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -13,10 +13,10 @@
|
|||||||
#include "utils.h" // Para Zone
|
#include "utils.h" // Para Zone
|
||||||
|
|
||||||
// Singleton
|
// Singleton
|
||||||
ServiceMenu *ServiceMenu::instance_ = nullptr;
|
ServiceMenu *ServiceMenu::instance = nullptr;
|
||||||
void ServiceMenu::init() { ServiceMenu::instance_ = new ServiceMenu(); }
|
void ServiceMenu::init() { ServiceMenu::instance = new ServiceMenu(); }
|
||||||
void ServiceMenu::destroy() { delete ServiceMenu::instance_; }
|
void ServiceMenu::destroy() { delete ServiceMenu::instance; }
|
||||||
ServiceMenu *ServiceMenu::get() { return ServiceMenu::instance_; }
|
auto ServiceMenu::get() -> ServiceMenu * { return ServiceMenu::instance; }
|
||||||
|
|
||||||
// Constructor
|
// Constructor
|
||||||
ServiceMenu::ServiceMenu()
|
ServiceMenu::ServiceMenu()
|
||||||
@@ -106,7 +106,13 @@ void ServiceMenu::selectOption() {
|
|||||||
return;
|
return;
|
||||||
if (current_settings_group_ == SettingsGroup::MAIN)
|
if (current_settings_group_ == SettingsGroup::MAIN)
|
||||||
main_menu_selected_ = selected_;
|
main_menu_selected_ = selected_;
|
||||||
auto &selected_option = display_options_.at(selected_);
|
|
||||||
|
auto *selected_option = display_options_.at(selected_);
|
||||||
|
if (!selected_option) {
|
||||||
|
// This shouldn't happen in normal operation, but protects against null pointer
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
if (auto folder = dynamic_cast<FolderOption *>(selected_option)) {
|
if (auto folder = dynamic_cast<FolderOption *>(selected_option)) {
|
||||||
previous_settings_group_ = current_settings_group_;
|
previous_settings_group_ = current_settings_group_;
|
||||||
current_settings_group_ = folder->getTargetGroup();
|
current_settings_group_ = folder->getTargetGroup();
|
||||||
@@ -150,7 +156,7 @@ void ServiceMenu::updateOptionPairs() {
|
|||||||
|
|
||||||
void ServiceMenu::updateMenu() {
|
void ServiceMenu::updateMenu() {
|
||||||
title_ = settingsGroupToString(current_settings_group_);
|
title_ = settingsGroupToString(current_settings_group_);
|
||||||
AdjustListValues();
|
adjustListValues();
|
||||||
|
|
||||||
// Actualiza las opciones visibles
|
// Actualiza las opciones visibles
|
||||||
updateDisplayOptions();
|
updateDisplayOptions();
|
||||||
@@ -184,7 +190,7 @@ void ServiceMenu::applySettingsSettings() {
|
|||||||
setHiddenOptions();
|
setHiddenOptions();
|
||||||
}
|
}
|
||||||
|
|
||||||
MenuOption *ServiceMenu::getOptionByCaption(const std::string &caption) const {
|
auto ServiceMenu::getOptionByCaption(const std::string &caption) const -> MenuOption * {
|
||||||
for (const auto &option : options_) {
|
for (const auto &option : options_) {
|
||||||
if (option->getCaption() == caption) {
|
if (option->getCaption() == caption) {
|
||||||
return option.get();
|
return option.get();
|
||||||
@@ -195,7 +201,7 @@ MenuOption *ServiceMenu::getOptionByCaption(const std::string &caption) const {
|
|||||||
|
|
||||||
// --- Getters y otros ---
|
// --- Getters y otros ---
|
||||||
|
|
||||||
ServiceMenu::GroupAlignment ServiceMenu::getCurrentGroupAlignment() const {
|
auto ServiceMenu::getCurrentGroupAlignment() const -> ServiceMenu::GroupAlignment {
|
||||||
switch (current_settings_group_) {
|
switch (current_settings_group_) {
|
||||||
case SettingsGroup::VIDEO:
|
case SettingsGroup::VIDEO:
|
||||||
case SettingsGroup::AUDIO:
|
case SettingsGroup::AUDIO:
|
||||||
@@ -206,7 +212,7 @@ ServiceMenu::GroupAlignment ServiceMenu::getCurrentGroupAlignment() const {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
size_t ServiceMenu::countOptionsInGroup(SettingsGroup group) const {
|
auto ServiceMenu::countOptionsInGroup(SettingsGroup group) const -> size_t {
|
||||||
size_t count = 0;
|
size_t count = 0;
|
||||||
for (const auto &option : options_) {
|
for (const auto &option : options_) {
|
||||||
if (option->getGroup() == group && !option->isHidden()) {
|
if (option->getGroup() == group && !option->isHidden()) {
|
||||||
@@ -254,7 +260,7 @@ void ServiceMenu::initializeOptions() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Sincroniza los valores de las opciones tipo lista
|
// Sincroniza los valores de las opciones tipo lista
|
||||||
void ServiceMenu::AdjustListValues() {
|
void ServiceMenu::adjustListValues() {
|
||||||
for (auto &option : options_) {
|
for (auto &option : options_) {
|
||||||
if (auto list_option = dynamic_cast<ListOption *>(option.get())) {
|
if (auto list_option = dynamic_cast<ListOption *>(option.get())) {
|
||||||
list_option->sync();
|
list_option->sync();
|
||||||
@@ -269,7 +275,7 @@ void ServiceMenu::playSelectSound() { Audio::get()->playSound("service_menu_sele
|
|||||||
void ServiceMenu::playBackSound() { Audio::get()->playSound("service_menu_select.wav", Audio::Group::INTERFACE); }
|
void ServiceMenu::playBackSound() { Audio::get()->playSound("service_menu_select.wav", Audio::Group::INTERFACE); }
|
||||||
|
|
||||||
// Devuelve el nombre del grupo como string para el título
|
// Devuelve el nombre del grupo como string para el título
|
||||||
std::string ServiceMenu::settingsGroupToString(SettingsGroup group) const {
|
auto ServiceMenu::settingsGroupToString(SettingsGroup group) const -> std::string {
|
||||||
switch (group) {
|
switch (group) {
|
||||||
case SettingsGroup::MAIN:
|
case SettingsGroup::MAIN:
|
||||||
return Lang::getText("[SERVICE_MENU] TITLE");
|
return Lang::getText("[SERVICE_MENU] TITLE");
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
#include <stddef.h> // Para size_t
|
#include <cstddef> // Para size_t
|
||||||
|
|
||||||
#include <memory> // Para unique_ptr
|
#include <memory> // Para unique_ptr
|
||||||
#include <string> // Para basic_string, string
|
#include <string> // Para basic_string, string
|
||||||
#include <utility> // Para pair
|
#include <utility> // Para pair
|
||||||
@@ -28,13 +27,13 @@ class ServiceMenu {
|
|||||||
};
|
};
|
||||||
|
|
||||||
// --- Constantes públicas que el Renderer podría necesitar ---
|
// --- Constantes públicas que el Renderer podría necesitar ---
|
||||||
static constexpr size_t OPTIONS_HORIZONTAL_PADDING_ = 20;
|
static constexpr size_t OPTIONS_HORIZONTAL_PADDING = 20;
|
||||||
static constexpr size_t MIN_WIDTH_ = 240;
|
static constexpr size_t MIN_WIDTH = 240;
|
||||||
static constexpr size_t MIN_GAP_OPTION_VALUE_ = 30;
|
static constexpr size_t MIN_GAP_OPTION_VALUE = 30;
|
||||||
|
|
||||||
static void init();
|
static void init();
|
||||||
static void destroy();
|
static void destroy();
|
||||||
static ServiceMenu *get();
|
static auto get() -> ServiceMenu *;
|
||||||
|
|
||||||
void toggle();
|
void toggle();
|
||||||
void render();
|
void render();
|
||||||
@@ -49,17 +48,17 @@ class ServiceMenu {
|
|||||||
void moveBack();
|
void moveBack();
|
||||||
|
|
||||||
// --- Getters para que el Renderer pueda leer el estado ---
|
// --- Getters para que el Renderer pueda leer el estado ---
|
||||||
bool isEnabled() const { return enabled_; }
|
[[nodiscard]] auto isEnabled() const -> bool { return enabled_; }
|
||||||
const std::string &getTitle() const { return title_; }
|
[[nodiscard]] auto getTitle() const -> const std::string & { return title_; }
|
||||||
SettingsGroup getCurrentGroup() const { return current_settings_group_; }
|
[[nodiscard]] auto getCurrentGroup() const -> SettingsGroup { return current_settings_group_; }
|
||||||
GroupAlignment getCurrentGroupAlignment() const;
|
[[nodiscard]] auto getCurrentGroupAlignment() const -> GroupAlignment;
|
||||||
const std::vector<MenuOption *> &getDisplayOptions() const { return display_options_; }
|
[[nodiscard]] auto getDisplayOptions() const -> const std::vector<MenuOption *> & { return display_options_; }
|
||||||
const std::vector<std::unique_ptr<MenuOption>> &getAllOptions() const { return options_; }
|
[[nodiscard]] auto getAllOptions() const -> const std::vector<std::unique_ptr<MenuOption>> & { return options_; }
|
||||||
size_t getSelectedIndex() const { return selected_; }
|
[[nodiscard]] auto getSelectedIndex() const -> size_t { return selected_; }
|
||||||
const std::vector<std::pair<std::string, std::string>> &getOptionPairs() const { return option_pairs_; }
|
[[nodiscard]] auto getOptionPairs() const -> const std::vector<std::pair<std::string, std::string>> & { return option_pairs_; }
|
||||||
size_t countOptionsInGroup(SettingsGroup group) const;
|
[[nodiscard]] auto countOptionsInGroup(SettingsGroup group) const -> size_t;
|
||||||
|
|
||||||
private:
|
private:
|
||||||
// --- Lógica de estado del menú (Modelo) ---
|
// --- Lógica de estado del menú (Modelo) ---
|
||||||
bool enabled_ = false;
|
bool enabled_ = false;
|
||||||
std::vector<std::unique_ptr<MenuOption>> options_;
|
std::vector<std::unique_ptr<MenuOption>> options_;
|
||||||
@@ -88,19 +87,19 @@ class ServiceMenu {
|
|||||||
void applyVideoSettings();
|
void applyVideoSettings();
|
||||||
void applyAudioSettings();
|
void applyAudioSettings();
|
||||||
void applySettingsSettings();
|
void applySettingsSettings();
|
||||||
MenuOption *getOptionByCaption(const std::string &caption) const;
|
[[nodiscard]] auto getOptionByCaption(const std::string &caption) const -> MenuOption *;
|
||||||
void AdjustListValues();
|
void adjustListValues();
|
||||||
void playMoveSound();
|
void playMoveSound();
|
||||||
void playAdjustSound();
|
void playAdjustSound();
|
||||||
void playSelectSound();
|
void playSelectSound();
|
||||||
void playBackSound();
|
void playBackSound();
|
||||||
std::string settingsGroupToString(SettingsGroup group) const;
|
[[nodiscard]] auto settingsGroupToString(SettingsGroup group) const -> std::string;
|
||||||
void setHiddenOptions();
|
void setHiddenOptions();
|
||||||
|
|
||||||
// --- Singleton ---
|
// --- Singleton ---
|
||||||
ServiceMenu();
|
ServiceMenu();
|
||||||
~ServiceMenu() = default;
|
~ServiceMenu() = default;
|
||||||
ServiceMenu(const ServiceMenu &) = delete;
|
ServiceMenu(const ServiceMenu &) = delete;
|
||||||
ServiceMenu &operator=(const ServiceMenu &) = delete;
|
auto operator=(const ServiceMenu &) -> ServiceMenu & = delete;
|
||||||
static ServiceMenu *instance_;
|
static ServiceMenu *instance;
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,19 +1,20 @@
|
|||||||
#include "ui_message.h"
|
#include "ui_message.h"
|
||||||
|
|
||||||
#include <cmath> // Para pow
|
#include <cmath> // Para pow
|
||||||
|
#include <utility>
|
||||||
|
|
||||||
#include "text.h" // Para TEXT_CENTER, TEXT_COLOR, Text
|
#include "text.h" // Para TEXT_CENTER, TEXT_COLOR, Text
|
||||||
|
|
||||||
// Constructor: inicializa el renderizador, el texto y el color del mensaje
|
// Constructor: inicializa el renderizador, el texto y el color del mensaje
|
||||||
UIMessage::UIMessage(std::shared_ptr<Text> text_renderer, const std::string &message_text, const Color &color)
|
UIMessage::UIMessage(std::shared_ptr<Text> text_renderer, std::string message_text, const Color &color)
|
||||||
: text_renderer_(text_renderer), text_(message_text), color_(color) {}
|
: text_renderer_(std::move(text_renderer)), text_(std::move(message_text)), color_(color) {}
|
||||||
|
|
||||||
// Muestra el mensaje en la posición base_x, base_y con animación de entrada desde arriba
|
// Muestra el mensaje en la posición base_x, base_y con animación de entrada desde arriba
|
||||||
void UIMessage::show() {
|
void UIMessage::show() {
|
||||||
if (visible_ && target_y_ == 0.0f)
|
if (visible_ && target_y_ == 0.0f)
|
||||||
return; // Ya está visible y quieto
|
return; // Ya está visible y quieto
|
||||||
|
|
||||||
start_y_ = DESP_; // Empieza 8 píxeles arriba de la posición base
|
start_y_ = DESP; // Empieza 8 píxeles arriba de la posición base
|
||||||
target_y_ = 0.0f; // La posición final es la base
|
target_y_ = 0.0f; // La posición final es la base
|
||||||
y_offset_ = start_y_;
|
y_offset_ = start_y_;
|
||||||
anim_step_ = 0;
|
anim_step_ = 0;
|
||||||
@@ -27,7 +28,7 @@ void UIMessage::hide() {
|
|||||||
return;
|
return;
|
||||||
|
|
||||||
start_y_ = y_offset_; // Comienza desde la posición actual
|
start_y_ = y_offset_; // Comienza desde la posición actual
|
||||||
target_y_ = DESP_; // Termina 8 píxeles arriba de la base
|
target_y_ = DESP; // Termina 8 píxeles arriba de la base
|
||||||
anim_step_ = 0;
|
anim_step_ = 0;
|
||||||
animating_ = true;
|
animating_ = true;
|
||||||
}
|
}
|
||||||
@@ -76,7 +77,7 @@ void UIMessage::render() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Devuelve true si el mensaje está visible actualmente
|
// Devuelve true si el mensaje está visible actualmente
|
||||||
bool UIMessage::isVisible() const {
|
auto UIMessage::isVisible() const -> bool {
|
||||||
return visible_;
|
return visible_;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ class Text;
|
|||||||
class UIMessage {
|
class UIMessage {
|
||||||
public:
|
public:
|
||||||
// Constructor: recibe el renderizador de texto, el mensaje y el color
|
// Constructor: recibe el renderizador de texto, el mensaje y el color
|
||||||
UIMessage(std::shared_ptr<Text> text_renderer, const std::string &message_text, const Color &color);
|
UIMessage(std::shared_ptr<Text> text_renderer, std::string message_text, const Color &color);
|
||||||
|
|
||||||
// Muestra el mensaje con animación de entrada
|
// Muestra el mensaje con animación de entrada
|
||||||
void show();
|
void show();
|
||||||
@@ -26,7 +26,7 @@ class UIMessage {
|
|||||||
void render();
|
void render();
|
||||||
|
|
||||||
// Indica si el mensaje está visible actualmente
|
// Indica si el mensaje está visible actualmente
|
||||||
bool isVisible() const;
|
[[nodiscard]] auto isVisible() const -> bool;
|
||||||
|
|
||||||
// Permite actualizar la posición del mensaje (por ejemplo, si el menú se mueve)
|
// Permite actualizar la posición del mensaje (por ejemplo, si el menú se mueve)
|
||||||
void setPosition(float new_base_x, float new_base_y);
|
void setPosition(float new_base_x, float new_base_y);
|
||||||
@@ -49,7 +49,7 @@ class UIMessage {
|
|||||||
float target_y_ = 0.0f; // Posición Y objetivo de la animación
|
float target_y_ = 0.0f; // Posición Y objetivo de la animación
|
||||||
int anim_step_ = 0; // Paso actual de la animación
|
int anim_step_ = 0; // Paso actual de la animación
|
||||||
static constexpr int ANIMATION_STEPS = 8; // Número total de pasos de la animación
|
static constexpr int ANIMATION_STEPS = 8; // Número total de pasos de la animación
|
||||||
static constexpr float DESP_ = -8.0f; // Distancia a desplazarse
|
static constexpr float DESP = -8.0f; // Distancia a desplazarse
|
||||||
|
|
||||||
// Actualiza la interpolación de la animación (ease out/in cubic)
|
// Actualiza la interpolación de la animación (ease out/in cubic)
|
||||||
void updateAnimation();
|
void updateAnimation();
|
||||||
|
|||||||
@@ -67,7 +67,7 @@ void Writer::setEnabled(bool value) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Obtiene el valor de la variable
|
// Obtiene el valor de la variable
|
||||||
bool Writer::IsEnabled() const {
|
auto Writer::isEnabled() const -> bool {
|
||||||
return enabled_;
|
return enabled_;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -82,6 +82,6 @@ void Writer::center(int x) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Obtiene el valor de la variable
|
// Obtiene el valor de la variable
|
||||||
bool Writer::hasFinished() const {
|
auto Writer::hasFinished() const -> bool {
|
||||||
return finished_;
|
return finished_;
|
||||||
}
|
}
|
||||||
@@ -2,6 +2,7 @@
|
|||||||
|
|
||||||
#include <memory> // Para shared_ptr
|
#include <memory> // Para shared_ptr
|
||||||
#include <string> // Para string
|
#include <string> // Para string
|
||||||
|
#include <utility>
|
||||||
|
|
||||||
class Text;
|
class Text;
|
||||||
|
|
||||||
@@ -10,7 +11,7 @@ class Writer {
|
|||||||
public:
|
public:
|
||||||
// Constructor
|
// Constructor
|
||||||
explicit Writer(std::shared_ptr<Text> text)
|
explicit Writer(std::shared_ptr<Text> text)
|
||||||
: text_(text) {}
|
: text_(std::move(text)) {}
|
||||||
|
|
||||||
// Destructor
|
// Destructor
|
||||||
~Writer() = default;
|
~Writer() = default;
|
||||||
@@ -34,8 +35,8 @@ class Writer {
|
|||||||
void center(int x);
|
void center(int x);
|
||||||
|
|
||||||
// Getters
|
// Getters
|
||||||
bool IsEnabled() const; // Indica si el objeto está habilitado
|
[[nodiscard]] auto isEnabled() const -> bool; // Indica si el objeto está habilitado
|
||||||
bool hasFinished() const; // Indica si ya ha terminado
|
[[nodiscard]] auto hasFinished() const -> bool; // Indica si ya ha terminado
|
||||||
|
|
||||||
private:
|
private:
|
||||||
// --- Objetos y punteros ---
|
// --- Objetos y punteros ---
|
||||||
|
|||||||
Reference in New Issue
Block a user