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

View File

@@ -13,21 +13,21 @@
#include "game/ui/notifier.hpp" // Para Notifier, NotificationText
#include "utils/utils.hpp" // Para stringInVector
namespace globalInputs {
namespace GlobalInputs {
void quit() {
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);
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);
if (code_found) {
// 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;
} else {
// 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
void skip_section() {
void skipSection() {
switch (SceneManager::current) {
case SceneManager::Scene::LOGO:
case SceneManager::Scene::LOADING_SCREEN:
@@ -52,7 +52,7 @@ void check() {
}
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)) {
@@ -62,7 +62,7 @@ void check() {
else if (Input::get()->checkInput(InputAction::TOGGLE_VIDEOMODE, INPUT_DO_NOT_ALLOW_REPEAT)) {
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)) {
@@ -102,4 +102,4 @@ void check() {
Screen::get()->toggleDebugInfo();
}
}
} // namespace globalInputs
} // namespace GlobalInputs

View File

@@ -1,6 +1,6 @@
#pragma once
namespace globalInputs {
namespace GlobalInputs {
// Comprueba los inputs que se pueden introducir en cualquier sección del juego
void check();
} // namespace globalInputs
} // namespace GlobalInputs

View File

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

View File

@@ -48,7 +48,7 @@ enum class InputAction {
class Input {
private:
// [SINGLETON] Objeto privado
static Input* input_;
static Input* input;
struct KeyBindings {
Uint8 scancode; // Scancode asociado
@@ -107,7 +107,7 @@ class Input {
// Asigna inputs a botones del mando
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
bool checkInput(InputAction input, bool repeat = true, InputDeviceToUse device = InputDeviceToUse::ANY, int controller_index = 0);
@@ -119,7 +119,7 @@ class Input {
bool discoverGameControllers();
// Comprueba si hay algun mando conectado
bool gameControllerFound();
bool gameControllerFound() const;
// Obten el número de mandos conectados
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");
}
int i, bit;
int i;
int bit;
int prev = -1;
std::vector<DictionaryEntry> dictionary;
int dictionary_ind;
@@ -69,7 +70,8 @@ void Gif::decompress(int code_length, const uint8_t* input, int input_length, ui
dictionary_ind += 2;
prev = -1;
continue;
} else if (code == stop_code) {
}
if (code == stop_code) {
break;
}
@@ -83,13 +85,15 @@ void Gif::decompress(int code_length, const uint8_t* input, int input_length, ui
int ptr;
if (code == dictionary_ind) {
ptr = prev;
while (dictionary[ptr].prev != -1)
while (dictionary[ptr].prev != -1) {
ptr = dictionary[ptr].prev;
}
dictionary[dictionary_ind].byte = dictionary[ptr].byte;
} else {
ptr = code;
while (dictionary[ptr].prev != -1)
while (dictionary[ptr].prev != -1) {
ptr = dictionary[ptr].prev;
}
dictionary[dictionary_ind].byte = dictionary[ptr].byte;
}
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");
}
int curCode = code; // Variable temporal para recorrer la cadena.
match_len = dictionary[curCode].len;
while (curCode != -1) {
int cur_code = code; // Variable temporal para recorrer la cadena.
match_len = dictionary[cur_code].len;
while (cur_code != -1) {
// Se asume que dictionary[curCode].len > 0.
out[dictionary[curCode].len - 1] = dictionary[curCode].byte;
if (dictionary[curCode].prev == curCode) {
out[dictionary[cur_code].len - 1] = dictionary[cur_code].byte;
if (dictionary[cur_code].prev == cur_code) {
std::cerr << "Internal error; self-reference detected." << std::endl;
throw std::runtime_error("Internal error in decompress: self-reference");
}
curCode = dictionary[curCode].prev;
cur_code = dictionary[cur_code].prev;
}
out += match_len;
}
@@ -165,7 +169,7 @@ std::vector<uint32_t> Gif::loadPalette(const uint8_t* buffer) {
buffer += sizeof(ScreenDescriptor);
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));
global_color_table.resize(global_color_table_size);
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;
// Opcional: Validar header
std::string headerStr(reinterpret_cast<char*>(header), 6);
if (headerStr != "GIF87a" && headerStr != "GIF89a") {
std::string header_str(reinterpret_cast<char*>(header), 6);
if (header_str != "GIF87a" && header_str != "GIF89a") {
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;
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));
global_color_table.resize(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
{
// Procesar Graphic Control Extension:
uint8_t blockSize = *buffer++; // Normalmente, blockSize == 4
buffer += blockSize; // Saltamos los 4 bytes del bloque fijo
uint8_t block_size = *buffer++; // Normalmente, blockSize == 4
buffer += block_size; // Saltamos los 4 bytes del bloque fijo
// Saltar los sub-bloques
uint8_t subBlockSize = *buffer++;
while (subBlockSize != 0) {
buffer += subBlockSize;
subBlockSize = *buffer++;
uint8_t sub_block_size = *buffer++;
while (sub_block_size != 0) {
buffer += sub_block_size;
sub_block_size = *buffer++;
}
break;
}
@@ -234,23 +238,23 @@ std::vector<uint8_t> Gif::processGifStream(const uint8_t* buffer, uint16_t& w, u
case PLAINTEXT_EXTENSION: // 0x01
{
// Para estas extensiones, saltamos el bloque fijo y los sub-bloques.
uint8_t blockSize = *buffer++;
buffer += blockSize;
uint8_t subBlockSize = *buffer++;
while (subBlockSize != 0) {
buffer += subBlockSize;
subBlockSize = *buffer++;
uint8_t block_size = *buffer++;
buffer += block_size;
uint8_t sub_block_size = *buffer++;
while (sub_block_size != 0) {
buffer += sub_block_size;
sub_block_size = *buffer++;
}
break;
}
default: {
// Si la etiqueta de extensión es desconocida, saltarla también:
uint8_t blockSize = *buffer++;
buffer += blockSize;
uint8_t subBlockSize = *buffer++;
while (subBlockSize != 0) {
buffer += subBlockSize;
subBlockSize = *buffer++;
uint8_t block_size = *buffer++;
buffer += block_size;
uint8_t sub_block_size = *buffer++;
while (sub_block_size != 0) {
buffer += sub_block_size;
sub_block_size = *buffer++;
}
break;
}

View File

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

View File

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

View File

@@ -19,21 +19,21 @@
#include "game/ui/notifier.hpp" // Para Notifier
// [SINGLETON]
Screen* Screen::screen_ = nullptr;
Screen* Screen::screen = nullptr;
// [SINGLETON] Crearemos el objeto con esta función estática
void Screen::init() {
Screen::screen_ = new Screen();
Screen::screen = new Screen();
}
// [SINGLETON] Destruiremos el objeto con esta función estática
void Screen::destroy() {
delete Screen::screen_;
delete Screen::screen;
}
// [SINGLETON] Con este método obtenemos el objeto y podemos trabajar con él
Screen* Screen::get() {
return Screen::screen_;
return Screen::screen;
}
// Constructor
@@ -332,7 +332,7 @@ void Screen::renderInfo() {
auto color = static_cast<Uint8>(PaletteColor::YELLOW);
// 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);
// Resolution

View File

@@ -33,34 +33,34 @@ class Screen {
struct FPS {
Uint32 ticks; // Tiempo en milisegundos desde que se comenzó a contar.
int frameCount; // Número acumulado de frames en el intervalo.
int lastValue; // Número de frames calculado en el último segundo.
int frame_count; // Número acumulado de frames en el intervalo.
int last_value; // Número de frames calculado en el último segundo.
// Constructor para inicializar la estructura.
FPS()
: ticks(0),
frameCount(0),
lastValue(0) {}
frame_count(0),
last_value(0) {}
// Incrementador que se llama en cada frame.
void increment() {
frameCount++;
frame_count++;
}
// Método para calcular y devolver el valor de FPS.
int calculate(Uint32 currentTicks) {
if (currentTicks - ticks >= 1000) // Si ha pasado un segundo o más.
int calculate(Uint32 current_ticks) {
if (current_ticks - ticks >= 1000) // Si ha pasado un segundo o más.
{
lastValue = frameCount; // Actualizamos el valor del último FPS.
frameCount = 0; // Reiniciamos el contador de frames.
ticks = currentTicks; // Actualizamos el tiempo base.
last_value = frame_count; // Actualizamos el valor del último FPS.
frame_count = 0; // Reiniciamos el contador de frames.
ticks = current_ticks; // Actualizamos el tiempo base.
}
return lastValue;
return last_value;
}
};
// [SINGLETON] Objeto privado
static Screen* screen_;
static Screen* screen;
// Objetos y punteros
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
std::istringstream ss(line);
int r, g, b;
int r;
int g;
int b;
if (ss >> r >> g >> b) {
// Construir el color ARGB (A = 255 por defecto)
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)
: transparent_color_(static_cast<Uint8>(PaletteColor::TRANSPARENT)) {
SurfaceData loadedData = loadSurface(file_path);
surface_data_ = std::make_shared<SurfaceData>(std::move(loadedData));
SurfaceData loaded_data = loadSurface(file_path);
surface_data_ = std::make_shared<SurfaceData>(std::move(loaded_data));
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
GIF::Gif gif;
Uint16 w = 0, h = 0;
std::vector<Uint8> rawPixels = gif.loadGif(buffer.data(), w, h);
if (rawPixels.empty()) {
Uint16 w = 0;
Uint16 h = 0;
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;
throw std::runtime_error("Error loading GIF");
}
// Si el constructor de Surface espera un std::shared_ptr<Uint8[]>,
// reservamos un bloque dinámico y copiamos los datos del vector.
size_t pixelCount = rawPixels.size();
auto pixels = std::shared_ptr<Uint8[]>(new Uint8[pixelCount], std::default_delete<Uint8[]>());
std::memcpy(pixels.get(), rawPixels.data(), pixelCount);
size_t pixel_count = raw_pixels.size();
auto pixels = std::shared_ptr<Uint8[]>(new Uint8[pixel_count], std::default_delete<Uint8[]>());
std::memcpy(pixels.get(), raw_pixels.data(), pixel_count);
// Crear y devolver directamente el objeto SurfaceData
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
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();
std::fill(data_ptr, data_ptr + total_pixels, color);
std::fill(data_ptr, data_ptr + TOTAL_PIXELS, color);
}
// Pone un pixel en la SurfaceData
@@ -173,12 +176,12 @@ void Surface::putPixel(int x, int y, Uint8 color) {
return; // Coordenadas fuera de rango
}
const int index = x + y * surface_data_->width;
surface_data_->data.get()[index] = color;
const int INDEX = x + (y * surface_data_->width);
surface_data_->data.get()[INDEX] = color;
}
// 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
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
for (int y = y_start; y < y_end; ++y) {
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;
}
}
@@ -208,22 +211,22 @@ void Surface::drawRectBorder(const SDL_FRect* rect, Uint8 color) {
// Dibujar bordes horizontales
for (int x = x_start; x < x_end; ++x) {
// Borde superior
const int top_index = x + y_start * surface_data_->width;
surface_data_->data.get()[top_index] = color;
const int TOP_INDEX = x + (y_start * surface_data_->width);
surface_data_->data.get()[TOP_INDEX] = color;
// Borde inferior
const int bottom_index = x + (y_end - 1) * surface_data_->width;
surface_data_->data.get()[bottom_index] = color;
const int BOTTOM_INDEX = x + ((y_end - 1) * surface_data_->width);
surface_data_->data.get()[BOTTOM_INDEX] = color;
}
// Dibujar bordes verticales
for (int y = y_start; y < y_end; ++y) {
// 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;
// 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;
}
}
@@ -243,12 +246,13 @@ void Surface::drawLine(float x1, float y1, float x2, float y2, Uint8 color) {
while (true) {
// 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) {
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
if (x1 == x2 && y1 == y2)
if (x1 == x2 && y1 == y2) {
break;
}
int e2 = 2 * err;
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_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_) {
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();
// Determina la región de origen (clip) a renderizar
float sx = (srcRect) ? srcRect->x : 0;
float sy = (srcRect) ? srcRect->y : 0;
float w = (srcRect) ? srcRect->w : surface_data_->width;
float h = (srcRect) ? srcRect->h : surface_data_->height;
float sx = ((src_rect) != nullptr) ? src_rect->x : 0;
float sy = ((src_rect) != nullptr) ? src_rect->y : 0;
float w = ((src_rect) != nullptr) ? src_rect->w : surface_data_->width;
float h = ((src_rect) != nullptr) ? src_rect->h : surface_data_->height;
// Limitar la región para evitar accesos fuera de rango en origen
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
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
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_) {
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
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();
// Si srcRect es nullptr, tomar toda la superficie fuente
float sx = (srcRect) ? srcRect->x : 0;
float sy = (srcRect) ? srcRect->y : 0;
float sw = (srcRect) ? srcRect->w : surface_data_->width;
float sh = (srcRect) ? srcRect->h : surface_data_->height;
float sx = ((src_rect) != nullptr) ? src_rect->x : 0;
float sy = ((src_rect) != nullptr) ? src_rect->y : 0;
float sw = ((src_rect) != nullptr) ? src_rect->w : surface_data_->width;
float sh = ((src_rect) != nullptr) ? src_rect->h : surface_data_->height;
// Si dstRect es nullptr, asignar las mismas dimensiones que srcRect
float dx = (dstRect) ? dstRect->x : 0;
float dy = (dstRect) ? dstRect->y : 0;
float dw = (dstRect) ? dstRect->w : sw;
float dh = (dstRect) ? dstRect->h : sh;
float dx = ((dst_rect) != nullptr) ? dst_rect->x : 0;
float dy = ((dst_rect) != nullptr) ? dst_rect->y : 0;
float dw = ((dst_rect) != nullptr) ? dst_rect->w : sw;
float dh = ((dst_rect) != nullptr) ? dst_rect->h : sh;
// Asegurarse de que srcRect y dstRect tienen las mismas dimensiones
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_y = dy + iy; dest_y >= 0 && dest_y < surface_data->height) {
// 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_) {
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
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();
// Determina la región de origen (clip) a renderizar
float sx = (srcRect) ? srcRect->x : 0;
float sy = (srcRect) ? srcRect->y : 0;
float w = (srcRect) ? srcRect->w : surface_data_->width;
float h = (srcRect) ? srcRect->h : surface_data_->height;
float sx = ((src_rect) != nullptr) ? src_rect->x : 0;
float sy = ((src_rect) != nullptr) ? src_rect->y : 0;
float w = ((src_rect) != nullptr) ? src_rect->w : surface_data_->width;
float h = ((src_rect) != nullptr) ? src_rect->h : surface_data_->height;
// Limitar la región para evitar accesos fuera de rango
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
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_) {
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;
}
}
@@ -427,11 +431,11 @@ void Surface::renderWithColorReplace(int x, int y, Uint8 source_color, Uint8 tar
// Vuelca la superficie a una textura
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.");
}
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.");
}
@@ -449,8 +453,8 @@ void Surface::copyToTexture(SDL_Renderer* renderer, SDL_Texture* texture) {
for (int y = 0; y < surface_data_->height; ++y) {
for (int x = 0; x < surface_data_->width; ++x) {
// Calcular la posición correcta en la textura teniendo en cuenta el stride
int texture_index = y * row_stride + x;
int surface_index = y * surface_data_->width + x;
int texture_index = (y * row_stride) + x;
int surface_index = (y * surface_data_->width) + x;
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
void Surface::copyToTexture(SDL_Renderer* renderer, SDL_Texture* texture, SDL_FRect* srcRect, SDL_FRect* destRect) {
if (!renderer || !texture || !surface_data_) {
void Surface::copyToTexture(SDL_Renderer* renderer, SDL_Texture* texture, SDL_FRect* src_rect, SDL_FRect* dest_rect) {
if ((renderer == nullptr) || (texture == nullptr) || !surface_data_) {
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.");
}
Uint32* pixels = nullptr;
int pitch = 0;
SDL_Rect lockRect;
if (destRect) {
lockRect.x = static_cast<int>(destRect->x);
lockRect.y = static_cast<int>(destRect->y);
lockRect.w = static_cast<int>(destRect->w);
lockRect.h = static_cast<int>(destRect->h);
SDL_Rect lock_rect;
if (dest_rect != nullptr) {
lock_rect.x = static_cast<int>(dest_rect->x);
lock_rect.y = static_cast<int>(dest_rect->y);
lock_rect.w = static_cast<int>(dest_rect->w);
lock_rect.h = static_cast<int>(dest_rect->h);
}
// 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()));
}
@@ -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 x = 0; x < surface_data_->width; ++x) {
int texture_index = y * row_stride + x;
int surface_index = y * surface_data_->width + x;
int texture_index = (y * row_stride) + x;
int surface_index = (y * surface_data_->width) + x;
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);
// 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()));
}
}
@@ -512,8 +516,8 @@ void Surface::copyToTexture(SDL_Renderer* renderer, SDL_Texture* texture, SDL_FR
// Realiza un efecto de fundido en la paleta principal
bool Surface::fadePalette() {
// Verificar que el tamaño mínimo de palette_ sea adecuado
static constexpr int palette_size = 19;
if (sizeof(palette_) / sizeof(palette_[0]) < palette_size) {
static constexpr int PALETTE_SIZE = 19;
if (sizeof(palette_) / sizeof(palette_[0]) < PALETTE_SIZE) {
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
bool Surface::fadeSubPalette(Uint32 delay) {
// Variable estática para almacenar el último tick
static Uint32 last_tick = 0;
static Uint32 last_tick_ = 0;
// Obtener el tiempo actual
Uint32 current_tick = SDL_GetTicks();
// 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
}
// Actualizar el último tick
last_tick = current_tick;
last_tick_ = current_tick;
// Verificar que el tamaño mínimo de sub_palette_ sea adecuado
static constexpr int sub_palette_size = 19;
if (sizeof(sub_palette_) / sizeof(sub_palette_[0]) < sub_palette_size) {
static constexpr int SUB_PALETTE_SIZE = 19;
if (sizeof(sub_palette_) / sizeof(sub_palette_[0]) < SUB_PALETTE_SIZE) {
throw std::runtime_error("Palette size is insufficient for fadePalette operation.");
}

View File

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

View File

@@ -19,8 +19,7 @@ struct AnimationData {
int counter; // Contador para las animaciones
AnimationData()
: name(std::string()),
speed(5),
: speed(5),
loop(0),
completed(false),
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)
: SurfaceSprite(surface),
x_(0.0f),
y_(0.0f),
x_(0.0F),
y_(0.0F),
flip_(SDL_FLIP_NONE) { SurfaceSprite::clear(); }
// Reinicia todas las variables
void SurfaceMovingSprite::clear() {
x_ = 0.0f; // Posición en el eje X
y_ = 0.0f; // Posición en el eje Y
x_ = 0.0F; // Posición en el eje X
y_ = 0.0F; // Posición en el eje Y
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
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
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
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
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
void SurfaceMovingSprite::setPos(SDL_FRect rect) {
x_ = static_cast<float>(rect.x);
y_ = static_cast<float>(rect.y);
x_ = rect.x;
y_ = rect.y;
pos_ = rect;
}

View File

@@ -14,11 +14,11 @@ class SurfaceMovingSprite : public SurfaceSprite {
float x_; // Posición en el eje X
float y_; // Posición en el eje Y
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 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 ax_ = 0.0f; // Aceleración en el eje X. Variación de la velocidad
float ay_ = 0.0f; // Aceleración en el eje Y. Variación de la velocidad
float ax_ = 0.0F; // Aceleración en el eje X. Variación de la velocidad
float ay_ = 0.0F; // Aceleración en el eje Y. Variación de la velocidad
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;
while (std::getline(file, buffer)) {
// Almacena solo las lineas impares
if (line_read % 2 == 1)
if (line_read % 2 == 1) {
tf->offset[index++].w = std::stoi(buffer);
}
// Limpia el buffer
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) {
int shift = 0;
if (lenght == -1)
if (lenght == -1) {
lenght = text.length();
}
sprite_->setY(y);
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
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 height = box_height_ + shadow_distance;
auto surface = std::make_shared<Surface>(width, height);
auto previuos_renderer = Screen::get()->getRendererSurface();
Screen::get()->setRendererSurface(surface);
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);
return surface;
@@ -188,21 +190,21 @@ void Text::writeCentered(int x, int y, const std::string& text, int kerning, int
}
// Escribe texto con extras
void Text::writeDX(Uint8 flags, int x, int y, const std::string& text, int kerning, Uint8 textColor, Uint8 shadow_distance, Uint8 shadow_color, int lenght) {
const auto centered = ((flags & TEXT_CENTER) == TEXT_CENTER);
const auto shadowed = ((flags & TEXT_SHADOW) == TEXT_SHADOW);
const auto colored = ((flags & TEXT_COLOR) == TEXT_COLOR);
const auto stroked = ((flags & TEXT_STROKE) == TEXT_STROKE);
void Text::writeDX(Uint8 flags, int x, int y, const std::string& text, int kerning, Uint8 text_color, Uint8 shadow_distance, Uint8 shadow_color, int lenght) {
const auto CENTERED = ((flags & TEXT_CENTER) == TEXT_CENTER);
const auto SHADOWED = ((flags & TEXT_SHADOW) == TEXT_SHADOW);
const auto COLORED = ((flags & TEXT_COLOR) == TEXT_COLOR);
const auto STROKED = ((flags & TEXT_STROKE) == TEXT_STROKE);
if (centered) {
if (CENTERED) {
x -= (Text::lenght(text, kerning) / 2);
}
if (shadowed) {
if (SHADOWED) {
writeColored(x + shadow_distance, y + shadow_distance, text, shadow_color, kerning, lenght);
}
if (stroked) {
if (STROKED) {
for (int dist = 1; dist <= shadow_distance; ++dist) {
for (int dy = -dist; dy <= dist; ++dy) {
for (int dx = -dist; dx <= dist; ++dx) {
@@ -212,10 +214,10 @@ void Text::writeDX(Uint8 flags, int x, int y, const std::string& text, int kerni
}
}
if (colored) {
writeColored(x, y, text, textColor, kerning, lenght);
if (COLORED) {
writeColored(x, y, text, text_color, kerning, lenght);
} else {
writeColored(x, y, text, textColor, kerning, lenght);
writeColored(x, y, text, text_color, 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
int Text::lenght(const std::string& text, int kerning) const {
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);
}
// Descuenta el kerning del último caracter
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);
// 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
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);
// 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
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
if (!path_.empty()) {
// Obtiene la extensión
const std::string extension = path_.substr(path_.find_last_of(".") + 1);
const std::string EXTENSION = path_.substr(path_.find_last_of(".") + 1);
// .png
if (extension == "png") {
if (EXTENSION == "png") {
loadFromFile(path_);
}
}
@@ -42,14 +42,15 @@ bool Texture::loadFromFile(const std::string& file_path) {
}
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);
if (!data) {
if (data == nullptr) {
std::cerr << "Error: Fichero no encontrado " << getFileName(file_path) << std::endl;
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;
SDL_PixelFormat pixel_format;
@@ -61,7 +62,7 @@ bool Texture::loadFromFile(const std::string& file_path) {
unloadTexture();
// La textura final
SDL_Texture* newTexture = nullptr;
SDL_Texture* new_texture = nullptr;
// Carga la imagen desde una ruta específica
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;
} else {
// Crea la textura desde los pixels de la surface
newTexture = SDL_CreateTextureFromSurface(renderer_, loaded_surface);
if (newTexture == nullptr) {
new_texture = SDL_CreateTextureFromSurface(renderer_, loaded_surface);
if (new_texture == nullptr) {
std::cout << "Unable to create texture from " << file_path << "! SDL Error: " << SDL_GetError() << std::endl;
} else {
// Obtiene las dimensiones de la imagen
@@ -84,7 +85,7 @@ bool Texture::loadFromFile(const std::string& file_path) {
// Return success
stbi_image_free(data);
texture_ = newTexture;
texture_ = new_texture;
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
void Texture::unloadTexture() {
// Libera la textura
if (texture_) {
if (texture_ != nullptr) {
SDL_DestroyTexture(texture_);
texture_ = nullptr;
width_ = 0;
@@ -124,7 +125,7 @@ void Texture::setBlendMode(SDL_BlendMode blending) { SDL_SetTextureBlendMode(tex
void Texture::setAlpha(Uint8 alpha) { SDL_SetTextureAlphaMod(texture_, alpha); }
// 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
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
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.y = render_quad.y + (render_quad.h / 2);
render_quad.w = render_quad.w * zoomW;
render_quad.h = render_quad.h * zoomH;
render_quad.w = render_quad.w * zoom_w;
render_quad.h = render_quad.h * zoom_h;
render_quad.x = render_quad.x - (render_quad.w / 2);
render_quad.y = render_quad.y - (render_quad.h / 2);
}
@@ -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
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
bool Texture::reLoad() { return loadFromFile(path_); }

View File

@@ -45,16 +45,16 @@ class Texture {
void setAlpha(Uint8 alpha);
// 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
void setAsRenderTarget(SDL_Renderer* renderer);
// Obtiene el ancho de la imagen
int getWidth();
int getWidth() const { return width_; }
// Obtiene el alto de la imagen
int getHeight();
int getHeight() const { return height_; }
// Recarga la textura
bool reLoad();

View File

@@ -8,21 +8,21 @@
#include "utils/utils.hpp" // Para getFileName, printWithDots
// [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
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
void Asset::destroy() {
delete Asset::asset_;
delete Asset::asset;
}
// [SINGLETON] Con este método obtenemos el objeto asset y podemos trabajar con él
Asset* Asset::get() {
return Asset::asset_;
return Asset::asset;
}
// 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()) {
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
@@ -74,8 +73,9 @@ bool Asset::check() const {
success &= checkFile(f.file);
}
}
if (success)
if (success) {
std::cout << " All files are OK." << std::endl;
}
}
}
@@ -86,7 +86,7 @@ bool Asset::check() const {
}
// Comprueba que existe un fichero
bool Asset::checkFile(const std::string& path) const {
bool Asset::checkFile(const std::string& path) {
std::ifstream file(path);
bool success = file.good();
file.close();
@@ -99,7 +99,7 @@ bool Asset::checkFile(const std::string& path) const {
}
// Devuelve el nombre del tipo de recurso
std::string Asset::getTypeName(AssetType type) const {
std::string Asset::getTypeName(AssetType type) {
switch (type) {
case AssetType::DATA:
return "DATA";

View File

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

View File

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

View File

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

View File

@@ -5,7 +5,7 @@
#include "core/input/mouse.hpp"
#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
void check(const SDL_Event& event) {
// Evento de salida de la aplicación
@@ -20,4 +20,4 @@ void check(const SDL_Event& event) {
Mouse::handleEvent(event);
}
} // namespace globalEvents
} // namespace GlobalEvents

View File

@@ -2,7 +2,7 @@
#include <SDL3/SDL.h>
namespace globalEvents {
namespace GlobalEvents {
// Comprueba los eventos que se pueden producir en cualquier sección del juego
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_->setHeight(enemy.h);
const SDL_FlipMode FLIP = (should_flip_ && enemy.vx < 0.0f) ? SDL_FLIP_HORIZONTAL : SDL_FLIP_NONE;
const SDL_FlipMode FLIP = (should_flip_ && enemy.vx < 0.0F) ? SDL_FLIP_HORIZONTAL : SDL_FLIP_NONE;
const SDL_FlipMode MIRROR = should_mirror_ ? SDL_FLIP_VERTICAL : SDL_FLIP_NONE;
sprite_->setFlip(static_cast<SDL_FlipMode>(FLIP | MIRROR));

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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