This commit is contained in:
2025-10-27 11:53:12 +01:00
parent 231dcd4b3b
commit 5d8811026d
69 changed files with 899 additions and 888 deletions

View File

@@ -25,7 +25,7 @@ Enemy::Enemy(const EnemyData& enemy)
sprite_->setWidth(enemy.w);
sprite_->setHeight(enemy.h);
const SDL_FlipMode FLIP = (should_flip_ && enemy.vx < 0.0f) ? SDL_FLIP_HORIZONTAL : SDL_FLIP_NONE;
const SDL_FlipMode FLIP = (should_flip_ && enemy.vx < 0.0F) ? SDL_FLIP_HORIZONTAL : SDL_FLIP_NONE;
const SDL_FlipMode MIRROR = should_mirror_ ? SDL_FLIP_VERTICAL : SDL_FLIP_NONE;
sprite_->setFlip(static_cast<SDL_FlipMode>(FLIP | MIRROR));

View File

@@ -5,12 +5,12 @@
// Constructor
Item::Item(ItemData item)
: sprite_(std::make_shared<SurfaceSprite>(Resource::get()->getSurface(item.tile_set_file), item.x, item.y, ITEM_SIZE_, ITEM_SIZE_)),
change_color_speed(4) {
: sprite_(std::make_shared<SurfaceSprite>(Resource::get()->getSurface(item.tile_set_file), item.x, item.y, ITEM_SIZE, ITEM_SIZE)),
change_color_speed_(4) {
// Inicia variables
sprite_->setClip((item.tile % 10) * ITEM_SIZE_, (item.tile / 10) * ITEM_SIZE_, ITEM_SIZE_, ITEM_SIZE_);
sprite_->setClip((item.tile % 10) * ITEM_SIZE, (item.tile / 10) * ITEM_SIZE, ITEM_SIZE, ITEM_SIZE);
collider_ = sprite_->getRect();
counter_ = item.counter * change_color_speed;
counter_ = item.counter * change_color_speed_;
// Inicializa los colores
color_.push_back(item.color1);
@@ -22,7 +22,7 @@ Item::Item(ItemData item)
// Pinta el objeto en pantalla
void Item::render() {
const int INDEX = (counter_ / change_color_speed) % color_.size();
const int INDEX = (counter_ / change_color_speed_) % color_.size();
sprite_->render(1, color_.at(INDEX));
}

View File

@@ -29,7 +29,7 @@ struct ItemData {
class Item {
private:
// Constantes
static constexpr float ITEM_SIZE_ = 8;
static constexpr float ITEM_SIZE = 8;
// Objetos y punteros
std::shared_ptr<SurfaceSprite> sprite_; // SSprite del objeto
@@ -38,7 +38,7 @@ class Item {
std::vector<Uint8> color_; // Vector con los colores del objeto
int counter_; // Contador interno
SDL_FRect collider_; // Rectangulo de colisión
int change_color_speed; // Cuanto mas alto, mas tarda en cambiar de color
int change_color_speed_; // Cuanto mas alto, mas tarda en cambiar de color
public:
// Constructor

View File

@@ -10,21 +10,21 @@
#include "game/ui/notifier.hpp" // Para Notifier
// [SINGLETON]
Cheevos* Cheevos::cheevos_ = nullptr;
Cheevos* Cheevos::cheevos = nullptr;
// [SINGLETON] Crearemos el objeto con esta función estática
void Cheevos::init(const std::string& file) {
Cheevos::cheevos_ = new Cheevos(file);
Cheevos::cheevos = new Cheevos(file);
}
// [SINGLETON] Destruiremos el objeto con esta función estática
void Cheevos::destroy() {
delete Cheevos::cheevos_;
delete Cheevos::cheevos;
}
// [SINGLETON] Con este método obtenemos el objeto y podemos trabajar con él
Cheevos* Cheevos::get() {
return Cheevos::cheevos_;
return Cheevos::cheevos;
}
// Constructor
@@ -88,11 +88,11 @@ void Cheevos::unlock(int id) {
// Invalida un logro
void Cheevos::setUnobtainable(int id) {
const int index = find(id);
const int INDEX = find(id);
// Si el índice es válido, se invalida el logro
if (index != -1) {
cheevos_list_.at(index).obtainable = false;
if (INDEX != -1) {
cheevos_list_.at(INDEX).obtainable = false;
}
}
@@ -107,16 +107,16 @@ void Cheevos::loadFromFile() {
}
// Crea el fichero en modo escritura (binario)
std::ofstream newFile(file_, std::ios::binary);
std::ofstream new_file(file_, std::ios::binary);
if (newFile) {
if (new_file) {
if (Options::console) {
std::cout << "New " << file_ << " created!" << std::endl;
}
// Guarda la información
for (const auto& cheevo : cheevos_list_) {
newFile.write(reinterpret_cast<const char*>(&cheevo.completed), sizeof(bool));
new_file.write(reinterpret_cast<const char*>(&cheevo.completed), sizeof(bool));
}
} else {
if (Options::console) {

View File

@@ -32,7 +32,7 @@ struct Achievement {
class Cheevos {
private:
// [SINGLETON] Objeto privado
static Cheevos* cheevos_;
static Cheevos* cheevos;
// Variables
std::vector<Achievement> cheevos_list_; // Listado de logros

View File

@@ -1,29 +1,29 @@
#include "game/gameplay/item_tracker.hpp"
// [SINGLETON]
ItemTracker* ItemTracker::item_tracker_ = nullptr;
ItemTracker* ItemTracker::item_tracker = nullptr;
// [SINGLETON] Crearemos el objeto con esta función estática
void ItemTracker::init() {
ItemTracker::item_tracker_ = new ItemTracker();
ItemTracker::item_tracker = new ItemTracker();
}
// [SINGLETON] Destruiremos el objeto con esta función estática
void ItemTracker::destroy() {
delete ItemTracker::item_tracker_;
delete ItemTracker::item_tracker;
}
// [SINGLETON] Con este método obtenemos el objeto y podemos trabajar con él
ItemTracker* ItemTracker::get() {
return ItemTracker::item_tracker_;
return ItemTracker::item_tracker;
}
// Comprueba si el objeto ya ha sido cogido
bool ItemTracker::hasBeenPicked(const std::string& name, SDL_FPoint pos) {
// Primero busca si ya hay una entrada con ese nombre
if (const int index = findByName(name); index != -1) {
if (const int INDEX = findByName(name); INDEX != -1) {
// Luego busca si existe ya una entrada con esa posición
if (findByPos(index, pos) != -1) {
if (findByPos(INDEX, pos) != -1) {
return true;
}
}
@@ -36,8 +36,8 @@ void ItemTracker::addItem(const std::string& name, SDL_FPoint pos) {
// Comprueba si el objeto no ha sido recogido con anterioridad
if (!hasBeenPicked(name, pos)) {
// Primero busca si ya hay una entrada con ese nombre
if (const int index = findByName(name); index != -1) {
item_list_.at(index).pos.push_back(pos);
if (const int INDEX = findByName(name); INDEX != -1) {
item_list_.at(INDEX).pos.push_back(pos);
}
// En caso contrario crea la entrada
else {

View File

@@ -19,7 +19,7 @@ struct ItemTrackerData {
class ItemTracker {
private:
// [SINGLETON] Objeto privado
static ItemTracker* item_tracker_;
static ItemTracker* item_tracker;
// Variables
std::vector<ItemTrackerData> item_list_; // Lista con todos los objetos recogidos

View File

@@ -19,8 +19,8 @@
// Carga las variables y texturas desde un fichero de mapa de tiles
std::vector<int> loadRoomTileFile(const std::string& file_path, bool verbose) {
std::vector<int> tileMapFile;
const std::string filename = file_path.substr(file_path.find_last_of("\\/") + 1);
std::vector<int> tile_map_file;
const std::string FILENAME = file_path.substr(file_path.find_last_of("\\/") + 1);
std::ifstream file(file_path);
// El fichero se puede abrir
@@ -35,7 +35,7 @@ std::vector<int> loadRoomTileFile(const std::string& file_path, bool verbose) {
std::stringstream ss(line);
std::string tmp;
while (getline(ss, tmp, ',')) {
tileMapFile.push_back(std::stoi(tmp) - 1);
tile_map_file.push_back(std::stoi(tmp) - 1);
}
// Lee la siguiente linea
@@ -46,18 +46,18 @@ std::vector<int> loadRoomTileFile(const std::string& file_path, bool verbose) {
// Cierra el fichero
if (verbose) {
std::cout << "TileMap loaded: " << filename.c_str() << std::endl;
std::cout << "TileMap loaded: " << FILENAME.c_str() << std::endl;
}
file.close();
}
else { // El fichero no se puede abrir
if (verbose) {
std::cout << "Warning: Unable to open " << filename.c_str() << " file" << std::endl;
std::cout << "Warning: Unable to open " << FILENAME.c_str() << " file" << std::endl;
}
}
return tileMapFile;
return tile_map_file;
}
// Carga las variables desde un fichero de mapa
@@ -67,8 +67,8 @@ RoomData loadRoomFile(const std::string& file_path, bool verbose) {
room.item_color2 = "magenta";
room.conveyor_belt_direction = 1;
const std::string fileName = file_path.substr(file_path.find_last_of("\\/") + 1);
room.number = fileName.substr(0, fileName.find_last_of("."));
const std::string FILE_NAME = file_path.substr(file_path.find_last_of("\\/") + 1);
room.number = FILE_NAME.substr(0, FILE_NAME.find_last_of("."));
std::ifstream file(file_path);
@@ -93,10 +93,11 @@ RoomData loadRoomFile(const std::string& file_path, bool verbose) {
// Procesa las dos subcadenas
std::string key = line.substr(0, pos);
std::string value = line.substr(pos + 1, line.length());
if (!setEnemy(&enemy, key, value))
if (!setEnemy(&enemy, key, value)) {
if (verbose) {
std::cout << "Warning: file " << fileName.c_str() << "\n, unknown parameter \"" << line.substr(0, pos).c_str() << "\"" << std::endl;
std::cout << "Warning: file " << FILE_NAME.c_str() << "\n, unknown parameter \"" << line.substr(0, pos).c_str() << "\"" << std::endl;
}
}
} while (line != "[/enemy]");
// Añade el enemigo al vector de enemigos
@@ -121,7 +122,7 @@ RoomData loadRoomFile(const std::string& file_path, bool verbose) {
std::string value = line.substr(pos + 1, line.length());
if (!setItem(&item, key, value)) {
if (verbose) {
std::cout << "Warning: file " << fileName.c_str() << "\n, unknown parameter \"" << line.substr(0, pos).c_str() << "\"" << std::endl;
std::cout << "Warning: file " << FILE_NAME.c_str() << "\n, unknown parameter \"" << line.substr(0, pos).c_str() << "\"" << std::endl;
}
}
@@ -140,7 +141,7 @@ RoomData loadRoomFile(const std::string& file_path, bool verbose) {
std::string value = line.substr(pos + 1, line.length());
if (!setRoom(&room, key, value)) {
if (verbose) {
std::cout << "Warning: file " << fileName.c_str() << "\n, unknown parameter \"" << line.substr(0, pos).c_str() << "\"" << std::endl;
std::cout << "Warning: file " << FILE_NAME.c_str() << "\n, unknown parameter \"" << line.substr(0, pos).c_str() << "\"" << std::endl;
}
}
}
@@ -148,14 +149,14 @@ RoomData loadRoomFile(const std::string& file_path, bool verbose) {
// Cierra el fichero
if (verbose) {
std::cout << "Room loaded: " << fileName.c_str() << std::endl;
std::cout << "Room loaded: " << FILE_NAME.c_str() << std::endl;
}
file.close();
}
// El fichero no se puede abrir
else {
{
std::cout << "Warning: Unable to open " << fileName.c_str() << " file" << std::endl;
std::cout << "Warning: Unable to open " << FILE_NAME.c_str() << " file" << std::endl;
}
}
@@ -192,7 +193,7 @@ bool setRoom(RoomData* room, const std::string& key, const std::string& value) {
room->right_room = value;
} else if (key == "autoSurface") {
room->conveyor_belt_direction = (value == "right") ? 1 : -1;
} else if (key == "" || key.substr(0, 1) == "#") {
} else if (key.empty() || key.substr(0, 1) == "#") {
// No se realiza ninguna acción para estas claves
} else {
success = false;
@@ -327,56 +328,57 @@ void Room::initializeRoom(const RoomData& room) {
conveyor_belt_direction_ = room.conveyor_belt_direction;
tile_map_ = Resource::get()->getTileMap(room.tile_map_file);
surface_ = Resource::get()->getSurface(room.tile_set_file);
tile_set_width_ = surface_->getWidth() / TILE_SIZE_;
tile_set_width_ = surface_->getWidth() / TILE_SIZE;
is_paused_ = false;
counter_ = 0;
// Crear los enemigos
for (auto& enemy_data : room.enemies) {
for (const auto& enemy_data : room.enemies) {
enemies_.emplace_back(std::make_shared<Enemy>(enemy_data));
}
// Crear los items
for (const auto& item : room.items) {
const SDL_FPoint itemPos = {item.x, item.y};
const SDL_FPoint ITEM_POS = {item.x, item.y};
if (!ItemTracker::get()->hasBeenPicked(room.name, itemPos)) {
if (!ItemTracker::get()->hasBeenPicked(room.name, ITEM_POS)) {
// Crear una copia local de los datos del item
ItemData itemCopy = item;
itemCopy.color1 = stringToColor(item_color1_);
itemCopy.color2 = stringToColor(item_color2_);
ItemData item_copy = item;
item_copy.color1 = stringToColor(item_color1_);
item_copy.color2 = stringToColor(item_color2_);
// Crear el objeto Item usando la copia modificada
items_.emplace_back(std::make_shared<Item>(itemCopy));
items_.emplace_back(std::make_shared<Item>(item_copy));
}
}
}
// Crea la textura con el mapeado de la habitación
void Room::fillMapTexture() {
const Uint8 color = stringToColor(bg_color_);
const Uint8 COLOR = stringToColor(bg_color_);
auto previuos_renderer = Screen::get()->getRendererSurface();
Screen::get()->setRendererSurface(map_surface_);
map_surface_->clear(color);
map_surface_->clear(COLOR);
// Los tileSetFiles son de 20x20 tiles. El primer tile es el 0. Cuentan hacia la derecha y hacia abajo
SDL_FRect clip = {0, 0, TILE_SIZE_, TILE_SIZE_};
for (int y = 0; y < MAP_HEIGHT_; ++y)
for (int x = 0; x < MAP_WIDTH_; ++x) {
SDL_FRect clip = {0, 0, TILE_SIZE, TILE_SIZE};
for (int y = 0; y < MAP_HEIGHT; ++y) {
for (int x = 0; x < MAP_WIDTH; ++x) {
// Tiled pone los tiles vacios del mapa como cero y empieza a contar de 1 a n.
// Al cargar el mapa en memoria, se resta uno, por tanto los tiles vacios son -1
// Tampoco hay que dibujar los tiles animados que estan en la fila 19 (indices)
const int INDEX = (y * MAP_WIDTH_) + x;
const int INDEX = (y * MAP_WIDTH) + x;
const bool A = (tile_map_[INDEX] >= 18 * tile_set_width_) && (tile_map_[INDEX] < 19 * tile_set_width_);
const bool B = tile_map_[INDEX] > -1;
if (B && !A) {
clip.x = (tile_map_[INDEX] % tile_set_width_) * TILE_SIZE_;
clip.y = (tile_map_[INDEX] / tile_set_width_) * TILE_SIZE_;
surface_->render(x * TILE_SIZE_, y * TILE_SIZE_, &clip);
clip.x = (tile_map_[INDEX] % tile_set_width_) * TILE_SIZE;
clip.y = (tile_map_[INDEX] / tile_set_width_) * TILE_SIZE;
surface_->render(x * TILE_SIZE, y * TILE_SIZE, &clip);
}
}
}
#ifdef _DEBUG
if (Debug::get()->getEnabled()) {
@@ -517,23 +519,23 @@ std::string Room::getRoom(RoomBorder border) {
// Devuelve el tipo de tile que hay en ese pixel
TileType Room::getTile(SDL_FPoint point) {
const int pos = ((point.y / TILE_SIZE_) * MAP_WIDTH_) + (point.x / TILE_SIZE_);
return getTile(pos);
const int POS = ((point.y / TILE_SIZE) * MAP_WIDTH) + (point.x / TILE_SIZE);
return getTile(POS);
}
// Devuelve el tipo de tile que hay en ese indice
TileType Room::getTile(int index) {
// const bool onRange = (index > -1) && (index < mapWidth * mapHeight);
const bool onRange = (index > -1) && (index < (int)tile_map_.size());
const bool ON_RANGE = (index > -1) && (index < (int)tile_map_.size());
if (onRange) {
if (ON_RANGE) {
// Las filas 0-8 son de tiles t_wall
if ((tile_map_[index] >= 0) && (tile_map_[index] < 9 * tile_set_width_)) {
return TileType::WALL;
}
// Las filas 9-17 son de tiles t_passable
else if ((tile_map_[index] >= 9 * tile_set_width_) && (tile_map_[index] < 18 * tile_set_width_)) {
if ((tile_map_[index] >= 9 * tile_set_width_) && (tile_map_[index] < 18 * tile_set_width_)) {
return TileType::PASSABLE;
}
@@ -590,25 +592,25 @@ bool Room::itemCollision(SDL_FRect& rect) {
// Obten la coordenada de la cuesta a partir de un punto perteneciente a ese tile
int Room::getSlopeHeight(SDL_FPoint p, TileType slope) {
// Calcula la base del tile
int base = ((p.y / TILE_SIZE_) * TILE_SIZE_) + TILE_SIZE_;
int base = ((p.y / TILE_SIZE) * TILE_SIZE) + TILE_SIZE;
#ifdef _DEBUG
Debug::get()->add("BASE = " + std::to_string(base));
#endif
// Calcula cuanto se ha entrado en el tile horizontalmente
const int pos = (static_cast<int>(p.x) % TILE_SIZE_); // Esto da un valor entre 0 y 7
const int POS = (static_cast<int>(p.x) % TILE_SIZE); // Esto da un valor entre 0 y 7
#ifdef _DEBUG
Debug::get()->add("POS = " + std::to_string(pos));
Debug::get()->add("POS = " + std::to_string(POS));
#endif
// Se resta a la base la cantidad de pixeles pos en funcion de la rampa
if (slope == TileType::SLOPE_R) {
base -= pos + 1;
base -= POS + 1;
#ifdef _DEBUG
Debug::get()->add("BASE_R = " + std::to_string(base));
#endif
} else {
base -= (TILE_SIZE_ - pos);
base -= (TILE_SIZE - POS);
#ifdef _DEBUG
Debug::get()->add("BASE_L = " + std::to_string(base));
#endif
@@ -623,12 +625,12 @@ void Room::setBottomSurfaces() {
// Busca todos los tiles de tipo muro que no tengan debajo otro muro
// Hay que recorrer la habitación por filas (excepto los de la última fila)
for (int i = 0; i < (int)tile_map_.size() - MAP_WIDTH_; ++i) {
if (getTile(i) == TileType::WALL && getTile(i + MAP_WIDTH_) != TileType::WALL) {
for (int i = 0; i < (int)tile_map_.size() - MAP_WIDTH; ++i) {
if (getTile(i) == TileType::WALL && getTile(i + MAP_WIDTH) != TileType::WALL) {
tile.push_back(i);
// Si llega al final de la fila, introduce un separador
if (i % MAP_WIDTH_ == MAP_WIDTH_ - 1) {
if (i % MAP_WIDTH == MAP_WIDTH - 1) {
tile.push_back(-1);
}
}
@@ -642,8 +644,8 @@ void Room::setBottomSurfaces() {
int i = 0;
do {
LineHorizontal line;
line.x1 = (tile[i] % MAP_WIDTH_) * TILE_SIZE_;
line.y = ((tile[i] / MAP_WIDTH_) * TILE_SIZE_) + TILE_SIZE_ - 1;
line.x1 = (tile[i] % MAP_WIDTH) * TILE_SIZE;
line.y = ((tile[i] / MAP_WIDTH) * TILE_SIZE) + TILE_SIZE - 1;
int last_one = i;
i++;
@@ -657,7 +659,7 @@ void Room::setBottomSurfaces() {
}
}
line.x2 = ((tile[last_one] % MAP_WIDTH_) * TILE_SIZE_) + TILE_SIZE_ - 1;
line.x2 = ((tile[last_one] % MAP_WIDTH) * TILE_SIZE) + TILE_SIZE - 1;
bottom_floors_.push_back(line);
if (i <= (int)tile.size() - 1) {
if (tile[i] == -1) { // Si el siguiente elemento es un separador, hay que saltarlo
@@ -674,12 +676,12 @@ void Room::setTopSurfaces() {
// Busca todos los tiles de tipo muro o pasable que no tengan encima un muro
// Hay que recorrer la habitación por filas (excepto los de la primera fila)
for (int i = MAP_WIDTH_; i < (int)tile_map_.size(); ++i) {
if ((getTile(i) == TileType::WALL || getTile(i) == TileType::PASSABLE) && getTile(i - MAP_WIDTH_) != TileType::WALL) {
for (int i = MAP_WIDTH; i < (int)tile_map_.size(); ++i) {
if ((getTile(i) == TileType::WALL || getTile(i) == TileType::PASSABLE) && getTile(i - MAP_WIDTH) != TileType::WALL) {
tile.push_back(i);
// Si llega al final de la fila, introduce un separador
if (i % MAP_WIDTH_ == MAP_WIDTH_ - 1) {
if (i % MAP_WIDTH == MAP_WIDTH - 1) {
tile.push_back(-1);
}
}
@@ -693,8 +695,8 @@ void Room::setTopSurfaces() {
int i = 0;
do {
LineHorizontal line;
line.x1 = (tile[i] % MAP_WIDTH_) * TILE_SIZE_;
line.y = (tile[i] / MAP_WIDTH_) * TILE_SIZE_;
line.x1 = (tile[i] % MAP_WIDTH) * TILE_SIZE;
line.y = (tile[i] / MAP_WIDTH) * TILE_SIZE;
int last_one = i;
i++;
@@ -708,7 +710,7 @@ void Room::setTopSurfaces() {
}
}
line.x2 = ((tile[last_one] % MAP_WIDTH_) * TILE_SIZE_) + TILE_SIZE_ - 1;
line.x2 = ((tile[last_one] % MAP_WIDTH) * TILE_SIZE) + TILE_SIZE - 1;
top_floors_.push_back(line);
if (i <= (int)tile.size() - 1) {
if (tile[i] == -1) { // Si el siguiente elemento es un separador, hay que saltarlo
@@ -725,11 +727,11 @@ void Room::setLeftSurfaces() {
// Busca todos los tiles de tipo muro que no tienen a su izquierda un tile de tipo muro
// Hay que recorrer la habitación por columnas (excepto los de la primera columna)
for (int i = 1; i < MAP_WIDTH_; ++i) {
for (int j = 0; j < MAP_HEIGHT_; ++j) {
const int pos = (j * MAP_WIDTH_ + i);
if (getTile(pos) == TileType::WALL && getTile(pos - 1) != TileType::WALL) {
tile.push_back(pos);
for (int i = 1; i < MAP_WIDTH; ++i) {
for (int j = 0; j < MAP_HEIGHT; ++j) {
const int POS = ((j * MAP_WIDTH) + i);
if (getTile(POS) == TileType::WALL && getTile(POS - 1) != TileType::WALL) {
tile.push_back(POS);
}
}
}
@@ -744,15 +746,15 @@ void Room::setLeftSurfaces() {
int i = 0;
do {
LineVertical line;
line.x = (tile[i] % MAP_WIDTH_) * TILE_SIZE_;
line.y1 = ((tile[i] / MAP_WIDTH_) * TILE_SIZE_);
while (tile[i] + MAP_WIDTH_ == tile[i + 1]) {
line.x = (tile[i] % MAP_WIDTH) * TILE_SIZE;
line.y1 = ((tile[i] / MAP_WIDTH) * TILE_SIZE);
while (tile[i] + MAP_WIDTH == tile[i + 1]) {
if (i == (int)tile.size() - 1) {
break;
}
i++;
}
line.y2 = ((tile[i] / MAP_WIDTH_) * TILE_SIZE_) + TILE_SIZE_ - 1;
line.y2 = ((tile[i] / MAP_WIDTH) * TILE_SIZE) + TILE_SIZE - 1;
left_walls_.push_back(line);
i++;
} while (i < (int)tile.size() - 1);
@@ -765,11 +767,11 @@ void Room::setRightSurfaces() {
// Busca todos los tiles de tipo muro que no tienen a su derecha un tile de tipo muro
// Hay que recorrer la habitación por columnas (excepto los de la última columna)
for (int i = 0; i < MAP_WIDTH_ - 1; ++i) {
for (int j = 0; j < MAP_HEIGHT_; ++j) {
const int pos = (j * MAP_WIDTH_ + i);
if (getTile(pos) == TileType::WALL && getTile(pos + 1) != TileType::WALL) {
tile.push_back(pos);
for (int i = 0; i < MAP_WIDTH - 1; ++i) {
for (int j = 0; j < MAP_HEIGHT; ++j) {
const int POS = ((j * MAP_WIDTH) + i);
if (getTile(POS) == TileType::WALL && getTile(POS + 1) != TileType::WALL) {
tile.push_back(POS);
}
}
}
@@ -784,15 +786,15 @@ void Room::setRightSurfaces() {
int i = 0;
do {
LineVertical line;
line.x = ((tile[i] % MAP_WIDTH_) * TILE_SIZE_) + TILE_SIZE_ - 1;
line.y1 = ((tile[i] / MAP_WIDTH_) * TILE_SIZE_);
while (tile[i] + MAP_WIDTH_ == tile[i + 1]) {
line.x = ((tile[i] % MAP_WIDTH) * TILE_SIZE) + TILE_SIZE - 1;
line.y1 = ((tile[i] / MAP_WIDTH) * TILE_SIZE);
while (tile[i] + MAP_WIDTH == tile[i + 1]) {
if (i == (int)tile.size() - 1) {
break;
}
i++;
}
line.y2 = ((tile[i] / MAP_WIDTH_) * TILE_SIZE_) + TILE_SIZE_ - 1;
line.y2 = ((tile[i] / MAP_WIDTH) * TILE_SIZE) + TILE_SIZE - 1;
right_walls_.push_back(line);
i++;
} while (i < (int)tile.size() - 1);
@@ -813,23 +815,23 @@ void Room::setLeftSlopes() {
// que seran i + mapWidth + 1. Conforme se añaden se eliminan y se vuelve a escudriñar el vector de
// tiles encontrados hasta que esté vacío
while (found.size() > 0) {
while (!found.empty()) {
LineDiagonal line;
line.x1 = (found[0] % MAP_WIDTH_) * TILE_SIZE_;
line.y1 = (found[0] / MAP_WIDTH_) * TILE_SIZE_;
int lookingFor = found[0] + MAP_WIDTH_ + 1;
int lastOneFound = found[0];
line.x1 = (found[0] % MAP_WIDTH) * TILE_SIZE;
line.y1 = (found[0] / MAP_WIDTH) * TILE_SIZE;
int looking_for = found[0] + MAP_WIDTH + 1;
int last_one_found = found[0];
found.erase(found.begin());
for (int i = 0; i < (int)found.size(); ++i) {
if (found[i] == lookingFor) {
lastOneFound = lookingFor;
lookingFor += MAP_WIDTH_ + 1;
if (found[i] == looking_for) {
last_one_found = looking_for;
looking_for += MAP_WIDTH + 1;
found.erase(found.begin() + i);
i--;
}
}
line.x2 = ((lastOneFound % MAP_WIDTH_) * TILE_SIZE_) + TILE_SIZE_ - 1;
line.y2 = ((lastOneFound / MAP_WIDTH_) * TILE_SIZE_) + TILE_SIZE_ - 1;
line.x2 = ((last_one_found % MAP_WIDTH) * TILE_SIZE) + TILE_SIZE - 1;
line.y2 = ((last_one_found / MAP_WIDTH) * TILE_SIZE) + TILE_SIZE - 1;
left_slopes_.push_back(line);
}
}
@@ -848,23 +850,23 @@ void Room::setRightSlopes() {
// que seran i + mapWidth - 1. Conforme se añaden se eliminan y se vuelve a escudriñar el vector de
// tiles encontrados hasta que esté vacío
while (found.size() > 0) {
while (!found.empty()) {
LineDiagonal line;
line.x1 = ((found[0] % MAP_WIDTH_) * TILE_SIZE_) + TILE_SIZE_ - 1;
line.y1 = (found[0] / MAP_WIDTH_) * TILE_SIZE_;
int lookingFor = found[0] + MAP_WIDTH_ - 1;
int lastOneFound = found[0];
line.x1 = ((found[0] % MAP_WIDTH) * TILE_SIZE) + TILE_SIZE - 1;
line.y1 = (found[0] / MAP_WIDTH) * TILE_SIZE;
int looking_for = found[0] + MAP_WIDTH - 1;
int last_one_found = found[0];
found.erase(found.begin());
for (int i = 0; i < (int)found.size(); ++i) {
if (found[i] == lookingFor) {
lastOneFound = lookingFor;
lookingFor += MAP_WIDTH_ - 1;
if (found[i] == looking_for) {
last_one_found = looking_for;
looking_for += MAP_WIDTH - 1;
found.erase(found.begin() + i);
i--;
}
}
line.x2 = (lastOneFound % MAP_WIDTH_) * TILE_SIZE_;
line.y2 = ((lastOneFound / MAP_WIDTH_) * TILE_SIZE_) + TILE_SIZE_ - 1;
line.x2 = (last_one_found % MAP_WIDTH) * TILE_SIZE;
line.y2 = ((last_one_found / MAP_WIDTH) * TILE_SIZE) + TILE_SIZE - 1;
right_slopes_.push_back(line);
}
}
@@ -875,12 +877,12 @@ void Room::setAutoSurfaces() {
// Busca todos los tiles de tipo animado
// Hay que recorrer la habitación por filas (excepto los de la primera fila)
for (int i = MAP_WIDTH_; i < (int)tile_map_.size(); ++i) {
for (int i = MAP_WIDTH; i < (int)tile_map_.size(); ++i) {
if (getTile(i) == TileType::ANIMATED) {
tile.push_back(i);
// Si llega al final de la fila, introduce un separador
if (i % MAP_WIDTH_ == MAP_WIDTH_ - 1) {
if (i % MAP_WIDTH == MAP_WIDTH - 1) {
tile.push_back(-1);
}
}
@@ -891,8 +893,8 @@ void Room::setAutoSurfaces() {
int i = 0;
do {
LineHorizontal line;
line.x1 = (tile[i] % MAP_WIDTH_) * TILE_SIZE_;
line.y = (tile[i] / MAP_WIDTH_) * TILE_SIZE_;
line.x1 = (tile[i] % MAP_WIDTH) * TILE_SIZE;
line.y = (tile[i] / MAP_WIDTH) * TILE_SIZE;
int last_one = i;
i++;
@@ -906,7 +908,7 @@ void Room::setAutoSurfaces() {
}
}
line.x2 = ((tile[last_one] % MAP_WIDTH_) * TILE_SIZE_) + TILE_SIZE_ - 1;
line.x2 = ((tile[last_one] % MAP_WIDTH) * TILE_SIZE) + TILE_SIZE - 1;
conveyor_belt_floors_.push_back(line);
if (i <= (int)tile.size() - 1) {
if (tile[i] == -1) { // Si el siguiente elemento es un separador, hay que saltarlo
@@ -923,17 +925,17 @@ void Room::setAnimatedTiles() {
for (int i = 0; i < (int)tile_map_.size(); ++i) {
if (getTile(i) == TileType::ANIMATED) {
// La i es la ubicación
const int x = (i % MAP_WIDTH_) * TILE_SIZE_;
const int y = (i / MAP_WIDTH_) * TILE_SIZE_;
const int X = (i % MAP_WIDTH) * TILE_SIZE;
const int Y = (i / MAP_WIDTH) * TILE_SIZE;
// TileMap[i] es el tile a poner
const int xc = (tile_map_[i] % tile_set_width_) * TILE_SIZE_;
const int yc = (tile_map_[i] / tile_set_width_) * TILE_SIZE_;
const int XC = (tile_map_[i] % tile_set_width_) * TILE_SIZE;
const int YC = (tile_map_[i] / tile_set_width_) * TILE_SIZE;
AnimatedTile at;
at.sprite = std::make_shared<SurfaceSprite>(surface_, x, y, 8, 8);
at.sprite->setClip(xc, yc, 8, 8);
at.x_orig = xc;
at.sprite = std::make_shared<SurfaceSprite>(surface_, X, Y, 8, 8);
at.sprite->setClip(XC, YC, 8, 8);
at.x_orig = XC;
animated_tiles_.push_back(at);
}
}
@@ -941,12 +943,12 @@ void Room::setAnimatedTiles() {
// Actualiza los tiles animados
void Room::updateAnimatedTiles() {
const int numFrames = 4;
const int NUM_FRAMES = 4;
int offset = 0;
if (conveyor_belt_direction_ == -1) {
offset = ((counter_ / 3) % numFrames * TILE_SIZE_);
offset = ((counter_ / 3) % NUM_FRAMES * TILE_SIZE);
} else {
offset = ((numFrames - 1 - ((counter_ / 3) % numFrames)) * TILE_SIZE_);
offset = ((NUM_FRAMES - 1 - ((counter_ / 3) % NUM_FRAMES)) * TILE_SIZE);
}
for (auto& a : animated_tiles_) {
@@ -1043,9 +1045,9 @@ bool Room::checkAutoSurfaces(SDL_FPoint* p) {
// Comprueba las colisiones
int Room::checkLeftSlopes(const LineVertical* line) {
for (const auto& slope : left_slopes_) {
const auto p = checkCollision(slope, *line);
if (p.x != -1) {
return p.y;
const auto P = checkCollision(slope, *line);
if (P.x != -1) {
return P.y;
}
}
@@ -1066,9 +1068,9 @@ bool Room::checkLeftSlopes(SDL_FPoint* p) {
// Comprueba las colisiones
int Room::checkRightSlopes(const LineVertical* line) {
for (const auto& slope : right_slopes_) {
const auto p = checkCollision(slope, *line);
if (p.x != -1) {
return p.y;
const auto P = checkCollision(slope, *line);
if (P.x != -1) {
return P.y;
}
}

View File

@@ -72,9 +72,9 @@ bool setItem(ItemData* item, const std::string& key, const std::string& value);
class Room {
private:
// Constantes
static constexpr int TILE_SIZE_ = 8; // Ancho del tile en pixels
static constexpr int MAP_WIDTH_ = 32; // Ancho del mapa en tiles
static constexpr int MAP_HEIGHT_ = 16; // Alto del mapa en tiles
static constexpr int TILE_SIZE = 8; // Ancho del tile en pixels
static constexpr int MAP_WIDTH = 32; // Ancho del mapa en tiles
static constexpr int MAP_HEIGHT = 16; // Alto del mapa en tiles
// Objetos y punteros
std::vector<std::shared_ptr<Enemy>> enemies_; // Listado con los enemigos de la habitación
@@ -195,10 +195,10 @@ class Room {
bool itemCollision(SDL_FRect& rect);
// Obten el tamaño del tile
int getTileSize() const { return TILE_SIZE_; }
static int getTileSize() { return TILE_SIZE; }
// Obten la coordenada de la cuesta a partir de un punto perteneciente a ese tile
int getSlopeHeight(SDL_FPoint p, TileType slope);
static int getSlopeHeight(SDL_FPoint p, TileType slope);
// Comprueba las colisiones
int checkRightSurfaces(SDL_FRect* rect);

View File

@@ -2,7 +2,7 @@
// Comprueba si la habitación ya ha sido visitada
bool RoomTracker::hasBeenVisited(const std::string& name) {
for (const auto& l : list) {
for (const auto& l : list_) {
if (l == name) {
return true;
}
@@ -16,7 +16,7 @@ bool RoomTracker::addRoom(const std::string& name) {
// Comprueba si la habitación ya ha sido visitada
if (!hasBeenVisited(name)) {
// En caso contrario añádela a la lista
list.push_back(name);
list_.push_back(name);
return true;
}

View File

@@ -6,7 +6,7 @@
class RoomTracker {
private:
// Variables
std::vector<std::string> list; // Lista con las habitaciones visitadas
std::vector<std::string> list_; // Lista con las habitaciones visitadas
// Comprueba si la habitación ya ha sido visitada
bool hasBeenVisited(const std::string& name);

View File

@@ -14,10 +14,9 @@
// Constructor
Scoreboard::Scoreboard(std::shared_ptr<ScoreboardData> data)
: item_surface_(Resource::get()->getSurface("items.gif")),
data_(data),
clock_(ClockData()) {
const float SURFACE_WIDTH_ = Options::game.width;
constexpr float SURFACE_HEIGHT_ = 6.0F * BLOCK;
data_(data) {
const float SURFACE_WIDTH = Options::game.width;
constexpr float SURFACE_HEIGHT = 6.0F * BLOCK;
// Reserva memoria para los objetos
auto player_texture = Resource::get()->getSurface(Options::cheats.alternate_skin == Options::Cheat::State::ENABLED ? "player2.gif" : "player.gif");
@@ -25,8 +24,8 @@ Scoreboard::Scoreboard(std::shared_ptr<ScoreboardData> data)
player_sprite_ = std::make_shared<SurfaceAnimatedSprite>(player_texture, player_animations);
player_sprite_->setCurrentAnimation("walk_menu");
surface_ = std::make_shared<Surface>(SURFACE_WIDTH_, SURFACE_HEIGHT_);
surface_dest_ = {0, Options::game.height - SURFACE_HEIGHT_, SURFACE_WIDTH_, SURFACE_HEIGHT_};
surface_ = std::make_shared<Surface>(SURFACE_WIDTH, SURFACE_HEIGHT);
surface_dest_ = {0, Options::game.height - SURFACE_HEIGHT, SURFACE_WIDTH, SURFACE_HEIGHT};
// Inicializa las variables
counter_ = 0;
@@ -67,13 +66,13 @@ void Scoreboard::update() {
// Obtiene el tiempo transcurrido de partida
Scoreboard::ClockData Scoreboard::getTime() {
const Uint32 timeElapsed = SDL_GetTicks() - data_->ini_clock - paused_time_elapsed_;
const Uint32 TIME_ELAPSED = SDL_GetTicks() - data_->ini_clock - paused_time_elapsed_;
ClockData time;
time.hours = timeElapsed / 3600000;
time.minutes = timeElapsed / 60000;
time.seconds = timeElapsed / 1000;
time.separator = (timeElapsed % 1000 <= 500) ? ":" : " ";
time.hours = TIME_ELAPSED / 3600000;
time.minutes = TIME_ELAPSED / 60000;
time.seconds = TIME_ELAPSED / 1000;
time.separator = (TIME_ELAPSED % 1000 <= 500) ? ":" : " ";
return time;
}
@@ -128,21 +127,21 @@ void Scoreboard::fillTexture() {
constexpr int LINE2 = 3 * BLOCK;
// Dibuja las vidas
const int desp = (counter_ / 40) % 8;
const int frame = desp % 4;
player_sprite_->setCurrentAnimationFrame(frame);
const int DESP = (counter_ / 40) % 8;
const int FRAME = DESP % 4;
player_sprite_->setCurrentAnimationFrame(FRAME);
player_sprite_->setPosY(LINE2);
for (int i = 0; i < data_->lives; ++i) {
player_sprite_->setPosX(8 + (16 * i) + desp);
const int index = i % color_.size();
player_sprite_->render(1, color_.at(index));
player_sprite_->setPosX(8 + (16 * i) + DESP);
const int INDEX = i % color_.size();
player_sprite_->render(1, color_.at(INDEX));
}
// Muestra si suena la música
if (data_->music) {
const Uint8 c = data_->color;
const Uint8 C = data_->color;
SDL_FRect clip = {0, 8, 8, 8};
item_surface_->renderWithColorReplace(20 * BLOCK, LINE2, 1, c, &clip);
item_surface_->renderWithColorReplace(20 * BLOCK, LINE2, 1, C, &clip);
}
// Escribe los textos

View File

@@ -7,8 +7,8 @@
// Constructor
Stats::Stats(const std::string& file, const std::string& buffer)
: bufferPath(buffer),
filePath(file) {}
: buffer_path_(buffer),
file_path_(file) {}
// Destructor
Stats::~Stats() {
@@ -19,20 +19,20 @@ Stats::~Stats() {
checkWorstNightmare();
// Guarda las estadísticas
saveToFile(bufferPath, bufferList);
saveToFile(filePath, list);
saveToFile(buffer_path_, buffer_list_);
saveToFile(file_path_, list_);
bufferList.clear();
list.clear();
dictionary.clear();
buffer_list_.clear();
list_.clear();
dictionary_.clear();
}
// Inicializador
void Stats::init()
// Se debe llamar a este procedimiento una vez se haya creado el diccionario numero-nombre
{
loadFromFile(bufferPath, bufferList);
loadFromFile(filePath, list);
loadFromFile(buffer_path_, buffer_list_);
loadFromFile(file_path_, list_);
// Vuelca los datos del buffer en la lista de estadisticas
updateListFromBuffer();
@@ -41,9 +41,9 @@ void Stats::init()
// Añade una muerte a las estadisticas
void Stats::addDeath(const std::string& name) {
// Primero busca si ya hay una entrada con ese nombre
const int index = findByName(name, bufferList);
if (index != -1) {
bufferList[index].died++;
const int INDEX = findByName(name, buffer_list_);
if (INDEX != -1) {
buffer_list_[INDEX].died++;
}
// En caso contrario crea la entrada
@@ -52,16 +52,16 @@ void Stats::addDeath(const std::string& name) {
item.name = name;
item.visited = 0;
item.died = 1;
bufferList.push_back(item);
buffer_list_.push_back(item);
}
}
// Añade una visita a las estadisticas
void Stats::addVisit(const std::string& name) {
// Primero busca si ya hay una entrada con ese nombre
const int index = findByName(name, bufferList);
if (index != -1) {
bufferList[index].visited++;
const int INDEX = findByName(name, buffer_list_);
if (INDEX != -1) {
buffer_list_[INDEX].visited++;
}
// En caso contrario crea la entrada
@@ -70,15 +70,15 @@ void Stats::addVisit(const std::string& name) {
item.name = name;
item.visited = 1;
item.died = 0;
bufferList.push_back(item);
buffer_list_.push_back(item);
}
}
// Busca una entrada en la lista por nombre
int Stats::findByName(const std::string& name, const std::vector<StatsData>& list) {
int Stats::findByName(const std::string& name, const std::vector<StatsData>& list_) {
int i = 0;
for (const auto& l : list) {
for (const auto& l : list_) {
if (l.name == name) {
return i;
}
@@ -89,8 +89,8 @@ int Stats::findByName(const std::string& name, const std::vector<StatsData>& lis
}
// Carga las estadisticas desde un fichero
bool Stats::loadFromFile(const std::string& file_path, std::vector<StatsData>& list) {
list.clear();
bool Stats::loadFromFile(const std::string& file_path, std::vector<StatsData>& list_) {
list_.clear();
// Indicador de éxito en la carga
bool success = true;
@@ -121,7 +121,7 @@ bool Stats::loadFromFile(const std::string& file_path, std::vector<StatsData>& l
getline(ss, tmp, ';');
stat.died = std::stoi(tmp);
list.push_back(stat);
list_.push_back(stat);
}
}
@@ -132,20 +132,20 @@ bool Stats::loadFromFile(const std::string& file_path, std::vector<StatsData>& l
// El fichero no existe
else {
// Crea el fichero con los valores por defecto
saveToFile(file_path, list);
saveToFile(file_path, list_);
}
return success;
}
// Guarda las estadisticas en un fichero
void Stats::saveToFile(const std::string& file_path, const std::vector<StatsData>& list) {
void Stats::saveToFile(const std::string& file_path, const std::vector<StatsData>& list_) {
// Crea y abre el fichero de texto
std::ofstream file(file_path);
// Escribe en el fichero
file << "# ROOM NAME;VISITS;DEATHS" << std::endl;
for (const auto& item : list) {
for (const auto& item : list_) {
file << item.name << ";" << item.visited << ";" << item.died << std::endl;
}
@@ -156,7 +156,7 @@ void Stats::saveToFile(const std::string& file_path, const std::vector<StatsData
// Calcula cual es la habitación con más muertes
void Stats::checkWorstNightmare() {
int deaths = 0;
for (const auto& item : list) {
for (const auto& item : list_) {
if (item.died > deaths) {
deaths = item.died;
Options::stats.worst_nightmare = item.name;
@@ -166,27 +166,27 @@ void Stats::checkWorstNightmare() {
// Añade una entrada al diccionario
void Stats::addDictionary(const std::string& number, const std::string& name) {
dictionary.push_back({number, name});
dictionary_.push_back({number, name});
}
// Vuelca los datos del buffer en la lista de estadisticas
void Stats::updateListFromBuffer() {
// Actualiza list desde bufferList
for (const auto& buffer : bufferList) {
int index = findByName(buffer.name, list);
// Actualiza list_ desde buffer_list_
for (const auto& buffer : buffer_list_) {
int index = findByName(buffer.name, list_);
if (index != -1) { // Encontrado. Aumenta sus estadisticas
list[index].visited += buffer.visited;
list[index].died += buffer.died;
list_[index].visited += buffer.visited;
list_[index].died += buffer.died;
} else { // En caso contrario crea la entrada
StatsData item;
item.name = buffer.name;
item.visited = buffer.visited;
item.died = buffer.died;
list.push_back(item);
list_.push_back(item);
}
}
saveToFile(bufferPath, bufferList);
saveToFile(filePath, list);
saveToFile(buffer_path_, buffer_list_);
saveToFile(file_path_, list_);
}

View File

@@ -17,20 +17,20 @@ class Stats {
};
// Variables
std::vector<StatsDictionary> dictionary; // Lista con la equivalencia nombre-numero de habitacion
std::vector<StatsData> bufferList; // Lista con las estadisticas temporales por habitación
std::vector<StatsData> list; // Lista con las estadisticas completas por habitación
std::string bufferPath; // Fichero con las estadísticas temporales
std::string filePath; // Fichero con las estadísticas completas
std::vector<StatsDictionary> dictionary_; // Lista con la equivalencia nombre-numero de habitacion
std::vector<StatsData> buffer_list_; // Lista con las estadisticas temporales por habitación
std::vector<StatsData> list_; // Lista con las estadisticas completas por habitación
std::string buffer_path_; // Fichero con las estadísticas temporales
std::string file_path_; // Fichero con las estadísticas completas
// Busca una entrada en la lista por nombre
int findByName(const std::string& name, const std::vector<StatsData>& list);
static int findByName(const std::string& name, const std::vector<StatsData>& list);
// Carga las estadisticas desde un fichero
bool loadFromFile(const std::string& filePath, std::vector<StatsData>& list);
bool loadFromFile(const std::string& file_path, std::vector<StatsData>& list);
// Guarda las estadisticas en un fichero
void saveToFile(const std::string& filePath, const std::vector<StatsData>& list);
static void saveToFile(const std::string& file_path, const std::vector<StatsData>& list);
// Calcula cual es la habitación con más muertes
void checkWorstNightmare();

View File

@@ -33,7 +33,7 @@ bool loadFromFile(const std::string& file_path) {
bool success = true;
// Versión actual del fichero
const std::string configVersion = version;
const std::string CONFIG_VERSION = version;
version = "";
// Variables para manejar el fichero
@@ -61,7 +61,8 @@ bool loadFromFile(const std::string& file_path) {
// Usa un stringstream para dividir la línea en dos partes
std::istringstream iss(line);
std::string key, value;
std::string key;
std::string value;
if (iss >> key >> value) {
if (!setOptions(key, value)) {
@@ -85,7 +86,7 @@ bool loadFromFile(const std::string& file_path) {
}
// Si la versión de fichero no coincide, crea un fichero nuevo con los valores por defecto
if (configVersion != version) {
if (CONFIG_VERSION != version) {
init();
saveToFile(file_path);
if (console) {
@@ -155,7 +156,7 @@ bool saveToFile(const std::string& file_path) {
}
bool setOptions(const std::string& var, const std::string& value) {
static const std::unordered_map<std::string, std::function<void(const std::string&)>> optionHandlers = {
static const std::unordered_map<std::string, std::function<void(const std::string&)>> OPTION_HANDLERS = {
{"version", [](const std::string& v) { version = v; }},
{"keys", [](const std::string& v) {
int val = safeStoi(v, static_cast<int>(GameDefaults::CONTROL_SCHEME));
@@ -207,8 +208,8 @@ bool setOptions(const std::string& var, const std::string& value) {
video.palette = v;
}}};
auto it = optionHandlers.find(var);
if (it != optionHandlers.end()) {
auto it = OPTION_HANDLERS.find(var);
if (it != OPTION_HANDLERS.end()) {
it->second(value);
return true;
}

View File

@@ -145,8 +145,7 @@ struct Stats {
// Constructor por defecto
Stats()
: rooms(0),
items(0),
worst_nightmare("") {}
items(0) {}
// Constructor
Stats(int room_count, int item_count, const std::string& worst_nightmare_room)
@@ -213,9 +212,8 @@ struct Video {
shaders(GameDefaults::VIDEO_SHADERS),
integer_scale(GameDefaults::VIDEO_INTEGER_SCALE),
keep_aspect(GameDefaults::VIDEO_KEEP_ASPECT),
border(Border()),
palette(GameDefaults::PALETTE_NAME),
info("") {}
palette(GameDefaults::PALETTE_NAME) {}
// Constructor
Video(bool is_fullscreen, ScreenFilter screen_filter, bool vsync, bool use_shaders, bool int_scale, bool keep_aspect_ratio, Border video_border, const std::string& palette_name)
@@ -226,8 +224,7 @@ struct Video {
integer_scale(int_scale),
keep_aspect(keep_aspect_ratio),
border(video_border),
palette(palette_name),
info("") {}
palette(palette_name) {}
};
// Estructura para las opciones de musica
@@ -283,9 +280,7 @@ struct Audio {
// Constructor por defecto
Audio()
: music(Music()),
sound(Sound()),
enabled(GameDefaults::AUDIO_ENABLED),
: enabled(GameDefaults::AUDIO_ENABLED),
volume(VolumeHelpers::convertVolume(GameDefaults::AUDIO_VOLUME)) {}
// Constructor

View File

@@ -41,18 +41,18 @@ Credits::Credits()
void Credits::checkEvents() {
SDL_Event event;
while (SDL_PollEvent(&event)) {
globalEvents::check(event);
GlobalEvents::check(event);
}
}
// Comprueba las entradas
void Credits::checkInput() {
globalInputs::check();
GlobalInputs::check();
}
// Inicializa los textos
void Credits::iniTexts() {
std::string keys = "";
std::string keys;
switch (Options::keys) {
case Options::ControlScheme::CURSOR:
@@ -205,9 +205,9 @@ void Credits::render() {
text_surface_->render(0, 0);
// Dibuja la textura que cubre el texto
const int offset = std::min(counter_ / 8, 192 / 2);
SDL_FRect srcRect = {0.0F, 0.0F, 256.0F, 192.0F - (offset * 2.0F)};
cover_surface_->render(0, offset * 2, &srcRect);
const int OFFSET = std::min(counter_ / 8, 192 / 2);
SDL_FRect src_rect = {0.0F, 0.0F, 256.0F, 192.0F - (OFFSET * 2.0F)};
cover_surface_->render(0, OFFSET * 2, &src_rect);
// Dibuja el sprite con el brillo
shining_sprite_->render(1, static_cast<Uint8>(PaletteColor::BRIGHT_WHITE));

View File

@@ -34,10 +34,10 @@ class Credits {
void render();
// Comprueba el manejador de eventos
void checkEvents();
static void checkEvents();
// Comprueba las entradas
void checkInput();
static void checkInput();
// Actualiza el contador
void updateCounter();

View File

@@ -104,13 +104,13 @@ void Ending::render() {
void Ending::checkEvents() {
SDL_Event event;
while (SDL_PollEvent(&event)) {
globalEvents::check(event);
GlobalEvents::check(event);
}
}
// Comprueba las entradas
void Ending::checkInput() {
globalInputs::check();
GlobalInputs::check();
}
// Inicializa los textos
@@ -407,9 +407,7 @@ void Ending::updateSpriteCovers() {
sprite_pics_.at(current_scene_).cover_clip_desp -= 2;
} else if (sprite_pics_.at(current_scene_).cover_clip_height > 0) {
sprite_pics_.at(current_scene_).cover_clip_height -= 2;
if (sprite_pics_.at(current_scene_).cover_clip_height < 0) {
sprite_pics_.at(current_scene_).cover_clip_height = 0;
}
sprite_pics_.at(current_scene_).cover_clip_height = std::max(sprite_pics_.at(current_scene_).cover_clip_height, 0);
sprite_pics_.at(current_scene_).cover_sprite->setY(sprite_pics_.at(current_scene_).cover_sprite->getY() + 2);
}
sprite_pics_.at(current_scene_).cover_sprite->setClip(0, sprite_pics_.at(current_scene_).cover_clip_desp, sprite_pics_.at(current_scene_).cover_sprite->getWidth(), sprite_pics_.at(current_scene_).cover_clip_height);
@@ -441,21 +439,21 @@ void Ending::fillCoverTexture() {
cover_surface_->clear(static_cast<Uint8>(PaletteColor::TRANSPARENT));
// Los primeros 8 pixels crea una malla
const Uint8 color = static_cast<Uint8>(PaletteColor::BLACK);
const Uint8 COLOR = static_cast<Uint8>(PaletteColor::BLACK);
auto surface = Screen::get()->getRendererSurface();
for (int i = 0; i < 256; i += 2) {
surface->putPixel(i + 0, Options::game.height + 0, color);
surface->putPixel(i + 1, Options::game.height + 1, color);
surface->putPixel(i + 0, Options::game.height + 2, color);
surface->putPixel(i + 1, Options::game.height + 3, color);
surface->putPixel(i + 0, Options::game.height + 0, COLOR);
surface->putPixel(i + 1, Options::game.height + 1, COLOR);
surface->putPixel(i + 0, Options::game.height + 2, COLOR);
surface->putPixel(i + 1, Options::game.height + 3, COLOR);
surface->putPixel(i, Options::game.height + 4, color);
surface->putPixel(i, Options::game.height + 6, color);
surface->putPixel(i, Options::game.height + 4, COLOR);
surface->putPixel(i, Options::game.height + 6, COLOR);
}
// El resto se rellena de color sólido
SDL_FRect rect = {0, 0, 256, Options::game.height};
surface->fillRect(&rect, color);
surface->fillRect(&rect, COLOR);
Screen::get()->setRendererSurface(previuos_renderer);
}
@@ -465,17 +463,17 @@ void Ending::renderCoverTexture() {
if (cover_counter_ > 0) {
// Dibuja la textura que cubre el texto
const int OFFSET = std::min(cover_counter_, 100);
SDL_FRect srcRect = {0.0F, 200.0F - (cover_counter_ * 2.0F), 256.0F, OFFSET * 2.0F};
SDL_FRect dstRect = {0.0F, 0.0F, 256.0F, OFFSET * 2.0F};
cover_surface_->render(&srcRect, &dstRect);
SDL_FRect src_rect = {0.0F, 200.0F - (cover_counter_ * 2.0F), 256.0F, OFFSET * 2.0F};
SDL_FRect dst_rect = {0.0F, 0.0F, 256.0F, OFFSET * 2.0F};
cover_surface_->render(&src_rect, &dst_rect);
}
}
// Actualiza el volumen de la musica
void Ending::updateMusicVolume() {
void Ending::updateMusicVolume() const {
if (current_scene_ == 4 && cover_counter_ > 0) {
const float step = (100.0f - cover_counter_) / 100.0f;
const int volume = 128 * step;
JA_SetVolume(volume);
const float STEP = (100.0F - cover_counter_) / 100.0F;
const int VOLUME = 128 * STEP;
JA_SetVolume(VOLUME);
}
}

View File

@@ -59,10 +59,10 @@ class Ending {
void render();
// Comprueba el manejador de eventos
void checkEvents();
static void checkEvents();
// Comprueba las entradas
void checkInput();
static void checkInput();
// Inicializa los textos
void iniTexts();
@@ -89,7 +89,7 @@ class Ending {
void renderCoverTexture();
// Actualiza el volumen de la musica
void updateMusicVolume();
void updateMusicVolume() const;
public:
// Constructor

View File

@@ -20,7 +20,7 @@
// Constructor
Ending2::Ending2()
: state_(EndingState::PRE_CREDITS, SDL_GetTicks(), STATE_PRE_CREDITS_DURATION_) {
: state_(EndingState::PRE_CREDITS, SDL_GetTicks(), STATE_PRE_CREDITS_DURATION) {
SceneManager::current = SceneManager::Scene::ENDING2;
SceneManager::options = SceneManager::Options::NONE;
@@ -134,13 +134,13 @@ void Ending2::render() {
void Ending2::checkEvents() {
SDL_Event event;
while (SDL_PollEvent(&event)) {
globalEvents::check(event);
GlobalEvents::check(event);
}
}
// Comprueba las entradas
void Ending2::checkInput() {
globalInputs::check();
GlobalInputs::check();
}
// Bucle principal
@@ -168,13 +168,13 @@ void Ending2::updateState() {
case EndingState::CREDITS:
if (texts_.back()->getPosY() <= GAMECANVAS_CENTER_Y) {
state_.set(EndingState::POST_CREDITS, STATE_POST_CREDITS_DURATION_);
state_.set(EndingState::POST_CREDITS, STATE_POST_CREDITS_DURATION);
}
break;
case EndingState::POST_CREDITS:
if (state_.hasEnded(EndingState::POST_CREDITS)) {
state_.set(EndingState::FADING, STATE_FADE_DURATION_);
state_.set(EndingState::FADING, STATE_FADE_DURATION);
}
break;
@@ -344,15 +344,15 @@ void Ending2::renderTexts() {
// Coloca los sprites en su sito
void Ending2::placeSprites() {
for (int i = 0; i < static_cast<int>(sprites_.size()); ++i) {
const float X = i % 2 == 0 ? FIRST_COL_ : SECOND_COL_;
const float Y = (i / 1) * (sprite_max_height_ + DIST_SPRITE_TEXT_ + Resource::get()->getText("smb2")->getCharacterSize() + DIST_SPRITE_SPRITE_) + Options::game.height + 40;
const float X = i % 2 == 0 ? FIRST_COL : SECOND_COL;
const float Y = (i / 1) * (sprite_max_height_ + DIST_SPRITE_TEXT + Resource::get()->getText("smb2")->getCharacterSize() + DIST_SPRITE_SPRITE) + Options::game.height + 40;
const float W = sprites_.at(i)->getWidth();
const float H = sprites_.at(i)->getHeight();
const float DX = -(W / 2);
const float DY = sprite_max_height_ - H;
sprites_.at(i)->setPos({X + DX, Y + DY, W, H});
sprites_.at(i)->setVelY(SPRITE_DESP_SPEED_);
sprites_.at(i)->setVelY(SPRITE_DESP_SPEED);
}
// Recoloca el sprite del jugador, que es el último de la lista
@@ -382,10 +382,10 @@ void Ending2::createSpriteTexts() {
// Determina la columna y la posición X del texto
const float X = (i == sprite_list_.size() - 1)
? (GAMECANVAS_CENTER_X - (W / 2))
: ((i % 2 == 0 ? FIRST_COL_ : SECOND_COL_) - (W / 2));
: ((i % 2 == 0 ? FIRST_COL : SECOND_COL) - (W / 2));
// Calcula la posición Y del texto en base a la posición y altura del sprite
const float Y = sprites_.at(i)->getPosY() + sprites_.at(i)->getHeight() + DIST_SPRITE_TEXT_;
const float Y = sprites_.at(i)->getPosY() + sprites_.at(i)->getHeight() + DIST_SPRITE_TEXT;
// Crea la surface
auto surface = std::make_shared<Surface>(W, H);
@@ -396,7 +396,7 @@ void Ending2::createSpriteTexts() {
// Crea el sprite
SDL_FRect pos = {X, Y, W, H};
sprite_texts_.emplace_back(std::make_shared<SurfaceMovingSprite>(surface, pos));
sprite_texts_.back()->setVelY(SPRITE_DESP_SPEED_);
sprite_texts_.back()->setVelY(SPRITE_DESP_SPEED);
Screen::get()->setRendererSurface(previuos_renderer);
}
}
@@ -427,7 +427,7 @@ void Ending2::createTexts() {
// Crea el sprite
SDL_FRect pos = {X + DX, Y, W, H};
texts_.emplace_back(std::make_shared<SurfaceMovingSprite>(surface, pos));
texts_.back()->setVelY(SPRITE_DESP_SPEED_);
texts_.back()->setVelY(SPRITE_DESP_SPEED);
Screen::get()->setRendererSurface(previuos_renderer);
}
@@ -456,7 +456,7 @@ void Ending2::createTexts() {
// Crea el sprite
SDL_FRect pos = {X + DX, Y, W, H};
texts_.emplace_back(std::make_shared<SurfaceMovingSprite>(surface, pos));
texts_.back()->setVelY(SPRITE_DESP_SPEED_);
texts_.back()->setVelY(SPRITE_DESP_SPEED);
Screen::get()->setRendererSurface(previuos_renderer);
}
}

View File

@@ -27,15 +27,15 @@ class Ending2 {
Uint32 duration; // Duración en milisegundos para el estado actual
// Constructor parametrizado para inicializar la estructura
State(EndingState initialState, Uint32 initialTicks, Uint32 stateDuration)
: state(initialState),
init_ticks(initialTicks),
duration(stateDuration) {}
State(EndingState initial_state, Uint32 initial_ticks, Uint32 state_duration)
: state(initial_state),
init_ticks(initial_ticks),
duration(state_duration) {}
// Método para comprobar si el estado ha terminado y verifica el nombre del estado
bool hasEnded(EndingState expectedState) const {
bool hasEnded(EndingState expected_state) const {
// Comprobar si el estado actual coincide con el estado esperado
if (state != expectedState) {
if (state != expected_state) {
return false; // Si no coincide, considerar que no ha terminado
}
@@ -44,22 +44,22 @@ class Ending2 {
}
// Método para establecer un nuevo estado
void set(EndingState newState, Uint32 newDuration) {
state = newState; // Actualizar el estado
void set(EndingState new_state, Uint32 new_duration) {
state = new_state; // Actualizar el estado
init_ticks = SDL_GetTicks(); // Reiniciar el tiempo de inicio
duration = newDuration; // Actualizar la duración
duration = new_duration; // Actualizar la duración
}
};
// Constantes
static constexpr int FIRST_COL_ = GAMECANVAS_FIRST_QUARTER_X + (GAMECANVAS_WIDTH / 16); // Primera columna por donde desfilan los sprites
static constexpr int SECOND_COL_ = GAMECANVAS_THIRD_QUARTER_X - (GAMECANVAS_WIDTH / 16); // Segunda columna por donde desfilan los sprites
static constexpr int DIST_SPRITE_TEXT_ = 8; // Distancia entre el sprite y el texto que lo acompaña
static constexpr int DIST_SPRITE_SPRITE_ = 0; // Distancia entre dos sprites de la misma columna
static constexpr float SPRITE_DESP_SPEED_ = -0.2f; // Velocidad de desplazamiento de los sprites
static constexpr int STATE_PRE_CREDITS_DURATION_ = 3000;
static constexpr int STATE_POST_CREDITS_DURATION_ = 5000;
static constexpr int STATE_FADE_DURATION_ = 5000;
static constexpr int FIRST_COL = GAMECANVAS_FIRST_QUARTER_X + (GAMECANVAS_WIDTH / 16); // Primera columna por donde desfilan los sprites
static constexpr int SECOND_COL = GAMECANVAS_THIRD_QUARTER_X - (GAMECANVAS_WIDTH / 16); // Segunda columna por donde desfilan los sprites
static constexpr int DIST_SPRITE_TEXT = 8; // Distancia entre el sprite y el texto que lo acompaña
static constexpr int DIST_SPRITE_SPRITE = 0; // Distancia entre dos sprites de la misma columna
static constexpr float SPRITE_DESP_SPEED = -0.2F; // Velocidad de desplazamiento de los sprites
static constexpr int STATE_PRE_CREDITS_DURATION = 3000;
static constexpr int STATE_POST_CREDITS_DURATION = 5000;
static constexpr int STATE_FADE_DURATION = 5000;
// Objetos y punteros
std::vector<std::shared_ptr<SurfaceAnimatedSprite>> sprites_; // Vector con todos los sprites a dibujar

View File

@@ -47,7 +47,7 @@ Game::Game(GameMode mode)
// Crea objetos e inicializa variables
ItemTracker::init();
DEMO_init();
demoInit();
room_ = std::make_shared<Room>(current_room_, board_);
initPlayer(spawn_point_, room_);
initStats();
@@ -71,7 +71,7 @@ Game::~Game() {
void Game::checkEvents() {
SDL_Event event;
while (SDL_PollEvent(&event)) {
globalEvents::check(event);
GlobalEvents::check(event);
#ifdef _DEBUG
checkDebugEvents(event);
#endif
@@ -91,7 +91,7 @@ void Game::checkInput() {
Notifier::get()->show({std::string(paused_ ? "GAME PAUSED" : "GAME RUNNING")}, NotificationText::CENTER);
}
globalInputs::check();
GlobalInputs::check();
}
// Bucle para el juego
@@ -139,7 +139,7 @@ void Game::update() {
checkRestoringJail();
checkSomeCheevos();
}
DEMO_checkRoomChange();
demoCheckRoomChange();
scoreboard_->update();
keepMusicPlaying();
updateBlackScreen();
@@ -270,7 +270,7 @@ bool Game::changeRoom(const std::string& room_path) {
}
// Verifica que exista el fichero que se va a cargar
if (Asset::get()->get(room_path) != "") {
if (!Asset::get()->get(room_path).empty()) {
// Crea un objeto habitación nuevo a partir del fichero
room_ = std::make_shared<Room>(room_path, board_);
@@ -304,8 +304,8 @@ bool Game::changeRoom(const std::string& room_path) {
// Comprueba si el jugador esta en el borde de la pantalla
void Game::checkPlayerIsOnBorder() {
if (player_->getOnBorder()) {
const std::string roomName = room_->getRoom(player_->getBorder());
if (changeRoom(roomName)) {
const std::string ROOM_NAME = room_->getRoom(player_->getBorder());
if (changeRoom(ROOM_NAME)) {
player_->switchBorders();
spawn_point_ = player_->getSpawnParams();
}
@@ -314,11 +314,11 @@ void Game::checkPlayerIsOnBorder() {
// Comprueba las colisiones del jugador con los enemigos
bool Game::checkPlayerAndEnemies() {
const bool death = room_->enemyCollision(player_->getCollider());
if (death) {
const bool DEATH = room_->enemyCollision(player_->getCollider());
if (DEATH) {
killPlayer();
}
return death;
return DEATH;
}
// Comprueba las colisiones del jugador con los objetos
@@ -393,12 +393,12 @@ void Game::updateBlackScreen() {
}
// Dibuja la pantalla negra
void Game::renderBlackScreen() {
void Game::renderBlackScreen() const {
if (black_screen_) {
auto const color = static_cast<Uint8>(PaletteColor::BLACK);
auto const COLOR = static_cast<Uint8>(PaletteColor::BLACK);
Screen::get()->setRendererSurface();
Screen::get()->clearSurface(color);
Screen::get()->setBorderColor(color);
Screen::get()->clearSurface(COLOR);
Screen::get()->setBorderColor(COLOR);
}
}
@@ -416,15 +416,15 @@ void Game::setScoreBoardColor() {
// Comprueba si ha finalizado el juego
bool Game::checkEndGame() {
const bool isOnTheRoom = room_->getName() == "THE JAIL"; // Estar en la habitación que toca
const bool haveTheItems = board_->items >= int(total_items_ * 0.9f) || Options::cheats.jail_is_open == Options::Cheat::State::ENABLED; // Con mas del 90% de los items recogidos
const bool isOnTheDoor = player_->getRect().x <= 128; // Y en la ubicación que toca (En la puerta)
const bool IS_ON_THE_ROOM = room_->getName() == "THE JAIL"; // Estar en la habitación que toca
const bool HAVE_THE_ITEMS = board_->items >= int(total_items_ * 0.9F) || Options::cheats.jail_is_open == Options::Cheat::State::ENABLED; // Con mas del 90% de los items recogidos
const bool IS_ON_THE_DOOR = player_->getRect().x <= 128; // Y en la ubicación que toca (En la puerta)
if (haveTheItems) {
if (HAVE_THE_ITEMS) {
board_->jail_is_open = true;
}
if (haveTheItems && isOnTheRoom && isOnTheDoor) {
if (HAVE_THE_ITEMS && IS_ON_THE_ROOM && IS_ON_THE_DOOR) {
// Comprueba los logros de completar el juego
checkEndGameCheevos();
@@ -462,21 +462,21 @@ void Game::checkRestoringJail() {
return;
}
static int counter = 0;
static int counter_ = 0;
if (!paused_) {
counter++;
counter_++;
}
// Incrementa el numero de vidas
if (counter == 100) {
counter = 0;
if (counter_ == 100) {
counter_ = 0;
board_->lives++;
JA_PlaySound(Resource::get()->getSound("death.wav"));
// Invalida el logro de completar el juego sin entrar a la jail
const bool haveTheItems = board_->items >= int(total_items_ * 0.9f);
if (!haveTheItems) {
const bool HAVE_THE_ITEMS = board_->items >= int(total_items_ * 0.9F);
if (!HAVE_THE_ITEMS) {
Cheevos::get()->setUnobtainable(9);
}
}
@@ -512,7 +512,7 @@ void Game::fillRoomNameTexture() {
// Comprueba algunos logros
void Game::checkSomeCheevos() {
auto cheevos = Cheevos::get();
auto* cheevos = Cheevos::get();
// Logros sobre la cantidad de items
if (board_->items == total_items_) {
@@ -520,14 +520,14 @@ void Game::checkSomeCheevos() {
cheevos->unlock(3);
cheevos->unlock(2);
cheevos->unlock(1);
} else if (board_->items >= total_items_ * 0.75f) {
} else if (board_->items >= total_items_ * 0.75F) {
cheevos->unlock(3);
cheevos->unlock(2);
cheevos->unlock(1);
} else if (board_->items >= total_items_ * 0.5f) {
} else if (board_->items >= total_items_ * 0.5F) {
cheevos->unlock(2);
cheevos->unlock(1);
} else if (board_->items >= total_items_ * 0.25f) {
} else if (board_->items >= total_items_ * 0.25F) {
cheevos->unlock(1);
}
@@ -546,7 +546,7 @@ void Game::checkSomeCheevos() {
// Comprueba los logros de completar el juego
void Game::checkEndGameCheevos() {
auto cheevos = Cheevos::get();
auto* cheevos = Cheevos::get();
// "Complete the game"
cheevos->unlock(8);
@@ -572,8 +572,8 @@ void Game::checkEndGameCheevos() {
void Game::initPlayer(const PlayerSpawn& spawn_point, std::shared_ptr<Room> room) {
std::string player_texture = Options::cheats.alternate_skin == Options::Cheat::State::ENABLED ? "player2.gif" : "player.gif";
std::string player_animations = Options::cheats.alternate_skin == Options::Cheat::State::ENABLED ? "player2.ani" : "player.ani";
const PlayerData player(spawn_point, player_texture, player_animations, room);
player_ = std::make_shared<Player>(player);
const PlayerData PLAYER(spawn_point, player_texture, player_animations, room);
player_ = std::make_shared<Player>(PLAYER);
}
// Crea la textura para poner el nombre de la habitación
@@ -587,16 +587,16 @@ void Game::createRoomNameTexture() {
// Hace sonar la música
void Game::keepMusicPlaying() {
const std::string music_path = mode_ == GameMode::GAME ? "game.ogg" : "title.ogg";
const std::string MUSIC_PATH = mode_ == GameMode::GAME ? "game.ogg" : "title.ogg";
// Si la música no está sonando
if (JA_GetMusicState() == JA_MUSIC_INVALID || JA_GetMusicState() == JA_MUSIC_STOPPED) {
JA_PlayMusic(Resource::get()->getMusic(music_path));
JA_PlayMusic(Resource::get()->getMusic(MUSIC_PATH));
}
}
// DEMO MODE: Inicializa las variables para el modo demo
void Game::DEMO_init() {
void Game::demoInit() {
if (mode_ == GameMode::DEMO) {
demo_ = DemoData(0, 400, 0, {"04.room", "54.room", "20.room", "09.room", "05.room", "11.room", "31.room", "44.room"});
current_room_ = demo_.rooms.front();
@@ -604,7 +604,7 @@ void Game::DEMO_init() {
}
// DEMO MODE: Comprueba si se ha de cambiar de habitación
void Game::DEMO_checkRoomChange() {
void Game::demoCheckRoomChange() {
if (mode_ == GameMode::DEMO) {
demo_.counter++;
if (demo_.counter == demo_.room_time) {

View File

@@ -119,7 +119,7 @@ class Game {
void updateBlackScreen();
// Dibuja la pantalla negra
void renderBlackScreen();
void renderBlackScreen() const;
// Pone el color del marcador en función del color del borde de la habitación
void setScoreBoardColor();
@@ -128,7 +128,7 @@ class Game {
bool checkEndGame();
// Obtiene la cantidad total de items que hay en el mapeado del juego
int getTotalItems();
static int getTotalItems();
// Pone el juego en pausa
void togglePause();
@@ -158,10 +158,10 @@ class Game {
void keepMusicPlaying();
// DEMO MODE: Inicializa las variables para el modo demo
void DEMO_init();
void demoInit();
// DEMO MODE: Comprueba si se ha de cambiar de habitación
void DEMO_checkRoomChange();
void demoCheckRoomChange();
public:
// Constructor

View File

@@ -102,13 +102,13 @@ void GameOver::render() {
void GameOver::checkEvents() {
SDL_Event event;
while (SDL_PollEvent(&event)) {
globalEvents::check(event);
GlobalEvents::check(event);
}
}
// Comprueba las entradas
void GameOver::checkInput() {
globalInputs::check();
GlobalInputs::check();
}
// Bucle principal
@@ -122,14 +122,14 @@ void GameOver::run() {
// Actualiza el color usado para renderizar los textos e imagenes
void GameOver::updateColor() {
const int half = COUNTER_SECTION_END_ / 2;
const int HALF = COUNTER_SECTION_END / 2;
if (counter_ < half) {
const float STEP = std::min(counter_, COUNTER_FADE_LENGHT_) / (float)COUNTER_FADE_LENGHT_;
if (counter_ < HALF) {
const float STEP = std::min(counter_, COUNTER_FADE_LENGHT) / (float)COUNTER_FADE_LENGHT;
const int INDEX = (colors_.size() - 1) - int((colors_.size() - 1) * STEP);
color_ = colors_[INDEX];
} else {
const float STEP = std::min(std::max(counter_, COUNTER_INIT_FADE_) - COUNTER_INIT_FADE_, COUNTER_FADE_LENGHT_) / (float)COUNTER_FADE_LENGHT_;
const float STEP = std::min(std::max(counter_, COUNTER_INIT_FADE) - COUNTER_INIT_FADE, COUNTER_FADE_LENGHT) / (float)COUNTER_FADE_LENGHT;
const int INDEX = (colors_.size() - 1) * STEP;
color_ = colors_[INDEX];
}
@@ -156,7 +156,7 @@ void GameOver::updateCounters() {
}
// Comprueba si ha terminado la sección
else if (counter_ == COUNTER_SECTION_END_) {
else if (counter_ == COUNTER_SECTION_END) {
SceneManager::current = SceneManager::Scene::LOGO;
SceneManager::options = SceneManager::Options::LOGO_TO_TITLE;
}

View File

@@ -9,9 +9,9 @@ class SurfaceAnimatedSprite; // lines 7-7
class GameOver {
private:
// Constantes
static constexpr int COUNTER_SECTION_END_ = 400; // Contador: cuando acaba la sección
static constexpr int COUNTER_INIT_FADE_ = 310; // Contador: cuando emiepza el fade
static constexpr int COUNTER_FADE_LENGHT_ = 20; // Contador: duración del fade
static constexpr int COUNTER_SECTION_END = 400; // Contador: cuando acaba la sección
static constexpr int COUNTER_INIT_FADE = 310; // Contador: cuando emiepza el fade
static constexpr int COUNTER_FADE_LENGHT = 20; // Contador: duración del fade
// Objetos y punteros
std::shared_ptr<SurfaceAnimatedSprite> player_sprite_; // Sprite con el jugador
@@ -31,10 +31,10 @@ class GameOver {
void render();
// Comprueba el manejador de eventos
void checkEvents();
static void checkEvents();
// Comprueba las entradas
void checkInput();
static void checkInput();
// Actualiza el color usado para renderizar los textos e imagenes
void updateColor();

View File

@@ -24,9 +24,9 @@ LoadingScreen::LoadingScreen()
screen_surface_(std::make_shared<Surface>(Options::game.width, Options::game.height)),
delta_timer_(std::make_unique<DeltaTimer>()),
state_(LoadingState::SILENT1),
state_time_(0.0f),
state_time_(0.0F),
current_border_type_(BorderType::NONE),
load_rect_{0, 0, 0, 1.0f} {
load_rect_{0, 0, 0, 1.0F} {
// Configura la superficie donde se van a pintar los sprites
screen_surface_->clear(static_cast<Uint8>(PaletteColor::WHITE));
@@ -51,13 +51,13 @@ LoadingScreen::~LoadingScreen() {
void LoadingScreen::checkEvents() {
SDL_Event event;
while (SDL_PollEvent(&event)) {
globalEvents::check(event);
GlobalEvents::check(event);
}
}
// Comprueba las entradas
void LoadingScreen::checkInput() {
globalInputs::check();
GlobalInputs::check();
}
// Inicializa el array de índices de líneas (imita el direccionamiento de memoria del Spectrum)
@@ -76,7 +76,7 @@ void LoadingScreen::initLineIndexArray() {
// Transiciona a un nuevo estado
void LoadingScreen::transitionToState(LoadingState new_state) {
state_ = new_state;
state_time_ = 0.0f;
state_time_ = 0.0F;
// Acciones específicas al entrar en cada estado
switch (new_state) {
@@ -172,31 +172,31 @@ void LoadingScreen::updateState(float delta_time) {
void LoadingScreen::updateMonoLoad(float delta_time) {
// Calcular progreso lineal (0.0 - 1.0)
float progress = state_time_ / LOADING_MONO_DURATION;
progress = std::min(progress, 1.0f);
progress = std::min(progress, 1.0F);
// Calcular paso total actual (0-959)
const int total_steps = MONO_TOTAL_LINES * MONO_STEPS_PER_LINE; // 192 * 5 = 960
const int current_step = static_cast<int>(progress * total_steps);
const int TOTAL_STEPS = MONO_TOTAL_LINES * MONO_STEPS_PER_LINE; // 192 * 5 = 960
const int CURRENT_STEP = static_cast<int>(progress * TOTAL_STEPS);
// Calcular línea y sub-paso
const int current_line = current_step / MONO_STEPS_PER_LINE; // 0-191
const int current_substep = current_step % MONO_STEPS_PER_LINE; // 0-4
const int CURRENT_LINE = CURRENT_STEP / MONO_STEPS_PER_LINE; // 0-191
const int CURRENT_SUBSTEP = CURRENT_STEP % MONO_STEPS_PER_LINE; // 0-4
// Verificar si ha completado todas las líneas
if (current_line >= MONO_TOTAL_LINES) {
if (CURRENT_LINE >= MONO_TOTAL_LINES) {
transitionToState(LoadingState::LOADING_COLOR);
return;
}
// Calcular rectángulo de clip (con floats para mayor precisión)
const float texture_width = static_cast<float>(mono_loading_screen_surface_->getWidth());
const float clip_width = texture_width / MONO_STEPS_PER_LINE;
const float clip_x = current_substep * clip_width;
const float TEXTURE_WIDTH = mono_loading_screen_surface_->getWidth();
const float CLIP_WIDTH = TEXTURE_WIDTH / MONO_STEPS_PER_LINE;
const float CLIP_X = CURRENT_SUBSTEP * CLIP_WIDTH;
load_rect_.x = clip_x;
load_rect_.y = static_cast<float>(line_index_[current_line]);
load_rect_.w = clip_width;
load_rect_.h = 1.0f;
load_rect_.x = CLIP_X;
load_rect_.y = static_cast<float>(line_index_[CURRENT_LINE]);
load_rect_.w = CLIP_WIDTH;
load_rect_.h = 1.0F;
// Configurar y dibujar sobre screen_surface_
mono_loading_screen_sprite_->setClip(load_rect_);
@@ -212,24 +212,24 @@ void LoadingScreen::updateMonoLoad(float delta_time) {
void LoadingScreen::updateColorLoad(float delta_time) {
// Calcular progreso lineal (0.0 - 1.0)
float progress = state_time_ / LOADING_COLOR_DURATION;
progress = std::min(progress, 1.0f);
progress = std::min(progress, 1.0F);
// Calcular iteración actual (el código original incrementaba de 2 en 2)
const int total_iterations = COLOR_TOTAL_BLOCKS / 2; // 768 / 2 = 384 iteraciones
const int current_iteration = static_cast<int>(progress * total_iterations);
const int TOTAL_ITERATIONS = COLOR_TOTAL_BLOCKS / 2; // 768 / 2 = 384 iteraciones
const int CURRENT_ITERATION = static_cast<int>(progress * TOTAL_ITERATIONS);
// Convertir a bloque (incrementa de 2 en 2, empezando en 0)
const int current_block = current_iteration * 2;
const int CURRENT_BLOCK = CURRENT_ITERATION * 2;
// Verificar si ha completado todos los bloques
if (current_block >= COLOR_TOTAL_BLOCKS) {
if (CURRENT_BLOCK >= COLOR_TOTAL_BLOCKS) {
transitionToState(LoadingState::BYTES2);
return;
}
// Calcular posición del bloque
load_rect_.x = static_cast<float>((current_block * COLOR_BLOCK_SPACING) % 256);
load_rect_.y = static_cast<float>((current_block / COLOR_BLOCKS_PER_ROW) * COLOR_BLOCK_SPACING);
load_rect_.x = static_cast<float>((CURRENT_BLOCK * COLOR_BLOCK_SPACING) % 256);
load_rect_.y = static_cast<float>((CURRENT_BLOCK / COLOR_BLOCKS_PER_ROW) * COLOR_BLOCK_SPACING);
load_rect_.w = static_cast<float>(COLOR_BLOCK_WIDTH);
load_rect_.h = static_cast<float>(COLOR_BLOCK_HEIGHT);
@@ -255,7 +255,7 @@ void LoadingScreen::renderYellowBorder() {
const Uint8 COLOR = static_cast<Uint8>(PaletteColor::YELLOW);
const int WIDTH = Options::game.width + (Options::video.border.width * 2);
const int HEIGHT = Options::game.height + (Options::video.border.height * 2);
bool draw_enabled = rand() % 2 == 0 ? true : false;
bool draw_enabled = rand() % 2 == 0;
int row = 0;
while (row < HEIGHT) {
@@ -320,10 +320,10 @@ void LoadingScreen::renderWhiteBorder() {
// Actualiza las variables
void LoadingScreen::update() {
// Obtener delta time desde el último frame
const float delta_time = delta_timer_->tick();
const float DELTA_TIME = delta_timer_->tick();
checkInput(); // Comprueba las entradas
updateState(delta_time); // Actualiza el estado y gestiona transiciones
updateState(DELTA_TIME); // Actualiza el estado y gestiona transiciones
// Actualizar la carga según el estado actual
switch (state_) {
@@ -338,11 +338,11 @@ void LoadingScreen::update() {
break;
case LoadingState::LOADING_MONO:
updateMonoLoad(delta_time);
updateMonoLoad(DELTA_TIME);
break;
case LoadingState::LOADING_COLOR:
updateColorLoad(delta_time);
updateColorLoad(DELTA_TIME);
break;
case LoadingState::COMPLETE:

View File

@@ -38,14 +38,14 @@ class LoadingScreen {
private:
// --- Constantes de tiempo (en segundos) ---
static constexpr float SILENT1_DURATION = 1.0f; // Pausa inicial
static constexpr float HEADER1_DURATION = 2.0f; // Cabecera
static constexpr float BYTES1_DURATION = 0.5f; // Datos
static constexpr float SILENT2_DURATION = 2.0f; // Segunda pausa
static constexpr float HEADER2_DURATION = 2.0f; // Cabecera pantalla
static constexpr float LOADING_MONO_DURATION = 16.0f; // Duración total de la carga monocromática
static constexpr float LOADING_COLOR_DURATION = 4.0f; // Duración total de la carga en color
static constexpr float BYTES2_DURATION = 2.0f; // Datos
static constexpr float SILENT1_DURATION = 1.0F; // Pausa inicial
static constexpr float HEADER1_DURATION = 2.0F; // Cabecera
static constexpr float BYTES1_DURATION = 0.5F; // Datos
static constexpr float SILENT2_DURATION = 2.0F; // Segunda pausa
static constexpr float HEADER2_DURATION = 2.0F; // Cabecera pantalla
static constexpr float LOADING_MONO_DURATION = 16.0F; // Duración total de la carga monocromática
static constexpr float LOADING_COLOR_DURATION = 4.0F; // Duración total de la carga en color
static constexpr float BYTES2_DURATION = 2.0F; // Datos
// --- Constantes de geometría ---
static constexpr int MONO_TOTAL_LINES = 192; // Total de líneas en carga monocromática
@@ -74,15 +74,15 @@ class LoadingScreen {
// --- Funciones ---
void update(); // Actualiza las variables
void render(); // Dibuja en pantalla
void checkEvents(); // Comprueba el manejador de eventos
void checkInput(); // Comprueba las entradas
static void checkEvents(); // Comprueba el manejador de eventos
static void checkInput(); // Comprueba las entradas
void updateState(float delta_time); // Actualiza el estado actual
void transitionToState(LoadingState new_state); // Transiciona a un nuevo estado
void updateMonoLoad(float delta_time); // Gestiona la carga monocromática (time-based)
void updateColorLoad(float delta_time); // Gestiona la carga en color (time-based)
void renderBorder(); // Pinta el borde
void renderYellowBorder(); // Dibuja el efecto de carga amarillo y azul en el borde
void renderRedBorder(); // Dibuja el efecto de carga rojo y azul en el borde
void renderWhiteBorder(); // Dibuja el borde de color blanco
static void renderYellowBorder(); // Dibuja el efecto de carga amarillo y azul en el borde
static void renderRedBorder(); // Dibuja el efecto de carga rojo y azul en el borde
static void renderWhiteBorder(); // Dibuja el borde de color blanco
void initLineIndexArray(); // Inicializa el array de índices de líneas
};

View File

@@ -22,7 +22,7 @@ Logo::Logo()
since_1998_sprite_(std::make_shared<SurfaceSprite>(since_1998_surface_, (256 - since_1998_surface_->getWidth()) / 2, 83 + jailgames_surface_->getHeight() + 5, since_1998_surface_->getWidth(), since_1998_surface_->getHeight())),
delta_timer_(std::make_unique<DeltaTimer>()),
state_(LogoState::INITIAL),
state_time_(0.0f) {
state_time_(0.0F) {
// Configura variables
since_1998_sprite_->setClip(0, 0, since_1998_surface_->getWidth(), since_1998_surface_->getHeight());
since_1998_color_ = static_cast<Uint8>(PaletteColor::BLACK);
@@ -42,13 +42,13 @@ Logo::Logo()
void Logo::checkEvents() {
SDL_Event event;
while (SDL_PollEvent(&event)) {
globalEvents::check(event);
GlobalEvents::check(event);
}
}
// Comprueba las entradas
void Logo::checkInput() {
globalInputs::check();
GlobalInputs::check();
}
// Gestiona el logo de JAILGAME (time-based)
@@ -59,24 +59,24 @@ void Logo::updateJAILGAMES(float delta_time) {
}
// Calcular el desplazamiento basado en velocidad y delta time
const float displacement = JAILGAMES_SLIDE_SPEED * delta_time;
const float DISPLACEMENT = JAILGAMES_SLIDE_SPEED * delta_time;
// Actualizar cada línea del sprite JAILGAMES
for (size_t i = 1; i < jailgames_sprite_.size(); ++i) {
const int current_x = jailgames_sprite_[i]->getX();
const int CURRENT_X = jailgames_sprite_[i]->getX();
// Las líneas pares se mueven desde la derecha, las impares desde la izquierda
if (i % 2 == 0) {
// Mover hacia la izquierda
if (current_x > JAILGAMES_DEST_X) {
const int new_x = static_cast<int>(current_x - displacement);
jailgames_sprite_[i]->setX(new_x < JAILGAMES_DEST_X ? JAILGAMES_DEST_X : new_x);
if (CURRENT_X > JAILGAMES_DEST_X) {
const int NEW_X = static_cast<int>(CURRENT_X - DISPLACEMENT);
jailgames_sprite_[i]->setX(NEW_X < JAILGAMES_DEST_X ? JAILGAMES_DEST_X : NEW_X);
}
} else {
// Mover hacia la derecha
if (current_x < JAILGAMES_DEST_X) {
const int new_x = static_cast<int>(current_x + displacement);
jailgames_sprite_[i]->setX(new_x > JAILGAMES_DEST_X ? JAILGAMES_DEST_X : new_x);
if (CURRENT_X < JAILGAMES_DEST_X) {
const int NEW_X = static_cast<int>(CURRENT_X + DISPLACEMENT);
jailgames_sprite_[i]->setX(NEW_X > JAILGAMES_DEST_X ? JAILGAMES_DEST_X : NEW_X);
}
}
}
@@ -85,13 +85,13 @@ void Logo::updateJAILGAMES(float delta_time) {
// Calcula el índice de color según el progreso (0.0-1.0)
int Logo::getColorIndex(float progress) const {
// Asegurar que progress esté en el rango [0.0, 1.0]
progress = std::clamp(progress, 0.0f, 1.0f);
progress = std::clamp(progress, 0.0F, 1.0F);
// Mapear el progreso al índice de color (0-7)
const int max_index = static_cast<int>(color_.size()) - 1;
const int index = static_cast<int>(progress * max_index);
const int MAX_INDEX = static_cast<int>(color_.size()) - 1;
const int INDEX = static_cast<int>(progress * MAX_INDEX);
return index;
return INDEX;
}
// Gestiona el color de las texturas
@@ -99,8 +99,8 @@ void Logo::updateTextureColors() {
switch (state_) {
case LogoState::SINCE_1998_FADE_IN: {
// Fade-in de "Since 1998" de negro a blanco
const float progress = state_time_ / SINCE_1998_FADE_DURATION;
since_1998_color_ = color_[getColorIndex(progress)];
const float PROGRESS = state_time_ / SINCE_1998_FADE_DURATION;
since_1998_color_ = color_[getColorIndex(PROGRESS)];
break;
}
@@ -113,10 +113,10 @@ void Logo::updateTextureColors() {
case LogoState::FADE_OUT: {
// Fade-out de ambos logos de blanco a negro
const float progress = 1.0f - (state_time_ / FADE_OUT_DURATION);
const int color_index = getColorIndex(progress);
jailgames_color_ = color_[color_index];
since_1998_color_ = color_[color_index];
const float PROGRESS = 1.0F - (state_time_ / FADE_OUT_DURATION);
const int COLOR_INDEX = getColorIndex(PROGRESS);
jailgames_color_ = color_[COLOR_INDEX];
since_1998_color_ = color_[COLOR_INDEX];
break;
}
@@ -129,7 +129,7 @@ void Logo::updateTextureColors() {
// Transiciona a un nuevo estado
void Logo::transitionToState(LogoState new_state) {
state_ = new_state;
state_time_ = 0.0f;
state_time_ = 0.0F;
}
// Actualiza el estado actual
@@ -178,11 +178,11 @@ void Logo::updateState(float delta_time) {
// Actualiza las variables
void Logo::update() {
// Obtener delta time desde el último frame
const float delta_time = delta_timer_->tick();
const float DELTA_TIME = delta_timer_->tick();
checkInput(); // Comprueba las entradas
updateState(delta_time); // Actualiza el estado y gestiona transiciones
updateJAILGAMES(delta_time); // Gestiona el logo de JAILGAME
updateState(DELTA_TIME); // Actualiza el estado y gestiona transiciones
updateJAILGAMES(DELTA_TIME); // Gestiona el logo de JAILGAME
updateTextureColors(); // Gestiona el color de las texturas
Screen::get()->update(); // Actualiza el objeto Screen
}

View File

@@ -27,14 +27,14 @@ class Logo {
private:
// --- Constantes de tiempo (en segundos) ---
static constexpr float INITIAL_DELAY = 0.5f; // Tiempo antes de que empiece la animación
static constexpr float JAILGAMES_SLIDE_DURATION = 1.2f; // Duración del slide-in de JAILGAMES
static constexpr float SINCE_1998_FADE_DURATION = 0.5f; // Duración del fade-in de "Since 1998"
static constexpr float DISPLAY_DURATION = 3.5f; // Tiempo que el logo permanece visible
static constexpr float FADE_OUT_DURATION = 0.5f; // Duración del fade-out final
static constexpr float INITIAL_DELAY = 0.5F; // Tiempo antes de que empiece la animación
static constexpr float JAILGAMES_SLIDE_DURATION = 1.2F; // Duración del slide-in de JAILGAMES
static constexpr float SINCE_1998_FADE_DURATION = 0.5F; // Duración del fade-in de "Since 1998"
static constexpr float DISPLAY_DURATION = 3.5F; // Tiempo que el logo permanece visible
static constexpr float FADE_OUT_DURATION = 0.5F; // Duración del fade-out final
// --- Constantes de animación ---
static constexpr float JAILGAMES_SLIDE_SPEED = 800.0f; // Velocidad de slide-in (pixels/segundo)
static constexpr float JAILGAMES_SLIDE_SPEED = 800.0F; // Velocidad de slide-in (pixels/segundo)
static constexpr int JAILGAMES_DEST_X = 37; // Posición X de destino para JAILGAMES
// --- Objetos y punteros ---
@@ -54,14 +54,14 @@ class Logo {
// --- Funciones ---
void update(); // Actualiza las variables
void render(); // Dibuja en pantalla
void checkEvents(); // Comprueba el manejador de eventos
void checkInput(); // Comprueba las entradas
static void checkEvents(); // Comprueba el manejador de eventos
static void checkInput(); // Comprueba las entradas
void updateJAILGAMES(float delta_time); // Gestiona el logo de JAILGAME (time-based)
void updateTextureColors(); // Gestiona el color de las texturas
void updateState(float delta_time); // Actualiza el estado actual
void transitionToState(LogoState new_state); // Transiciona a un nuevo estado
int getColorIndex(float progress) const; // Calcula el índice de color según el progreso (0.0-1.0)
void endSection(); // Termina la sección
static void endSection(); // Termina la sección
void initColors(); // Inicializa el vector de colores
void initSprites(); // Crea los sprites de cada linea
};

View File

@@ -29,9 +29,9 @@ Title::Title()
marquee_text_(Resource::get()->getText("gauntlet")),
first_active_letter_(0),
last_active_letter_(0),
state_time_(0.0f),
fade_accumulator_(0.0f),
current_delta_(0.0f) {
state_time_(0.0F),
fade_accumulator_(0.0F),
current_delta_(0.0F) {
// Inicializa variables
state_ = SceneManager::options == SceneManager::Options::TITLE_WITH_LOADING_SCREEN ? TitleState::SHOW_LOADING_SCREEN : TitleState::SHOW_MENU;
SceneManager::current = SceneManager::Scene::TITLE;
@@ -75,7 +75,7 @@ void Title::initMarquee() {
void Title::checkEvents() {
SDL_Event event;
while (SDL_PollEvent(&event)) {
globalEvents::check(event);
GlobalEvents::check(event);
// Solo se comprueban estas teclas si no está activo el menu de logros
if (event.type == SDL_EVENT_KEY_DOWN) {
@@ -116,19 +116,19 @@ void Title::checkInput() {
}
}
globalInputs::check();
GlobalInputs::check();
}
// Actualiza la marquesina
void Title::updateMarquee(float delta_time) {
const float displacement = MARQUEE_SPEED * delta_time;
const float DISPLACEMENT = MARQUEE_SPEED * delta_time;
// Solo procesar letras en rango activo + 1 para poder activar la siguiente
for (int i = first_active_letter_; i <= last_active_letter_ + 1 && i < (int)letters_.size(); ++i) {
auto& letter = letters_[i];
if (letter.enabled) {
letter.x -= displacement;
letter.x -= DISPLACEMENT;
// Desactivar si sale de pantalla
if (letter.x < MARQUEE_EXIT_X) {
@@ -196,7 +196,7 @@ void Title::updateState(float delta_time) {
case TitleState::FADE_LOADING_SCREEN:
fade_accumulator_ += delta_time;
if (fade_accumulator_ >= FADE_STEP_INTERVAL) {
fade_accumulator_ = 0.0f;
fade_accumulator_ = 0.0F;
if (loading_screen_surface_->fadeSubPalette()) {
transitionToState(TitleState::SHOW_MENU);
}
@@ -222,8 +222,8 @@ void Title::updateState(float delta_time) {
// Transiciona a un nuevo estado
void Title::transitionToState(TitleState new_state) {
state_ = new_state;
state_time_ = 0.0f;
fade_accumulator_ = 0.0f;
state_time_ = 0.0F;
fade_accumulator_ = 0.0F;
}
// Dibuja en pantalla
@@ -272,12 +272,12 @@ void Title::run() {
// Desplaza la lista de logros
void Title::moveCheevosList(int direction, float delta_time) {
// Calcula el desplazamiento basado en tiempo
const float displacement = CHEEVOS_SCROLL_SPEED * delta_time;
const float DISPLACEMENT = CHEEVOS_SCROLL_SPEED * delta_time;
// Modifica la posición de la ventana de vista
cheevos_surface_view_.y = direction == 0
? cheevos_surface_view_.y - displacement
: cheevos_surface_view_.y + displacement;
? cheevos_surface_view_.y - DISPLACEMENT
: cheevos_surface_view_.y + DISPLACEMENT;
// Ajusta los limites
const float BOTTOM = cheevos_surface_->getHeight() - cheevos_surface_view_.h;

View File

@@ -27,17 +27,17 @@ class Title {
};
// --- Constantes de tiempo (en segundos) ---
static constexpr float SHOW_LOADING_DURATION = 5.0f; // Tiempo mostrando loading screen (antes 500 frames)
static constexpr float FADE_STEP_INTERVAL = 0.033f; // Intervalo entre pasos de fade (antes cada 4 frames)
static constexpr float AUTO_CREDITS_TIMEOUT = 22.0f; // Timeout para ir a créditos (antes 2200 frames)
static constexpr float MARQUEE_SPEED = 100.0f; // Velocidad de marquesina (pixels/segundo)
static constexpr float CHEEVOS_SCROLL_SPEED = 120.0f; // Velocidad de scroll de logros (pixels/segundo)
static constexpr float SHOW_LOADING_DURATION = 5.0F; // Tiempo mostrando loading screen (antes 500 frames)
static constexpr float FADE_STEP_INTERVAL = 0.033F; // Intervalo entre pasos de fade (antes cada 4 frames)
static constexpr float AUTO_CREDITS_TIMEOUT = 22.0F; // Timeout para ir a créditos (antes 2200 frames)
static constexpr float MARQUEE_SPEED = 100.0F; // Velocidad de marquesina (pixels/segundo)
static constexpr float CHEEVOS_SCROLL_SPEED = 120.0F; // Velocidad de scroll de logros (pixels/segundo)
// --- Constantes de marquesina ---
static constexpr float MARQUEE_START_X = 256.0f; // Posición inicial (ancho pantalla)
static constexpr float MARQUEE_EXIT_X = -10.0f; // Cuando desaparece de pantalla
static constexpr float MARQUEE_Y = 184.0f; // Posición Y
static constexpr float MARQUEE_LETTER_SPACING = 1.0f; // Espaciado entre letras
static constexpr float MARQUEE_START_X = 256.0F; // Posición inicial (ancho pantalla)
static constexpr float MARQUEE_EXIT_X = -10.0F; // Cuando desaparece de pantalla
static constexpr float MARQUEE_Y = 184.0F; // Posición Y
static constexpr float MARQUEE_LETTER_SPACING = 1.0F; // Espaciado entre letras
// Objetos y punteros
std::shared_ptr<Surface> title_logo_surface_; // Textura con los graficos

View File

@@ -17,21 +17,21 @@
#include "utils/utils.hpp" // Para PaletteColor
// [SINGLETON]
Notifier* Notifier::notifier_ = nullptr;
Notifier* Notifier::notifier = nullptr;
// [SINGLETON] Crearemos el objeto con esta función estática
void Notifier::init(const std::string& icon_file, const std::string& text) {
Notifier::notifier_ = new Notifier(icon_file, text);
Notifier::notifier = new Notifier(icon_file, text);
}
// [SINGLETON] Destruiremos el objeto con esta función estática
void Notifier::destroy() {
delete Notifier::notifier_;
delete Notifier::notifier;
}
// [SINGLETON] Con este método obtenemos el objeto y podemos trabajar con él
Notifier* Notifier::get() {
return Notifier::notifier_;
return Notifier::notifier;
}
// Constructor
@@ -138,9 +138,9 @@ void Notifier::show(std::vector<std::string> texts, NotificationText text_is, Ui
const int text_size = 6;
const auto PADDING_IN_H = text_size;
const auto PADDING_IN_V = text_size / 2;
const int ICON_SPACE = icon >= 0 ? ICON_SIZE_ + PADDING_IN_H : 0;
const int ICON_SPACE = icon >= 0 ? ICON_SIZE + PADDING_IN_H : 0;
text_is = ICON_SPACE > 0 ? NotificationText::LEFT : text_is;
const float WIDTH = Options::game.width - (PADDING_OUT_ * 2);
const float WIDTH = Options::game.width - (PADDING_OUT * 2);
const float HEIGHT = (text_size * texts.size()) + (PADDING_IN_V * 2);
const auto SHAPE = NotificationShape::SQUARED;
@@ -148,7 +148,7 @@ void Notifier::show(std::vector<std::string> texts, NotificationText text_is, Ui
float desp_h = 0;
switch (Options::notifications.getHorizontalPosition()) {
case Options::NotificationPosition::LEFT:
desp_h = PADDING_OUT_;
desp_h = PADDING_OUT;
break;
case Options::NotificationPosition::CENTER:
@@ -156,7 +156,7 @@ void Notifier::show(std::vector<std::string> texts, NotificationText text_is, Ui
break;
case Options::NotificationPosition::RIGHT:
desp_h = Options::game.width - WIDTH - PADDING_OUT_;
desp_h = Options::game.width - WIDTH - PADDING_OUT;
break;
default:
@@ -165,10 +165,10 @@ void Notifier::show(std::vector<std::string> texts, NotificationText text_is, Ui
}
// Posición vertical
const int DESP_V = (Options::notifications.getVerticalPosition() == Options::NotificationPosition::TOP) ? PADDING_OUT_ : Options::game.height - HEIGHT - PADDING_OUT_;
const int DESP_V = (Options::notifications.getVerticalPosition() == Options::NotificationPosition::TOP) ? PADDING_OUT : Options::game.height - HEIGHT - PADDING_OUT;
// Offset
const auto TRAVEL_DIST = HEIGHT + PADDING_OUT_;
const auto TRAVEL_DIST = HEIGHT + PADDING_OUT;
const int TRAVEL_MOD = (Options::notifications.getVerticalPosition() == Options::NotificationPosition::TOP) ? 1 : -1;
const int OFFSET = !notifications_.empty() ? notifications_.back().y + TRAVEL_MOD * notifications_.back().travel_dist : DESP_V;
@@ -217,9 +217,9 @@ void Notifier::show(std::vector<std::string> texts, NotificationText text_is, Ui
// Dibuja el icono de la notificación
if (has_icons_ && icon >= 0 && texts.size() >= 2) {
auto sp = std::make_unique<SurfaceSprite>(icon_surface_, (SDL_FRect){0, 0, ICON_SIZE_, ICON_SIZE_});
sp->setPosition({PADDING_IN_H, PADDING_IN_V, ICON_SIZE_, ICON_SIZE_});
sp->setClip((SDL_FRect){ICON_SIZE_ * (icon % 10), ICON_SIZE_ * (icon / 10), ICON_SIZE_, ICON_SIZE_});
auto sp = std::make_unique<SurfaceSprite>(icon_surface_, (SDL_FRect){0, 0, ICON_SIZE, ICON_SIZE});
sp->setPosition({PADDING_IN_H, PADDING_IN_V, ICON_SIZE, ICON_SIZE});
sp->setClip((SDL_FRect){ICON_SIZE * (icon % 10), ICON_SIZE * (icon / 10), ICON_SIZE, ICON_SIZE});
sp->render();
}

View File

@@ -22,11 +22,11 @@ enum class NotificationText {
class Notifier {
private:
// Constantes
static constexpr float ICON_SIZE_ = 16.0F;
static constexpr float PADDING_OUT_ = 0.0F;
static constexpr float ICON_SIZE = 16.0F;
static constexpr float PADDING_OUT = 0.0F;
// [SINGLETON] Objeto notifier
static Notifier* notifier_;
static Notifier* notifier;
enum class NotificationStatus {
RISING,
@@ -59,14 +59,12 @@ class Notifier {
// Constructor
explicit Notification()
: surface(nullptr), // Inicializar superficie como nula
sprite(nullptr), // Inicializar sprite como nulo
texts(), // Inicializar lista de textos vacía
sprite(nullptr), // Inicializar lista de textos vacía
state(NotificationStatus::RISING), // Estado inicial como "RISING"
shape(NotificationShape::SQUARED), // Forma inicial como "SQUARED"
rect{0, 0, 0, 0}, // Rectángulo inicial vacío
y(0), // Posición Y inicializada a 0
travel_dist(0), // Distancia inicializada a 0
code(""), // Código identificador vacío
travel_dist(0), // Código identificador vacío
can_be_removed(true), // Inicialmente se puede eliminar
height(0), // Altura inicializada a 0
start_time(0), // Tiempo de creación inicializado a 0