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

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

View File

@@ -13,21 +13,21 @@
#include "game/ui/notifier.hpp" // Para Notifier, NotificationText #include "game/ui/notifier.hpp" // Para Notifier, NotificationText
#include "utils/utils.hpp" // Para stringInVector #include "utils/utils.hpp" // Para stringInVector
namespace globalInputs { namespace GlobalInputs {
void quit() { void quit() {
const std::string code = SceneManager::current == SceneManager::Scene::GAME ? "PRESS AGAIN TO RETURN TO MENU" : "PRESS AGAIN TO EXIT"; const std::string CODE = SceneManager::current == SceneManager::Scene::GAME ? "PRESS AGAIN TO RETURN TO MENU" : "PRESS AGAIN TO EXIT";
auto code_found = stringInVector(Notifier::get()->getCodes(), code); auto code_found = stringInVector(Notifier::get()->getCodes(), CODE);
if (code_found) { if (code_found) {
// Si la notificación de salir está activa, cambia de sección // Si la notificación de salir está activa, cambia de sección
SceneManager::current = SceneManager::current == SceneManager::Scene::GAME ? SceneManager::Scene::TITLE : SceneManager::Scene::QUIT; SceneManager::current = SceneManager::current == SceneManager::Scene::GAME ? SceneManager::Scene::TITLE : SceneManager::Scene::QUIT;
} else { } else {
// Si la notificación de salir no está activa, muestra la notificación // Si la notificación de salir no está activa, muestra la notificación
Notifier::get()->show({code}, NotificationText::CENTER, 2000, -1, true, code); Notifier::get()->show({CODE}, NotificationText::CENTER, 2000, -1, true, CODE);
} }
} }
// Cambia de seccion // Cambia de seccion
void skip_section() { void skipSection() {
switch (SceneManager::current) { switch (SceneManager::current) {
case SceneManager::Scene::LOGO: case SceneManager::Scene::LOGO:
case SceneManager::Scene::LOADING_SCREEN: case SceneManager::Scene::LOADING_SCREEN:
@@ -52,7 +52,7 @@ void check() {
} }
else if (Input::get()->checkInput(InputAction::ACCEPT, INPUT_DO_NOT_ALLOW_REPEAT)) { else if (Input::get()->checkInput(InputAction::ACCEPT, INPUT_DO_NOT_ALLOW_REPEAT)) {
skip_section(); skipSection();
} }
else if (Input::get()->checkInput(InputAction::TOGGLE_BORDER, INPUT_DO_NOT_ALLOW_REPEAT)) { else if (Input::get()->checkInput(InputAction::TOGGLE_BORDER, INPUT_DO_NOT_ALLOW_REPEAT)) {
@@ -62,7 +62,7 @@ void check() {
else if (Input::get()->checkInput(InputAction::TOGGLE_VIDEOMODE, INPUT_DO_NOT_ALLOW_REPEAT)) { else if (Input::get()->checkInput(InputAction::TOGGLE_VIDEOMODE, INPUT_DO_NOT_ALLOW_REPEAT)) {
Screen::get()->toggleVideoMode(); Screen::get()->toggleVideoMode();
Notifier::get()->show({"FULLSCREEN " + std::string(Options::video.fullscreen == 0 ? "DISABLED" : "ENABLED")}, NotificationText::CENTER); Notifier::get()->show({"FULLSCREEN " + std::string(static_cast<int>(Options::video.fullscreen) == 0 ? "DISABLED" : "ENABLED")}, NotificationText::CENTER);
} }
else if (Input::get()->checkInput(InputAction::WINDOW_DEC_ZOOM, INPUT_DO_NOT_ALLOW_REPEAT)) { else if (Input::get()->checkInput(InputAction::WINDOW_DEC_ZOOM, INPUT_DO_NOT_ALLOW_REPEAT)) {
@@ -102,4 +102,4 @@ void check() {
Screen::get()->toggleDebugInfo(); Screen::get()->toggleDebugInfo();
} }
} }
} // namespace globalInputs } // namespace GlobalInputs

View File

@@ -1,6 +1,6 @@
#pragma once #pragma once
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
void check(); void check();
} // namespace globalInputs } // namespace GlobalInputs

View File

@@ -9,21 +9,21 @@
#include <utility> // Para pair #include <utility> // Para pair
// [SINGLETON] // [SINGLETON]
Input* Input::input_ = nullptr; Input* Input::input = nullptr;
// [SINGLETON] Crearemos el objeto con esta función estática // [SINGLETON] Crearemos el objeto con esta función estática
void Input::init(const std::string& game_controller_db_path) { void Input::init(const std::string& game_controller_db_path) {
Input::input_ = new Input(game_controller_db_path); Input::input = new Input(game_controller_db_path);
} }
// [SINGLETON] Destruiremos el objeto con esta función estática // [SINGLETON] Destruiremos el objeto con esta función estática
void Input::destroy() { void Input::destroy() {
delete Input::input_; delete Input::input;
} }
// [SINGLETON] Con este método obtenemos el objeto y podemos trabajar con él // [SINGLETON] Con este método obtenemos el objeto y podemos trabajar con él
Input* Input::get() { Input* Input::get() {
return Input::input_; return Input::input;
} }
// Constructor // Constructor
@@ -63,24 +63,24 @@ void Input::bindGameControllerButton(int controller_index, InputAction input_tar
bool Input::checkInput(InputAction input, bool repeat, InputDeviceToUse device, int controller_index) { bool Input::checkInput(InputAction input, bool repeat, InputDeviceToUse device, int controller_index) {
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);
if (device == InputDeviceToUse::KEYBOARD || device == InputDeviceToUse::ANY) { if (device == InputDeviceToUse::KEYBOARD || device == InputDeviceToUse::ANY) {
auto key_states = SDL_GetKeyboardState(nullptr); const auto* key_states = SDL_GetKeyboardState(nullptr);
if (repeat) { if (repeat) {
success_keyboard = key_states[key_bindings_[input_index].scancode] != 0; success_keyboard = static_cast<int>(key_states[key_bindings_[INPUT_INDEX].scancode]) != 0;
} else { } else {
if (!key_bindings_[input_index].active) { if (!key_bindings_[INPUT_INDEX].active) {
if (key_states[key_bindings_[input_index].scancode] != 0) { if (static_cast<int>(key_states[key_bindings_[INPUT_INDEX].scancode]) != 0) {
key_bindings_[input_index].active = true; key_bindings_[INPUT_INDEX].active = true;
success_keyboard = true; success_keyboard = true;
} else { } else {
success_keyboard = false; success_keyboard = false;
} }
} else { } else {
if (key_states[key_bindings_[input_index].scancode] == 0) { if (static_cast<int>(key_states[key_bindings_[INPUT_INDEX].scancode]) == 0) {
key_bindings_[input_index].active = false; key_bindings_[INPUT_INDEX].active = false;
} }
success_keyboard = false; success_keyboard = false;
} }
@@ -93,18 +93,18 @@ bool Input::checkInput(InputAction input, bool repeat, InputDeviceToUse device,
if (!success_controller) { if (!success_controller) {
if (repeat) { if (repeat) {
success_controller = SDL_GetGamepadButton(connected_controllers_.at(controller_index), controller_bindings_.at(controller_index).at(input_index).button) != 0; success_controller = static_cast<int>(SDL_GetGamepadButton(connected_controllers_.at(controller_index), controller_bindings_.at(controller_index).at(INPUT_INDEX).button)) != 0;
} else { } else {
if (!controller_bindings_.at(controller_index).at(input_index).active) { if (!controller_bindings_.at(controller_index).at(INPUT_INDEX).active) {
if (SDL_GetGamepadButton(connected_controllers_.at(controller_index), controller_bindings_.at(controller_index).at(input_index).button) != 0) { if (static_cast<int>(SDL_GetGamepadButton(connected_controllers_.at(controller_index), controller_bindings_.at(controller_index).at(INPUT_INDEX).button)) != 0) {
controller_bindings_.at(controller_index).at(input_index).active = true; controller_bindings_.at(controller_index).at(INPUT_INDEX).active = true;
success_controller = true; success_controller = true;
} else { } else {
success_controller = false; success_controller = false;
} }
} else { } else {
if (SDL_GetGamepadButton(connected_controllers_.at(controller_index), controller_bindings_.at(controller_index).at(input_index).button) == 0) { if (static_cast<int>(SDL_GetGamepadButton(connected_controllers_.at(controller_index), controller_bindings_.at(controller_index).at(INPUT_INDEX).button)) == 0) {
controller_bindings_.at(controller_index).at(input_index).active = false; controller_bindings_.at(controller_index).at(INPUT_INDEX).active = false;
} }
success_controller = false; success_controller = false;
} }
@@ -122,7 +122,7 @@ bool Input::checkAnyInput(InputDeviceToUse device, int controller_index) {
const bool* key_states = SDL_GetKeyboardState(nullptr); const bool* key_states = SDL_GetKeyboardState(nullptr);
for (int i = 0; i < (int)key_bindings_.size(); ++i) { for (int i = 0; i < (int)key_bindings_.size(); ++i) {
if (key_states[key_bindings_[i].scancode] != 0 && !key_bindings_[i].active) { if (static_cast<int>(key_states[key_bindings_[i].scancode]) != 0 && !key_bindings_[i].active) {
key_bindings_[i].active = true; key_bindings_[i].active = true;
return true; return true;
} }
@@ -132,7 +132,7 @@ bool Input::checkAnyInput(InputDeviceToUse device, int controller_index) {
if (gameControllerFound()) { if (gameControllerFound()) {
if (device == InputDeviceToUse::CONTROLLER || device == InputDeviceToUse::ANY) { if (device == InputDeviceToUse::CONTROLLER || device == InputDeviceToUse::ANY) {
for (int i = 0; i < (int)controller_bindings_.size(); ++i) { for (int i = 0; i < (int)controller_bindings_.size(); ++i) {
if (SDL_GetGamepadButton(connected_controllers_[controller_index], controller_bindings_[controller_index][i].button) != 0 && !controller_bindings_[controller_index][i].active) { if (static_cast<int>(SDL_GetGamepadButton(connected_controllers_[controller_index], controller_bindings_[controller_index][i].button)) != 0 && !controller_bindings_[controller_index][i].active) {
controller_bindings_[controller_index][i].active = true; controller_bindings_[controller_index][i].active = true;
return true; return true;
} }
@@ -191,12 +191,12 @@ bool Input::discoverGameControllers() {
for (int i = 0; i < num_joysticks_; i++) { for (int i = 0; i < num_joysticks_; i++) {
if (SDL_IsGamepad(joystick_ids[i])) { if (SDL_IsGamepad(joystick_ids[i])) {
SDL_Gamepad* pad = SDL_OpenGamepad(joystick_ids[i]); SDL_Gamepad* pad = SDL_OpenGamepad(joystick_ids[i]);
if (pad && SDL_GamepadConnected(pad)) { if ((pad != nullptr) && SDL_GamepadConnected(pad)) {
connected_controllers_.push_back(pad); connected_controllers_.push_back(pad);
const char* name = SDL_GetGamepadName(pad); const char* name = SDL_GetGamepadName(pad);
std::cout << "#" << i << ": " << (name ? name : "Unknown") << std::endl; std::cout << "#" << i << ": " << ((name != nullptr) ? name : "Unknown") << std::endl;
controller_names_.push_back(name ? name : "Unknown"); controller_names_.push_back((name != nullptr) ? name : "Unknown");
} else { } else {
std::cout << "SDL_GetError() = " << SDL_GetError() << std::endl; std::cout << "SDL_GetError() = " << SDL_GetError() << std::endl;
} }
@@ -214,7 +214,7 @@ bool Input::discoverGameControllers() {
} }
// Comprueba si hay algun mando conectado // Comprueba si hay algun mando conectado
bool Input::gameControllerFound() { return num_gamepads_ > 0 ? true : false; } bool Input::gameControllerFound() const { return num_gamepads_ > 0; }
// 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(); } std::string Input::getControllerName(int controller_index) const { return num_gamepads_ > 0 ? controller_names_.at(controller_index) : std::string(); }
@@ -246,21 +246,21 @@ int Input::getIndexByName(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) { bool Input::checkAxisInput(InputAction input, int controller_index, bool repeat) {
// Umbral para considerar el eje como activo // Umbral para considerar el eje como activo
const Sint16 threshold = 30000; const Sint16 THRESHOLD = 30000;
bool axis_active_now = false; bool axis_active_now = false;
switch (input) { switch (input) {
case InputAction::LEFT: case InputAction::LEFT:
axis_active_now = SDL_GetGamepadAxis(connected_controllers_[controller_index], SDL_GAMEPAD_AXIS_LEFTX) < -threshold; axis_active_now = SDL_GetGamepadAxis(connected_controllers_[controller_index], SDL_GAMEPAD_AXIS_LEFTX) < -THRESHOLD;
break; break;
case InputAction::RIGHT: case InputAction::RIGHT:
axis_active_now = SDL_GetGamepadAxis(connected_controllers_[controller_index], SDL_GAMEPAD_AXIS_LEFTX) > threshold; axis_active_now = SDL_GetGamepadAxis(connected_controllers_[controller_index], SDL_GAMEPAD_AXIS_LEFTX) > THRESHOLD;
break; break;
case InputAction::UP: case InputAction::UP:
axis_active_now = SDL_GetGamepadAxis(connected_controllers_[controller_index], SDL_GAMEPAD_AXIS_LEFTY) < -threshold; axis_active_now = SDL_GetGamepadAxis(connected_controllers_[controller_index], SDL_GAMEPAD_AXIS_LEFTY) < -THRESHOLD;
break; break;
case InputAction::DOWN: case InputAction::DOWN:
axis_active_now = SDL_GetGamepadAxis(connected_controllers_[controller_index], SDL_GAMEPAD_AXIS_LEFTY) > threshold; axis_active_now = SDL_GetGamepadAxis(connected_controllers_[controller_index], SDL_GAMEPAD_AXIS_LEFTY) > THRESHOLD;
break; break;
default: default:
return false; return false;
@@ -272,17 +272,15 @@ bool Input::checkAxisInput(InputAction input, int controller_index, bool repeat)
if (repeat) { if (repeat) {
// Si se permite repetir, simplemente devolvemos el estado actual // Si se permite repetir, simplemente devolvemos el estado actual
return axis_active_now; return axis_active_now;
} else { } // Si no se permite repetir, aplicamos la lógica de transición
// Si no se permite repetir, aplicamos la lógica de transición if (axis_active_now && !binding.axis_active) {
if (axis_active_now && !binding.axis_active) { // Transición de inactivo a activo
// Transición de inactivo a activo binding.axis_active = true;
binding.axis_active = true; return true;
return true; } else if (!axis_active_now && binding.axis_active) {
} else if (!axis_active_now && binding.axis_active) { // Transición de activo a inactivo
// Transición de activo a inactivo binding.axis_active = false;
binding.axis_active = false;
}
// Mantener el estado actual
return false;
} }
// Mantener el estado actual
return false;
} }

View File

@@ -48,7 +48,7 @@ enum class InputAction {
class Input { class Input {
private: private:
// [SINGLETON] Objeto privado // [SINGLETON] Objeto privado
static Input* input_; static Input* input;
struct KeyBindings { struct KeyBindings {
Uint8 scancode; // Scancode asociado Uint8 scancode; // Scancode asociado
@@ -107,7 +107,7 @@ class Input {
// Asigna inputs a botones del mando // Asigna inputs a botones del mando
void bindGameControllerButton(int controller_index, InputAction input, SDL_GamepadButton button); void bindGameControllerButton(int controller_index, InputAction input, SDL_GamepadButton button);
void bindGameControllerButton(int controller_index, InputAction inputTarget, InputAction inputSource); void bindGameControllerButton(int controller_index, InputAction input_target, InputAction input_source);
// Comprueba si un input esta activo // Comprueba si un input esta activo
bool checkInput(InputAction input, bool repeat = true, InputDeviceToUse device = InputDeviceToUse::ANY, int controller_index = 0); bool checkInput(InputAction input, bool repeat = true, InputDeviceToUse device = InputDeviceToUse::ANY, int controller_index = 0);
@@ -119,7 +119,7 @@ class Input {
bool discoverGameControllers(); bool discoverGameControllers();
// Comprueba si hay algun mando conectado // Comprueba si hay algun mando conectado
bool gameControllerFound(); bool gameControllerFound() const;
// Obten el número de mandos conectados // Obten el número de mandos conectados
int getNumControllers() const; int getNumControllers() const;

View File

@@ -20,7 +20,8 @@ void Gif::decompress(int code_length, const uint8_t* input, int input_length, ui
throw std::runtime_error("Invalid LZW code length"); throw std::runtime_error("Invalid LZW code length");
} }
int i, bit; int i;
int bit;
int prev = -1; int prev = -1;
std::vector<DictionaryEntry> dictionary; std::vector<DictionaryEntry> dictionary;
int dictionary_ind; int dictionary_ind;
@@ -69,7 +70,8 @@ void Gif::decompress(int code_length, const uint8_t* input, int input_length, ui
dictionary_ind += 2; dictionary_ind += 2;
prev = -1; prev = -1;
continue; continue;
} else if (code == stop_code) { }
if (code == stop_code) {
break; break;
} }
@@ -83,13 +85,15 @@ void Gif::decompress(int code_length, const uint8_t* input, int input_length, ui
int ptr; int ptr;
if (code == dictionary_ind) { if (code == dictionary_ind) {
ptr = prev; ptr = prev;
while (dictionary[ptr].prev != -1) while (dictionary[ptr].prev != -1) {
ptr = dictionary[ptr].prev; ptr = dictionary[ptr].prev;
}
dictionary[dictionary_ind].byte = dictionary[ptr].byte; dictionary[dictionary_ind].byte = dictionary[ptr].byte;
} else { } else {
ptr = code; ptr = code;
while (dictionary[ptr].prev != -1) while (dictionary[ptr].prev != -1) {
ptr = dictionary[ptr].prev; ptr = dictionary[ptr].prev;
}
dictionary[dictionary_ind].byte = dictionary[ptr].byte; dictionary[dictionary_ind].byte = dictionary[ptr].byte;
} }
dictionary[dictionary_ind].prev = prev; dictionary[dictionary_ind].prev = prev;
@@ -111,16 +115,16 @@ void Gif::decompress(int code_length, const uint8_t* input, int input_length, ui
throw std::runtime_error("LZW error: invalid code encountered"); throw std::runtime_error("LZW error: invalid code encountered");
} }
int curCode = code; // Variable temporal para recorrer la cadena. int cur_code = code; // Variable temporal para recorrer la cadena.
match_len = dictionary[curCode].len; match_len = dictionary[cur_code].len;
while (curCode != -1) { while (cur_code != -1) {
// Se asume que dictionary[curCode].len > 0. // Se asume que dictionary[curCode].len > 0.
out[dictionary[curCode].len - 1] = dictionary[curCode].byte; out[dictionary[cur_code].len - 1] = dictionary[cur_code].byte;
if (dictionary[curCode].prev == curCode) { if (dictionary[cur_code].prev == cur_code) {
std::cerr << "Internal error; self-reference detected." << std::endl; std::cerr << "Internal error; self-reference detected." << std::endl;
throw std::runtime_error("Internal error in decompress: self-reference"); throw std::runtime_error("Internal error in decompress: self-reference");
} }
curCode = dictionary[curCode].prev; cur_code = dictionary[cur_code].prev;
} }
out += match_len; out += match_len;
} }
@@ -165,7 +169,7 @@ std::vector<uint32_t> Gif::loadPalette(const uint8_t* buffer) {
buffer += sizeof(ScreenDescriptor); buffer += sizeof(ScreenDescriptor);
std::vector<uint32_t> global_color_table; std::vector<uint32_t> global_color_table;
if (screen_descriptor.fields & 0x80) { if ((screen_descriptor.fields & 0x80) != 0) {
int global_color_table_size = 1 << (((screen_descriptor.fields & 0x07) + 1)); int global_color_table_size = 1 << (((screen_descriptor.fields & 0x07) + 1));
global_color_table.resize(global_color_table_size); global_color_table.resize(global_color_table_size);
for (int i = 0; i < global_color_table_size; ++i) { for (int i = 0; i < global_color_table_size; ++i) {
@@ -186,8 +190,8 @@ std::vector<uint8_t> Gif::processGifStream(const uint8_t* buffer, uint16_t& w, u
buffer += 6; buffer += 6;
// Opcional: Validar header // Opcional: Validar header
std::string headerStr(reinterpret_cast<char*>(header), 6); std::string header_str(reinterpret_cast<char*>(header), 6);
if (headerStr != "GIF87a" && headerStr != "GIF89a") { if (header_str != "GIF87a" && header_str != "GIF89a") {
throw std::runtime_error("Formato de archivo GIF inválido."); throw std::runtime_error("Formato de archivo GIF inválido.");
} }
@@ -201,7 +205,7 @@ std::vector<uint8_t> Gif::processGifStream(const uint8_t* buffer, uint16_t& w, u
int color_resolution_bits = ((screen_descriptor.fields & 0x70) >> 4) + 1; int color_resolution_bits = ((screen_descriptor.fields & 0x70) >> 4) + 1;
std::vector<RGB> global_color_table; std::vector<RGB> global_color_table;
if (screen_descriptor.fields & 0x80) { if ((screen_descriptor.fields & 0x80) != 0) {
int global_color_table_size = 1 << (((screen_descriptor.fields & 0x07) + 1)); int global_color_table_size = 1 << (((screen_descriptor.fields & 0x07) + 1));
global_color_table.resize(global_color_table_size); global_color_table.resize(global_color_table_size);
std::memcpy(global_color_table.data(), buffer, 3 * global_color_table_size); std::memcpy(global_color_table.data(), buffer, 3 * global_color_table_size);
@@ -219,13 +223,13 @@ std::vector<uint8_t> Gif::processGifStream(const uint8_t* buffer, uint16_t& w, u
case GRAPHIC_CONTROL: // 0xF9 case GRAPHIC_CONTROL: // 0xF9
{ {
// Procesar Graphic Control Extension: // Procesar Graphic Control Extension:
uint8_t blockSize = *buffer++; // Normalmente, blockSize == 4 uint8_t block_size = *buffer++; // Normalmente, blockSize == 4
buffer += blockSize; // Saltamos los 4 bytes del bloque fijo buffer += block_size; // Saltamos los 4 bytes del bloque fijo
// Saltar los sub-bloques // Saltar los sub-bloques
uint8_t subBlockSize = *buffer++; uint8_t sub_block_size = *buffer++;
while (subBlockSize != 0) { while (sub_block_size != 0) {
buffer += subBlockSize; buffer += sub_block_size;
subBlockSize = *buffer++; sub_block_size = *buffer++;
} }
break; break;
} }
@@ -234,23 +238,23 @@ std::vector<uint8_t> Gif::processGifStream(const uint8_t* buffer, uint16_t& w, u
case PLAINTEXT_EXTENSION: // 0x01 case PLAINTEXT_EXTENSION: // 0x01
{ {
// Para estas extensiones, saltamos el bloque fijo y los sub-bloques. // Para estas extensiones, saltamos el bloque fijo y los sub-bloques.
uint8_t blockSize = *buffer++; uint8_t block_size = *buffer++;
buffer += blockSize; buffer += block_size;
uint8_t subBlockSize = *buffer++; uint8_t sub_block_size = *buffer++;
while (subBlockSize != 0) { while (sub_block_size != 0) {
buffer += subBlockSize; buffer += sub_block_size;
subBlockSize = *buffer++; sub_block_size = *buffer++;
} }
break; break;
} }
default: { default: {
// Si la etiqueta de extensión es desconocida, saltarla también: // Si la etiqueta de extensión es desconocida, saltarla también:
uint8_t blockSize = *buffer++; uint8_t block_size = *buffer++;
buffer += blockSize; buffer += block_size;
uint8_t subBlockSize = *buffer++; uint8_t sub_block_size = *buffer++;
while (subBlockSize != 0) { while (sub_block_size != 0) {
buffer += subBlockSize; buffer += sub_block_size;
subBlockSize = *buffer++; sub_block_size = *buffer++;
} }
break; break;
} }

View File

@@ -68,11 +68,11 @@ class Gif {
public: public:
// Descompone (uncompress) el bloque comprimido usando LZW. // Descompone (uncompress) el bloque comprimido usando LZW.
// Este método puede lanzar std::runtime_error en caso de error. // Este método puede lanzar std::runtime_error en caso de error.
void decompress(int code_length, const uint8_t* input, int input_length, uint8_t* out); static void decompress(int code_length, const uint8_t* input, int input_length, uint8_t* out);
// Carga la paleta (global color table) a partir de un buffer, // Carga la paleta (global color table) a partir de un buffer,
// retornándola en un vector de uint32_t (cada color se compone de R, G, B). // retornándola en un vector de uint32_t (cada color se compone de R, G, B).
std::vector<uint32_t> loadPalette(const uint8_t* buffer); static std::vector<uint32_t> loadPalette(const uint8_t* buffer);
// Carga el stream GIF; devuelve un vector con los datos de imagen sin comprimir y // Carga el stream GIF; devuelve un vector con los datos de imagen sin comprimir y
// asigna el ancho y alto mediante referencias. // asigna el ancho y alto mediante referencias.
@@ -80,7 +80,7 @@ class Gif {
private: private:
// Lee los sub-bloques de datos y los acumula en un std::vector<uint8_t>. // Lee los sub-bloques de datos y los acumula en un std::vector<uint8_t>.
std::vector<uint8_t> readSubBlocks(const uint8_t*& buffer); static std::vector<uint8_t> readSubBlocks(const uint8_t*& buffer);
// Procesa el Image Descriptor y retorna el vector de datos sin comprimir. // Procesa el Image Descriptor y retorna el vector de datos sin comprimir.
std::vector<uint8_t> processImageDescriptor(const uint8_t*& buffer, const std::vector<RGB>& gct, int resolution_bits); std::vector<uint8_t> processImageDescriptor(const uint8_t*& buffer, const std::vector<RGB>& gct, int resolution_bits);

View File

@@ -2,6 +2,7 @@
#include <SDL3/SDL.h> #include <SDL3/SDL.h>
#include <algorithm>
#include <cstring> #include <cstring>
#include <stdexcept> #include <stdexcept>
#include <vector> #include <vector>
@@ -40,13 +41,13 @@ bool OpenGLShader::initGLExtensions() {
glVertexAttribPointer = (PFNGLVERTEXATTRIBPOINTERPROC)SDL_GL_GetProcAddress("glVertexAttribPointer"); glVertexAttribPointer = (PFNGLVERTEXATTRIBPOINTERPROC)SDL_GL_GetProcAddress("glVertexAttribPointer");
glEnableVertexAttribArray = (PFNGLENABLEVERTEXATTRIBARRAYPROC)SDL_GL_GetProcAddress("glEnableVertexAttribArray"); glEnableVertexAttribArray = (PFNGLENABLEVERTEXATTRIBARRAYPROC)SDL_GL_GetProcAddress("glEnableVertexAttribArray");
return glCreateShader && glShaderSource && glCompileShader && glGetShaderiv && return (glCreateShader != nullptr) && (glShaderSource != nullptr) && (glCompileShader != nullptr) && (glGetShaderiv != nullptr) &&
glGetShaderInfoLog && glDeleteShader && glAttachShader && glCreateProgram && (glGetShaderInfoLog != nullptr) && (glDeleteShader != nullptr) && (glAttachShader != nullptr) && (glCreateProgram != nullptr) &&
glLinkProgram && glValidateProgram && glGetProgramiv && glGetProgramInfoLog && (glLinkProgram != nullptr) && (glValidateProgram != nullptr) && (glGetProgramiv != nullptr) && (glGetProgramInfoLog != nullptr) &&
glUseProgram && glDeleteProgram && glGetUniformLocation && glUniform2f && (glUseProgram != nullptr) && (glDeleteProgram != nullptr) && (glGetUniformLocation != nullptr) && (glUniform2f != nullptr) &&
glGenVertexArrays && glBindVertexArray && glDeleteVertexArrays && (glGenVertexArrays != nullptr) && (glBindVertexArray != nullptr) && (glDeleteVertexArrays != nullptr) &&
glGenBuffers && glBindBuffer && glBufferData && glDeleteBuffers && (glGenBuffers != nullptr) && (glBindBuffer != nullptr) && (glBufferData != nullptr) && (glDeleteBuffers != nullptr) &&
glVertexAttribPointer && glEnableVertexAttribArray; (glVertexAttribPointer != nullptr) && (glEnableVertexAttribArray != nullptr);
} }
#endif #endif
@@ -149,22 +150,22 @@ void OpenGLShader::createQuadGeometry() {
// Formato: x, y, u, v // Formato: x, y, u, v
float vertices[] = { float vertices[] = {
// Posición // TexCoords // Posición // TexCoords
-1.0f, -1.0F,
-1.0f, -1.0F,
0.0f, 0.0F,
0.0f, // Inferior izquierda 0.0F, // Inferior izquierda
1.0f, 1.0F,
-1.0f, -1.0F,
1.0f, 1.0F,
0.0f, // Inferior derecha 0.0F, // Inferior derecha
1.0f, 1.0F,
1.0f, 1.0F,
1.0f, 1.0F,
1.0f, // Superior derecha 1.0F, // Superior derecha
-1.0f, -1.0F,
1.0f, 1.0F,
0.0f, 0.0F,
1.0f // Superior izquierda 1.0F // Superior izquierda
}; };
// Índices para dibujar el quad con dos triángulos // Índices para dibujar el quad con dos triángulos
@@ -210,7 +211,9 @@ void OpenGLShader::createQuadGeometry() {
} }
GLuint OpenGLShader::getTextureID(SDL_Texture* texture) { GLuint OpenGLShader::getTextureID(SDL_Texture* texture) {
if (!texture) return 1; if (texture == nullptr) {
return 1;
}
SDL_PropertiesID props = SDL_GetTextureProperties(texture); SDL_PropertiesID props = SDL_GetTextureProperties(texture);
GLuint texture_id = 0; GLuint texture_id = 0;
@@ -243,7 +246,7 @@ bool OpenGLShader::init(SDL_Window* window,
back_buffer_ = texture; back_buffer_ = texture;
renderer_ = SDL_GetRenderer(window); renderer_ = SDL_GetRenderer(window);
if (!renderer_) { if (renderer_ == nullptr) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
"Error: No se pudo obtener el renderer"); "Error: No se pudo obtener el renderer");
return false; return false;
@@ -262,10 +265,10 @@ bool OpenGLShader::init(SDL_Window* window,
// Verificar que es OpenGL // Verificar que es OpenGL
const char* renderer_name = SDL_GetRendererName(renderer_); const char* renderer_name = SDL_GetRendererName(renderer_);
if (!renderer_name || strncmp(renderer_name, "opengl", 6) != 0) { if ((renderer_name == nullptr) || strncmp(renderer_name, "opengl", 6) != 0) {
SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION, SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION,
"Renderer no es OpenGL: %s", "Renderer no es OpenGL: %s",
renderer_name ? renderer_name : "unknown"); (renderer_name != nullptr) ? renderer_name : "unknown");
return false; return false;
} }
@@ -291,8 +294,12 @@ bool OpenGLShader::init(SDL_Window* window,
if (vertex_shader == 0 || fragment_shader == 0) { if (vertex_shader == 0 || fragment_shader == 0) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
"Error al compilar shaders"); "Error al compilar shaders");
if (vertex_shader != 0) glDeleteShader(vertex_shader); if (vertex_shader != 0) {
if (fragment_shader != 0) glDeleteShader(fragment_shader); glDeleteShader(vertex_shader);
}
if (fragment_shader != 0) {
glDeleteShader(fragment_shader);
}
return false; return false;
} }
@@ -347,7 +354,8 @@ void OpenGLShader::render() {
} }
// Obtener tamaño actual de ventana (puede haber cambiado) // Obtener tamaño actual de ventana (puede haber cambiado)
int current_width, current_height; int current_width;
int current_height;
SDL_GetWindowSize(window_, &current_width, &current_height); SDL_GetWindowSize(window_, &current_width, &current_height);
// Guardar estados OpenGL // Guardar estados OpenGL
@@ -380,7 +388,8 @@ void OpenGLShader::render() {
checkGLError("glUseProgram"); checkGLError("glUseProgram");
// Configurar viewport (obtener tamaño lógico de SDL) // Configurar viewport (obtener tamaño lógico de SDL)
int logical_w, logical_h; int logical_w;
int logical_h;
SDL_RendererLogicalPresentation mode; SDL_RendererLogicalPresentation mode;
SDL_GetRenderLogicalPresentation(renderer_, &logical_w, &logical_h, &mode); SDL_GetRenderLogicalPresentation(renderer_, &logical_w, &logical_h, &mode);
@@ -390,14 +399,16 @@ void OpenGLShader::render() {
} }
// Calcular viewport considerando aspect ratio // Calcular viewport considerando aspect ratio
int viewport_x = 0, viewport_y = 0; int viewport_x = 0;
int viewport_w = current_width, viewport_h = current_height; int viewport_y = 0;
int viewport_w = current_width;
int viewport_h = current_height;
if (mode == SDL_LOGICAL_PRESENTATION_INTEGER_SCALE) { if (mode == SDL_LOGICAL_PRESENTATION_INTEGER_SCALE) {
int scale_x = current_width / logical_w; int scale_x = current_width / logical_w;
int scale_y = current_height / logical_h; int scale_y = current_height / logical_h;
int scale = (scale_x < scale_y) ? scale_x : scale_y; int scale = (scale_x < scale_y) ? scale_x : scale_y;
if (scale < 1) scale = 1; scale = std::max(scale, 1);
viewport_w = logical_w * scale; viewport_w = logical_w * scale;
viewport_h = logical_h * scale; viewport_h = logical_h * scale;
@@ -430,7 +441,7 @@ void OpenGLShader::render() {
// Restaurar estados OpenGL // Restaurar estados OpenGL
glUseProgram(old_program); glUseProgram(old_program);
glBindTexture(GL_TEXTURE_2D, old_texture); glBindTexture(GL_TEXTURE_2D, old_texture);
if (!was_texture_enabled) { if (was_texture_enabled == 0u) {
glDisable(GL_TEXTURE_2D); glDisable(GL_TEXTURE_2D);
} }
glBindVertexArray(old_vao); glBindVertexArray(old_vao);

View File

@@ -39,8 +39,8 @@ class OpenGLShader : public ShaderBackend {
GLuint compileShader(const std::string& source, GLenum shader_type); GLuint compileShader(const std::string& source, GLenum shader_type);
GLuint linkProgram(GLuint vertex_shader, GLuint fragment_shader); GLuint linkProgram(GLuint vertex_shader, GLuint fragment_shader);
void createQuadGeometry(); void createQuadGeometry();
GLuint getTextureID(SDL_Texture* texture); static GLuint getTextureID(SDL_Texture* texture);
void checkGLError(const char* operation); static void checkGLError(const char* operation);
// Estado SDL // Estado SDL
SDL_Window* window_ = nullptr; SDL_Window* window_ = nullptr;
@@ -59,13 +59,14 @@ class OpenGLShader : public ShaderBackend {
// Tamaños // Tamaños
int window_width_ = 0; int window_width_ = 0;
int window_height_ = 0; int window_height_ = 0;
float texture_width_ = 0.0f; float texture_width_ = 0.0F;
float texture_height_ = 0.0f; float texture_height_ = 0.0F;
// Estado // Estado
bool is_initialized_ = false; bool is_initialized_ = false;
#ifndef __APPLE__ #ifndef __APPLE__
// NOLINTBEGIN
// Punteros a funciones OpenGL en Windows/Linux // Punteros a funciones OpenGL en Windows/Linux
PFNGLCREATESHADERPROC glCreateShader = nullptr; PFNGLCREATESHADERPROC glCreateShader = nullptr;
PFNGLSHADERSOURCEPROC glShaderSource = nullptr; PFNGLSHADERSOURCEPROC glShaderSource = nullptr;
@@ -92,6 +93,7 @@ class OpenGLShader : public ShaderBackend {
PFNGLDELETEBUFFERSPROC glDeleteBuffers = nullptr; PFNGLDELETEBUFFERSPROC glDeleteBuffers = nullptr;
PFNGLVERTEXATTRIBPOINTERPROC glVertexAttribPointer = nullptr; PFNGLVERTEXATTRIBPOINTERPROC glVertexAttribPointer = nullptr;
PFNGLENABLEVERTEXATTRIBARRAYPROC glEnableVertexAttribArray = nullptr; PFNGLENABLEVERTEXATTRIBARRAYPROC glEnableVertexAttribArray = nullptr;
// NOLINTEND
#endif #endif
}; };

View File

@@ -19,21 +19,21 @@
#include "game/ui/notifier.hpp" // Para Notifier #include "game/ui/notifier.hpp" // Para Notifier
// [SINGLETON] // [SINGLETON]
Screen* Screen::screen_ = nullptr; Screen* Screen::screen = nullptr;
// [SINGLETON] Crearemos el objeto con esta función estática // [SINGLETON] Crearemos el objeto con esta función estática
void Screen::init() { void Screen::init() {
Screen::screen_ = new Screen(); Screen::screen = new Screen();
} }
// [SINGLETON] Destruiremos el objeto con esta función estática // [SINGLETON] Destruiremos el objeto con esta función estática
void Screen::destroy() { void Screen::destroy() {
delete Screen::screen_; delete Screen::screen;
} }
// [SINGLETON] Con este método obtenemos el objeto y podemos trabajar con él // [SINGLETON] Con este método obtenemos el objeto y podemos trabajar con él
Screen* Screen::get() { Screen* Screen::get() {
return Screen::screen_; return Screen::screen;
} }
// Constructor // Constructor
@@ -332,7 +332,7 @@ void Screen::renderInfo() {
auto color = static_cast<Uint8>(PaletteColor::YELLOW); auto color = static_cast<Uint8>(PaletteColor::YELLOW);
// FPS // FPS
const std::string FPS_TEXT = std::to_string(fps_.lastValue) + " FPS"; const std::string FPS_TEXT = std::to_string(fps_.last_value) + " FPS";
text->writeColored(Options::game.width - text->lenght(FPS_TEXT), 0, FPS_TEXT, color); text->writeColored(Options::game.width - text->lenght(FPS_TEXT), 0, FPS_TEXT, color);
// Resolution // Resolution

View File

@@ -33,34 +33,34 @@ class Screen {
struct FPS { struct FPS {
Uint32 ticks; // Tiempo en milisegundos desde que se comenzó a contar. Uint32 ticks; // Tiempo en milisegundos desde que se comenzó a contar.
int frameCount; // Número acumulado de frames en el intervalo. int frame_count; // Número acumulado de frames en el intervalo.
int lastValue; // Número de frames calculado en el último segundo. int last_value; // Número de frames calculado en el último segundo.
// Constructor para inicializar la estructura. // Constructor para inicializar la estructura.
FPS() FPS()
: ticks(0), : ticks(0),
frameCount(0), frame_count(0),
lastValue(0) {} last_value(0) {}
// Incrementador que se llama en cada frame. // Incrementador que se llama en cada frame.
void increment() { void increment() {
frameCount++; frame_count++;
} }
// Método para calcular y devolver el valor de FPS. // Método para calcular y devolver el valor de FPS.
int calculate(Uint32 currentTicks) { int calculate(Uint32 current_ticks) {
if (currentTicks - ticks >= 1000) // Si ha pasado un segundo o más. if (current_ticks - ticks >= 1000) // Si ha pasado un segundo o más.
{ {
lastValue = frameCount; // Actualizamos el valor del último FPS. last_value = frame_count; // Actualizamos el valor del último FPS.
frameCount = 0; // Reiniciamos el contador de frames. frame_count = 0; // Reiniciamos el contador de frames.
ticks = currentTicks; // Actualizamos el tiempo base. ticks = current_ticks; // Actualizamos el tiempo base.
} }
return lastValue; return last_value;
} }
}; };
// [SINGLETON] Objeto privado // [SINGLETON] Objeto privado
static Screen* screen_; static Screen* screen;
// Objetos y punteros // Objetos y punteros
SDL_Window* window_; // Ventana de la aplicación SDL_Window* window_; // Ventana de la aplicación

View File

@@ -75,7 +75,9 @@ Palette readPalFile(const std::string& file_path) {
// Procesar las líneas restantes con valores RGB // Procesar las líneas restantes con valores RGB
std::istringstream ss(line); std::istringstream ss(line);
int r, g, b; int r;
int g;
int b;
if (ss >> r >> g >> b) { if (ss >> r >> g >> b) {
// Construir el color ARGB (A = 255 por defecto) // Construir el color ARGB (A = 255 por defecto)
Uint32 color = (255 << 24) | (r << 16) | (g << 8) | b; Uint32 color = (255 << 24) | (r << 16) | (g << 8) | b;
@@ -99,8 +101,8 @@ Surface::Surface(int w, int h)
Surface::Surface(const std::string& file_path) Surface::Surface(const std::string& file_path)
: transparent_color_(static_cast<Uint8>(PaletteColor::TRANSPARENT)) { : transparent_color_(static_cast<Uint8>(PaletteColor::TRANSPARENT)) {
SurfaceData loadedData = loadSurface(file_path); SurfaceData loaded_data = loadSurface(file_path);
surface_data_ = std::make_shared<SurfaceData>(std::move(loadedData)); surface_data_ = std::make_shared<SurfaceData>(std::move(loaded_data));
initializeSubPalette(sub_palette_); initializeSubPalette(sub_palette_);
} }
@@ -127,18 +129,19 @@ SurfaceData Surface::loadSurface(const std::string& file_path) {
// Crear un objeto Gif y llamar a la función loadGif // Crear un objeto Gif y llamar a la función loadGif
GIF::Gif gif; GIF::Gif gif;
Uint16 w = 0, h = 0; Uint16 w = 0;
std::vector<Uint8> rawPixels = gif.loadGif(buffer.data(), w, h); Uint16 h = 0;
if (rawPixels.empty()) { std::vector<Uint8> raw_pixels = gif.loadGif(buffer.data(), w, h);
if (raw_pixels.empty()) {
std::cerr << "Error loading GIF from file: " << file_path << std::endl; std::cerr << "Error loading GIF from file: " << file_path << std::endl;
throw std::runtime_error("Error loading GIF"); throw std::runtime_error("Error loading GIF");
} }
// Si el constructor de Surface espera un std::shared_ptr<Uint8[]>, // Si el constructor de Surface espera un std::shared_ptr<Uint8[]>,
// reservamos un bloque dinámico y copiamos los datos del vector. // reservamos un bloque dinámico y copiamos los datos del vector.
size_t pixelCount = rawPixels.size(); size_t pixel_count = raw_pixels.size();
auto pixels = std::shared_ptr<Uint8[]>(new Uint8[pixelCount], std::default_delete<Uint8[]>()); auto pixels = std::shared_ptr<Uint8[]>(new Uint8[pixel_count], std::default_delete<Uint8[]>());
std::memcpy(pixels.get(), rawPixels.data(), pixelCount); std::memcpy(pixels.get(), raw_pixels.data(), pixel_count);
// Crear y devolver directamente el objeto SurfaceData // Crear y devolver directamente el objeto SurfaceData
printWithDots("Surface : ", file_path.substr(file_path.find_last_of("\\/") + 1), "[ LOADED ]"); printWithDots("Surface : ", file_path.substr(file_path.find_last_of("\\/") + 1), "[ LOADED ]");
@@ -162,9 +165,9 @@ void Surface::setColor(int index, Uint32 color) {
// Rellena la superficie con un color // Rellena la superficie con un color
void Surface::clear(Uint8 color) { void Surface::clear(Uint8 color) {
const size_t total_pixels = surface_data_->width * surface_data_->height; const size_t TOTAL_PIXELS = surface_data_->width * surface_data_->height;
Uint8* data_ptr = surface_data_->data.get(); Uint8* data_ptr = surface_data_->data.get();
std::fill(data_ptr, data_ptr + total_pixels, color); std::fill(data_ptr, data_ptr + TOTAL_PIXELS, color);
} }
// Pone un pixel en la SurfaceData // Pone un pixel en la SurfaceData
@@ -173,12 +176,12 @@ void Surface::putPixel(int x, int y, Uint8 color) {
return; // Coordenadas fuera de rango return; // Coordenadas fuera de rango
} }
const int index = x + y * surface_data_->width; const int INDEX = x + (y * surface_data_->width);
surface_data_->data.get()[index] = color; surface_data_->data.get()[INDEX] = color;
} }
// Obtiene el color de un pixel de la surface_data // Obtiene el color de un pixel de la surface_data
Uint8 Surface::getPixel(int x, int y) { return surface_data_->data.get()[x + y * static_cast<int>(surface_data_->width)]; } Uint8 Surface::getPixel(int x, int y) { return surface_data_->data.get()[x + (y * static_cast<int>(surface_data_->width))]; }
// Dibuja un rectangulo relleno // Dibuja un rectangulo relleno
void Surface::fillRect(const SDL_FRect* rect, Uint8 color) { void Surface::fillRect(const SDL_FRect* rect, Uint8 color) {
@@ -191,7 +194,7 @@ void Surface::fillRect(const SDL_FRect* rect, Uint8 color) {
// Recorrer cada píxel dentro del rectángulo directamente // Recorrer cada píxel dentro del rectángulo directamente
for (int y = y_start; y < y_end; ++y) { for (int y = y_start; y < y_end; ++y) {
for (int x = x_start; x < x_end; ++x) { for (int x = x_start; x < x_end; ++x) {
const int INDEX = x + y * surface_data_->width; const int INDEX = x + (y * surface_data_->width);
surface_data_->data.get()[INDEX] = color; surface_data_->data.get()[INDEX] = color;
} }
} }
@@ -208,22 +211,22 @@ void Surface::drawRectBorder(const SDL_FRect* rect, Uint8 color) {
// Dibujar bordes horizontales // Dibujar bordes horizontales
for (int x = x_start; x < x_end; ++x) { for (int x = x_start; x < x_end; ++x) {
// Borde superior // Borde superior
const int top_index = x + y_start * surface_data_->width; const int TOP_INDEX = x + (y_start * surface_data_->width);
surface_data_->data.get()[top_index] = color; surface_data_->data.get()[TOP_INDEX] = color;
// Borde inferior // Borde inferior
const int bottom_index = x + (y_end - 1) * surface_data_->width; const int BOTTOM_INDEX = x + ((y_end - 1) * surface_data_->width);
surface_data_->data.get()[bottom_index] = color; surface_data_->data.get()[BOTTOM_INDEX] = color;
} }
// Dibujar bordes verticales // Dibujar bordes verticales
for (int y = y_start; y < y_end; ++y) { for (int y = y_start; y < y_end; ++y) {
// Borde izquierdo // Borde izquierdo
const int LEFT_INDEX = x_start + y * surface_data_->width; const int LEFT_INDEX = x_start + (y * surface_data_->width);
surface_data_->data.get()[LEFT_INDEX] = color; surface_data_->data.get()[LEFT_INDEX] = color;
// Borde derecho // Borde derecho
const int RIGHT_INDEX = (x_end - 1) + y * surface_data_->width; const int RIGHT_INDEX = (x_end - 1) + (y * surface_data_->width);
surface_data_->data.get()[RIGHT_INDEX] = color; surface_data_->data.get()[RIGHT_INDEX] = color;
} }
} }
@@ -243,12 +246,13 @@ void Surface::drawLine(float x1, float y1, float x2, float y2, Uint8 color) {
while (true) { while (true) {
// Asegúrate de no dibujar fuera de los límites de la superficie // Asegúrate de no dibujar fuera de los límites de la superficie
if (x1 >= 0 && x1 < surface_data_->width && y1 >= 0 && y1 < surface_data_->height) { if (x1 >= 0 && x1 < surface_data_->width && y1 >= 0 && y1 < surface_data_->height) {
surface_data_->data.get()[static_cast<size_t>(x1 + y1 * surface_data_->width)] = color; surface_data_->data.get()[static_cast<size_t>(x1 + (y1 * surface_data_->width))] = color;
} }
// Si alcanzamos el punto final, salimos // Si alcanzamos el punto final, salimos
if (x1 == x2 && y1 == y2) if (x1 == x2 && y1 == y2) {
break; break;
}
int e2 = 2 * err; int e2 = 2 * err;
if (e2 > -dy) { if (e2 > -dy) {
@@ -281,9 +285,9 @@ void Surface::render(float dx, float dy, float sx, float sy, float w, float h) {
int src_x = sx + ix; int src_x = sx + ix;
int src_y = sy + iy; int src_y = sy + iy;
Uint8 color = surface_data_->data.get()[static_cast<size_t>(src_x + src_y * surface_data_->width)]; Uint8 color = surface_data_->data.get()[static_cast<size_t>(src_x + (src_y * surface_data_->width))];
if (color != transparent_color_) { if (color != transparent_color_) {
surface_data->data.get()[static_cast<size_t>(dest_x + dest_y * surface_data->width)] = sub_palette_[color]; surface_data->data.get()[static_cast<size_t>(dest_x + (dest_y * surface_data->width))] = sub_palette_[color];
} }
} }
} }
@@ -291,14 +295,14 @@ void Surface::render(float dx, float dy, float sx, float sy, float w, float h) {
} }
} }
void Surface::render(int x, int y, SDL_FRect* srcRect, SDL_FlipMode flip) { void Surface::render(int x, int y, SDL_FRect* src_rect, SDL_FlipMode flip) {
auto surface_data_dest = Screen::get()->getRendererSurface()->getSurfaceData(); auto surface_data_dest = Screen::get()->getRendererSurface()->getSurfaceData();
// Determina la región de origen (clip) a renderizar // Determina la región de origen (clip) a renderizar
float sx = (srcRect) ? srcRect->x : 0; float sx = ((src_rect) != nullptr) ? src_rect->x : 0;
float sy = (srcRect) ? srcRect->y : 0; float sy = ((src_rect) != nullptr) ? src_rect->y : 0;
float w = (srcRect) ? srcRect->w : surface_data_->width; float w = ((src_rect) != nullptr) ? src_rect->w : surface_data_->width;
float h = (srcRect) ? srcRect->h : surface_data_->height; float h = ((src_rect) != nullptr) ? src_rect->h : surface_data_->height;
// Limitar la región para evitar accesos fuera de rango en origen // Limitar la región para evitar accesos fuera de rango en origen
w = std::min(w, surface_data_->width - sx); w = std::min(w, surface_data_->width - sx);
@@ -324,9 +328,9 @@ void Surface::render(int x, int y, SDL_FRect* srcRect, SDL_FlipMode flip) {
// Verificar que las coordenadas de destino están dentro de los límites // Verificar que las coordenadas de destino están dentro de los límites
if (dest_x >= 0 && dest_x < surface_data_dest->width && dest_y >= 0 && dest_y < surface_data_dest->height) { if (dest_x >= 0 && dest_x < surface_data_dest->width && dest_y >= 0 && dest_y < surface_data_dest->height) {
// Copia el píxel si no es transparente // Copia el píxel si no es transparente
Uint8 color = surface_data_->data.get()[static_cast<size_t>(src_x + src_y * surface_data_->width)]; Uint8 color = surface_data_->data.get()[static_cast<size_t>(src_x + (src_y * surface_data_->width))];
if (color != transparent_color_) { if (color != transparent_color_) {
surface_data_dest->data[dest_x + dest_y * surface_data_dest->width] = sub_palette_[color]; surface_data_dest->data[dest_x + (dest_y * surface_data_dest->width)] = sub_palette_[color];
} }
} }
} }
@@ -334,20 +338,20 @@ void Surface::render(int x, int y, SDL_FRect* srcRect, SDL_FlipMode flip) {
} }
// Copia una región de la superficie de origen a la de destino // Copia una región de la superficie de origen a la de destino
void Surface::render(SDL_FRect* srcRect, SDL_FRect* dstRect, SDL_FlipMode flip) { void Surface::render(SDL_FRect* src_rect, SDL_FRect* dst_rect, SDL_FlipMode flip) {
auto surface_data = Screen::get()->getRendererSurface()->getSurfaceData(); auto surface_data = Screen::get()->getRendererSurface()->getSurfaceData();
// Si srcRect es nullptr, tomar toda la superficie fuente // Si srcRect es nullptr, tomar toda la superficie fuente
float sx = (srcRect) ? srcRect->x : 0; float sx = ((src_rect) != nullptr) ? src_rect->x : 0;
float sy = (srcRect) ? srcRect->y : 0; float sy = ((src_rect) != nullptr) ? src_rect->y : 0;
float sw = (srcRect) ? srcRect->w : surface_data_->width; float sw = ((src_rect) != nullptr) ? src_rect->w : surface_data_->width;
float sh = (srcRect) ? srcRect->h : surface_data_->height; float sh = ((src_rect) != nullptr) ? src_rect->h : surface_data_->height;
// Si dstRect es nullptr, asignar las mismas dimensiones que srcRect // Si dstRect es nullptr, asignar las mismas dimensiones que srcRect
float dx = (dstRect) ? dstRect->x : 0; float dx = ((dst_rect) != nullptr) ? dst_rect->x : 0;
float dy = (dstRect) ? dstRect->y : 0; float dy = ((dst_rect) != nullptr) ? dst_rect->y : 0;
float dw = (dstRect) ? dstRect->w : sw; float dw = ((dst_rect) != nullptr) ? dst_rect->w : sw;
float dh = (dstRect) ? dstRect->h : sh; float dh = ((dst_rect) != nullptr) ? dst_rect->h : sh;
// Asegurarse de que srcRect y dstRect tienen las mismas dimensiones // Asegurarse de que srcRect y dstRect tienen las mismas dimensiones
if (sw != dw || sh != dh) { if (sw != dw || sh != dh) {
@@ -375,9 +379,9 @@ void Surface::render(SDL_FRect* srcRect, SDL_FRect* dstRect, SDL_FlipMode flip)
if (int dest_x = dx + ix; dest_x >= 0 && dest_x < surface_data->width) { if (int dest_x = dx + ix; dest_x >= 0 && dest_x < surface_data->width) {
if (int dest_y = dy + iy; dest_y >= 0 && dest_y < surface_data->height) { if (int dest_y = dy + iy; dest_y >= 0 && dest_y < surface_data->height) {
// Copiar el píxel si no es transparente // Copiar el píxel si no es transparente
Uint8 color = surface_data_->data.get()[static_cast<size_t>(src_x + src_y * surface_data_->width)]; Uint8 color = surface_data_->data.get()[static_cast<size_t>(src_x + (src_y * surface_data_->width))];
if (color != transparent_color_) { if (color != transparent_color_) {
surface_data->data[dest_x + dest_y * surface_data->width] = sub_palette_[color]; surface_data->data[dest_x + (dest_y * surface_data->width)] = sub_palette_[color];
} }
} }
} }
@@ -386,14 +390,14 @@ void Surface::render(SDL_FRect* srcRect, SDL_FRect* dstRect, SDL_FlipMode flip)
} }
// Copia una región de la SurfaceData de origen a la SurfaceData de destino reemplazando un color por otro // Copia una región de la SurfaceData de origen a la SurfaceData de destino reemplazando un color por otro
void Surface::renderWithColorReplace(int x, int y, Uint8 source_color, Uint8 target_color, SDL_FRect* srcRect, SDL_FlipMode flip) { void Surface::renderWithColorReplace(int x, int y, Uint8 source_color, Uint8 target_color, SDL_FRect* src_rect, SDL_FlipMode flip) {
auto surface_data = Screen::get()->getRendererSurface()->getSurfaceData(); auto surface_data = Screen::get()->getRendererSurface()->getSurfaceData();
// Determina la región de origen (clip) a renderizar // Determina la región de origen (clip) a renderizar
float sx = (srcRect) ? srcRect->x : 0; float sx = ((src_rect) != nullptr) ? src_rect->x : 0;
float sy = (srcRect) ? srcRect->y : 0; float sy = ((src_rect) != nullptr) ? src_rect->y : 0;
float w = (srcRect) ? srcRect->w : surface_data_->width; float w = ((src_rect) != nullptr) ? src_rect->w : surface_data_->width;
float h = (srcRect) ? srcRect->h : surface_data_->height; float h = ((src_rect) != nullptr) ? src_rect->h : surface_data_->height;
// Limitar la región para evitar accesos fuera de rango // Limitar la región para evitar accesos fuera de rango
w = std::min(w, surface_data_->width - sx); w = std::min(w, surface_data_->width - sx);
@@ -416,9 +420,9 @@ void Surface::renderWithColorReplace(int x, int y, Uint8 source_color, Uint8 tar
} }
// Copia el píxel si no es transparente // Copia el píxel si no es transparente
Uint8 color = surface_data_->data.get()[static_cast<size_t>(src_x + src_y * surface_data_->width)]; Uint8 color = surface_data_->data.get()[static_cast<size_t>(src_x + (src_y * surface_data_->width))];
if (color != transparent_color_) { if (color != transparent_color_) {
surface_data->data[dest_x + dest_y * surface_data->width] = surface_data->data[dest_x + (dest_y * surface_data->width)] =
(color == source_color) ? target_color : color; (color == source_color) ? target_color : color;
} }
} }
@@ -427,11 +431,11 @@ void Surface::renderWithColorReplace(int x, int y, Uint8 source_color, Uint8 tar
// Vuelca la superficie a una textura // Vuelca la superficie a una textura
void Surface::copyToTexture(SDL_Renderer* renderer, SDL_Texture* texture) { void Surface::copyToTexture(SDL_Renderer* renderer, SDL_Texture* texture) {
if (!renderer || !texture || !surface_data_) { if ((renderer == nullptr) || (texture == nullptr) || !surface_data_) {
throw std::runtime_error("Renderer or texture is null."); throw std::runtime_error("Renderer or texture is null.");
} }
if (surface_data_->width <= 0 || surface_data_->height <= 0 || !surface_data_->data.get()) { if (surface_data_->width <= 0 || surface_data_->height <= 0 || (surface_data_->data.get() == nullptr)) {
throw std::runtime_error("Invalid surface dimensions or data."); throw std::runtime_error("Invalid surface dimensions or data.");
} }
@@ -449,8 +453,8 @@ void Surface::copyToTexture(SDL_Renderer* renderer, SDL_Texture* texture) {
for (int y = 0; y < surface_data_->height; ++y) { for (int y = 0; y < surface_data_->height; ++y) {
for (int x = 0; x < surface_data_->width; ++x) { for (int x = 0; x < surface_data_->width; ++x) {
// Calcular la posición correcta en la textura teniendo en cuenta el stride // Calcular la posición correcta en la textura teniendo en cuenta el stride
int texture_index = y * row_stride + x; int texture_index = (y * row_stride) + x;
int surface_index = y * surface_data_->width + x; int surface_index = (y * surface_data_->width) + x;
pixels[texture_index] = palette_[surface_data_->data.get()[surface_index]]; pixels[texture_index] = palette_[surface_data_->data.get()[surface_index]];
} }
@@ -465,28 +469,28 @@ void Surface::copyToTexture(SDL_Renderer* renderer, SDL_Texture* texture) {
} }
// Vuelca la superficie a una textura // Vuelca la superficie a una textura
void Surface::copyToTexture(SDL_Renderer* renderer, SDL_Texture* texture, SDL_FRect* srcRect, SDL_FRect* destRect) { void Surface::copyToTexture(SDL_Renderer* renderer, SDL_Texture* texture, SDL_FRect* src_rect, SDL_FRect* dest_rect) {
if (!renderer || !texture || !surface_data_) { if ((renderer == nullptr) || (texture == nullptr) || !surface_data_) {
throw std::runtime_error("Renderer or texture is null."); throw std::runtime_error("Renderer or texture is null.");
} }
if (surface_data_->width <= 0 || surface_data_->height <= 0 || !surface_data_->data.get()) { if (surface_data_->width <= 0 || surface_data_->height <= 0 || (surface_data_->data.get() == nullptr)) {
throw std::runtime_error("Invalid surface dimensions or data."); throw std::runtime_error("Invalid surface dimensions or data.");
} }
Uint32* pixels = nullptr; Uint32* pixels = nullptr;
int pitch = 0; int pitch = 0;
SDL_Rect lockRect; SDL_Rect lock_rect;
if (destRect) { if (dest_rect != nullptr) {
lockRect.x = static_cast<int>(destRect->x); lock_rect.x = static_cast<int>(dest_rect->x);
lockRect.y = static_cast<int>(destRect->y); lock_rect.y = static_cast<int>(dest_rect->y);
lockRect.w = static_cast<int>(destRect->w); lock_rect.w = static_cast<int>(dest_rect->w);
lockRect.h = static_cast<int>(destRect->h); lock_rect.h = static_cast<int>(dest_rect->h);
} }
// Usa lockRect solo si destRect no es nulo // Usa lockRect solo si destRect no es nulo
if (!SDL_LockTexture(texture, destRect ? &lockRect : nullptr, reinterpret_cast<void**>(&pixels), &pitch)) { if (!SDL_LockTexture(texture, (dest_rect != nullptr) ? &lock_rect : nullptr, reinterpret_cast<void**>(&pixels), &pitch)) {
throw std::runtime_error("Failed to lock texture: " + std::string(SDL_GetError())); throw std::runtime_error("Failed to lock texture: " + std::string(SDL_GetError()));
} }
@@ -494,8 +498,8 @@ void Surface::copyToTexture(SDL_Renderer* renderer, SDL_Texture* texture, SDL_FR
for (int y = 0; y < surface_data_->height; ++y) { for (int y = 0; y < surface_data_->height; ++y) {
for (int x = 0; x < surface_data_->width; ++x) { for (int x = 0; x < surface_data_->width; ++x) {
int texture_index = y * row_stride + x; int texture_index = (y * row_stride) + x;
int surface_index = y * surface_data_->width + x; int surface_index = (y * surface_data_->width) + x;
pixels[texture_index] = palette_[surface_data_->data.get()[surface_index]]; pixels[texture_index] = palette_[surface_data_->data.get()[surface_index]];
} }
@@ -504,7 +508,7 @@ void Surface::copyToTexture(SDL_Renderer* renderer, SDL_Texture* texture, SDL_FR
SDL_UnlockTexture(texture); SDL_UnlockTexture(texture);
// Renderiza la textura con los rectángulos especificados // Renderiza la textura con los rectángulos especificados
if (!SDL_RenderTexture(renderer, texture, srcRect, destRect)) { if (!SDL_RenderTexture(renderer, texture, src_rect, dest_rect)) {
throw std::runtime_error("Failed to copy texture to renderer: " + std::string(SDL_GetError())); throw std::runtime_error("Failed to copy texture to renderer: " + std::string(SDL_GetError()));
} }
} }
@@ -512,8 +516,8 @@ void Surface::copyToTexture(SDL_Renderer* renderer, SDL_Texture* texture, SDL_FR
// Realiza un efecto de fundido en la paleta principal // Realiza un efecto de fundido en la paleta principal
bool Surface::fadePalette() { bool Surface::fadePalette() {
// Verificar que el tamaño mínimo de palette_ sea adecuado // Verificar que el tamaño mínimo de palette_ sea adecuado
static constexpr int palette_size = 19; static constexpr int PALETTE_SIZE = 19;
if (sizeof(palette_) / sizeof(palette_[0]) < palette_size) { if (sizeof(palette_) / sizeof(palette_[0]) < PALETTE_SIZE) {
throw std::runtime_error("Palette size is insufficient for fadePalette operation."); throw std::runtime_error("Palette size is insufficient for fadePalette operation.");
} }
@@ -532,22 +536,22 @@ bool Surface::fadePalette() {
// Realiza un efecto de fundido en la paleta secundaria // Realiza un efecto de fundido en la paleta secundaria
bool Surface::fadeSubPalette(Uint32 delay) { bool Surface::fadeSubPalette(Uint32 delay) {
// Variable estática para almacenar el último tick // Variable estática para almacenar el último tick
static Uint32 last_tick = 0; static Uint32 last_tick_ = 0;
// Obtener el tiempo actual // Obtener el tiempo actual
Uint32 current_tick = SDL_GetTicks(); Uint32 current_tick = SDL_GetTicks();
// Verificar si ha pasado el tiempo de retardo // Verificar si ha pasado el tiempo de retardo
if (current_tick - last_tick < delay) { if (current_tick - last_tick_ < delay) {
return false; // No se realiza el fade return false; // No se realiza el fade
} }
// Actualizar el último tick // Actualizar el último tick
last_tick = current_tick; last_tick_ = current_tick;
// Verificar que el tamaño mínimo de sub_palette_ sea adecuado // Verificar que el tamaño mínimo de sub_palette_ sea adecuado
static constexpr int sub_palette_size = 19; static constexpr int SUB_PALETTE_SIZE = 19;
if (sizeof(sub_palette_) / sizeof(sub_palette_[0]) < sub_palette_size) { if (sizeof(sub_palette_) / sizeof(sub_palette_[0]) < SUB_PALETTE_SIZE) {
throw std::runtime_error("Palette size is insufficient for fadePalette operation."); throw std::runtime_error("Palette size is insufficient for fadePalette operation.");
} }

View File

@@ -70,7 +70,7 @@ class Surface {
~Surface() = default; ~Surface() = default;
// Carga una SurfaceData desde un archivo // Carga una SurfaceData desde un archivo
SurfaceData loadSurface(const std::string& file_path); static SurfaceData loadSurface(const std::string& file_path);
// Carga una paleta desde un archivo // Carga una paleta desde un archivo
void loadPalette(const std::string& file_path); void loadPalette(const std::string& file_path);
@@ -79,10 +79,10 @@ class Surface {
// Copia una región de la SurfaceData de origen a la SurfaceData de destino // Copia una región de la SurfaceData de origen a la SurfaceData de destino
void render(float dx, float dy, float sx, float sy, float w, float h); void render(float dx, float dy, float sx, float sy, float w, float h);
void render(int x, int y, SDL_FRect* clip = nullptr, SDL_FlipMode flip = SDL_FLIP_NONE); void render(int x, int y, SDL_FRect* clip = nullptr, SDL_FlipMode flip = SDL_FLIP_NONE);
void render(SDL_FRect* srcRect = nullptr, SDL_FRect* dstRect = nullptr, SDL_FlipMode flip = SDL_FLIP_NONE); void render(SDL_FRect* src_rect = nullptr, SDL_FRect* dst_rect = nullptr, SDL_FlipMode flip = SDL_FLIP_NONE);
// Copia una región de la SurfaceData de origen a la SurfaceData de destino reemplazando un color por otro // Copia una región de la SurfaceData de origen a la SurfaceData de destino reemplazando un color por otro
void renderWithColorReplace(int x, int y, Uint8 source_color = 0, Uint8 target_color = 0, SDL_FRect* srcRect = nullptr, SDL_FlipMode flip = SDL_FLIP_NONE); void renderWithColorReplace(int x, int y, Uint8 source_color = 0, Uint8 target_color = 0, SDL_FRect* src_rect = nullptr, SDL_FlipMode flip = SDL_FLIP_NONE);
// Establece un color en la paleta // Establece un color en la paleta
void setColor(int index, Uint32 color); void setColor(int index, Uint32 color);
@@ -92,7 +92,7 @@ class Surface {
// Vuelca la SurfaceData a una textura // Vuelca la SurfaceData a una textura
void copyToTexture(SDL_Renderer* renderer, SDL_Texture* texture); void copyToTexture(SDL_Renderer* renderer, SDL_Texture* texture);
void copyToTexture(SDL_Renderer* renderer, SDL_Texture* texture, SDL_FRect* srcRect, SDL_FRect* destRect); void copyToTexture(SDL_Renderer* renderer, SDL_Texture* texture, SDL_FRect* src_rect, SDL_FRect* dest_rect);
// Realiza un efecto de fundido en las paletas // Realiza un efecto de fundido en las paletas
bool fadePalette(); bool fadePalette();
@@ -129,5 +129,5 @@ class Surface {
void setPalette(const std::array<Uint32, 256>& palette) { palette_ = palette; } void setPalette(const std::array<Uint32, 256>& palette) { palette_ = palette; }
// Inicializa la sub paleta // Inicializa la sub paleta
void initializeSubPalette(SubPalette& palette) { std::iota(palette.begin(), palette.end(), 0); } static void initializeSubPalette(SubPalette& palette) { std::iota(palette.begin(), palette.end(), 0); }
}; };

View File

@@ -23,8 +23,9 @@ Animations loadAnimationsFromFile(const std::string& file_path) {
std::vector<std::string> buffer; std::vector<std::string> buffer;
std::string line; std::string line;
while (std::getline(file, line)) { while (std::getline(file, line)) {
if (!line.empty()) if (!line.empty()) {
buffer.push_back(line); buffer.push_back(line);
}
} }
return buffer; return buffer;
@@ -99,9 +100,9 @@ bool SurfaceAnimatedSprite::animationIsCompleted() {
// Establece la animacion actual // Establece la animacion actual
void SurfaceAnimatedSprite::setCurrentAnimation(const std::string& name) { void SurfaceAnimatedSprite::setCurrentAnimation(const std::string& name) {
const auto new_animation = getIndex(name); const auto NEW_ANIMATION = getIndex(name);
if (current_animation_ != new_animation) { if (current_animation_ != NEW_ANIMATION) {
current_animation_ = new_animation; current_animation_ = NEW_ANIMATION;
animations_[current_animation_].current_frame = 0; animations_[current_animation_].current_frame = 0;
animations_[current_animation_].counter = 0; animations_[current_animation_].counter = 0;
animations_[current_animation_].completed = false; animations_[current_animation_].completed = false;
@@ -111,9 +112,9 @@ void SurfaceAnimatedSprite::setCurrentAnimation(const std::string& name) {
// Establece la animacion actual // Establece la animacion actual
void SurfaceAnimatedSprite::setCurrentAnimation(int index) { void SurfaceAnimatedSprite::setCurrentAnimation(int index) {
const auto new_animation = index; const auto NEW_ANIMATION = index;
if (current_animation_ != new_animation) { if (current_animation_ != NEW_ANIMATION) {
current_animation_ = new_animation; current_animation_ = NEW_ANIMATION;
animations_[current_animation_].current_frame = 0; animations_[current_animation_].current_frame = 0;
animations_[current_animation_].counter = 0; animations_[current_animation_].counter = 0;
animations_[current_animation_].completed = false; animations_[current_animation_].completed = false;
@@ -154,17 +155,18 @@ void SurfaceAnimatedSprite::setAnimations(const Animations& animations) {
if (pos != std::string::npos) { if (pos != std::string::npos) {
std::string key = line.substr(0, pos); std::string key = line.substr(0, pos);
int value = std::stoi(line.substr(pos + 1)); int value = std::stoi(line.substr(pos + 1));
if (key == "frame_width") if (key == "frame_width") {
frame_width = value; frame_width = value;
else if (key == "frame_height") } else if (key == "frame_height") {
frame_height = value; frame_height = value;
else } else {
std::cout << "Warning: unknown parameter " << key << std::endl; std::cout << "Warning: unknown parameter " << key << std::endl;
}
frames_per_row = surface_->getWidth() / frame_width; frames_per_row = surface_->getWidth() / frame_width;
const int w = surface_->getWidth() / frame_width; const int W = surface_->getWidth() / frame_width;
const int h = surface_->getHeight() / frame_height; const int H = surface_->getHeight() / frame_height;
max_tiles = w * h; max_tiles = W * H;
} }
} }
@@ -180,30 +182,31 @@ void SurfaceAnimatedSprite::setAnimations(const Animations& animations) {
std::string key = line.substr(0, pos); std::string key = line.substr(0, pos);
std::string value = line.substr(pos + 1); std::string value = line.substr(pos + 1);
if (key == "name") if (key == "name") {
animation.name = value; animation.name = value;
else if (key == "speed") } else if (key == "speed") {
animation.speed = std::stoi(value); animation.speed = std::stoi(value);
else if (key == "loop") } else if (key == "loop") {
animation.loop = std::stoi(value); animation.loop = std::stoi(value);
else if (key == "frames") { } else if (key == "frames") {
// Se introducen los valores separados por comas en un vector // Se introducen los valores separados por comas en un vector
std::stringstream ss(value); std::stringstream ss(value);
std::string tmp; std::string tmp;
SDL_FRect rect = {0.0F, 0.0F, frame_width, frame_height}; SDL_FRect rect = {0.0F, 0.0F, frame_width, frame_height};
while (getline(ss, tmp, ',')) { while (getline(ss, tmp, ',')) {
// Comprueba que el tile no sea mayor que el maximo indice permitido // Comprueba que el tile no sea mayor que el maximo indice permitido
const int num_tile = std::stoi(tmp); const int NUM_TILE = std::stoi(tmp);
if (num_tile <= max_tiles) { if (NUM_TILE <= max_tiles) {
rect.x = (num_tile % frames_per_row) * frame_width; rect.x = (NUM_TILE % frames_per_row) * frame_width;
rect.y = (num_tile / frames_per_row) * frame_height; rect.y = (NUM_TILE / frames_per_row) * frame_height;
animation.frames.emplace_back(rect); animation.frames.emplace_back(rect);
} }
} }
} }
else else {
std::cout << "Warning: unknown parameter " << key << std::endl; std::cout << "Warning: unknown parameter " << key << std::endl;
}
} }
} while (line != "[/animation]"); } while (line != "[/animation]");

View File

@@ -19,8 +19,7 @@ struct AnimationData {
int counter; // Contador para las animaciones int counter; // Contador para las animaciones
AnimationData() AnimationData()
: name(std::string()), : speed(5),
speed(5),
loop(0), loop(0),
completed(false), completed(false),
current_frame(0), current_frame(0),

View File

@@ -17,20 +17,20 @@ SurfaceMovingSprite::SurfaceMovingSprite(std::shared_ptr<Surface> surface, SDL_F
SurfaceMovingSprite::SurfaceMovingSprite(std::shared_ptr<Surface> surface) SurfaceMovingSprite::SurfaceMovingSprite(std::shared_ptr<Surface> surface)
: SurfaceSprite(surface), : SurfaceSprite(surface),
x_(0.0f), x_(0.0F),
y_(0.0f), y_(0.0F),
flip_(SDL_FLIP_NONE) { SurfaceSprite::clear(); } flip_(SDL_FLIP_NONE) { SurfaceSprite::clear(); }
// Reinicia todas las variables // Reinicia todas las variables
void SurfaceMovingSprite::clear() { void SurfaceMovingSprite::clear() {
x_ = 0.0f; // Posición en el eje X x_ = 0.0F; // Posición en el eje X
y_ = 0.0f; // Posición en el eje Y y_ = 0.0F; // Posición en el eje Y
vx_ = 0.0f; // Velocidad en el eje X. Cantidad de pixeles a desplazarse vx_ = 0.0F; // Velocidad en el eje X. Cantidad de pixeles a desplazarse
vy_ = 0.0f; // Velocidad en el eje Y. Cantidad de pixeles a desplazarse vy_ = 0.0F; // Velocidad en el eje Y. Cantidad de pixeles a desplazarse
ax_ = 0.0f; // Aceleración en el eje X. Variación de la velocidad ax_ = 0.0F; // Aceleración en el eje X. Variación de la velocidad
ay_ = 0.0f; // Aceleración en el eje Y. Variación de la velocidad ay_ = 0.0F; // Aceleración en el eje Y. Variación de la velocidad
flip_ = SDL_FLIP_NONE; // Establece como se ha de voltear el sprite flip_ = SDL_FLIP_NONE; // Establece como se ha de voltear el sprite
@@ -66,8 +66,8 @@ void SurfaceMovingSprite::render(Uint8 source_color, Uint8 target_color) {
// Establece la posición y_ el tamaño del objeto // Establece la posición y_ el tamaño del objeto
void SurfaceMovingSprite::setPos(SDL_FRect rect) { void SurfaceMovingSprite::setPos(SDL_FRect rect) {
x_ = static_cast<float>(rect.x); x_ = rect.x;
y_ = static_cast<float>(rect.y); y_ = rect.y;
pos_ = rect; pos_ = rect;
} }

View File

@@ -14,11 +14,11 @@ class SurfaceMovingSprite : public SurfaceSprite {
float x_; // Posición en el eje X float x_; // Posición en el eje X
float y_; // Posición en el eje Y float y_; // Posición en el eje Y
float vx_ = 0.0f; // Velocidad en el eje X. Cantidad de pixeles a desplazarse float vx_ = 0.0F; // Velocidad en el eje X. Cantidad de pixeles a desplazarse
float vy_ = 0.0f; // Velocidad en el eje Y. Cantidad de pixeles a desplazarse float vy_ = 0.0F; // Velocidad en el eje Y. Cantidad de pixeles a desplazarse
float ax_ = 0.0f; // Aceleración en el eje X. Variación de la velocidad float ax_ = 0.0F; // Aceleración en el eje X. Variación de la velocidad
float ay_ = 0.0f; // Aceleración en el eje Y. Variación de la velocidad float ay_ = 0.0F; // Aceleración en el eje Y. Variación de la velocidad
SDL_FlipMode flip_; // Indica como se voltea el sprite SDL_FlipMode flip_; // Indica como se voltea el sprite

View File

@@ -45,8 +45,9 @@ std::shared_ptr<TextFile> loadTextFile(const std::string& file_path) {
auto line_read = 0; auto line_read = 0;
while (std::getline(file, buffer)) { while (std::getline(file, buffer)) {
// Almacena solo las lineas impares // Almacena solo las lineas impares
if (line_read % 2 == 1) if (line_read % 2 == 1) {
tf->offset[index++].w = std::stoi(buffer); tf->offset[index++].w = std::stoi(buffer);
}
// Limpia el buffer // Limpia el buffer
buffer.clear(); buffer.clear();
@@ -116,8 +117,9 @@ Text::Text(std::shared_ptr<Surface> surface, std::shared_ptr<TextFile> text_file
void Text::write(int x, int y, const std::string& text, int kerning, int lenght) { void Text::write(int x, int y, const std::string& text, int kerning, int lenght) {
int shift = 0; int shift = 0;
if (lenght == -1) if (lenght == -1) {
lenght = text.length(); lenght = text.length();
}
sprite_->setY(y); sprite_->setY(y);
for (int i = 0; i < lenght; ++i) { for (int i = 0; i < lenght; ++i) {
@@ -144,14 +146,14 @@ std::shared_ptr<Surface> Text::writeToSurface(const std::string& text, int zoom,
} }
// Escribe el texto con extras en una surface // Escribe el texto con extras en una surface
std::shared_ptr<Surface> Text::writeDXToSurface(Uint8 flags, const std::string& text, int kerning, Uint8 textColor, Uint8 shadow_distance, Uint8 shadow_color, int lenght) { std::shared_ptr<Surface> Text::writeDXToSurface(Uint8 flags, const std::string& text, int kerning, Uint8 text_color, Uint8 shadow_distance, Uint8 shadow_color, int lenght) {
auto width = Text::lenght(text, kerning) + shadow_distance; auto width = Text::lenght(text, kerning) + shadow_distance;
auto height = box_height_ + shadow_distance; auto height = box_height_ + shadow_distance;
auto surface = std::make_shared<Surface>(width, height); auto surface = std::make_shared<Surface>(width, height);
auto previuos_renderer = Screen::get()->getRendererSurface(); auto previuos_renderer = Screen::get()->getRendererSurface();
Screen::get()->setRendererSurface(surface); Screen::get()->setRendererSurface(surface);
surface->clear(stringToColor("transparent")); surface->clear(stringToColor("transparent"));
writeDX(flags, 0, 0, text, kerning, textColor, shadow_distance, shadow_color, lenght); writeDX(flags, 0, 0, text, kerning, text_color, shadow_distance, shadow_color, lenght);
Screen::get()->setRendererSurface(previuos_renderer); Screen::get()->setRendererSurface(previuos_renderer);
return surface; return surface;
@@ -188,21 +190,21 @@ void Text::writeCentered(int x, int y, const std::string& text, int kerning, int
} }
// Escribe texto con extras // Escribe texto con extras
void Text::writeDX(Uint8 flags, int x, int y, const std::string& text, int kerning, Uint8 textColor, Uint8 shadow_distance, Uint8 shadow_color, int lenght) { void Text::writeDX(Uint8 flags, int x, int y, const std::string& text, int kerning, Uint8 text_color, Uint8 shadow_distance, Uint8 shadow_color, int lenght) {
const auto centered = ((flags & TEXT_CENTER) == TEXT_CENTER); const auto CENTERED = ((flags & TEXT_CENTER) == TEXT_CENTER);
const auto shadowed = ((flags & TEXT_SHADOW) == TEXT_SHADOW); const auto SHADOWED = ((flags & TEXT_SHADOW) == TEXT_SHADOW);
const auto colored = ((flags & TEXT_COLOR) == TEXT_COLOR); const auto COLORED = ((flags & TEXT_COLOR) == TEXT_COLOR);
const auto stroked = ((flags & TEXT_STROKE) == TEXT_STROKE); const auto STROKED = ((flags & TEXT_STROKE) == TEXT_STROKE);
if (centered) { if (CENTERED) {
x -= (Text::lenght(text, kerning) / 2); x -= (Text::lenght(text, kerning) / 2);
} }
if (shadowed) { if (SHADOWED) {
writeColored(x + shadow_distance, y + shadow_distance, text, shadow_color, kerning, lenght); writeColored(x + shadow_distance, y + shadow_distance, text, shadow_color, kerning, lenght);
} }
if (stroked) { if (STROKED) {
for (int dist = 1; dist <= shadow_distance; ++dist) { for (int dist = 1; dist <= shadow_distance; ++dist) {
for (int dy = -dist; dy <= dist; ++dy) { for (int dy = -dist; dy <= dist; ++dy) {
for (int dx = -dist; dx <= dist; ++dx) { for (int dx = -dist; dx <= dist; ++dx) {
@@ -212,10 +214,10 @@ void Text::writeDX(Uint8 flags, int x, int y, const std::string& text, int kerni
} }
} }
if (colored) { if (COLORED) {
writeColored(x, y, text, textColor, kerning, lenght); writeColored(x, y, text, text_color, kerning, lenght);
} else { } else {
writeColored(x, y, text, textColor, kerning, lenght); writeColored(x, y, text, text_color, kerning, lenght);
// write(x, y, text, kerning, lenght); // write(x, y, text, kerning, lenght);
} }
} }
@@ -223,8 +225,9 @@ 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 { int Text::lenght(const std::string& text, int kerning) const {
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);
}
// Descuenta el kerning del último caracter // Descuenta el kerning del último caracter
return shift - kerning; return shift - kerning;

View File

@@ -53,7 +53,7 @@ class Text {
std::shared_ptr<Surface> writeToSurface(const std::string& text, int zoom = 1, int kerning = 1); std::shared_ptr<Surface> writeToSurface(const std::string& text, int zoom = 1, int kerning = 1);
// Escribe el texto con extras en una textura // Escribe el texto con extras en una textura
std::shared_ptr<Surface> writeDXToSurface(Uint8 flags, const std::string& text, int kerning = 1, Uint8 textColor = Uint8(), Uint8 shadow_distance = 1, Uint8 shadow_color = Uint8(), int lenght = -1); std::shared_ptr<Surface> writeDXToSurface(Uint8 flags, const std::string& text, int kerning = 1, Uint8 text_color = Uint8(), Uint8 shadow_distance = 1, Uint8 shadow_color = Uint8(), int lenght = -1);
// Escribe el texto con colores // Escribe el texto con colores
void writeColored(int x, int y, const std::string& text, Uint8 color, int kerning = 1, int lenght = -1); void writeColored(int x, int y, const std::string& text, Uint8 color, int kerning = 1, int lenght = -1);
@@ -65,7 +65,7 @@ class Text {
void writeCentered(int x, int y, const std::string& text, int kerning = 1, int lenght = -1); void writeCentered(int x, int y, const std::string& text, int kerning = 1, int lenght = -1);
// Escribe texto con extras // Escribe texto con extras
void writeDX(Uint8 flags, int x, int y, const std::string& text, int kerning = 1, Uint8 textColor = Uint8(), Uint8 shadow_distance = 1, Uint8 shadow_color = Uint8(), int lenght = -1); void writeDX(Uint8 flags, int x, int y, const std::string& text, int kerning = 1, Uint8 text_color = Uint8(), Uint8 shadow_distance = 1, Uint8 shadow_color = Uint8(), int lenght = -1);
// Obtiene la longitud en pixels de una cadena // Obtiene la longitud en pixels de una cadena
int lenght(const std::string& text, int kerning = 1) const; int lenght(const std::string& text, int kerning = 1) const;

View File

@@ -20,10 +20,10 @@ Texture::Texture(SDL_Renderer* renderer, const std::string& path)
// Carga el fichero en la textura // Carga el fichero en la textura
if (!path_.empty()) { if (!path_.empty()) {
// Obtiene la extensión // Obtiene la extensión
const std::string extension = path_.substr(path_.find_last_of(".") + 1); const std::string EXTENSION = path_.substr(path_.find_last_of(".") + 1);
// .png // .png
if (extension == "png") { if (EXTENSION == "png") {
loadFromFile(path_); loadFromFile(path_);
} }
} }
@@ -42,14 +42,15 @@ bool Texture::loadFromFile(const std::string& file_path) {
} }
int req_format = STBI_rgb_alpha; int req_format = STBI_rgb_alpha;
int width, height, orig_format; int width;
int height;
int orig_format;
unsigned char* data = stbi_load(file_path.c_str(), &width, &height, &orig_format, req_format); unsigned char* data = stbi_load(file_path.c_str(), &width, &height, &orig_format, req_format);
if (!data) { if (data == nullptr) {
std::cerr << "Error: Fichero no encontrado " << getFileName(file_path) << std::endl; std::cerr << "Error: Fichero no encontrado " << getFileName(file_path) << std::endl;
throw std::runtime_error("Fichero no encontrado: " + getFileName(file_path)); throw std::runtime_error("Fichero no encontrado: " + getFileName(file_path));
} else {
printWithDots("Image : ", getFileName(file_path), "[ LOADED ]");
} }
printWithDots("Image : ", getFileName(file_path), "[ LOADED ]");
int pitch; int pitch;
SDL_PixelFormat pixel_format; SDL_PixelFormat pixel_format;
@@ -61,7 +62,7 @@ bool Texture::loadFromFile(const std::string& file_path) {
unloadTexture(); unloadTexture();
// La textura final // La textura final
SDL_Texture* newTexture = nullptr; SDL_Texture* new_texture = nullptr;
// Carga la imagen desde una ruta específica // Carga la imagen desde una ruta específica
auto* loaded_surface = SDL_CreateSurfaceFrom(width, height, pixel_format, static_cast<void*>(data), pitch); auto* loaded_surface = SDL_CreateSurfaceFrom(width, height, pixel_format, static_cast<void*>(data), pitch);
@@ -69,8 +70,8 @@ bool Texture::loadFromFile(const std::string& file_path) {
std::cout << "Unable to load image " << file_path << std::endl; std::cout << "Unable to load image " << file_path << std::endl;
} else { } else {
// Crea la textura desde los pixels de la surface // Crea la textura desde los pixels de la surface
newTexture = SDL_CreateTextureFromSurface(renderer_, loaded_surface); new_texture = SDL_CreateTextureFromSurface(renderer_, loaded_surface);
if (newTexture == nullptr) { if (new_texture == nullptr) {
std::cout << "Unable to create texture from " << file_path << "! SDL Error: " << SDL_GetError() << std::endl; std::cout << "Unable to create texture from " << file_path << "! SDL Error: " << SDL_GetError() << std::endl;
} else { } else {
// Obtiene las dimensiones de la imagen // Obtiene las dimensiones de la imagen
@@ -84,7 +85,7 @@ bool Texture::loadFromFile(const std::string& file_path) {
// Return success // Return success
stbi_image_free(data); stbi_image_free(data);
texture_ = newTexture; texture_ = new_texture;
return texture_ != nullptr; return texture_ != nullptr;
} }
@@ -105,7 +106,7 @@ auto Texture::createBlank(int width, int height, SDL_PixelFormat format, SDL_Tex
// Libera la memoria de la textura // Libera la memoria de la textura
void Texture::unloadTexture() { void Texture::unloadTexture() {
// Libera la textura // Libera la textura
if (texture_) { if (texture_ != nullptr) {
SDL_DestroyTexture(texture_); SDL_DestroyTexture(texture_);
texture_ = nullptr; texture_ = nullptr;
width_ = 0; width_ = 0;
@@ -124,7 +125,7 @@ void Texture::setBlendMode(SDL_BlendMode blending) { SDL_SetTextureBlendMode(tex
void Texture::setAlpha(Uint8 alpha) { SDL_SetTextureAlphaMod(texture_, alpha); } void Texture::setAlpha(Uint8 alpha) { SDL_SetTextureAlphaMod(texture_, alpha); }
// Renderiza la textura en un punto específico // Renderiza la textura en un punto específico
void Texture::render(float x, float y, SDL_FRect* clip, float zoomW, float zoomH, double angle, SDL_FPoint* center, SDL_FlipMode flip) { void Texture::render(float x, float y, SDL_FRect* clip, float zoom_w, float zoom_h, double angle, SDL_FPoint* center, SDL_FlipMode flip) {
// Establece el destino de renderizado en la pantalla // Establece el destino de renderizado en la pantalla
SDL_FRect render_quad = {x, y, width_, height_}; SDL_FRect render_quad = {x, y, width_, height_};
@@ -135,11 +136,11 @@ void Texture::render(float x, float y, SDL_FRect* clip, float zoomW, float zoomH
} }
// Calcula el zoom y las coordenadas // Calcula el zoom y las coordenadas
if (zoomH != 1.0f || zoomW != 1.0f) { if (zoom_h != 1.0F || zoom_w != 1.0F) {
render_quad.x = render_quad.x + (render_quad.w / 2); render_quad.x = render_quad.x + (render_quad.w / 2);
render_quad.y = render_quad.y + (render_quad.h / 2); render_quad.y = render_quad.y + (render_quad.h / 2);
render_quad.w = render_quad.w * zoomW; render_quad.w = render_quad.w * zoom_w;
render_quad.h = render_quad.h * zoomH; render_quad.h = render_quad.h * zoom_h;
render_quad.x = render_quad.x - (render_quad.w / 2); render_quad.x = render_quad.x - (render_quad.w / 2);
render_quad.y = render_quad.y - (render_quad.h / 2); render_quad.y = render_quad.y - (render_quad.h / 2);
} }
@@ -151,12 +152,6 @@ void Texture::render(float x, float y, SDL_FRect* clip, float zoomW, float zoomH
// Establece la textura como objetivo de renderizado // Establece la textura como objetivo de renderizado
void Texture::setAsRenderTarget(SDL_Renderer* renderer) { SDL_SetRenderTarget(renderer, texture_); } void Texture::setAsRenderTarget(SDL_Renderer* renderer) { SDL_SetRenderTarget(renderer, texture_); }
// Obtiene el ancho de la imagen
int Texture::getWidth() { return width_; }
// Obtiene el alto de la imagen
int Texture::getHeight() { return height_; }
// Recarga la textura // Recarga la textura
bool Texture::reLoad() { return loadFromFile(path_); } bool Texture::reLoad() { return loadFromFile(path_); }

View File

@@ -45,16 +45,16 @@ class Texture {
void setAlpha(Uint8 alpha); void setAlpha(Uint8 alpha);
// Renderiza la textura en un punto específico // Renderiza la textura en un punto específico
void render(float x, float y, SDL_FRect* clip = nullptr, float zoomW = 1, float zoomH = 1, double angle = 0.0, SDL_FPoint* center = nullptr, SDL_FlipMode flip = SDL_FLIP_NONE); void render(float x, float 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);
// Establece la textura como objetivo de renderizado // Establece la textura como objetivo de renderizado
void setAsRenderTarget(SDL_Renderer* renderer); void setAsRenderTarget(SDL_Renderer* renderer);
// Obtiene el ancho de la imagen // Obtiene el ancho de la imagen
int getWidth(); int getWidth() const { return width_; }
// Obtiene el alto de la imagen // Obtiene el alto de la imagen
int getHeight(); int getHeight() const { return height_; }
// Recarga la textura // Recarga la textura
bool reLoad(); bool reLoad();

View File

@@ -8,21 +8,21 @@
#include "utils/utils.hpp" // Para getFileName, printWithDots #include "utils/utils.hpp" // Para getFileName, printWithDots
// [SINGLETON] Hay que definir las variables estáticas, desde el .h sólo la hemos declarado // [SINGLETON] Hay que definir las variables estáticas, desde el .h sólo la hemos declarado
Asset* Asset::asset_ = nullptr; Asset* Asset::asset = nullptr;
// [SINGLETON] Crearemos el objeto asset con esta función estática // [SINGLETON] Crearemos el objeto asset con esta función estática
void Asset::init(const std::string& executable_path) { void Asset::init(const std::string& executable_path) {
Asset::asset_ = new Asset(executable_path); Asset::asset = new Asset(executable_path);
} }
// [SINGLETON] Destruiremos el objeto asset con esta función estática // [SINGLETON] Destruiremos el objeto asset con esta función estática
void Asset::destroy() { void Asset::destroy() {
delete Asset::asset_; delete Asset::asset;
} }
// [SINGLETON] Con este método obtenemos el objeto asset y podemos trabajar con él // [SINGLETON] Con este método obtenemos el objeto asset y podemos trabajar con él
Asset* Asset::get() { Asset* Asset::get() {
return Asset::asset_; return Asset::asset;
} }
// Añade un elemento a la lista // Añade un elemento a la lista
@@ -39,10 +39,9 @@ std::string Asset::get(const std::string& text) const {
if (it != file_list_.end()) { if (it != file_list_.end()) {
return it->file; return it->file;
} else {
std::cout << "Warning: file " << text << " not found" << std::endl;
return "";
} }
std::cout << "Warning: file " << text << " not found" << std::endl;
return "";
} }
// Comprueba que existen todos los elementos // Comprueba que existen todos los elementos
@@ -74,8 +73,9 @@ bool Asset::check() const {
success &= checkFile(f.file); success &= checkFile(f.file);
} }
} }
if (success) if (success) {
std::cout << " All files are OK." << std::endl; std::cout << " All files are OK." << std::endl;
}
} }
} }
@@ -86,7 +86,7 @@ bool Asset::check() const {
} }
// Comprueba que existe un fichero // Comprueba que existe un fichero
bool Asset::checkFile(const std::string& path) const { bool Asset::checkFile(const std::string& path) {
std::ifstream file(path); std::ifstream file(path);
bool success = file.good(); bool success = file.good();
file.close(); file.close();
@@ -99,7 +99,7 @@ bool Asset::checkFile(const std::string& path) const {
} }
// Devuelve el nombre del tipo de recurso // Devuelve el nombre del tipo de recurso
std::string Asset::getTypeName(AssetType type) const { std::string Asset::getTypeName(AssetType type) {
switch (type) { switch (type) {
case AssetType::DATA: case AssetType::DATA:
return "DATA"; return "DATA";

View File

@@ -22,7 +22,7 @@ enum class AssetType : int {
class Asset { class Asset {
private: private:
// [SINGLETON] Objeto asset privado para Don Melitón // [SINGLETON] Objeto asset privado para Don Melitón
static Asset* asset_; static Asset* asset;
// Estructura para definir un item // Estructura para definir un item
struct AssetItem { struct AssetItem {
@@ -31,10 +31,10 @@ class Asset {
bool required; // Indica si es un fichero que debe de existir bool required; // Indica si es un fichero que debe de existir
// Constructor // Constructor
AssetItem(const std::string& filePath, AssetType assetType, bool isRequired) AssetItem(const std::string& file_path, AssetType asset_type, bool is_required)
: file(filePath), : file(file_path),
type(assetType), type(asset_type),
required(isRequired) {} required(is_required) {}
}; };
// Variables // Variables
@@ -43,10 +43,10 @@ class Asset {
std::string executable_path_; // Ruta al ejecutable std::string executable_path_; // Ruta al ejecutable
// Comprueba que existe un fichero // Comprueba que existe un fichero
bool checkFile(const std::string& path) const; static bool checkFile(const std::string& path);
// Devuelve el nombre del tipo de recurso // Devuelve el nombre del tipo de recurso
std::string getTypeName(AssetType type) const; static std::string getTypeName(AssetType type);
// Constructor // Constructor
explicit Asset(const std::string& executable_path) explicit Asset(const std::string& executable_path)

View File

@@ -8,21 +8,21 @@
#include "utils/utils.hpp" // Para Color #include "utils/utils.hpp" // Para Color
// [SINGLETON] // [SINGLETON]
Debug* Debug::debug_ = nullptr; Debug* Debug::debug = nullptr;
// [SINGLETON] Crearemos el objeto con esta función estática // [SINGLETON] Crearemos el objeto con esta función estática
void Debug::init() { void Debug::init() {
Debug::debug_ = new Debug(); Debug::debug = new Debug();
} }
// [SINGLETON] Destruiremos el objeto con esta función estática // [SINGLETON] Destruiremos el objeto con esta función estática
void Debug::destroy() { void Debug::destroy() {
delete Debug::debug_; delete Debug::debug;
} }
// [SINGLETON] Con este método obtenemos el objeto y podemos trabajar con él // [SINGLETON] Con este método obtenemos el objeto y podemos trabajar con él
Debug* Debug::get() { Debug* Debug::get() {
return Debug::debug_; return Debug::debug;
} }
// Dibuja en pantalla // Dibuja en pantalla

View File

@@ -9,7 +9,7 @@
class Debug { class Debug {
private: private:
// [SINGLETON] Objeto privado // [SINGLETON] Objeto privado
static Debug* debug_; static Debug* debug;
// Variables // Variables
std::vector<std::string> slot_; // Vector con los textos a escribir std::vector<std::string> slot_; // Vector con los textos a escribir
@@ -41,7 +41,7 @@ class Debug {
void setPos(SDL_FPoint p); void setPos(SDL_FPoint p);
// Getters // Getters
bool getEnabled() { return enabled_; } bool getEnabled() const { return enabled_; }
// Setters // Setters
void add(std::string text) { slot_.push_back(text); } void add(std::string text) { slot_.push_back(text); }

View File

@@ -5,7 +5,7 @@
#include "core/input/mouse.hpp" #include "core/input/mouse.hpp"
#include "game/options.hpp" // Para Options, options, OptionsGame, OptionsAudio #include "game/options.hpp" // Para Options, options, OptionsGame, OptionsAudio
namespace globalEvents { namespace GlobalEvents {
// Comprueba los eventos que se pueden producir en cualquier sección del juego // Comprueba los eventos que se pueden producir en cualquier sección del juego
void check(const SDL_Event& event) { void check(const SDL_Event& event) {
// Evento de salida de la aplicación // Evento de salida de la aplicación
@@ -20,4 +20,4 @@ void check(const SDL_Event& event) {
Mouse::handleEvent(event); Mouse::handleEvent(event);
} }
} // namespace globalEvents } // namespace GlobalEvents

View File

@@ -2,7 +2,7 @@
#include <SDL3/SDL.h> #include <SDL3/SDL.h>
namespace globalEvents { namespace GlobalEvents {
// Comprueba los eventos que se pueden producir en cualquier sección del juego // Comprueba los eventos que se pueden producir en cualquier sección del juego
void check(const SDL_Event& event); void check(const SDL_Event& event);
} // namespace globalEvents } // namespace GlobalEvents

View File

@@ -25,7 +25,7 @@ Enemy::Enemy(const EnemyData& enemy)
sprite_->setWidth(enemy.w); sprite_->setWidth(enemy.w);
sprite_->setHeight(enemy.h); 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; const SDL_FlipMode MIRROR = should_mirror_ ? SDL_FLIP_VERTICAL : SDL_FLIP_NONE;
sprite_->setFlip(static_cast<SDL_FlipMode>(FLIP | MIRROR)); sprite_->setFlip(static_cast<SDL_FlipMode>(FLIP | MIRROR));

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -19,7 +19,7 @@ struct ItemTrackerData {
class ItemTracker { class ItemTracker {
private: private:
// [SINGLETON] Objeto privado // [SINGLETON] Objeto privado
static ItemTracker* item_tracker_; static ItemTracker* item_tracker;
// Variables // Variables
std::vector<ItemTrackerData> item_list_; // Lista con todos los objetos recogidos 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 // 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> loadRoomTileFile(const std::string& file_path, bool verbose) {
std::vector<int> tileMapFile; std::vector<int> tile_map_file;
const std::string filename = file_path.substr(file_path.find_last_of("\\/") + 1); const std::string FILENAME = file_path.substr(file_path.find_last_of("\\/") + 1);
std::ifstream file(file_path); std::ifstream file(file_path);
// El fichero se puede abrir // 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::stringstream ss(line);
std::string tmp; std::string tmp;
while (getline(ss, 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 // Lee la siguiente linea
@@ -46,18 +46,18 @@ std::vector<int> loadRoomTileFile(const std::string& file_path, bool verbose) {
// Cierra el fichero // Cierra el fichero
if (verbose) { if (verbose) {
std::cout << "TileMap loaded: " << filename.c_str() << std::endl; std::cout << "TileMap loaded: " << FILENAME.c_str() << std::endl;
} }
file.close(); file.close();
} }
else { // El fichero no se puede abrir else { // El fichero no se puede abrir
if (verbose) { 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 // 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.item_color2 = "magenta";
room.conveyor_belt_direction = 1; room.conveyor_belt_direction = 1;
const std::string fileName = file_path.substr(file_path.find_last_of("\\/") + 1); const std::string FILE_NAME = file_path.substr(file_path.find_last_of("\\/") + 1);
room.number = fileName.substr(0, fileName.find_last_of(".")); room.number = FILE_NAME.substr(0, FILE_NAME.find_last_of("."));
std::ifstream file(file_path); std::ifstream file(file_path);
@@ -93,10 +93,11 @@ RoomData loadRoomFile(const std::string& file_path, bool verbose) {
// Procesa las dos subcadenas // Procesa las dos subcadenas
std::string key = line.substr(0, pos); std::string key = line.substr(0, pos);
std::string value = line.substr(pos + 1, line.length()); std::string value = line.substr(pos + 1, line.length());
if (!setEnemy(&enemy, key, value)) if (!setEnemy(&enemy, key, value)) {
if (verbose) { 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]"); } while (line != "[/enemy]");
// Añade el enemigo al vector de enemigos // 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()); std::string value = line.substr(pos + 1, line.length());
if (!setItem(&item, key, value)) { if (!setItem(&item, key, value)) {
if (verbose) { 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()); std::string value = line.substr(pos + 1, line.length());
if (!setRoom(&room, key, value)) { if (!setRoom(&room, key, value)) {
if (verbose) { 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 // Cierra el fichero
if (verbose) { if (verbose) {
std::cout << "Room loaded: " << fileName.c_str() << std::endl; std::cout << "Room loaded: " << FILE_NAME.c_str() << std::endl;
} }
file.close(); file.close();
} }
// El fichero no se puede abrir // El fichero no se puede abrir
else { 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; room->right_room = value;
} else if (key == "autoSurface") { } else if (key == "autoSurface") {
room->conveyor_belt_direction = (value == "right") ? 1 : -1; 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 // No se realiza ninguna acción para estas claves
} else { } else {
success = false; success = false;
@@ -327,56 +328,57 @@ void Room::initializeRoom(const RoomData& room) {
conveyor_belt_direction_ = room.conveyor_belt_direction; conveyor_belt_direction_ = room.conveyor_belt_direction;
tile_map_ = Resource::get()->getTileMap(room.tile_map_file); tile_map_ = Resource::get()->getTileMap(room.tile_map_file);
surface_ = Resource::get()->getSurface(room.tile_set_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; is_paused_ = false;
counter_ = 0; counter_ = 0;
// Crear los enemigos // 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)); enemies_.emplace_back(std::make_shared<Enemy>(enemy_data));
} }
// Crear los items // Crear los items
for (const auto& item : room.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 // Crear una copia local de los datos del item
ItemData itemCopy = item; ItemData item_copy = item;
itemCopy.color1 = stringToColor(item_color1_); item_copy.color1 = stringToColor(item_color1_);
itemCopy.color2 = stringToColor(item_color2_); item_copy.color2 = stringToColor(item_color2_);
// Crear el objeto Item usando la copia modificada // 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 // Crea la textura con el mapeado de la habitación
void Room::fillMapTexture() { void Room::fillMapTexture() {
const Uint8 color = stringToColor(bg_color_); const Uint8 COLOR = stringToColor(bg_color_);
auto previuos_renderer = Screen::get()->getRendererSurface(); auto previuos_renderer = Screen::get()->getRendererSurface();
Screen::get()->setRendererSurface(map_surface_); 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 // 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_}; SDL_FRect clip = {0, 0, TILE_SIZE, TILE_SIZE};
for (int y = 0; y < MAP_HEIGHT_; ++y) for (int y = 0; y < MAP_HEIGHT; ++y) {
for (int x = 0; x < MAP_WIDTH_; ++x) { 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. // 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 // 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) // 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 A = (tile_map_[INDEX] >= 18 * tile_set_width_) && (tile_map_[INDEX] < 19 * tile_set_width_);
const bool B = tile_map_[INDEX] > -1; const bool B = tile_map_[INDEX] > -1;
if (B && !A) { if (B && !A) {
clip.x = (tile_map_[INDEX] % tile_set_width_) * TILE_SIZE_; clip.x = (tile_map_[INDEX] % tile_set_width_) * TILE_SIZE;
clip.y = (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); surface_->render(x * TILE_SIZE, y * TILE_SIZE, &clip);
} }
} }
}
#ifdef _DEBUG #ifdef _DEBUG
if (Debug::get()->getEnabled()) { if (Debug::get()->getEnabled()) {
@@ -517,23 +519,23 @@ std::string Room::getRoom(RoomBorder border) {
// Devuelve el tipo de tile que hay en ese pixel // Devuelve el tipo de tile que hay en ese pixel
TileType Room::getTile(SDL_FPoint point) { TileType Room::getTile(SDL_FPoint point) {
const int pos = ((point.y / TILE_SIZE_) * MAP_WIDTH_) + (point.x / TILE_SIZE_); const int POS = ((point.y / TILE_SIZE) * MAP_WIDTH) + (point.x / TILE_SIZE);
return getTile(pos); return getTile(POS);
} }
// Devuelve el tipo de tile que hay en ese indice // Devuelve el tipo de tile que hay en ese indice
TileType Room::getTile(int index) { TileType Room::getTile(int index) {
// const bool onRange = (index > -1) && (index < mapWidth * mapHeight); // 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 // Las filas 0-8 son de tiles t_wall
if ((tile_map_[index] >= 0) && (tile_map_[index] < 9 * tile_set_width_)) { if ((tile_map_[index] >= 0) && (tile_map_[index] < 9 * tile_set_width_)) {
return TileType::WALL; return TileType::WALL;
} }
// Las filas 9-17 son de tiles t_passable // 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; 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 // Obten la coordenada de la cuesta a partir de un punto perteneciente a ese tile
int Room::getSlopeHeight(SDL_FPoint p, TileType slope) { int Room::getSlopeHeight(SDL_FPoint p, TileType slope) {
// Calcula la base del tile // 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 #ifdef _DEBUG
Debug::get()->add("BASE = " + std::to_string(base)); Debug::get()->add("BASE = " + std::to_string(base));
#endif #endif
// Calcula cuanto se ha entrado en el tile horizontalmente // 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 #ifdef _DEBUG
Debug::get()->add("POS = " + std::to_string(pos)); Debug::get()->add("POS = " + std::to_string(POS));
#endif #endif
// Se resta a la base la cantidad de pixeles pos en funcion de la rampa // Se resta a la base la cantidad de pixeles pos en funcion de la rampa
if (slope == TileType::SLOPE_R) { if (slope == TileType::SLOPE_R) {
base -= pos + 1; base -= POS + 1;
#ifdef _DEBUG #ifdef _DEBUG
Debug::get()->add("BASE_R = " + std::to_string(base)); Debug::get()->add("BASE_R = " + std::to_string(base));
#endif #endif
} else { } else {
base -= (TILE_SIZE_ - pos); base -= (TILE_SIZE - POS);
#ifdef _DEBUG #ifdef _DEBUG
Debug::get()->add("BASE_L = " + std::to_string(base)); Debug::get()->add("BASE_L = " + std::to_string(base));
#endif #endif
@@ -623,12 +625,12 @@ void Room::setBottomSurfaces() {
// Busca todos los tiles de tipo muro que no tengan debajo otro muro // 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) // 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) { for (int i = 0; i < (int)tile_map_.size() - MAP_WIDTH; ++i) {
if (getTile(i) == TileType::WALL && getTile(i + MAP_WIDTH_) != TileType::WALL) { if (getTile(i) == TileType::WALL && getTile(i + MAP_WIDTH) != TileType::WALL) {
tile.push_back(i); tile.push_back(i);
// Si llega al final de la fila, introduce un separador // 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); tile.push_back(-1);
} }
} }
@@ -642,8 +644,8 @@ void Room::setBottomSurfaces() {
int i = 0; int i = 0;
do { do {
LineHorizontal line; LineHorizontal line;
line.x1 = (tile[i] % MAP_WIDTH_) * TILE_SIZE_; line.x1 = (tile[i] % MAP_WIDTH) * TILE_SIZE;
line.y = ((tile[i] / MAP_WIDTH_) * TILE_SIZE_) + TILE_SIZE_ - 1; line.y = ((tile[i] / MAP_WIDTH) * TILE_SIZE) + TILE_SIZE - 1;
int last_one = i; int last_one = i;
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); bottom_floors_.push_back(line);
if (i <= (int)tile.size() - 1) { if (i <= (int)tile.size() - 1) {
if (tile[i] == -1) { // Si el siguiente elemento es un separador, hay que saltarlo 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 // 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) // 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::WALL || getTile(i) == TileType::PASSABLE) && getTile(i - MAP_WIDTH_) != TileType::WALL) { if ((getTile(i) == TileType::WALL || getTile(i) == TileType::PASSABLE) && getTile(i - MAP_WIDTH) != TileType::WALL) {
tile.push_back(i); tile.push_back(i);
// Si llega al final de la fila, introduce un separador // 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); tile.push_back(-1);
} }
} }
@@ -693,8 +695,8 @@ void Room::setTopSurfaces() {
int i = 0; int i = 0;
do { do {
LineHorizontal line; LineHorizontal line;
line.x1 = (tile[i] % MAP_WIDTH_) * TILE_SIZE_; line.x1 = (tile[i] % MAP_WIDTH) * TILE_SIZE;
line.y = (tile[i] / MAP_WIDTH_) * TILE_SIZE_; line.y = (tile[i] / MAP_WIDTH) * TILE_SIZE;
int last_one = i; int last_one = i;
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); top_floors_.push_back(line);
if (i <= (int)tile.size() - 1) { if (i <= (int)tile.size() - 1) {
if (tile[i] == -1) { // Si el siguiente elemento es un separador, hay que saltarlo 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 // 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) // Hay que recorrer la habitación por columnas (excepto los de la primera columna)
for (int i = 1; i < MAP_WIDTH_; ++i) { for (int i = 1; i < MAP_WIDTH; ++i) {
for (int j = 0; j < MAP_HEIGHT_; ++j) { for (int j = 0; j < MAP_HEIGHT; ++j) {
const int pos = (j * MAP_WIDTH_ + i); const int POS = ((j * MAP_WIDTH) + i);
if (getTile(pos) == TileType::WALL && getTile(pos - 1) != TileType::WALL) { if (getTile(POS) == TileType::WALL && getTile(POS - 1) != TileType::WALL) {
tile.push_back(pos); tile.push_back(POS);
} }
} }
} }
@@ -744,15 +746,15 @@ void Room::setLeftSurfaces() {
int i = 0; int i = 0;
do { do {
LineVertical line; LineVertical line;
line.x = (tile[i] % MAP_WIDTH_) * TILE_SIZE_; line.x = (tile[i] % MAP_WIDTH) * TILE_SIZE;
line.y1 = ((tile[i] / MAP_WIDTH_) * TILE_SIZE_); line.y1 = ((tile[i] / MAP_WIDTH) * TILE_SIZE);
while (tile[i] + MAP_WIDTH_ == tile[i + 1]) { while (tile[i] + MAP_WIDTH == tile[i + 1]) {
if (i == (int)tile.size() - 1) { if (i == (int)tile.size() - 1) {
break; break;
} }
i++; 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); left_walls_.push_back(line);
i++; i++;
} while (i < (int)tile.size() - 1); } 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 // 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) // 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 i = 0; i < MAP_WIDTH - 1; ++i) {
for (int j = 0; j < MAP_HEIGHT_; ++j) { for (int j = 0; j < MAP_HEIGHT; ++j) {
const int pos = (j * MAP_WIDTH_ + i); const int POS = ((j * MAP_WIDTH) + i);
if (getTile(pos) == TileType::WALL && getTile(pos + 1) != TileType::WALL) { if (getTile(POS) == TileType::WALL && getTile(POS + 1) != TileType::WALL) {
tile.push_back(pos); tile.push_back(POS);
} }
} }
} }
@@ -784,15 +786,15 @@ void Room::setRightSurfaces() {
int i = 0; int i = 0;
do { do {
LineVertical line; LineVertical line;
line.x = ((tile[i] % MAP_WIDTH_) * TILE_SIZE_) + TILE_SIZE_ - 1; line.x = ((tile[i] % MAP_WIDTH) * TILE_SIZE) + TILE_SIZE - 1;
line.y1 = ((tile[i] / MAP_WIDTH_) * TILE_SIZE_); line.y1 = ((tile[i] / MAP_WIDTH) * TILE_SIZE);
while (tile[i] + MAP_WIDTH_ == tile[i + 1]) { while (tile[i] + MAP_WIDTH == tile[i + 1]) {
if (i == (int)tile.size() - 1) { if (i == (int)tile.size() - 1) {
break; break;
} }
i++; 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); right_walls_.push_back(line);
i++; i++;
} while (i < (int)tile.size() - 1); } 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 // 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 // tiles encontrados hasta que esté vacío
while (found.size() > 0) { while (!found.empty()) {
LineDiagonal line; LineDiagonal line;
line.x1 = (found[0] % MAP_WIDTH_) * TILE_SIZE_; line.x1 = (found[0] % MAP_WIDTH) * TILE_SIZE;
line.y1 = (found[0] / MAP_WIDTH_) * TILE_SIZE_; line.y1 = (found[0] / MAP_WIDTH) * TILE_SIZE;
int lookingFor = found[0] + MAP_WIDTH_ + 1; int looking_for = found[0] + MAP_WIDTH + 1;
int lastOneFound = found[0]; int last_one_found = found[0];
found.erase(found.begin()); found.erase(found.begin());
for (int i = 0; i < (int)found.size(); ++i) { for (int i = 0; i < (int)found.size(); ++i) {
if (found[i] == lookingFor) { if (found[i] == looking_for) {
lastOneFound = lookingFor; last_one_found = looking_for;
lookingFor += MAP_WIDTH_ + 1; looking_for += MAP_WIDTH + 1;
found.erase(found.begin() + i); found.erase(found.begin() + i);
i--; i--;
} }
} }
line.x2 = ((lastOneFound % MAP_WIDTH_) * TILE_SIZE_) + TILE_SIZE_ - 1; line.x2 = ((last_one_found % MAP_WIDTH) * TILE_SIZE) + TILE_SIZE - 1;
line.y2 = ((lastOneFound / MAP_WIDTH_) * TILE_SIZE_) + TILE_SIZE_ - 1; line.y2 = ((last_one_found / MAP_WIDTH) * TILE_SIZE) + TILE_SIZE - 1;
left_slopes_.push_back(line); 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 // 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 // tiles encontrados hasta que esté vacío
while (found.size() > 0) { while (!found.empty()) {
LineDiagonal line; LineDiagonal line;
line.x1 = ((found[0] % MAP_WIDTH_) * TILE_SIZE_) + TILE_SIZE_ - 1; line.x1 = ((found[0] % MAP_WIDTH) * TILE_SIZE) + TILE_SIZE - 1;
line.y1 = (found[0] / MAP_WIDTH_) * TILE_SIZE_; line.y1 = (found[0] / MAP_WIDTH) * TILE_SIZE;
int lookingFor = found[0] + MAP_WIDTH_ - 1; int looking_for = found[0] + MAP_WIDTH - 1;
int lastOneFound = found[0]; int last_one_found = found[0];
found.erase(found.begin()); found.erase(found.begin());
for (int i = 0; i < (int)found.size(); ++i) { for (int i = 0; i < (int)found.size(); ++i) {
if (found[i] == lookingFor) { if (found[i] == looking_for) {
lastOneFound = lookingFor; last_one_found = looking_for;
lookingFor += MAP_WIDTH_ - 1; looking_for += MAP_WIDTH - 1;
found.erase(found.begin() + i); found.erase(found.begin() + i);
i--; i--;
} }
} }
line.x2 = (lastOneFound % MAP_WIDTH_) * TILE_SIZE_; line.x2 = (last_one_found % MAP_WIDTH) * TILE_SIZE;
line.y2 = ((lastOneFound / MAP_WIDTH_) * TILE_SIZE_) + TILE_SIZE_ - 1; line.y2 = ((last_one_found / MAP_WIDTH) * TILE_SIZE) + TILE_SIZE - 1;
right_slopes_.push_back(line); right_slopes_.push_back(line);
} }
} }
@@ -875,12 +877,12 @@ void Room::setAutoSurfaces() {
// Busca todos los tiles de tipo animado // Busca todos los tiles de tipo animado
// Hay que recorrer la habitación por filas (excepto los de la primera fila) // 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) { if (getTile(i) == TileType::ANIMATED) {
tile.push_back(i); tile.push_back(i);
// Si llega al final de la fila, introduce un separador // 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); tile.push_back(-1);
} }
} }
@@ -891,8 +893,8 @@ void Room::setAutoSurfaces() {
int i = 0; int i = 0;
do { do {
LineHorizontal line; LineHorizontal line;
line.x1 = (tile[i] % MAP_WIDTH_) * TILE_SIZE_; line.x1 = (tile[i] % MAP_WIDTH) * TILE_SIZE;
line.y = (tile[i] / MAP_WIDTH_) * TILE_SIZE_; line.y = (tile[i] / MAP_WIDTH) * TILE_SIZE;
int last_one = i; int last_one = i;
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); conveyor_belt_floors_.push_back(line);
if (i <= (int)tile.size() - 1) { if (i <= (int)tile.size() - 1) {
if (tile[i] == -1) { // Si el siguiente elemento es un separador, hay que saltarlo 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) { for (int i = 0; i < (int)tile_map_.size(); ++i) {
if (getTile(i) == TileType::ANIMATED) { if (getTile(i) == TileType::ANIMATED) {
// La i es la ubicación // La i es la ubicación
const int x = (i % MAP_WIDTH_) * TILE_SIZE_; const int X = (i % MAP_WIDTH) * TILE_SIZE;
const int y = (i / MAP_WIDTH_) * TILE_SIZE_; const int Y = (i / MAP_WIDTH) * TILE_SIZE;
// TileMap[i] es el tile a poner // TileMap[i] es el tile a poner
const int xc = (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_; const int YC = (tile_map_[i] / tile_set_width_) * TILE_SIZE;
AnimatedTile at; AnimatedTile at;
at.sprite = std::make_shared<SurfaceSprite>(surface_, x, y, 8, 8); at.sprite = std::make_shared<SurfaceSprite>(surface_, X, Y, 8, 8);
at.sprite->setClip(xc, yc, 8, 8); at.sprite->setClip(XC, YC, 8, 8);
at.x_orig = xc; at.x_orig = XC;
animated_tiles_.push_back(at); animated_tiles_.push_back(at);
} }
} }
@@ -941,12 +943,12 @@ void Room::setAnimatedTiles() {
// Actualiza los tiles animados // Actualiza los tiles animados
void Room::updateAnimatedTiles() { void Room::updateAnimatedTiles() {
const int numFrames = 4; const int NUM_FRAMES = 4;
int offset = 0; int offset = 0;
if (conveyor_belt_direction_ == -1) { if (conveyor_belt_direction_ == -1) {
offset = ((counter_ / 3) % numFrames * TILE_SIZE_); offset = ((counter_ / 3) % NUM_FRAMES * TILE_SIZE);
} else { } else {
offset = ((numFrames - 1 - ((counter_ / 3) % numFrames)) * TILE_SIZE_); offset = ((NUM_FRAMES - 1 - ((counter_ / 3) % NUM_FRAMES)) * TILE_SIZE);
} }
for (auto& a : animated_tiles_) { for (auto& a : animated_tiles_) {
@@ -1043,9 +1045,9 @@ bool Room::checkAutoSurfaces(SDL_FPoint* p) {
// Comprueba las colisiones // Comprueba las colisiones
int Room::checkLeftSlopes(const LineVertical* line) { int Room::checkLeftSlopes(const LineVertical* line) {
for (const auto& slope : left_slopes_) { for (const auto& slope : left_slopes_) {
const auto p = checkCollision(slope, *line); const auto P = checkCollision(slope, *line);
if (p.x != -1) { if (P.x != -1) {
return p.y; return P.y;
} }
} }
@@ -1066,9 +1068,9 @@ bool Room::checkLeftSlopes(SDL_FPoint* p) {
// Comprueba las colisiones // Comprueba las colisiones
int Room::checkRightSlopes(const LineVertical* line) { int Room::checkRightSlopes(const LineVertical* line) {
for (const auto& slope : right_slopes_) { for (const auto& slope : right_slopes_) {
const auto p = checkCollision(slope, *line); const auto P = checkCollision(slope, *line);
if (p.x != -1) { if (P.x != -1) {
return p.y; return P.y;
} }
} }

View File

@@ -72,9 +72,9 @@ bool setItem(ItemData* item, const std::string& key, const std::string& value);
class Room { class Room {
private: private:
// Constantes // Constantes
static constexpr int TILE_SIZE_ = 8; // Ancho del tile en pixels 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_WIDTH = 32; // Ancho del mapa en tiles
static constexpr int MAP_HEIGHT_ = 16; // Alto del mapa en tiles static constexpr int MAP_HEIGHT = 16; // Alto del mapa en tiles
// Objetos y punteros // Objetos y punteros
std::vector<std::shared_ptr<Enemy>> enemies_; // Listado con los enemigos de la habitación 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); bool itemCollision(SDL_FRect& rect);
// Obten el tamaño del tile // 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 // 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 // Comprueba las colisiones
int checkRightSurfaces(SDL_FRect* rect); int checkRightSurfaces(SDL_FRect* rect);

View File

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

View File

@@ -6,7 +6,7 @@
class RoomTracker { class RoomTracker {
private: private:
// Variables // 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 // Comprueba si la habitación ya ha sido visitada
bool hasBeenVisited(const std::string& name); bool hasBeenVisited(const std::string& name);

View File

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

View File

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

View File

@@ -17,20 +17,20 @@ class Stats {
}; };
// Variables // Variables
std::vector<StatsDictionary> dictionary; // Lista con la equivalencia nombre-numero de habitacion 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> buffer_list_; // Lista con las estadisticas temporales por habitación
std::vector<StatsData> list; // Lista con las estadisticas completas 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 buffer_path_; // Fichero con las estadísticas temporales
std::string filePath; // Fichero con las estadísticas completas std::string file_path_; // Fichero con las estadísticas completas
// Busca una entrada en la lista por nombre // 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 // 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 // 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 // Calcula cual es la habitación con más muertes
void checkWorstNightmare(); void checkWorstNightmare();

View File

@@ -33,7 +33,7 @@ bool loadFromFile(const std::string& file_path) {
bool success = true; bool success = true;
// Versión actual del fichero // Versión actual del fichero
const std::string configVersion = version; const std::string CONFIG_VERSION = version;
version = ""; version = "";
// Variables para manejar el fichero // 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 // Usa un stringstream para dividir la línea en dos partes
std::istringstream iss(line); std::istringstream iss(line);
std::string key, value; std::string key;
std::string value;
if (iss >> key >> value) { if (iss >> key >> value) {
if (!setOptions(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 // 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(); init();
saveToFile(file_path); saveToFile(file_path);
if (console) { if (console) {
@@ -155,7 +156,7 @@ bool saveToFile(const std::string& file_path) {
} }
bool setOptions(const std::string& var, const std::string& value) { 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; }}, {"version", [](const std::string& v) { version = v; }},
{"keys", [](const std::string& v) { {"keys", [](const std::string& v) {
int val = safeStoi(v, static_cast<int>(GameDefaults::CONTROL_SCHEME)); 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; video.palette = v;
}}}; }}};
auto it = optionHandlers.find(var); auto it = OPTION_HANDLERS.find(var);
if (it != optionHandlers.end()) { if (it != OPTION_HANDLERS.end()) {
it->second(value); it->second(value);
return true; return true;
} }

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -20,7 +20,7 @@
// Constructor // Constructor
Ending2::Ending2() 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::current = SceneManager::Scene::ENDING2;
SceneManager::options = SceneManager::Options::NONE; SceneManager::options = SceneManager::Options::NONE;
@@ -134,13 +134,13 @@ void Ending2::render() {
void Ending2::checkEvents() { void Ending2::checkEvents() {
SDL_Event event; SDL_Event event;
while (SDL_PollEvent(&event)) { while (SDL_PollEvent(&event)) {
globalEvents::check(event); GlobalEvents::check(event);
} }
} }
// Comprueba las entradas // Comprueba las entradas
void Ending2::checkInput() { void Ending2::checkInput() {
globalInputs::check(); GlobalInputs::check();
} }
// Bucle principal // Bucle principal
@@ -168,13 +168,13 @@ void Ending2::updateState() {
case EndingState::CREDITS: case EndingState::CREDITS:
if (texts_.back()->getPosY() <= GAMECANVAS_CENTER_Y) { 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; break;
case EndingState::POST_CREDITS: case EndingState::POST_CREDITS:
if (state_.hasEnded(EndingState::POST_CREDITS)) { if (state_.hasEnded(EndingState::POST_CREDITS)) {
state_.set(EndingState::FADING, STATE_FADE_DURATION_); state_.set(EndingState::FADING, STATE_FADE_DURATION);
} }
break; break;
@@ -344,15 +344,15 @@ void Ending2::renderTexts() {
// Coloca los sprites en su sito // Coloca los sprites en su sito
void Ending2::placeSprites() { void Ending2::placeSprites() {
for (int i = 0; i < static_cast<int>(sprites_.size()); ++i) { for (int i = 0; i < static_cast<int>(sprites_.size()); ++i) {
const float X = i % 2 == 0 ? FIRST_COL_ : SECOND_COL_; 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 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 W = sprites_.at(i)->getWidth();
const float H = sprites_.at(i)->getHeight(); const float H = sprites_.at(i)->getHeight();
const float DX = -(W / 2); const float DX = -(W / 2);
const float DY = sprite_max_height_ - H; const float DY = sprite_max_height_ - H;
sprites_.at(i)->setPos({X + DX, Y + DY, W, 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 // 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 // Determina la columna y la posición X del texto
const float X = (i == sprite_list_.size() - 1) const float X = (i == sprite_list_.size() - 1)
? (GAMECANVAS_CENTER_X - (W / 2)) ? (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 // 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 // Crea la surface
auto surface = std::make_shared<Surface>(W, H); auto surface = std::make_shared<Surface>(W, H);
@@ -396,7 +396,7 @@ void Ending2::createSpriteTexts() {
// Crea el sprite // Crea el sprite
SDL_FRect pos = {X, Y, W, H}; SDL_FRect pos = {X, Y, W, H};
sprite_texts_.emplace_back(std::make_shared<SurfaceMovingSprite>(surface, pos)); 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); Screen::get()->setRendererSurface(previuos_renderer);
} }
} }
@@ -427,7 +427,7 @@ void Ending2::createTexts() {
// Crea el sprite // Crea el sprite
SDL_FRect pos = {X + DX, Y, W, H}; SDL_FRect pos = {X + DX, Y, W, H};
texts_.emplace_back(std::make_shared<SurfaceMovingSprite>(surface, pos)); 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); Screen::get()->setRendererSurface(previuos_renderer);
} }
@@ -456,7 +456,7 @@ void Ending2::createTexts() {
// Crea el sprite // Crea el sprite
SDL_FRect pos = {X + DX, Y, W, H}; SDL_FRect pos = {X + DX, Y, W, H};
texts_.emplace_back(std::make_shared<SurfaceMovingSprite>(surface, pos)); 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); Screen::get()->setRendererSurface(previuos_renderer);
} }
} }

View File

@@ -27,15 +27,15 @@ class Ending2 {
Uint32 duration; // Duración en milisegundos para el estado actual Uint32 duration; // Duración en milisegundos para el estado actual
// Constructor parametrizado para inicializar la estructura // Constructor parametrizado para inicializar la estructura
State(EndingState initialState, Uint32 initialTicks, Uint32 stateDuration) State(EndingState initial_state, Uint32 initial_ticks, Uint32 state_duration)
: state(initialState), : state(initial_state),
init_ticks(initialTicks), init_ticks(initial_ticks),
duration(stateDuration) {} duration(state_duration) {}
// Método para comprobar si el estado ha terminado y verifica el nombre del estado // 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 // 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 return false; // Si no coincide, considerar que no ha terminado
} }
@@ -44,22 +44,22 @@ class Ending2 {
} }
// Método para establecer un nuevo estado // Método para establecer un nuevo estado
void set(EndingState newState, Uint32 newDuration) { void set(EndingState new_state, Uint32 new_duration) {
state = newState; // Actualizar el estado state = new_state; // Actualizar el estado
init_ticks = SDL_GetTicks(); // Reiniciar el tiempo de inicio init_ticks = SDL_GetTicks(); // Reiniciar el tiempo de inicio
duration = newDuration; // Actualizar la duración duration = new_duration; // Actualizar la duración
} }
}; };
// Constantes // Constantes
static constexpr int FIRST_COL_ = GAMECANVAS_FIRST_QUARTER_X + (GAMECANVAS_WIDTH / 16); // Primera columna por donde desfilan los sprites 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 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_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 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 float SPRITE_DESP_SPEED = -0.2F; // Velocidad de desplazamiento de los sprites
static constexpr int STATE_PRE_CREDITS_DURATION_ = 3000; static constexpr int STATE_PRE_CREDITS_DURATION = 3000;
static constexpr int STATE_POST_CREDITS_DURATION_ = 5000; static constexpr int STATE_POST_CREDITS_DURATION = 5000;
static constexpr int STATE_FADE_DURATION_ = 5000; static constexpr int STATE_FADE_DURATION = 5000;
// Objetos y punteros // Objetos y punteros
std::vector<std::shared_ptr<SurfaceAnimatedSprite>> sprites_; // Vector con todos los sprites a dibujar 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 // Crea objetos e inicializa variables
ItemTracker::init(); ItemTracker::init();
DEMO_init(); demoInit();
room_ = std::make_shared<Room>(current_room_, board_); room_ = std::make_shared<Room>(current_room_, board_);
initPlayer(spawn_point_, room_); initPlayer(spawn_point_, room_);
initStats(); initStats();
@@ -71,7 +71,7 @@ Game::~Game() {
void Game::checkEvents() { void Game::checkEvents() {
SDL_Event event; SDL_Event event;
while (SDL_PollEvent(&event)) { while (SDL_PollEvent(&event)) {
globalEvents::check(event); GlobalEvents::check(event);
#ifdef _DEBUG #ifdef _DEBUG
checkDebugEvents(event); checkDebugEvents(event);
#endif #endif
@@ -91,7 +91,7 @@ void Game::checkInput() {
Notifier::get()->show({std::string(paused_ ? "GAME PAUSED" : "GAME RUNNING")}, NotificationText::CENTER); Notifier::get()->show({std::string(paused_ ? "GAME PAUSED" : "GAME RUNNING")}, NotificationText::CENTER);
} }
globalInputs::check(); GlobalInputs::check();
} }
// Bucle para el juego // Bucle para el juego
@@ -139,7 +139,7 @@ void Game::update() {
checkRestoringJail(); checkRestoringJail();
checkSomeCheevos(); checkSomeCheevos();
} }
DEMO_checkRoomChange(); demoCheckRoomChange();
scoreboard_->update(); scoreboard_->update();
keepMusicPlaying(); keepMusicPlaying();
updateBlackScreen(); updateBlackScreen();
@@ -270,7 +270,7 @@ bool Game::changeRoom(const std::string& room_path) {
} }
// Verifica que exista el fichero que se va a cargar // 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 // Crea un objeto habitación nuevo a partir del fichero
room_ = std::make_shared<Room>(room_path, board_); 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 // Comprueba si el jugador esta en el borde de la pantalla
void Game::checkPlayerIsOnBorder() { void Game::checkPlayerIsOnBorder() {
if (player_->getOnBorder()) { if (player_->getOnBorder()) {
const std::string roomName = room_->getRoom(player_->getBorder()); const std::string ROOM_NAME = room_->getRoom(player_->getBorder());
if (changeRoom(roomName)) { if (changeRoom(ROOM_NAME)) {
player_->switchBorders(); player_->switchBorders();
spawn_point_ = player_->getSpawnParams(); spawn_point_ = player_->getSpawnParams();
} }
@@ -314,11 +314,11 @@ void Game::checkPlayerIsOnBorder() {
// Comprueba las colisiones del jugador con los enemigos // Comprueba las colisiones del jugador con los enemigos
bool Game::checkPlayerAndEnemies() { bool Game::checkPlayerAndEnemies() {
const bool death = room_->enemyCollision(player_->getCollider()); const bool DEATH = room_->enemyCollision(player_->getCollider());
if (death) { if (DEATH) {
killPlayer(); killPlayer();
} }
return death; return DEATH;
} }
// Comprueba las colisiones del jugador con los objetos // Comprueba las colisiones del jugador con los objetos
@@ -393,12 +393,12 @@ void Game::updateBlackScreen() {
} }
// Dibuja la pantalla negra // Dibuja la pantalla negra
void Game::renderBlackScreen() { void Game::renderBlackScreen() const {
if (black_screen_) { if (black_screen_) {
auto const color = static_cast<Uint8>(PaletteColor::BLACK); auto const COLOR = static_cast<Uint8>(PaletteColor::BLACK);
Screen::get()->setRendererSurface(); Screen::get()->setRendererSurface();
Screen::get()->clearSurface(color); Screen::get()->clearSurface(COLOR);
Screen::get()->setBorderColor(color); Screen::get()->setBorderColor(COLOR);
} }
} }
@@ -416,15 +416,15 @@ void Game::setScoreBoardColor() {
// Comprueba si ha finalizado el juego // Comprueba si ha finalizado el juego
bool Game::checkEndGame() { bool Game::checkEndGame() {
const bool isOnTheRoom = room_->getName() == "THE JAIL"; // Estar en la habitación que toca const bool IS_ON_THE_ROOM = 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 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 isOnTheDoor = player_->getRect().x <= 128; // Y en la ubicación que toca (En la puerta) 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; 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 // Comprueba los logros de completar el juego
checkEndGameCheevos(); checkEndGameCheevos();
@@ -462,21 +462,21 @@ void Game::checkRestoringJail() {
return; return;
} }
static int counter = 0; static int counter_ = 0;
if (!paused_) { if (!paused_) {
counter++; counter_++;
} }
// Incrementa el numero de vidas // Incrementa el numero de vidas
if (counter == 100) { if (counter_ == 100) {
counter = 0; counter_ = 0;
board_->lives++; board_->lives++;
JA_PlaySound(Resource::get()->getSound("death.wav")); JA_PlaySound(Resource::get()->getSound("death.wav"));
// Invalida el logro de completar el juego sin entrar a la jail // Invalida el logro de completar el juego sin entrar a la jail
const bool haveTheItems = board_->items >= int(total_items_ * 0.9f); const bool HAVE_THE_ITEMS = board_->items >= int(total_items_ * 0.9F);
if (!haveTheItems) { if (!HAVE_THE_ITEMS) {
Cheevos::get()->setUnobtainable(9); Cheevos::get()->setUnobtainable(9);
} }
} }
@@ -512,7 +512,7 @@ void Game::fillRoomNameTexture() {
// Comprueba algunos logros // Comprueba algunos logros
void Game::checkSomeCheevos() { void Game::checkSomeCheevos() {
auto cheevos = Cheevos::get(); auto* cheevos = Cheevos::get();
// Logros sobre la cantidad de items // Logros sobre la cantidad de items
if (board_->items == total_items_) { if (board_->items == total_items_) {
@@ -520,14 +520,14 @@ void Game::checkSomeCheevos() {
cheevos->unlock(3); cheevos->unlock(3);
cheevos->unlock(2); cheevos->unlock(2);
cheevos->unlock(1); cheevos->unlock(1);
} else if (board_->items >= total_items_ * 0.75f) { } else if (board_->items >= total_items_ * 0.75F) {
cheevos->unlock(3); cheevos->unlock(3);
cheevos->unlock(2); cheevos->unlock(2);
cheevos->unlock(1); cheevos->unlock(1);
} else if (board_->items >= total_items_ * 0.5f) { } else if (board_->items >= total_items_ * 0.5F) {
cheevos->unlock(2); cheevos->unlock(2);
cheevos->unlock(1); cheevos->unlock(1);
} else if (board_->items >= total_items_ * 0.25f) { } else if (board_->items >= total_items_ * 0.25F) {
cheevos->unlock(1); cheevos->unlock(1);
} }
@@ -546,7 +546,7 @@ void Game::checkSomeCheevos() {
// Comprueba los logros de completar el juego // Comprueba los logros de completar el juego
void Game::checkEndGameCheevos() { void Game::checkEndGameCheevos() {
auto cheevos = Cheevos::get(); auto* cheevos = Cheevos::get();
// "Complete the game" // "Complete the game"
cheevos->unlock(8); cheevos->unlock(8);
@@ -572,8 +572,8 @@ void Game::checkEndGameCheevos() {
void Game::initPlayer(const PlayerSpawn& spawn_point, std::shared_ptr<Room> room) { 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_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"; 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); const PlayerData PLAYER(spawn_point, player_texture, player_animations, room);
player_ = std::make_shared<Player>(player); player_ = std::make_shared<Player>(PLAYER);
} }
// Crea la textura para poner el nombre de la habitación // Crea la textura para poner el nombre de la habitación
@@ -587,16 +587,16 @@ void Game::createRoomNameTexture() {
// Hace sonar la música // Hace sonar la música
void Game::keepMusicPlaying() { 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 // Si la música no está sonando
if (JA_GetMusicState() == JA_MUSIC_INVALID || JA_GetMusicState() == JA_MUSIC_STOPPED) { 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 // DEMO MODE: Inicializa las variables para el modo demo
void Game::DEMO_init() { void Game::demoInit() {
if (mode_ == GameMode::DEMO) { 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"}); 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(); current_room_ = demo_.rooms.front();
@@ -604,7 +604,7 @@ void Game::DEMO_init() {
} }
// DEMO MODE: Comprueba si se ha de cambiar de habitación // DEMO MODE: Comprueba si se ha de cambiar de habitación
void Game::DEMO_checkRoomChange() { void Game::demoCheckRoomChange() {
if (mode_ == GameMode::DEMO) { if (mode_ == GameMode::DEMO) {
demo_.counter++; demo_.counter++;
if (demo_.counter == demo_.room_time) { if (demo_.counter == demo_.room_time) {

View File

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

View File

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

View File

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

View File

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

View File

@@ -38,14 +38,14 @@ class LoadingScreen {
private: private:
// --- Constantes de tiempo (en segundos) --- // --- Constantes de tiempo (en segundos) ---
static constexpr float SILENT1_DURATION = 1.0f; // Pausa inicial static constexpr float SILENT1_DURATION = 1.0F; // Pausa inicial
static constexpr float HEADER1_DURATION = 2.0f; // Cabecera static constexpr float HEADER1_DURATION = 2.0F; // Cabecera
static constexpr float BYTES1_DURATION = 0.5f; // Datos static constexpr float BYTES1_DURATION = 0.5F; // Datos
static constexpr float SILENT2_DURATION = 2.0f; // Segunda pausa static constexpr float SILENT2_DURATION = 2.0F; // Segunda pausa
static constexpr float HEADER2_DURATION = 2.0f; // Cabecera pantalla 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_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 LOADING_COLOR_DURATION = 4.0F; // Duración total de la carga en color
static constexpr float BYTES2_DURATION = 2.0f; // Datos static constexpr float BYTES2_DURATION = 2.0F; // Datos
// --- Constantes de geometría --- // --- Constantes de geometría ---
static constexpr int MONO_TOTAL_LINES = 192; // Total de líneas en carga monocromática static constexpr int MONO_TOTAL_LINES = 192; // Total de líneas en carga monocromática
@@ -74,15 +74,15 @@ class LoadingScreen {
// --- Funciones --- // --- Funciones ---
void update(); // Actualiza las variables void update(); // Actualiza las variables
void render(); // Dibuja en pantalla void render(); // Dibuja en pantalla
void checkEvents(); // Comprueba el manejador de eventos static void checkEvents(); // Comprueba el manejador de eventos
void checkInput(); // Comprueba las entradas static void checkInput(); // Comprueba las entradas
void updateState(float delta_time); // Actualiza el estado actual void updateState(float delta_time); // Actualiza el estado actual
void transitionToState(LoadingState new_state); // Transiciona a un nuevo estado void transitionToState(LoadingState new_state); // Transiciona a un nuevo estado
void updateMonoLoad(float delta_time); // Gestiona la carga monocromática (time-based) 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 updateColorLoad(float delta_time); // Gestiona la carga en color (time-based)
void renderBorder(); // Pinta el borde void renderBorder(); // Pinta el borde
void renderYellowBorder(); // Dibuja el efecto de carga amarillo y azul en el borde static 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 static void renderRedBorder(); // Dibuja el efecto de carga rojo y azul en el borde
void renderWhiteBorder(); // Dibuja el borde de color blanco static void renderWhiteBorder(); // Dibuja el borde de color blanco
void initLineIndexArray(); // Inicializa el array de índices de líneas 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())), 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>()), delta_timer_(std::make_unique<DeltaTimer>()),
state_(LogoState::INITIAL), state_(LogoState::INITIAL),
state_time_(0.0f) { state_time_(0.0F) {
// Configura variables // Configura variables
since_1998_sprite_->setClip(0, 0, since_1998_surface_->getWidth(), since_1998_surface_->getHeight()); since_1998_sprite_->setClip(0, 0, since_1998_surface_->getWidth(), since_1998_surface_->getHeight());
since_1998_color_ = static_cast<Uint8>(PaletteColor::BLACK); since_1998_color_ = static_cast<Uint8>(PaletteColor::BLACK);
@@ -42,13 +42,13 @@ Logo::Logo()
void Logo::checkEvents() { void Logo::checkEvents() {
SDL_Event event; SDL_Event event;
while (SDL_PollEvent(&event)) { while (SDL_PollEvent(&event)) {
globalEvents::check(event); GlobalEvents::check(event);
} }
} }
// Comprueba las entradas // Comprueba las entradas
void Logo::checkInput() { void Logo::checkInput() {
globalInputs::check(); GlobalInputs::check();
} }
// Gestiona el logo de JAILGAME (time-based) // 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 // 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 // Actualizar cada línea del sprite JAILGAMES
for (size_t i = 1; i < jailgames_sprite_.size(); ++i) { 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 // Las líneas pares se mueven desde la derecha, las impares desde la izquierda
if (i % 2 == 0) { if (i % 2 == 0) {
// Mover hacia la izquierda // Mover hacia la izquierda
if (current_x > JAILGAMES_DEST_X) { if (CURRENT_X > JAILGAMES_DEST_X) {
const int new_x = static_cast<int>(current_x - displacement); const int NEW_X = static_cast<int>(CURRENT_X - DISPLACEMENT);
jailgames_sprite_[i]->setX(new_x < JAILGAMES_DEST_X ? JAILGAMES_DEST_X : new_x); jailgames_sprite_[i]->setX(NEW_X < JAILGAMES_DEST_X ? JAILGAMES_DEST_X : NEW_X);
} }
} else { } else {
// Mover hacia la derecha // Mover hacia la derecha
if (current_x < JAILGAMES_DEST_X) { if (CURRENT_X < JAILGAMES_DEST_X) {
const int new_x = static_cast<int>(current_x + displacement); const int NEW_X = static_cast<int>(CURRENT_X + DISPLACEMENT);
jailgames_sprite_[i]->setX(new_x > JAILGAMES_DEST_X ? JAILGAMES_DEST_X : new_x); 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) // Calcula el índice de color según el progreso (0.0-1.0)
int Logo::getColorIndex(float progress) const { int Logo::getColorIndex(float progress) const {
// Asegurar que progress esté en el rango [0.0, 1.0] // 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) // Mapear el progreso al índice de color (0-7)
const int max_index = static_cast<int>(color_.size()) - 1; const int MAX_INDEX = static_cast<int>(color_.size()) - 1;
const int index = static_cast<int>(progress * max_index); const int INDEX = static_cast<int>(progress * MAX_INDEX);
return index; return INDEX;
} }
// Gestiona el color de las texturas // Gestiona el color de las texturas
@@ -99,8 +99,8 @@ void Logo::updateTextureColors() {
switch (state_) { switch (state_) {
case LogoState::SINCE_1998_FADE_IN: { case LogoState::SINCE_1998_FADE_IN: {
// Fade-in de "Since 1998" de negro a blanco // Fade-in de "Since 1998" de negro a blanco
const float progress = state_time_ / SINCE_1998_FADE_DURATION; const float PROGRESS = state_time_ / SINCE_1998_FADE_DURATION;
since_1998_color_ = color_[getColorIndex(progress)]; since_1998_color_ = color_[getColorIndex(PROGRESS)];
break; break;
} }
@@ -113,10 +113,10 @@ void Logo::updateTextureColors() {
case LogoState::FADE_OUT: { case LogoState::FADE_OUT: {
// Fade-out de ambos logos de blanco a negro // Fade-out de ambos logos de blanco a negro
const float progress = 1.0f - (state_time_ / FADE_OUT_DURATION); const float PROGRESS = 1.0F - (state_time_ / FADE_OUT_DURATION);
const int color_index = getColorIndex(progress); const int COLOR_INDEX = getColorIndex(PROGRESS);
jailgames_color_ = color_[color_index]; jailgames_color_ = color_[COLOR_INDEX];
since_1998_color_ = color_[color_index]; since_1998_color_ = color_[COLOR_INDEX];
break; break;
} }
@@ -129,7 +129,7 @@ void Logo::updateTextureColors() {
// Transiciona a un nuevo estado // Transiciona a un nuevo estado
void Logo::transitionToState(LogoState new_state) { void Logo::transitionToState(LogoState new_state) {
state_ = new_state; state_ = new_state;
state_time_ = 0.0f; state_time_ = 0.0F;
} }
// Actualiza el estado actual // Actualiza el estado actual
@@ -178,11 +178,11 @@ void Logo::updateState(float delta_time) {
// Actualiza las variables // Actualiza las variables
void Logo::update() { void Logo::update() {
// Obtener delta time desde el último frame // 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 checkInput(); // Comprueba las entradas
updateState(delta_time); // Actualiza el estado y gestiona transiciones updateState(DELTA_TIME); // Actualiza el estado y gestiona transiciones
updateJAILGAMES(delta_time); // Gestiona el logo de JAILGAME updateJAILGAMES(DELTA_TIME); // Gestiona el logo de JAILGAME
updateTextureColors(); // Gestiona el color de las texturas updateTextureColors(); // Gestiona el color de las texturas
Screen::get()->update(); // Actualiza el objeto Screen Screen::get()->update(); // Actualiza el objeto Screen
} }

View File

@@ -27,14 +27,14 @@ class Logo {
private: private:
// --- Constantes de tiempo (en segundos) --- // --- Constantes de tiempo (en segundos) ---
static constexpr float INITIAL_DELAY = 0.5f; // Tiempo antes de que empiece la animación 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 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 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 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 FADE_OUT_DURATION = 0.5F; // Duración del fade-out final
// --- Constantes de animación --- // --- 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 static constexpr int JAILGAMES_DEST_X = 37; // Posición X de destino para JAILGAMES
// --- Objetos y punteros --- // --- Objetos y punteros ---
@@ -54,14 +54,14 @@ class Logo {
// --- Funciones --- // --- Funciones ---
void update(); // Actualiza las variables void update(); // Actualiza las variables
void render(); // Dibuja en pantalla void render(); // Dibuja en pantalla
void checkEvents(); // Comprueba el manejador de eventos static void checkEvents(); // Comprueba el manejador de eventos
void checkInput(); // Comprueba las entradas static void checkInput(); // Comprueba las entradas
void updateJAILGAMES(float delta_time); // Gestiona el logo de JAILGAME (time-based) void updateJAILGAMES(float delta_time); // Gestiona el logo de JAILGAME (time-based)
void updateTextureColors(); // Gestiona el color de las texturas void updateTextureColors(); // Gestiona el color de las texturas
void updateState(float delta_time); // Actualiza el estado actual void updateState(float delta_time); // Actualiza el estado actual
void transitionToState(LogoState new_state); // Transiciona a un nuevo estado 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) 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 initColors(); // Inicializa el vector de colores
void initSprites(); // Crea los sprites de cada linea void initSprites(); // Crea los sprites de cada linea
}; };

View File

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

View File

@@ -27,17 +27,17 @@ class Title {
}; };
// --- Constantes de tiempo (en segundos) --- // --- Constantes de tiempo (en segundos) ---
static constexpr float SHOW_LOADING_DURATION = 5.0f; // Tiempo mostrando loading screen (antes 500 frames) 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 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 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 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 CHEEVOS_SCROLL_SPEED = 120.0F; // Velocidad de scroll de logros (pixels/segundo)
// --- Constantes de marquesina --- // --- Constantes de marquesina ---
static constexpr float MARQUEE_START_X = 256.0f; // Posición inicial (ancho pantalla) 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_EXIT_X = -10.0F; // Cuando desaparece de pantalla
static constexpr float MARQUEE_Y = 184.0f; // Posición Y 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_LETTER_SPACING = 1.0F; // Espaciado entre letras
// Objetos y punteros // Objetos y punteros
std::shared_ptr<Surface> title_logo_surface_; // Textura con los graficos std::shared_ptr<Surface> title_logo_surface_; // Textura con los graficos

View File

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

View File

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

View File

@@ -3,22 +3,22 @@
DeltaTimer::DeltaTimer() noexcept DeltaTimer::DeltaTimer() noexcept
: last_counter_(SDL_GetPerformanceCounter()), : last_counter_(SDL_GetPerformanceCounter()),
perf_freq_(static_cast<double>(SDL_GetPerformanceFrequency())), perf_freq_(static_cast<double>(SDL_GetPerformanceFrequency())),
time_scale_(1.0f) { time_scale_(1.0F) {
} }
float DeltaTimer::tick() noexcept { float DeltaTimer::tick() noexcept {
const Uint64 now = SDL_GetPerformanceCounter(); const Uint64 NOW = SDL_GetPerformanceCounter();
const Uint64 diff = (now > last_counter_) ? (now - last_counter_) : 0; const Uint64 DIFF = (NOW > last_counter_) ? (NOW - last_counter_) : 0;
last_counter_ = now; last_counter_ = NOW;
const double seconds = static_cast<double>(diff) / perf_freq_; const double SECONDS = static_cast<double>(DIFF) / perf_freq_;
return static_cast<float>(seconds * static_cast<double>(time_scale_)); return static_cast<float>(SECONDS * static_cast<double>(time_scale_));
} }
float DeltaTimer::peek() const noexcept { float DeltaTimer::peek() const noexcept {
const Uint64 now = SDL_GetPerformanceCounter(); const Uint64 NOW = SDL_GetPerformanceCounter();
const Uint64 diff = (now > last_counter_) ? (now - last_counter_) : 0; const Uint64 DIFF = (NOW > last_counter_) ? (NOW - last_counter_) : 0;
const double seconds = static_cast<double>(diff) / perf_freq_; const double SECONDS = static_cast<double>(DIFF) / perf_freq_;
return static_cast<float>(seconds * static_cast<double>(time_scale_)); return static_cast<float>(SECONDS * static_cast<double>(time_scale_));
} }
void DeltaTimer::reset(Uint64 counter) noexcept { void DeltaTimer::reset(Uint64 counter) noexcept {
@@ -30,7 +30,7 @@ void DeltaTimer::reset(Uint64 counter) noexcept {
} }
void DeltaTimer::setTimeScale(float scale) noexcept { void DeltaTimer::setTimeScale(float scale) noexcept {
time_scale_ = std::max(scale, 0.0f); time_scale_ = std::max(scale, 0.0F);
} }
float DeltaTimer::getTimeScale() const noexcept { float DeltaTimer::getTimeScale() const noexcept {

View File

@@ -17,19 +17,19 @@
// Calcula el cuadrado de la distancia entre dos puntos // Calcula el cuadrado de la distancia entre dos puntos
double distanceSquared(int x1, int y1, int x2, int y2) { double distanceSquared(int x1, int y1, int x2, int y2) {
const int deltaX = x2 - x1; const int DELTA_X = x2 - x1;
const int deltaY = y2 - y1; const int DELTA_Y = y2 - y1;
return deltaX * deltaX + deltaY * deltaY; return (DELTA_X * DELTA_X) + (DELTA_Y * DELTA_Y);
} }
// Detector de colisiones entre dos circulos // Detector de colisiones entre dos circulos
bool checkCollision(const Circle& a, const Circle& b) { bool checkCollision(const Circle& a, const Circle& b) {
// Calcula el radio total al cuadrado // Calcula el radio total al cuadrado
int totalRadiusSquared = a.r + b.r; int total_radius_squared = a.r + b.r;
totalRadiusSquared = totalRadiusSquared * totalRadiusSquared; total_radius_squared = total_radius_squared * total_radius_squared;
// Si la distancia entre el centro de los circulos es inferior a la suma de sus radios // Si la distancia entre el centro de los circulos es inferior a la suma de sus radios
if (distanceSquared(a.x, a.y, b.x, b.y) < (totalRadiusSquared)) { if (distanceSquared(a.x, a.y, b.x, b.y) < (total_radius_squared)) {
// Los circulos han colisionado // Los circulos han colisionado
return true; return true;
} }
@@ -42,7 +42,8 @@ bool checkCollision(const Circle& a, const Circle& b) {
bool checkCollision(const Circle& a, const SDL_FRect& rect) { bool checkCollision(const Circle& a, const SDL_FRect& rect) {
SDL_Rect b = toSDLRect(rect); SDL_Rect b = toSDLRect(rect);
// Closest point on collision box // Closest point on collision box
int cX, cY; int cX;
int cY;
// Find closest x offset // Find closest x offset
if (a.x < b.x) { if (a.x < b.x) {
@@ -77,31 +78,31 @@ bool checkCollision(const SDL_FRect& rect_a, const SDL_FRect& rect_b) {
SDL_Rect a = toSDLRect(rect_a); SDL_Rect a = toSDLRect(rect_a);
SDL_Rect b = toSDLRect(rect_b); SDL_Rect b = toSDLRect(rect_b);
// Calcula las caras del rectangulo a // Calcula las caras del rectangulo a
const int leftA = a.x; const int LEFT_A = a.x;
const int rightA = a.x + a.w; const int RIGHT_A = a.x + a.w;
const int topA = a.y; const int TOP_A = a.y;
const int bottomA = a.y + a.h; const int BOTTOM_A = a.y + a.h;
// Calcula las caras del rectangulo b // Calcula las caras del rectangulo b
const int leftB = b.x; const int LEFT_B = b.x;
const int rightB = b.x + b.w; const int RIGHT_B = b.x + b.w;
const int topB = b.y; const int TOP_B = b.y;
const int bottomB = b.y + b.h; const int BOTTOM_B = b.y + b.h;
// Si cualquiera de las caras de a está fuera de b // Si cualquiera de las caras de a está fuera de b
if (bottomA <= topB) { if (BOTTOM_A <= TOP_B) {
return false; return false;
} }
if (topA >= bottomB) { if (TOP_A >= BOTTOM_B) {
return false; return false;
} }
if (rightA <= leftB) { if (RIGHT_A <= LEFT_B) {
return false; return false;
} }
if (leftA >= rightB) { if (LEFT_A >= RIGHT_B) {
return false; return false;
} }
@@ -222,54 +223,54 @@ bool checkCollision(const LineHorizontal& l, const SDL_FPoint& point) {
// Detector de colisiones entre dos lineas // Detector de colisiones entre dos lineas
SDL_Point checkCollision(const Line& l1, const Line& l2) { SDL_Point checkCollision(const Line& l1, const Line& l2) {
const float x1 = l1.x1; const float X1 = l1.x1;
const float y1 = l1.y1; const float Y1 = l1.y1;
const float x2 = l1.x2; const float X2 = l1.x2;
const float y2 = l1.y2; const float Y2 = l1.y2;
const float x3 = l2.x1; const float X3 = l2.x1;
const float y3 = l2.y1; const float Y3 = l2.y1;
const float x4 = l2.x2; const float X4 = l2.x2;
const float y4 = l2.y2; const float Y4 = l2.y2;
// calculate the direction of the lines // calculate the direction of the lines
float uA = ((x4 - x3) * (y1 - y3) - (y4 - y3) * (x1 - x3)) / ((y4 - y3) * (x2 - x1) - (x4 - x3) * (y2 - y1)); float u_a = ((X4 - X3) * (Y1 - Y3) - (Y4 - Y3) * (X1 - X3)) / ((Y4 - Y3) * (X2 - X1) - (X4 - X3) * (Y2 - Y1));
float uB = ((x2 - x1) * (y1 - y3) - (y2 - y1) * (x1 - x3)) / ((y4 - y3) * (x2 - x1) - (x4 - x3) * (y2 - y1)); float u_b = ((X2 - X1) * (Y1 - Y3) - (Y2 - Y1) * (X1 - X3)) / ((Y4 - Y3) * (X2 - X1) - (X4 - X3) * (Y2 - Y1));
// if uA and uB are between 0-1, lines are colliding // if uA and uB are between 0-1, lines are colliding
if (uA >= 0 && uA <= 1 && uB >= 0 && uB <= 1) { if (u_a >= 0 && u_a <= 1 && u_b >= 0 && u_b <= 1) {
// Calcula la intersección // Calcula la intersección
const float x = x1 + (uA * (x2 - x1)); const float X = X1 + (u_a * (X2 - X1));
const float y = y1 + (uA * (y2 - y1)); const float Y = Y1 + (u_a * (Y2 - Y1));
return {static_cast<int>(round(x)), static_cast<int>(round(y))}; return {static_cast<int>(round(X)), static_cast<int>(round(Y))};
} }
return {-1, -1}; return {-1, -1};
} }
// Detector de colisiones entre dos lineas // Detector de colisiones entre dos lineas
SDL_Point checkCollision(const LineDiagonal& l1, const LineVertical& l2) { SDL_Point checkCollision(const LineDiagonal& l1, const LineVertical& l2) {
const float x1 = l1.x1; const float X1 = l1.x1;
const float y1 = l1.y1; const float Y1 = l1.y1;
const float x2 = l1.x2; const float X2 = l1.x2;
const float y2 = l1.y2; const float Y2 = l1.y2;
const float x3 = l2.x; const float X3 = l2.x;
const float y3 = l2.y1; const float Y3 = l2.y1;
const float x4 = l2.x; const float X4 = l2.x;
const float y4 = l2.y2; const float Y4 = l2.y2;
// calculate the direction of the lines // calculate the direction of the lines
float uA = ((x4 - x3) * (y1 - y3) - (y4 - y3) * (x1 - x3)) / ((y4 - y3) * (x2 - x1) - (x4 - x3) * (y2 - y1)); float u_a = ((X4 - X3) * (Y1 - Y3) - (Y4 - Y3) * (X1 - X3)) / ((Y4 - Y3) * (X2 - X1) - (X4 - X3) * (Y2 - Y1));
float uB = ((x2 - x1) * (y1 - y3) - (y2 - y1) * (x1 - x3)) / ((y4 - y3) * (x2 - x1) - (x4 - x3) * (y2 - y1)); float u_b = ((X2 - X1) * (Y1 - Y3) - (Y2 - Y1) * (X1 - X3)) / ((Y4 - Y3) * (X2 - X1) - (X4 - X3) * (Y2 - Y1));
// if uA and uB are between 0-1, lines are colliding // if uA and uB are between 0-1, lines are colliding
if (uA >= 0 && uA <= 1 && uB >= 0 && uB <= 1) { if (u_a >= 0 && u_a <= 1 && u_b >= 0 && u_b <= 1) {
// Calcula la intersección // Calcula la intersección
const float x = x1 + (uA * (x2 - x1)); const float X = X1 + (u_a * (X2 - X1));
const float y = y1 + (uA * (y2 - y1)); const float Y = Y1 + (u_a * (Y2 - Y1));
return {static_cast<int>(x), static_cast<int>(y)}; return {static_cast<int>(X), static_cast<int>(Y)};
} }
return {-1, -1}; return {-1, -1};
} }
@@ -279,12 +280,12 @@ void normalizeLine(LineDiagonal& l) {
// Las lineas diagonales van de izquierda a derecha // Las lineas diagonales van de izquierda a derecha
// x2 mayor que x1 // x2 mayor que x1
if (l.x2 < l.x1) { if (l.x2 < l.x1) {
const int x = l.x1; const int X = l.x1;
const int y = l.y1; const int Y = l.y1;
l.x1 = l.x2; l.x1 = l.x2;
l.y1 = l.y2; l.y1 = l.y2;
l.x2 = x; l.x2 = X;
l.y2 = y; l.y2 = Y;
} }
} }
@@ -324,7 +325,7 @@ bool checkCollision(const SDL_FPoint& point, const LineDiagonal& l) {
// Convierte una cadena a un indice de la paleta // Convierte una cadena a un indice de la paleta
Uint8 stringToColor(const std::string& str) { Uint8 stringToColor(const std::string& str) {
// Mapas de colores para cada paleta // Mapas de colores para cada paleta
static const std::unordered_map<std::string, Uint8> paletteMap = { static const std::unordered_map<std::string, Uint8> PALETTE_MAP = {
{"black", 0}, {"black", 0},
{"bright_black", 1}, {"bright_black", 1},
@@ -352,29 +353,27 @@ Uint8 stringToColor(const std::string& str) {
{"transparent", 255}}; {"transparent", 255}};
// Busca el color en el mapa // Busca el color en el mapa
auto it = paletteMap.find(str); auto it = PALETTE_MAP.find(str);
if (it != paletteMap.end()) { if (it != PALETTE_MAP.end()) {
return it->second; return it->second;
} else { } // Si no se encuentra el color, devolvemos negro por defecto
// Si no se encuentra el color, devolvemos negro por defecto return 0;
return 0;
}
} }
// Convierte una cadena a un entero de forma segura // Convierte una cadena a un entero de forma segura
int safeStoi(const std::string& value, int defaultValue) { int safeStoi(const std::string& value, int default_value) {
try { try {
return std::stoi(value); return std::stoi(value);
} catch (const std::exception&) { } catch (const std::exception&) {
return defaultValue; return default_value;
} }
} }
// Convierte una cadena a un booleano // Convierte una cadena a un booleano
bool stringToBool(const std::string& str) { bool stringToBool(const std::string& str) {
std::string lowerStr = str; std::string lower_str = str;
std::transform(lowerStr.begin(), lowerStr.end(), lowerStr.begin(), ::tolower); std::transform(lower_str.begin(), lower_str.end(), lower_str.begin(), ::tolower);
return (lowerStr == "true" || lowerStr == "1" || lowerStr == "yes" || lowerStr == "on"); return (lower_str == "true" || lower_str == "1" || lower_str == "yes" || lower_str == "on");
} }
// Convierte un booleano a una cadena // Convierte un booleano a una cadena
@@ -384,11 +383,11 @@ std::string boolToString(bool value) {
// Compara dos colores // Compara dos colores
bool colorAreEqual(Color color1, Color color2) { bool colorAreEqual(Color color1, Color color2) {
const bool r = color1.r == color2.r; const bool R = color1.r == color2.r;
const bool g = color1.g == color2.g; const bool G = color1.g == color2.g;
const bool b = color1.b == color2.b; const bool B = color1.b == color2.b;
return (r && g && b); return (R && G && B);
} }
// Función para convertir un string a minúsculas // Función para convertir un string a minúsculas

View File

@@ -119,7 +119,7 @@ void normalizeLine(LineDiagonal& l);
Uint8 stringToColor(const std::string& str); Uint8 stringToColor(const std::string& str);
// Convierte una cadena a un entero de forma segura // Convierte una cadena a un entero de forma segura
int safeStoi(const std::string& value, int defaultValue = 0); int safeStoi(const std::string& value, int default_value = 0);
// Convierte una cadena a un booleano // Convierte una cadena a un booleano
bool stringToBool(const std::string& str); bool stringToBool(const std::string& str);

0
tools/linter/generate_compile_commands_json.sh Normal file → Executable file
View File

0
tools/linter/run_clang-tidy.sh Normal file → Executable file
View File

0
tools/linter/run_iwyu.sh Normal file → Executable file
View File

0
tools/linter/run_iwyu_dry_run.sh Normal file → Executable file
View File

0
tools/linter/run_valgrind.sh Normal file → Executable file
View File