clang-tidy modernize
This commit is contained in:
@@ -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
|
||||||
|
|||||||
@@ -1,10 +1,10 @@
|
|||||||
#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 <memory> // Para unique_ptr, shared_ptr
|
#include <cstddef> // Para size_t
|
||||||
#include <vector> // Para vector
|
#include <memory> // Para unique_ptr, shared_ptr
|
||||||
|
#include <vector> // Para vector
|
||||||
|
|
||||||
#include "utils.h" // Para Color
|
#include "utils.h" // Para Color
|
||||||
|
|
||||||
|
|||||||
@@ -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; }
|
||||||
|
|||||||
@@ -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
|
||||||
|
|||||||
@@ -46,13 +46,13 @@ 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();
|
||||||
@@ -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,17 +34,17 @@ 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;
|
||||||
@@ -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 <memory> // Para shared_ptr
|
#include <cstddef> // Para size_t
|
||||||
#include <string> // Para basic_string, string
|
#include <memory> // Para shared_ptr
|
||||||
|
#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,9 +1,8 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
#include <stddef.h> // Para size_t
|
#include <array> // Para array
|
||||||
|
#include <cstddef> // Para size_t
|
||||||
#include <array> // Para array
|
#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;
|
||||||
};
|
};
|
||||||
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,9 +1,9 @@
|
|||||||
#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
|
||||||
@@ -18,11 +18,11 @@ void Input::init(const std::string &game_controller_db_path) { Input::instance =
|
|||||||
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,10 +139,10 @@ 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 ---
|
||||||
|
|||||||
@@ -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,7 +4,8 @@
|
|||||||
|
|
||||||
#include <algorithm> // Para remove_if
|
#include <algorithm> // Para remove_if
|
||||||
#include <string> // Para basic_string, string
|
#include <string> // Para basic_string, string
|
||||||
#include <vector> // Para vector
|
#include <utility>
|
||||||
|
#include <vector> // Para vector
|
||||||
|
|
||||||
#include "audio.h" // Para Audio
|
#include "audio.h" // Para Audio
|
||||||
#include "param.h" // Para Param, param, ParamNotification, ParamGame
|
#include "param.h" // Para Param, param, ParamNotification, ParamGame
|
||||||
@@ -23,13 +24,13 @@ void Notifier::init(const std::string &icon_file, std::shared_ptr<Text> text) {
|
|||||||
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,11 +26,11 @@ 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;
|
||||||
|
|
||||||
@@ -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;
|
||||||
|
|||||||
135
source/options.h
135
source/options.h
@@ -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,102 +25,89 @@ 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),
|
config_file() {}
|
||||||
autofire(true),
|
|
||||||
shutdown_enabled(false),
|
|
||||||
last_hi_score_entry({INVALID_INDEX, INVALID_INDEX}),
|
|
||||||
config_file() {}
|
|
||||||
|
|
||||||
// Reinicia las últimas entradas de puntuación
|
// Reinicia las últimas entradas de puntuación
|
||||||
void clearLastHiScoreEntries() {
|
void clearLastHiScoreEntries() {
|
||||||
last_hi_score_entry[0] = INVALID_INDEX;
|
last_hi_score_entry[0] = INVALID_INDEX;
|
||||||
last_hi_score_entry[1] = INVALID_INDEX;
|
last_hi_score_entry[1] = INVALID_INDEX;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -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)> &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>;
|
||||||
|
|
||||||
// --- 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 {
|
||||||
@@ -58,12 +58,12 @@ class PathSprite : public Sprite {
|
|||||||
|
|
||||||
// --- 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
|
||||||
@@ -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();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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; }
|
||||||
@@ -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_...
|
||||||
@@ -27,7 +28,7 @@ void Resource::init() { Resource::instance = new Resource(); }
|
|||||||
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,10 +1,10 @@
|
|||||||
#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 <memory> // Para shared_ptr
|
#include <cstddef> // Para size_t
|
||||||
#include <string> // Para basic_string, string
|
#include <memory> // Para shared_ptr
|
||||||
|
#include <string> // Para basic_string, string
|
||||||
#include <utility>
|
#include <utility>
|
||||||
#include <vector> // Para vector
|
#include <vector> // Para vector
|
||||||
|
|
||||||
|
|||||||
@@ -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...
|
||||||
|
|
||||||
@@ -29,7 +29,7 @@ void Scoreboard::destroy() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// [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::instance;
|
return Scoreboard::instance;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -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,11 +1,11 @@
|
|||||||
#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 <memory> // Para shared_ptr, unique_ptr
|
#include <cstddef> // Para size_t
|
||||||
#include <string> // Para basic_string, string
|
#include <memory> // Para shared_ptr, unique_ptr
|
||||||
#include <vector> // Para vector
|
#include <string> // Para basic_string, string
|
||||||
|
#include <vector> // Para vector
|
||||||
|
|
||||||
#include "utils.h" // Para Color
|
#include "utils.h" // Para Color
|
||||||
|
|
||||||
@@ -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
|
||||||
@@ -103,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
|
||||||
|
|||||||
@@ -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 ---
|
||||||
@@ -66,13 +66,13 @@ class Screen {
|
|||||||
|
|
||||||
// --- 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 frame_count; // Número acumulado de frames en el intervalo.
|
int frame_count{0}; // Número acumulado de frames en el intervalo.
|
||||||
int last_value; // 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), frame_count(0), last_value(0) {}
|
FPS() {}
|
||||||
void increment() { frame_count++; }
|
void increment() { frame_count++; }
|
||||||
int calculate(Uint32 current_ticks) {
|
auto calculate(Uint32 current_ticks) -> int {
|
||||||
if (current_ticks - ticks >= 1000) {
|
if (current_ticks - ticks >= 1000) {
|
||||||
last_value = frame_count;
|
last_value = frame_count;
|
||||||
frame_count = 0;
|
frame_count = 0;
|
||||||
@@ -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
|
||||||
@@ -156,7 +156,7 @@ class Screen {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
bool isEnabled() const { return enabled; }
|
[[nodiscard]] auto isEnabled() const -> bool { return enabled; }
|
||||||
};
|
};
|
||||||
|
|
||||||
#ifdef DEBUG
|
#ifdef DEBUG
|
||||||
@@ -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
|
||||||
|
|||||||
@@ -451,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;
|
||||||
|
|||||||
@@ -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
|
||||||
|
|
||||||
@@ -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;
|
||||||
|
|
||||||
@@ -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()) {
|
||||||
|
|||||||
@@ -74,28 +74,25 @@ class Game {
|
|||||||
|
|
||||||
// --- 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
|
||||||
int item_pacmar_odds; // Probabilidad de aparición del objeto
|
int item_pacmar_odds; // Probabilidad de aparición del objeto
|
||||||
int item_clock_odds; // Probabilidad de aparición del objeto
|
int item_clock_odds; // Probabilidad de aparición del objeto
|
||||||
int item_coffee_odds; // Probabilidad de aparición del objeto
|
int item_coffee_odds; // Probabilidad de aparición del objeto
|
||||||
int item_coffee_machine_odds; // Probabilidad de aparición del objeto
|
int item_coffee_machine_odds; // 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 ---
|
||||||
@@ -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,17 +195,17 @@ 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 player_id); // 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 demoHandleInput(); // 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.
|
||||||
|
|||||||
@@ -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;
|
||||||
|
|
||||||
|
|||||||
@@ -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,7 +289,7 @@ 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;
|
||||||
|
|
||||||
|
|||||||
@@ -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 start_time; // 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), start_time(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 start_delay); // 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
|
||||||
@@ -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()) {
|
||||||
|
|||||||
@@ -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,23 +2,24 @@
|
|||||||
#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 <vector> // Para vector
|
#include <utility>
|
||||||
|
#include <vector> // Para vector
|
||||||
|
|
||||||
#include "external/gif.h" // Para Gif
|
#include "external/gif.h" // Para Gif
|
||||||
#include "stb_image.h" // Para stbi_image_free, stbi_load, STBI_rgb_alpha
|
#include "stb_image.h" // Para stbi_image_free, stbi_load, STBI_rgb_alpha
|
||||||
#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,11 +1,11 @@
|
|||||||
#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 <memory> // Para shared_ptr
|
#include <cstddef> // Para size_t
|
||||||
#include <string> // Para string, basic_string
|
#include <memory> // Para shared_ptr
|
||||||
|
#include <string> // Para string, basic_string
|
||||||
#include <utility>
|
#include <utility>
|
||||||
#include <vector> // Para vector
|
#include <vector> // Para vector
|
||||||
|
|
||||||
@@ -28,54 +28,54 @@ 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 ---
|
||||||
auto loadFromFile(const std::string &path) -> bool; // Carga una imagen desde un fichero
|
auto loadFromFile(const std::string &path) -> bool; // Carga una imagen desde un fichero
|
||||||
auto createBlank(int width, int height, SDL_PixelFormat format = SDL_PIXELFORMAT_RGBA8888, SDL_TextureAccess access = SDL_TEXTUREACCESS_STREAMING) -> bool; // Crea una textura en blanco
|
auto createBlank(int width, int height, SDL_PixelFormat format = SDL_PIXELFORMAT_RGBA8888, SDL_TextureAccess access = SDL_TEXTUREACCESS_STREAMING) -> bool; // Crea una textura en blanco
|
||||||
auto reLoad() -> bool; // Recarga la textura
|
auto reLoad() -> bool; // Recarga la textura
|
||||||
|
|
||||||
// --- Renderizado ---
|
// --- Renderizado ---
|
||||||
void render(int x, int y, SDL_FRect *clip = nullptr, float zoom_w = 1, float zoom_h = 1, double angle = 0.0, SDL_FPoint *center = nullptr, SDL_FlipMode flip = SDL_FLIP_NONE); // Renderiza la textura en un punto específico
|
void render(int x, int y, SDL_FRect *clip = nullptr, float zoom_w = 1, float zoom_h = 1, double angle = 0.0, SDL_FPoint *center = nullptr, SDL_FlipMode flip = SDL_FLIP_NONE); // Renderiza la textura en un punto específico
|
||||||
void setAsRenderTarget(SDL_Renderer *renderer); // Establece la textura como objetivo de renderizado
|
void setAsRenderTarget(SDL_Renderer *renderer); // Establece la textura como objetivo de renderizado
|
||||||
|
|
||||||
// --- Modificadores de color y blending ---
|
// --- Modificadores de color y blending ---
|
||||||
void setColor(Uint8 red, Uint8 green, Uint8 blue); // Establece el color para la modulación
|
void setColor(Uint8 red, Uint8 green, Uint8 blue); // Establece el color para la modulación
|
||||||
void setColor(Color color); // Establece el color para la modulación
|
void setColor(Color color); // Establece el color para la modulación
|
||||||
void setBlendMode(SDL_BlendMode blending); // Establece el blending
|
void setBlendMode(SDL_BlendMode blending); // Establece el blending
|
||||||
void setAlpha(Uint8 alpha); // Establece el alpha para la modulación
|
void setAlpha(Uint8 alpha); // Establece el alpha para la modulación
|
||||||
|
|
||||||
// --- Paletas ---
|
// --- Paletas ---
|
||||||
void addPaletteFromGifFile(const std::string &path); // Añade una paleta a la lista
|
void addPaletteFromGifFile(const std::string &path); // Añade una paleta a la lista
|
||||||
void addPaletteFromPalFile(const std::string &path); // Añade una paleta a la lista
|
void addPaletteFromPalFile(const std::string &path); // Añade una paleta a la lista
|
||||||
void setPaletteColor(int palette, int index, Uint32 color); // Establece un color de la paleta
|
void setPaletteColor(int palette, int index, Uint32 color); // Establece un color de la paleta
|
||||||
void setPalette(size_t palette); // Cambia la paleta de la textura
|
void setPalette(size_t palette); // Cambia la paleta de la textura
|
||||||
|
|
||||||
// --- Getters ---
|
// --- Getters ---
|
||||||
auto getWidth() -> int; // Obtiene el ancho de la imagen
|
auto getWidth() -> int; // Obtiene el ancho de la imagen
|
||||||
auto getHeight() -> int; // Obtiene el alto de la imagen
|
auto getHeight() -> int; // Obtiene el alto de la imagen
|
||||||
auto getSDLTexture() -> SDL_Texture *; // Obtiene la textura SDL
|
auto getSDLTexture() -> SDL_Texture *; // Obtiene la textura SDL
|
||||||
auto getRenderer() -> SDL_Renderer *; // Obtiene el renderizador
|
auto getRenderer() -> SDL_Renderer *; // Obtiene el renderizador
|
||||||
|
|
||||||
private:
|
private:
|
||||||
// --- Objetos y punteros ---
|
// --- Objetos y punteros ---
|
||||||
SDL_Renderer *renderer_; // Renderizador donde dibujar la textura
|
SDL_Renderer *renderer_; // Renderizador donde dibujar la textura
|
||||||
SDL_Texture *texture_ = nullptr; // La textura
|
SDL_Texture *texture_ = nullptr; // La textura
|
||||||
std::shared_ptr<Surface> surface_ = nullptr; // Surface para usar imágenes en formato gif con paleta
|
std::shared_ptr<Surface> surface_ = nullptr; // Surface para usar imágenes en formato gif con paleta
|
||||||
|
|
||||||
// --- Variables ---
|
// --- Variables ---
|
||||||
std::string path_; // Ruta de la imagen de la textura
|
std::string path_; // Ruta de la imagen de la textura
|
||||||
int width_ = 0; // Ancho de la imagen
|
int width_ = 0; // Ancho de la imagen
|
||||||
int height_ = 0; // Alto de la imagen
|
int height_ = 0; // Alto de la imagen
|
||||||
std::vector<Palette> palettes_; // Vector con las diferentes paletas
|
std::vector<Palette> palettes_; // Vector con las diferentes paletas
|
||||||
int current_palette_ = 0; // Índice de la paleta en uso
|
int current_palette_ = 0; // Índice de la paleta en uso
|
||||||
|
|
||||||
// --- Métodos internos ---
|
// --- Métodos internos ---
|
||||||
auto loadSurface(const std::string &file_name) -> std::shared_ptr<Surface>; // Crea una surface desde un fichero .gif
|
auto loadSurface(const std::string &file_name) -> std::shared_ptr<Surface>; // Crea una surface desde un fichero .gif
|
||||||
void flipSurface(); // Vuelca la surface en la textura
|
void flipSurface(); // Vuelca la surface en la textura
|
||||||
auto loadPaletteFromFile(const std::string &file_name) -> Palette; // Carga una paleta desde un fichero
|
auto loadPaletteFromFile(const std::string &file_name) -> Palette; // Carga una paleta desde un fichero
|
||||||
void unloadTexture(); // Libera la memoria de la textura
|
void unloadTexture(); // Libera la memoria de la textura
|
||||||
void unloadSurface(); // Libera la surface actual
|
void unloadSurface(); // Libera la surface actual
|
||||||
auto readPalFile(const std::string &file_path) -> Palette; // Carga una paleta desde un archivo .pal
|
auto readPalFile(const std::string &file_path) -> Palette; // Carga una paleta desde un archivo .pal
|
||||||
};
|
};
|
||||||
@@ -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 <memory> // Para unique_ptr, make_unique
|
#include <cstdlib> // Para rand
|
||||||
|
#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
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -35,9 +35,9 @@ 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
|
||||||
|
|||||||
@@ -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 new_value = *linked_variable_ + (adjust_up ? step_value_ : -step_value_);
|
int new_value = *linked_variable_ + (adjust_up ? step_value_ : -step_value_);
|
||||||
*linked_variable_ = std::clamp(new_value, 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
|
||||||
@@ -100,14 +100,13 @@ class IntOption : public MenuOption {
|
|||||||
|
|
||||||
class ListOption : public MenuOption {
|
class ListOption : public MenuOption {
|
||||||
public:
|
public:
|
||||||
ListOption(const std::string &cap, ServiceMenu::SettingsGroup grp, std::vector<std::string> values, std::function<std::string()> current_value_getter, std::function<void(const std::string &)> new_value_setter)
|
ListOption(const std::string &cap, ServiceMenu::SettingsGroup grp, std::vector<std::string> values, std::function<std::string()> current_value_getter, std::function<void(const std::string &)> new_value_setter)
|
||||||
: 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();
|
}
|
||||||
}
|
|
||||||
|
|
||||||
void sync() {
|
void sync() {
|
||||||
std::string current_value = getter_();
|
std::string current_value = getter_();
|
||||||
@@ -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_();
|
||||||
|
|||||||
@@ -100,7 +100,7 @@ void MenuRenderer::setAnchors(const ServiceMenu *menu_state) {
|
|||||||
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);
|
||||||
@@ -172,7 +172,7 @@ void MenuRenderer::precalculateMenuWidths(const std::vector<std::unique_ptr<Menu
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
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,10 +1,10 @@
|
|||||||
#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 <memory> // Para shared_ptr, unique_ptr
|
#include <cstddef> // Para size_t
|
||||||
#include <vector> // Para vector
|
#include <memory> // Para shared_ptr, unique_ptr
|
||||||
|
#include <vector> // Para vector
|
||||||
|
|
||||||
#include "ui/service_menu.h" // Para ServiceMenu
|
#include "ui/service_menu.h" // Para ServiceMenu
|
||||||
#include "utils.h" // Para Color
|
#include "utils.h" // Para Color
|
||||||
@@ -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;
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -16,7 +16,7 @@
|
|||||||
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();
|
||||||
@@ -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()) {
|
||||||
@@ -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
|
||||||
@@ -34,7 +33,7 @@ class ServiceMenu {
|
|||||||
|
|
||||||
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,12 +1,13 @@
|
|||||||
#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() {
|
||||||
@@ -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,25 +11,25 @@ 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();
|
||||||
|
|
||||||
// Oculta el mensaje con animación de salida
|
// Oculta el mensaje con animación de salida
|
||||||
void hide();
|
void hide();
|
||||||
|
|
||||||
// Actualiza el estado de la animación (debe llamarse cada frame)
|
// Actualiza el estado de la animación (debe llamarse cada frame)
|
||||||
void update();
|
void update();
|
||||||
|
|
||||||
// Dibuja el mensaje en pantalla si está visible
|
// Dibuja el mensaje en pantalla si está visible
|
||||||
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);
|
||||||
|
|
||||||
private:
|
private:
|
||||||
// --- Configuración ---
|
// --- Configuración ---
|
||||||
|
|||||||
@@ -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;
|
||||||
|
|
||||||
@@ -9,33 +10,33 @@ class Text;
|
|||||||
class Writer {
|
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;
|
||||||
|
|
||||||
// Actualiza el objeto
|
// Actualiza el objeto
|
||||||
void update();
|
void update();
|
||||||
|
|
||||||
// Dibuja el objeto en pantalla
|
// Dibuja el objeto en pantalla
|
||||||
void render() const;
|
void render() const;
|
||||||
|
|
||||||
// Setters
|
// Setters
|
||||||
void setPosX(int value); // Establece la posición X
|
void setPosX(int value); // Establece la posición X
|
||||||
void setPosY(int value); // Establece la posición Y
|
void setPosY(int value); // Establece la posición Y
|
||||||
void setKerning(int value); // Establece el kerning (espaciado entre caracteres)
|
void setKerning(int value); // Establece el kerning (espaciado entre caracteres)
|
||||||
void setCaption(const std::string &text); // Establece el texto a escribir
|
void setCaption(const std::string &text); // Establece el texto a escribir
|
||||||
void setSpeed(int value); // Establece la velocidad de escritura
|
void setSpeed(int value); // Establece la velocidad de escritura
|
||||||
void setEnabled(bool value); // Habilita o deshabilita el objeto
|
void setEnabled(bool value); // Habilita o deshabilita el objeto
|
||||||
void setFinishedCounter(int time); // Establece el temporizador para deshabilitar el objeto
|
void setFinishedCounter(int time); // Establece el temporizador para deshabilitar el objeto
|
||||||
|
|
||||||
// Centra la cadena de texto a un punto X
|
// Centra la cadena de texto a un punto X
|
||||||
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