forked from jaildesigner-jailgames/jaildoctors_dilemma
linter
This commit is contained in:
28
.clang-tidy
28
.clang-tidy
@@ -1,21 +1,21 @@
|
|||||||
Checks:
|
Checks:
|
||||||
- readability-*
|
- readability-*
|
||||||
# - modernize-*
|
- modernize-*
|
||||||
# - performance-*
|
- performance-*
|
||||||
# - bugprone-unchecked-optional-access
|
- bugprone-unchecked-optional-access
|
||||||
# - bugprone-sizeof-expression
|
- bugprone-sizeof-expression
|
||||||
# - bugprone-suspicious-missing-comma
|
- bugprone-suspicious-missing-comma
|
||||||
# - bugprone-suspicious-index
|
- bugprone-suspicious-index
|
||||||
# - bugprone-undefined-memory-manipulation
|
- bugprone-undefined-memory-manipulation
|
||||||
# - bugprone-use-after-move
|
- bugprone-use-after-move
|
||||||
# - bugprone-out-of-bound-access
|
- bugprone-out-of-bound-access
|
||||||
- -readability-identifier-length
|
- -readability-identifier-length
|
||||||
- -readability-magic-numbers
|
- -readability-magic-numbers
|
||||||
# - -bugprone-narrowing-conversions
|
- -bugprone-narrowing-conversions
|
||||||
# - -performance-enum-size
|
- -performance-enum-size
|
||||||
# - -performance-inefficient-string-concatenation
|
- -performance-inefficient-string-concatenation
|
||||||
# - -bugprone-integer-division
|
- -bugprone-integer-division
|
||||||
# - -bugprone-easily-swappable-parameters
|
- -bugprone-easily-swappable-parameters
|
||||||
|
|
||||||
WarningsAsErrors: '*'
|
WarningsAsErrors: '*'
|
||||||
# Solo incluir archivos de tu código fuente
|
# Solo incluir archivos de tu código fuente
|
||||||
|
|||||||
@@ -22,13 +22,13 @@ void Input::destroy() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// [SINGLETON] Con este método obtenemos el objeto y podemos trabajar con él
|
// [SINGLETON] Con este método obtenemos el objeto y podemos trabajar con él
|
||||||
Input* Input::get() {
|
auto Input::get() -> Input* {
|
||||||
return Input::input;
|
return Input::input;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Constructor
|
// Constructor
|
||||||
Input::Input(const std::string& game_controller_db_path)
|
Input::Input(const std::string& game_controller_db_path)
|
||||||
: game_controller_db_path_(game_controller_db_path) {
|
: game_controller_db_path_(std::move(game_controller_db_path)) {
|
||||||
// Busca si hay mandos conectados
|
// Busca si hay mandos conectados
|
||||||
discoverGameControllers();
|
discoverGameControllers();
|
||||||
|
|
||||||
@@ -60,7 +60,7 @@ void Input::bindGameControllerButton(int controller_index, InputAction input_tar
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Comprueba si un input esta activo
|
// Comprueba si un input esta activo
|
||||||
bool Input::checkInput(InputAction input, bool repeat, InputDeviceToUse device, int controller_index) {
|
auto Input::checkInput(InputAction input, bool repeat, InputDeviceToUse device, int controller_index) -> bool {
|
||||||
bool success_keyboard = false;
|
bool success_keyboard = false;
|
||||||
bool success_controller = false;
|
bool success_controller = false;
|
||||||
const int INPUT_INDEX = static_cast<int>(input);
|
const int INPUT_INDEX = static_cast<int>(input);
|
||||||
@@ -117,13 +117,13 @@ bool Input::checkInput(InputAction input, bool repeat, InputDeviceToUse device,
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Comprueba si hay almenos un input activo
|
// Comprueba si hay almenos un input activo
|
||||||
bool Input::checkAnyInput(InputDeviceToUse device, int controller_index) {
|
auto Input::checkAnyInput(InputDeviceToUse device, int controller_index) -> bool {
|
||||||
if (device == InputDeviceToUse::KEYBOARD || device == InputDeviceToUse::ANY) {
|
if (device == InputDeviceToUse::KEYBOARD || device == InputDeviceToUse::ANY) {
|
||||||
const bool* key_states = SDL_GetKeyboardState(nullptr);
|
const bool* key_states = SDL_GetKeyboardState(nullptr);
|
||||||
|
|
||||||
for (int i = 0; i < (int)key_bindings_.size(); ++i) {
|
for (auto& key_binding : key_bindings_) {
|
||||||
if (static_cast<int>(key_states[key_bindings_[i].scancode]) != 0 && !key_bindings_[i].active) {
|
if (static_cast<int>(key_states[key_binding.scancode]) != 0 && !key_binding.active) {
|
||||||
key_bindings_[i].active = true;
|
key_binding.active = true;
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -144,7 +144,7 @@ bool Input::checkAnyInput(InputDeviceToUse device, int controller_index) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Busca si hay mandos conectados
|
// Busca si hay mandos conectados
|
||||||
bool Input::discoverGameControllers() {
|
auto Input::discoverGameControllers() -> bool {
|
||||||
bool found = false;
|
bool found = false;
|
||||||
|
|
||||||
// Asegúrate de que el subsistema de gamepads está inicializado
|
// Asegúrate de que el subsistema de gamepads está inicializado
|
||||||
@@ -155,7 +155,7 @@ bool Input::discoverGameControllers() {
|
|||||||
// Carga el mapping de mandos desde archivo
|
// Carga el mapping de mandos desde archivo
|
||||||
if (SDL_AddGamepadMappingsFromFile(game_controller_db_path_.c_str()) < 0) {
|
if (SDL_AddGamepadMappingsFromFile(game_controller_db_path_.c_str()) < 0) {
|
||||||
std::cout << "Error, could not load " << game_controller_db_path_.c_str()
|
std::cout << "Error, could not load " << game_controller_db_path_.c_str()
|
||||||
<< " file: " << SDL_GetError() << std::endl;
|
<< " file: " << SDL_GetError() << '\n';
|
||||||
}
|
}
|
||||||
|
|
||||||
// En SDL3 ya no existe SDL_NumJoysticks()
|
// En SDL3 ya no existe SDL_NumJoysticks()
|
||||||
@@ -177,12 +177,12 @@ bool Input::discoverGameControllers() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
std::cout << "\n** LOOKING FOR GAME CONTROLLERS" << std::endl;
|
std::cout << "\n** LOOKING FOR GAME CONTROLLERS" << '\n';
|
||||||
if (num_joysticks_ != num_gamepads_) {
|
if (num_joysticks_ != num_gamepads_) {
|
||||||
std::cout << "Joysticks found: " << num_joysticks_ << std::endl;
|
std::cout << "Joysticks found: " << num_joysticks_ << '\n';
|
||||||
std::cout << "Gamepads found : " << num_gamepads_ << std::endl;
|
std::cout << "Gamepads found : " << num_gamepads_ << '\n';
|
||||||
} else {
|
} else {
|
||||||
std::cout << "Gamepads found: " << num_gamepads_ << std::endl;
|
std::cout << "Gamepads found: " << num_gamepads_ << '\n';
|
||||||
}
|
}
|
||||||
|
|
||||||
if (num_gamepads_ > 0) {
|
if (num_gamepads_ > 0) {
|
||||||
@@ -195,10 +195,10 @@ bool Input::discoverGameControllers() {
|
|||||||
connected_controllers_.push_back(pad);
|
connected_controllers_.push_back(pad);
|
||||||
|
|
||||||
const char* name = SDL_GetGamepadName(pad);
|
const char* name = SDL_GetGamepadName(pad);
|
||||||
std::cout << "#" << i << ": " << ((name != nullptr) ? name : "Unknown") << std::endl;
|
std::cout << "#" << i << ": " << ((name != nullptr) ? name : "Unknown") << '\n';
|
||||||
controller_names_.push_back((name != nullptr) ? name : "Unknown");
|
controller_names_.emplace_back((name != nullptr) ? name : "Unknown");
|
||||||
} else {
|
} else {
|
||||||
std::cout << "SDL_GetError() = " << SDL_GetError() << std::endl;
|
std::cout << "SDL_GetError() = " << SDL_GetError() << '\n';
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -209,21 +209,21 @@ bool Input::discoverGameControllers() {
|
|||||||
|
|
||||||
SDL_free(joystick_ids);
|
SDL_free(joystick_ids);
|
||||||
|
|
||||||
std::cout << "\n** FINISHED LOOKING FOR GAME CONTROLLERS" << std::endl;
|
std::cout << "\n** FINISHED LOOKING FOR GAME CONTROLLERS" << '\n';
|
||||||
return found;
|
return found;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Comprueba si hay algun mando conectado
|
// Comprueba si hay algun mando conectado
|
||||||
bool Input::gameControllerFound() const { return num_gamepads_ > 0; }
|
auto Input::gameControllerFound() const -> bool { return num_gamepads_ > 0; }
|
||||||
|
|
||||||
// Obten el nombre de un mando de juego
|
// Obten el nombre de un mando de juego
|
||||||
std::string Input::getControllerName(int controller_index) const { return num_gamepads_ > 0 ? controller_names_.at(controller_index) : std::string(); }
|
auto Input::getControllerName(int controller_index) const -> std::string { return num_gamepads_ > 0 ? controller_names_.at(controller_index) : std::string(); }
|
||||||
|
|
||||||
// Obten el número de mandos conectados
|
// Obten el número de mandos conectados
|
||||||
int Input::getNumControllers() const { return num_gamepads_; }
|
auto Input::getNumControllers() const -> int { return num_gamepads_; }
|
||||||
|
|
||||||
// Obtiene el indice del controlador a partir de un event.id
|
// Obtiene el indice del controlador a partir de un event.id
|
||||||
int Input::getJoyIndex(SDL_JoystickID id) const {
|
auto Input::getJoyIndex(SDL_JoystickID id) const -> int {
|
||||||
for (int i = 0; i < num_joysticks_; ++i) {
|
for (int i = 0; i < num_joysticks_; ++i) {
|
||||||
if (SDL_GetJoystickID(joysticks_[i]) == id) {
|
if (SDL_GetJoystickID(joysticks_[i]) == id) {
|
||||||
return i;
|
return i;
|
||||||
@@ -233,18 +233,18 @@ int Input::getJoyIndex(SDL_JoystickID id) const {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Obtiene el SDL_GamepadButton asignado a un input
|
// Obtiene el SDL_GamepadButton asignado a un input
|
||||||
SDL_GamepadButton Input::getControllerBinding(int controller_index, InputAction input) const {
|
auto Input::getControllerBinding(int controller_index, InputAction input) const -> SDL_GamepadButton {
|
||||||
return controller_bindings_[controller_index][static_cast<int>(input)].button;
|
return controller_bindings_[controller_index][static_cast<int>(input)].button;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Obtiene el indice a partir del nombre del mando
|
// Obtiene el indice a partir del nombre del mando
|
||||||
int Input::getIndexByName(const std::string& name) const {
|
auto Input::getIndexByName(const std::string& name) const -> int {
|
||||||
auto it = std::find(controller_names_.begin(), controller_names_.end(), name);
|
auto it = std::ranges::find(controller_names_, name);
|
||||||
return it != controller_names_.end() ? std::distance(controller_names_.begin(), it) : -1;
|
return it != controller_names_.end() ? std::distance(controller_names_.begin(), it) : -1;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Comprueba el eje del mando
|
// Comprueba el eje del mando
|
||||||
bool Input::checkAxisInput(InputAction input, int controller_index, bool repeat) {
|
auto Input::checkAxisInput(InputAction input, int controller_index, bool repeat) -> bool {
|
||||||
// Umbral para considerar el eje como activo
|
// Umbral para considerar el eje como activo
|
||||||
const Sint16 THRESHOLD = 30000;
|
const Sint16 THRESHOLD = 30000;
|
||||||
bool axis_active_now = false;
|
bool axis_active_now = false;
|
||||||
|
|||||||
@@ -84,7 +84,7 @@ class Input {
|
|||||||
std::string game_controller_db_path_; // Ruta al archivo gamecontrollerdb.txt
|
std::string game_controller_db_path_; // Ruta al archivo gamecontrollerdb.txt
|
||||||
|
|
||||||
// Comprueba el eje del mando
|
// Comprueba el eje del mando
|
||||||
bool checkAxisInput(InputAction input, int controller_index, bool repeat);
|
auto checkAxisInput(InputAction input, int controller_index, bool repeat) -> bool;
|
||||||
|
|
||||||
// Constructor
|
// Constructor
|
||||||
explicit Input(const std::string& game_controller_db_path);
|
explicit Input(const std::string& game_controller_db_path);
|
||||||
@@ -100,7 +100,7 @@ class Input {
|
|||||||
static void destroy();
|
static void destroy();
|
||||||
|
|
||||||
// [SINGLETON] Con este método obtenemos el objeto y podemos trabajar con él
|
// [SINGLETON] Con este método obtenemos el objeto y podemos trabajar con él
|
||||||
static Input* get();
|
static auto get() -> Input*;
|
||||||
|
|
||||||
// Asigna inputs a teclas
|
// Asigna inputs a teclas
|
||||||
void bindKey(InputAction input, SDL_Scancode code);
|
void bindKey(InputAction input, SDL_Scancode code);
|
||||||
@@ -110,29 +110,29 @@ class Input {
|
|||||||
void bindGameControllerButton(int controller_index, InputAction input_target, InputAction input_source);
|
void bindGameControllerButton(int controller_index, InputAction input_target, InputAction input_source);
|
||||||
|
|
||||||
// Comprueba si un input esta activo
|
// Comprueba si un input esta activo
|
||||||
bool checkInput(InputAction input, bool repeat = true, InputDeviceToUse device = InputDeviceToUse::ANY, int controller_index = 0);
|
auto checkInput(InputAction input, bool repeat = true, InputDeviceToUse device = InputDeviceToUse::ANY, int controller_index = 0) -> bool;
|
||||||
|
|
||||||
// Comprueba si hay almenos un input activo
|
// Comprueba si hay almenos un input activo
|
||||||
bool checkAnyInput(InputDeviceToUse device = InputDeviceToUse::ANY, int controller_index = 0);
|
auto checkAnyInput(InputDeviceToUse device = InputDeviceToUse::ANY, int controller_index = 0) -> bool;
|
||||||
|
|
||||||
// Busca si hay mandos conectados
|
// Busca si hay mandos conectados
|
||||||
bool discoverGameControllers();
|
auto discoverGameControllers() -> bool;
|
||||||
|
|
||||||
// Comprueba si hay algun mando conectado
|
// Comprueba si hay algun mando conectado
|
||||||
bool gameControllerFound() const;
|
[[nodiscard]] auto gameControllerFound() const -> bool;
|
||||||
|
|
||||||
// Obten el número de mandos conectados
|
// Obten el número de mandos conectados
|
||||||
int getNumControllers() const;
|
[[nodiscard]] auto getNumControllers() const -> int;
|
||||||
|
|
||||||
// Obten el nombre de un mando de juego
|
// Obten el nombre de un mando de juego
|
||||||
std::string getControllerName(int controller_index) const;
|
[[nodiscard]] auto getControllerName(int controller_index) const -> std::string;
|
||||||
|
|
||||||
// Obtiene el indice del controlador a partir de un event.id
|
// Obtiene el indice del controlador a partir de un event.id
|
||||||
int getJoyIndex(SDL_JoystickID id) const;
|
[[nodiscard]] auto getJoyIndex(SDL_JoystickID id) const -> int;
|
||||||
|
|
||||||
// Obtiene el SDL_GamepadButton asignado a un input
|
// Obtiene el SDL_GamepadButton asignado a un input
|
||||||
SDL_GamepadButton getControllerBinding(int controller_index, InputAction input) const;
|
[[nodiscard]] auto getControllerBinding(int controller_index, InputAction input) const -> SDL_GamepadButton;
|
||||||
|
|
||||||
// Obtiene el indice a partir del nombre del mando
|
// Obtiene el indice a partir del nombre del mando
|
||||||
int getIndexByName(const std::string& name) const;
|
[[nodiscard]] auto getIndexByName(const std::string& name) const -> int;
|
||||||
};
|
};
|
||||||
@@ -27,7 +27,7 @@ inline void initializeDictionary(std::vector<DictionaryEntry>& dictionary, int c
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Lee los próximos bits del stream de entrada para formar un código
|
// Lee los próximos bits del stream de entrada para formar un código
|
||||||
inline int readNextCode(const uint8_t*& input, int& input_length, unsigned int& mask, int code_length) {
|
inline auto readNextCode(const uint8_t*& input, int& input_length, unsigned int& mask, int code_length) -> int {
|
||||||
int code = 0;
|
int code = 0;
|
||||||
for (int i = 0; i < (code_length + 1); i++) {
|
for (int i = 0; i < (code_length + 1); i++) {
|
||||||
if (input_length <= 0) {
|
if (input_length <= 0) {
|
||||||
@@ -46,7 +46,7 @@ inline int readNextCode(const uint8_t*& input, int& input_length, unsigned int&
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Encuentra el primer byte de una cadena del diccionario
|
// Encuentra el primer byte de una cadena del diccionario
|
||||||
inline uint8_t findFirstByte(const std::vector<DictionaryEntry>& dictionary, int code) {
|
inline auto findFirstByte(const std::vector<DictionaryEntry>& dictionary, int code) -> uint8_t {
|
||||||
int ptr = code;
|
int ptr = code;
|
||||||
while (dictionary[ptr].prev != -1) {
|
while (dictionary[ptr].prev != -1) {
|
||||||
ptr = dictionary[ptr].prev;
|
ptr = dictionary[ptr].prev;
|
||||||
@@ -76,13 +76,13 @@ inline void addDictionaryEntry(std::vector<DictionaryEntry>& dictionary, int& di
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Escribe la cadena decodificada al buffer de salida
|
// Escribe la cadena decodificada al buffer de salida
|
||||||
inline int writeDecodedString(const std::vector<DictionaryEntry>& dictionary, int code, uint8_t*& out) {
|
inline auto writeDecodedString(const std::vector<DictionaryEntry>& dictionary, int code, uint8_t*& out) -> int {
|
||||||
int cur_code = code;
|
int cur_code = code;
|
||||||
int match_len = dictionary[cur_code].len;
|
int match_len = dictionary[cur_code].len;
|
||||||
while (cur_code != -1) {
|
while (cur_code != -1) {
|
||||||
out[dictionary[cur_code].len - 1] = dictionary[cur_code].byte;
|
out[dictionary[cur_code].len - 1] = dictionary[cur_code].byte;
|
||||||
if (dictionary[cur_code].prev == cur_code) {
|
if (dictionary[cur_code].prev == cur_code) {
|
||||||
std::cerr << "Internal error; self-reference detected." << std::endl;
|
std::cerr << "Internal error; self-reference detected." << '\n';
|
||||||
throw std::runtime_error("Internal error in decompress: self-reference");
|
throw std::runtime_error("Internal error in decompress: self-reference");
|
||||||
}
|
}
|
||||||
cur_code = dictionary[cur_code].prev;
|
cur_code = dictionary[cur_code].prev;
|
||||||
@@ -127,7 +127,7 @@ void Gif::decompress(int code_length, const uint8_t* input, int input_length, ui
|
|||||||
if (prev > -1 && code_length < 12) {
|
if (prev > -1 && code_length < 12) {
|
||||||
if (code > dictionary_ind) {
|
if (code > dictionary_ind) {
|
||||||
std::cerr << "code = " << std::hex << code
|
std::cerr << "code = " << std::hex << code
|
||||||
<< ", but dictionary_ind = " << dictionary_ind << std::endl;
|
<< ", but dictionary_ind = " << dictionary_ind << '\n';
|
||||||
throw std::runtime_error("LZW error: code exceeds dictionary_ind.");
|
throw std::runtime_error("LZW error: code exceeds dictionary_ind.");
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -139,7 +139,7 @@ void Gif::decompress(int code_length, const uint8_t* input, int input_length, ui
|
|||||||
// Verifica que 'code' sea un índice válido antes de usarlo.
|
// Verifica que 'code' sea un índice válido antes de usarlo.
|
||||||
if (code < 0 || static_cast<size_t>(code) >= dictionary.size()) {
|
if (code < 0 || static_cast<size_t>(code) >= dictionary.size()) {
|
||||||
std::cerr << "Invalid LZW code " << code
|
std::cerr << "Invalid LZW code " << code
|
||||||
<< ", dictionary size " << dictionary.size() << std::endl;
|
<< ", dictionary size " << dictionary.size() << '\n';
|
||||||
throw std::runtime_error("LZW error: invalid code encountered");
|
throw std::runtime_error("LZW error: invalid code encountered");
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -147,7 +147,7 @@ void Gif::decompress(int code_length, const uint8_t* input, int input_length, ui
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
std::vector<uint8_t> Gif::readSubBlocks(const uint8_t*& buffer) {
|
auto Gif::readSubBlocks(const uint8_t*& buffer) -> std::vector<uint8_t> {
|
||||||
std::vector<uint8_t> data;
|
std::vector<uint8_t> data;
|
||||||
uint8_t block_size = *buffer;
|
uint8_t block_size = *buffer;
|
||||||
buffer++;
|
buffer++;
|
||||||
@@ -160,7 +160,7 @@ std::vector<uint8_t> Gif::readSubBlocks(const uint8_t*& buffer) {
|
|||||||
return data;
|
return data;
|
||||||
}
|
}
|
||||||
|
|
||||||
std::vector<uint8_t> Gif::processImageDescriptor(const uint8_t*& buffer, const std::vector<RGB>& gct, int resolution_bits) {
|
auto Gif::processImageDescriptor(const uint8_t*& buffer, const std::vector<RGB>& gct, int resolution_bits) -> std::vector<uint8_t> {
|
||||||
ImageDescriptor image_descriptor;
|
ImageDescriptor image_descriptor;
|
||||||
// Lee 9 bytes para el image descriptor.
|
// Lee 9 bytes para el image descriptor.
|
||||||
readBytes(buffer, &image_descriptor, sizeof(ImageDescriptor));
|
readBytes(buffer, &image_descriptor, sizeof(ImageDescriptor));
|
||||||
@@ -176,7 +176,7 @@ std::vector<uint8_t> Gif::processImageDescriptor(const uint8_t*& buffer, const s
|
|||||||
return uncompressed_data;
|
return uncompressed_data;
|
||||||
}
|
}
|
||||||
|
|
||||||
std::vector<uint32_t> Gif::loadPalette(const uint8_t* buffer) {
|
auto Gif::loadPalette(const uint8_t* buffer) -> std::vector<uint32_t> {
|
||||||
uint8_t header[6];
|
uint8_t header[6];
|
||||||
std::memcpy(header, buffer, 6);
|
std::memcpy(header, buffer, 6);
|
||||||
buffer += 6;
|
buffer += 6;
|
||||||
@@ -200,7 +200,7 @@ std::vector<uint32_t> Gif::loadPalette(const uint8_t* buffer) {
|
|||||||
return global_color_table;
|
return global_color_table;
|
||||||
}
|
}
|
||||||
|
|
||||||
std::vector<uint8_t> Gif::processGifStream(const uint8_t* buffer, uint16_t& w, uint16_t& h) {
|
auto Gif::processGifStream(const uint8_t* buffer, uint16_t& w, uint16_t& h) -> std::vector<uint8_t> {
|
||||||
// Leer la cabecera de 6 bytes ("GIF87a" o "GIF89a")
|
// Leer la cabecera de 6 bytes ("GIF87a" o "GIF89a")
|
||||||
uint8_t header[6];
|
uint8_t header[6];
|
||||||
std::memcpy(header, buffer, 6);
|
std::memcpy(header, buffer, 6);
|
||||||
@@ -280,7 +280,7 @@ std::vector<uint8_t> Gif::processGifStream(const uint8_t* buffer, uint16_t& w, u
|
|||||||
// Procesar el Image Descriptor y retornar los datos de imagen
|
// Procesar el Image Descriptor y retornar los datos de imagen
|
||||||
return processImageDescriptor(buffer, global_color_table, color_resolution_bits);
|
return processImageDescriptor(buffer, global_color_table, color_resolution_bits);
|
||||||
} else {
|
} else {
|
||||||
std::cerr << "Unrecognized block type " << std::hex << static_cast<int>(block_type) << std::endl;
|
std::cerr << "Unrecognized block type " << std::hex << static_cast<int>(block_type) << '\n';
|
||||||
return std::vector<uint8_t>{};
|
return std::vector<uint8_t>{};
|
||||||
}
|
}
|
||||||
block_type = *buffer++;
|
block_type = *buffer++;
|
||||||
@@ -289,7 +289,7 @@ std::vector<uint8_t> Gif::processGifStream(const uint8_t* buffer, uint16_t& w, u
|
|||||||
return std::vector<uint8_t>{};
|
return std::vector<uint8_t>{};
|
||||||
}
|
}
|
||||||
|
|
||||||
std::vector<uint8_t> Gif::loadGif(const uint8_t* buffer, uint16_t& w, uint16_t& h) {
|
auto Gif::loadGif(const uint8_t* buffer, uint16_t& w, uint16_t& h) -> std::vector<uint8_t> {
|
||||||
return processGifStream(buffer, w, h);
|
return processGifStream(buffer, w, h);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -72,21 +72,21 @@ class Gif {
|
|||||||
|
|
||||||
// Carga la paleta (global color table) a partir de un buffer,
|
// Carga la paleta (global color table) a partir de un buffer,
|
||||||
// retornándola en un vector de uint32_t (cada color se compone de R, G, B).
|
// retornándola en un vector de uint32_t (cada color se compone de R, G, B).
|
||||||
static std::vector<uint32_t> loadPalette(const uint8_t* buffer);
|
static auto loadPalette(const uint8_t* buffer) -> std::vector<uint32_t>;
|
||||||
|
|
||||||
// Carga el stream GIF; devuelve un vector con los datos de imagen sin comprimir y
|
// Carga el stream GIF; devuelve un vector con los datos de imagen sin comprimir y
|
||||||
// asigna el ancho y alto mediante referencias.
|
// asigna el ancho y alto mediante referencias.
|
||||||
static std::vector<uint8_t> loadGif(const uint8_t* buffer, uint16_t& w, uint16_t& h);
|
static auto loadGif(const uint8_t* buffer, uint16_t& w, uint16_t& h) -> std::vector<uint8_t>;
|
||||||
|
|
||||||
private:
|
private:
|
||||||
// Lee los sub-bloques de datos y los acumula en un std::vector<uint8_t>.
|
// Lee los sub-bloques de datos y los acumula en un std::vector<uint8_t>.
|
||||||
static std::vector<uint8_t> readSubBlocks(const uint8_t*& buffer);
|
static auto readSubBlocks(const uint8_t*& buffer) -> std::vector<uint8_t>;
|
||||||
|
|
||||||
// Procesa el Image Descriptor y retorna el vector de datos sin comprimir.
|
// Procesa el Image Descriptor y retorna el vector de datos sin comprimir.
|
||||||
static std::vector<uint8_t> processImageDescriptor(const uint8_t*& buffer, const std::vector<RGB>& gct, int resolution_bits);
|
static auto processImageDescriptor(const uint8_t*& buffer, const std::vector<RGB>& gct, int resolution_bits) -> std::vector<uint8_t>;
|
||||||
|
|
||||||
// Procesa el stream completo del GIF y devuelve los datos sin comprimir.
|
// Procesa el stream completo del GIF y devuelve los datos sin comprimir.
|
||||||
static std::vector<uint8_t> processGifStream(const uint8_t* buffer, uint16_t& w, uint16_t& h);
|
static auto processGifStream(const uint8_t* buffer, uint16_t& w, uint16_t& h) -> std::vector<uint8_t>;
|
||||||
};
|
};
|
||||||
|
|
||||||
} // namespace GIF
|
} // namespace GIF
|
||||||
|
|||||||
@@ -14,7 +14,7 @@ OpenGLShader::~OpenGLShader() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#ifndef __APPLE__
|
#ifndef __APPLE__
|
||||||
bool OpenGLShader::initGLExtensions() {
|
auto OpenGLShader::initGLExtensions() -> bool {
|
||||||
glCreateShader = (PFNGLCREATESHADERPROC)SDL_GL_GetProcAddress("glCreateShader");
|
glCreateShader = (PFNGLCREATESHADERPROC)SDL_GL_GetProcAddress("glCreateShader");
|
||||||
glShaderSource = (PFNGLSHADERSOURCEPROC)SDL_GL_GetProcAddress("glShaderSource");
|
glShaderSource = (PFNGLSHADERSOURCEPROC)SDL_GL_GetProcAddress("glShaderSource");
|
||||||
glCompileShader = (PFNGLCOMPILESHADERPROC)SDL_GL_GetProcAddress("glCompileShader");
|
glCompileShader = (PFNGLCOMPILESHADERPROC)SDL_GL_GetProcAddress("glCompileShader");
|
||||||
@@ -61,7 +61,7 @@ void OpenGLShader::checkGLError(const char* operation) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
GLuint OpenGLShader::compileShader(const std::string& source, GLenum shader_type) {
|
auto OpenGLShader::compileShader(const std::string& source, GLenum shader_type) -> GLuint {
|
||||||
if (source.empty()) {
|
if (source.empty()) {
|
||||||
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
|
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
|
||||||
"ERROR: El código fuente del shader está vacío");
|
"ERROR: El código fuente del shader está vacío");
|
||||||
@@ -104,7 +104,7 @@ GLuint OpenGLShader::compileShader(const std::string& source, GLenum shader_type
|
|||||||
return shader_id;
|
return shader_id;
|
||||||
}
|
}
|
||||||
|
|
||||||
GLuint OpenGLShader::linkProgram(GLuint vertex_shader, GLuint fragment_shader) {
|
auto OpenGLShader::linkProgram(GLuint vertex_shader, GLuint fragment_shader) -> GLuint {
|
||||||
GLuint program = glCreateProgram();
|
GLuint program = glCreateProgram();
|
||||||
if (program == 0) {
|
if (program == 0) {
|
||||||
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
|
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
|
||||||
@@ -196,7 +196,7 @@ void OpenGLShader::createQuadGeometry() {
|
|||||||
checkGLError("glBufferData(EBO)");
|
checkGLError("glBufferData(EBO)");
|
||||||
|
|
||||||
// Atributo 0: Posición (2 floats)
|
// Atributo 0: Posición (2 floats)
|
||||||
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(float), (void*)0);
|
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(float), (void*)nullptr);
|
||||||
glEnableVertexAttribArray(0);
|
glEnableVertexAttribArray(0);
|
||||||
checkGLError("glVertexAttribPointer(position)");
|
checkGLError("glVertexAttribPointer(position)");
|
||||||
|
|
||||||
@@ -210,7 +210,7 @@ void OpenGLShader::createQuadGeometry() {
|
|||||||
glBindVertexArray(0);
|
glBindVertexArray(0);
|
||||||
}
|
}
|
||||||
|
|
||||||
GLuint OpenGLShader::getTextureID(SDL_Texture* texture) {
|
auto OpenGLShader::getTextureID(SDL_Texture* texture) -> GLuint {
|
||||||
if (texture == nullptr) {
|
if (texture == nullptr) {
|
||||||
return 1;
|
return 1;
|
||||||
}
|
}
|
||||||
@@ -238,10 +238,10 @@ GLuint OpenGLShader::getTextureID(SDL_Texture* texture) {
|
|||||||
return texture_id;
|
return texture_id;
|
||||||
}
|
}
|
||||||
|
|
||||||
bool OpenGLShader::init(SDL_Window* window,
|
auto OpenGLShader::init(SDL_Window* window,
|
||||||
SDL_Texture* texture,
|
SDL_Texture* texture,
|
||||||
const std::string& vertex_source,
|
const std::string& vertex_source,
|
||||||
const std::string& fragment_source) {
|
const std::string& fragment_source) -> bool {
|
||||||
window_ = window;
|
window_ = window;
|
||||||
back_buffer_ = texture;
|
back_buffer_ = texture;
|
||||||
renderer_ = SDL_GetRenderer(window);
|
renderer_ = SDL_GetRenderer(window);
|
||||||
@@ -432,7 +432,7 @@ void OpenGLShader::render() {
|
|||||||
|
|
||||||
// Dibujar quad usando VAO
|
// Dibujar quad usando VAO
|
||||||
glBindVertexArray(vao_);
|
glBindVertexArray(vao_);
|
||||||
glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
|
glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, nullptr);
|
||||||
checkGLError("glDrawElements");
|
checkGLError("glDrawElements");
|
||||||
|
|
||||||
// Presentar
|
// Presentar
|
||||||
|
|||||||
@@ -23,23 +23,23 @@ class OpenGLShader : public ShaderBackend {
|
|||||||
OpenGLShader() = default;
|
OpenGLShader() = default;
|
||||||
~OpenGLShader() override;
|
~OpenGLShader() override;
|
||||||
|
|
||||||
bool init(SDL_Window* window,
|
auto init(SDL_Window* window,
|
||||||
SDL_Texture* texture,
|
SDL_Texture* texture,
|
||||||
const std::string& vertex_source,
|
const std::string& vertex_source,
|
||||||
const std::string& fragment_source) override;
|
const std::string& fragment_source) -> bool override;
|
||||||
|
|
||||||
void render() override;
|
void render() override;
|
||||||
void setTextureSize(float width, float height) override;
|
void setTextureSize(float width, float height) override;
|
||||||
void cleanup() final;
|
void cleanup() final;
|
||||||
bool isHardwareAccelerated() const override { return is_initialized_; }
|
[[nodiscard]] auto isHardwareAccelerated() const -> bool override { return is_initialized_; }
|
||||||
|
|
||||||
private:
|
private:
|
||||||
// Funciones auxiliares
|
// Funciones auxiliares
|
||||||
bool initGLExtensions();
|
auto initGLExtensions() -> bool;
|
||||||
GLuint compileShader(const std::string& source, GLenum shader_type);
|
auto compileShader(const std::string& source, GLenum shader_type) -> GLuint;
|
||||||
GLuint linkProgram(GLuint vertex_shader, GLuint fragment_shader);
|
auto linkProgram(GLuint vertex_shader, GLuint fragment_shader) -> GLuint;
|
||||||
void createQuadGeometry();
|
void createQuadGeometry();
|
||||||
static GLuint getTextureID(SDL_Texture* texture);
|
static auto getTextureID(SDL_Texture* texture) -> GLuint;
|
||||||
static void checkGLError(const char* operation);
|
static void checkGLError(const char* operation);
|
||||||
|
|
||||||
// Estado SDL
|
// Estado SDL
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
#include <SDL3/SDL.h>
|
#include <SDL3/SDL.h>
|
||||||
#include <stddef.h> // Para size_t
|
|
||||||
|
|
||||||
|
#include <cstddef> // Para size_t
|
||||||
#include <memory> // Para shared_ptr, __shared_ptr_access
|
#include <memory> // Para shared_ptr, __shared_ptr_access
|
||||||
#include <string> // Para string
|
#include <string> // Para string
|
||||||
#include <vector> // Para vector
|
#include <vector> // Para vector
|
||||||
@@ -32,15 +32,14 @@ class Screen {
|
|||||||
};
|
};
|
||||||
|
|
||||||
struct FPS {
|
struct FPS {
|
||||||
Uint32 ticks; // Tiempo en milisegundos desde que se comenzó a contar.
|
Uint32 ticks{0}; // Tiempo en milisegundos desde que se comenzó a contar.
|
||||||
int frame_count; // Número acumulado de frames en el intervalo.
|
int frame_count{0}; // Número acumulado de frames en el intervalo.
|
||||||
int last_value; // Número de frames calculado en el último segundo.
|
int last_value{0}; // Número de frames calculado en el último segundo.
|
||||||
|
|
||||||
// Constructor para inicializar la estructura.
|
// Constructor para inicializar la estructura.
|
||||||
FPS()
|
FPS()
|
||||||
: ticks(0),
|
|
||||||
frame_count(0),
|
{}
|
||||||
last_value(0) {}
|
|
||||||
|
|
||||||
// Incrementador que se llama en cada frame.
|
// Incrementador que se llama en cada frame.
|
||||||
void increment() {
|
void increment() {
|
||||||
@@ -48,7 +47,7 @@ class Screen {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Método para calcular y devolver el valor de FPS.
|
// Método para calcular y devolver el valor de FPS.
|
||||||
int calculate(Uint32 current_ticks) {
|
auto calculate(Uint32 current_ticks) -> int {
|
||||||
if (current_ticks - ticks >= 1000) // Si ha pasado un segundo o más.
|
if (current_ticks - ticks >= 1000) // Si ha pasado un segundo o más.
|
||||||
{
|
{
|
||||||
last_value = frame_count; // Actualizamos el valor del último FPS.
|
last_value = frame_count; // Actualizamos el valor del último FPS.
|
||||||
@@ -114,7 +113,7 @@ class Screen {
|
|||||||
void renderOverlays();
|
void renderOverlays();
|
||||||
|
|
||||||
// Localiza la paleta dentro del vector de paletas
|
// Localiza la paleta dentro del vector de paletas
|
||||||
size_t findPalette(const std::string& name);
|
auto findPalette(const std::string& name) -> size_t;
|
||||||
|
|
||||||
void initShaders(); // Inicializa los shaders
|
void initShaders(); // Inicializa los shaders
|
||||||
void loadShaders(); // Carga el contenido del archivo GLSL
|
void loadShaders(); // Carga el contenido del archivo GLSL
|
||||||
@@ -136,7 +135,7 @@ class Screen {
|
|||||||
static void destroy();
|
static void destroy();
|
||||||
|
|
||||||
// [SINGLETON] Con este método obtenemos el objeto y podemos trabajar con él
|
// [SINGLETON] Con este método obtenemos el objeto y podemos trabajar con él
|
||||||
static Screen* get();
|
static auto get() -> Screen*;
|
||||||
|
|
||||||
// Limpia el renderer
|
// Limpia el renderer
|
||||||
void clearRenderer(Color color = {0x00, 0x00, 0x00});
|
void clearRenderer(Color color = {0x00, 0x00, 0x00});
|
||||||
@@ -163,10 +162,10 @@ class Screen {
|
|||||||
void toggleIntegerScale();
|
void toggleIntegerScale();
|
||||||
|
|
||||||
// Reduce el tamaño de la ventana
|
// Reduce el tamaño de la ventana
|
||||||
bool decWindowZoom();
|
auto decWindowZoom() -> bool;
|
||||||
|
|
||||||
// Aumenta el tamaño de la ventana
|
// Aumenta el tamaño de la ventana
|
||||||
bool incWindowZoom();
|
auto incWindowZoom() -> bool;
|
||||||
|
|
||||||
// Cambia el color del borde
|
// Cambia el color del borde
|
||||||
void setBorderColor(Uint8 color);
|
void setBorderColor(Uint8 color);
|
||||||
@@ -209,7 +208,7 @@ class Screen {
|
|||||||
void toggleDebugInfo();
|
void toggleDebugInfo();
|
||||||
|
|
||||||
// Getters
|
// Getters
|
||||||
SDL_Renderer* getRenderer();
|
auto getRenderer() -> SDL_Renderer*;
|
||||||
std::shared_ptr<Surface> getRendererSurface();
|
auto getRendererSurface() -> std::shared_ptr<Surface>;
|
||||||
std::shared_ptr<Surface> getBorderSurface();
|
auto getBorderSurface() -> std::shared_ptr<Surface>;
|
||||||
};
|
};
|
||||||
@@ -24,10 +24,10 @@ class ShaderBackend {
|
|||||||
* @param fragment_source Código fuente del fragment shader
|
* @param fragment_source Código fuente del fragment shader
|
||||||
* @return true si la inicialización fue exitosa
|
* @return true si la inicialización fue exitosa
|
||||||
*/
|
*/
|
||||||
virtual bool init(SDL_Window* window,
|
virtual auto init(SDL_Window* window,
|
||||||
SDL_Texture* texture,
|
SDL_Texture* texture,
|
||||||
const std::string& vertex_source,
|
const std::string& vertex_source,
|
||||||
const std::string& fragment_source) = 0;
|
const std::string& fragment_source) -> bool = 0;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @brief Renderiza la textura con los shaders aplicados
|
* @brief Renderiza la textura con los shaders aplicados
|
||||||
@@ -50,7 +50,7 @@ class ShaderBackend {
|
|||||||
* @brief Verifica si el backend está usando aceleración por hardware
|
* @brief Verifica si el backend está usando aceleración por hardware
|
||||||
* @return true si usa aceleración (OpenGL/Metal/Vulkan)
|
* @return true si usa aceleración (OpenGL/Metal/Vulkan)
|
||||||
*/
|
*/
|
||||||
virtual bool isHardwareAccelerated() const = 0;
|
[[nodiscard]] virtual auto isHardwareAccelerated() const -> bool = 0;
|
||||||
};
|
};
|
||||||
|
|
||||||
} // namespace Rendering
|
} // namespace Rendering
|
||||||
|
|||||||
@@ -18,7 +18,7 @@
|
|||||||
#include "core/rendering/screen.hpp" // Para Screen
|
#include "core/rendering/screen.hpp" // Para Screen
|
||||||
|
|
||||||
// Carga una paleta desde un archivo .gif
|
// Carga una paleta desde un archivo .gif
|
||||||
Palette loadPalette(const std::string& file_path) {
|
auto loadPalette(const std::string& file_path) -> Palette {
|
||||||
// Abrir el archivo en modo binario
|
// Abrir el archivo en modo binario
|
||||||
std::ifstream file(file_path, std::ios::binary | std::ios::ate);
|
std::ifstream file(file_path, std::ios::binary | std::ios::ate);
|
||||||
if (!file.is_open()) {
|
if (!file.is_open()) {
|
||||||
@@ -51,7 +51,7 @@ Palette loadPalette(const std::string& file_path) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Carga una paleta desde un archivo .pal
|
// Carga una paleta desde un archivo .pal
|
||||||
Palette readPalFile(const std::string& file_path) {
|
auto readPalFile(const std::string& file_path) -> Palette {
|
||||||
Palette palette{};
|
Palette palette{};
|
||||||
palette.fill(0); // Inicializar todo con 0 (transparente por defecto)
|
palette.fill(0); // Inicializar todo con 0 (transparente por defecto)
|
||||||
|
|
||||||
@@ -107,11 +107,11 @@ Surface::Surface(const std::string& file_path)
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Carga una superficie desde un archivo
|
// Carga una superficie desde un archivo
|
||||||
SurfaceData Surface::loadSurface(const std::string& file_path) {
|
auto Surface::loadSurface(const std::string& file_path) -> SurfaceData {
|
||||||
// Abrir el archivo usando std::ifstream para manejo automático del recurso
|
// Abrir el archivo usando std::ifstream para manejo automático del recurso
|
||||||
std::ifstream file(file_path, std::ios::binary | std::ios::ate);
|
std::ifstream file(file_path, std::ios::binary | std::ios::ate);
|
||||||
if (!file.is_open()) {
|
if (!file.is_open()) {
|
||||||
std::cerr << "Error opening file: " << file_path << std::endl;
|
std::cerr << "Error opening file: " << file_path << '\n';
|
||||||
throw std::runtime_error("Error opening file");
|
throw std::runtime_error("Error opening file");
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -122,7 +122,7 @@ SurfaceData Surface::loadSurface(const std::string& file_path) {
|
|||||||
// Leer el contenido del archivo en un buffer
|
// Leer el contenido del archivo en un buffer
|
||||||
std::vector<Uint8> buffer(size);
|
std::vector<Uint8> buffer(size);
|
||||||
if (!file.read(reinterpret_cast<char*>(buffer.data()), size)) {
|
if (!file.read(reinterpret_cast<char*>(buffer.data()), size)) {
|
||||||
std::cerr << "Error reading file: " << file_path << std::endl;
|
std::cerr << "Error reading file: " << file_path << '\n';
|
||||||
throw std::runtime_error("Error reading file");
|
throw std::runtime_error("Error reading file");
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -131,7 +131,7 @@ SurfaceData Surface::loadSurface(const std::string& file_path) {
|
|||||||
Uint16 h = 0;
|
Uint16 h = 0;
|
||||||
std::vector<Uint8> raw_pixels = GIF::Gif::loadGif(buffer.data(), w, h);
|
std::vector<Uint8> raw_pixels = GIF::Gif::loadGif(buffer.data(), w, h);
|
||||||
if (raw_pixels.empty()) {
|
if (raw_pixels.empty()) {
|
||||||
std::cerr << "Error loading GIF from file: " << file_path << std::endl;
|
std::cerr << "Error loading GIF from file: " << file_path << '\n';
|
||||||
throw std::runtime_error("Error loading GIF");
|
throw std::runtime_error("Error loading GIF");
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -143,7 +143,7 @@ SurfaceData Surface::loadSurface(const std::string& file_path) {
|
|||||||
|
|
||||||
// Crear y devolver directamente el objeto SurfaceData
|
// Crear y devolver directamente el objeto SurfaceData
|
||||||
printWithDots("Surface : ", file_path.substr(file_path.find_last_of("\\/") + 1), "[ LOADED ]");
|
printWithDots("Surface : ", file_path.substr(file_path.find_last_of("\\/") + 1), "[ LOADED ]");
|
||||||
return SurfaceData(w, h, pixels);
|
return {static_cast<float>(w), static_cast<float>(h), pixels};
|
||||||
}
|
}
|
||||||
|
|
||||||
// Carga una paleta desde un archivo
|
// Carga una paleta desde un archivo
|
||||||
@@ -179,7 +179,7 @@ void Surface::putPixel(int x, int y, Uint8 color) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Obtiene el color de un pixel de la surface_data
|
// Obtiene el color de un pixel de la surface_data
|
||||||
Uint8 Surface::getPixel(int x, int y) { return surface_data_->data.get()[x + (y * static_cast<int>(surface_data_->width))]; }
|
auto Surface::getPixel(int x, int y) -> Uint8 { return surface_data_->data.get()[x + (y * static_cast<int>(surface_data_->width))]; }
|
||||||
|
|
||||||
// Dibuja un rectangulo relleno
|
// Dibuja un rectangulo relleno
|
||||||
void Surface::fillRect(const SDL_FRect* rect, Uint8 color) {
|
void Surface::fillRect(const SDL_FRect* rect, Uint8 color) {
|
||||||
@@ -527,7 +527,7 @@ void Surface::copyToTexture(SDL_Renderer* renderer, SDL_Texture* texture, SDL_FR
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Realiza un efecto de fundido en la paleta principal
|
// Realiza un efecto de fundido en la paleta principal
|
||||||
bool Surface::fadePalette() {
|
auto Surface::fadePalette() -> bool {
|
||||||
// Verificar que el tamaño mínimo de palette_ sea adecuado
|
// Verificar que el tamaño mínimo de palette_ sea adecuado
|
||||||
static constexpr int PALETTE_SIZE = 19;
|
static constexpr int PALETTE_SIZE = 19;
|
||||||
if (sizeof(palette_) / sizeof(palette_[0]) < PALETTE_SIZE) {
|
if (sizeof(palette_) / sizeof(palette_[0]) < PALETTE_SIZE) {
|
||||||
@@ -547,7 +547,7 @@ bool Surface::fadePalette() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Realiza un efecto de fundido en la paleta secundaria
|
// Realiza un efecto de fundido en la paleta secundaria
|
||||||
bool Surface::fadeSubPalette(Uint32 delay) {
|
auto Surface::fadeSubPalette(Uint32 delay) -> bool {
|
||||||
// Variable estática para almacenar el último tick
|
// Variable estática para almacenar el último tick
|
||||||
static Uint32 last_tick_ = 0;
|
static Uint32 last_tick_ = 0;
|
||||||
|
|
||||||
|
|||||||
@@ -15,10 +15,10 @@ using Palette = std::array<Uint32, 256>;
|
|||||||
using SubPalette = std::array<Uint8, 256>;
|
using SubPalette = std::array<Uint8, 256>;
|
||||||
|
|
||||||
// Carga una paleta desde un archivo .gif
|
// Carga una paleta desde un archivo .gif
|
||||||
Palette loadPalette(const std::string& file_path);
|
auto loadPalette(const std::string& file_path) -> Palette;
|
||||||
|
|
||||||
// Carga una paleta desde un archivo .pal
|
// Carga una paleta desde un archivo .pal
|
||||||
Palette readPalFile(const std::string& file_path);
|
auto readPalFile(const std::string& file_path) -> Palette;
|
||||||
|
|
||||||
struct SurfaceData {
|
struct SurfaceData {
|
||||||
std::shared_ptr<Uint8[]> data; // Usa std::shared_ptr para gestión automática
|
std::shared_ptr<Uint8[]> data; // Usa std::shared_ptr para gestión automática
|
||||||
@@ -47,11 +47,11 @@ struct SurfaceData {
|
|||||||
SurfaceData(SurfaceData&& other) noexcept = default;
|
SurfaceData(SurfaceData&& other) noexcept = default;
|
||||||
|
|
||||||
// Operador de movimiento
|
// Operador de movimiento
|
||||||
SurfaceData& operator=(SurfaceData&& other) noexcept = default;
|
auto operator=(SurfaceData&& other) noexcept -> SurfaceData& = default;
|
||||||
|
|
||||||
// Evita copias accidentales
|
// Evita copias accidentales
|
||||||
SurfaceData(const SurfaceData&) = delete;
|
SurfaceData(const SurfaceData&) = delete;
|
||||||
SurfaceData& operator=(const SurfaceData&) = delete;
|
auto operator=(const SurfaceData&) -> SurfaceData& = delete;
|
||||||
};
|
};
|
||||||
|
|
||||||
class Surface {
|
class Surface {
|
||||||
@@ -70,7 +70,7 @@ class Surface {
|
|||||||
~Surface() = default;
|
~Surface() = default;
|
||||||
|
|
||||||
// Carga una SurfaceData desde un archivo
|
// Carga una SurfaceData desde un archivo
|
||||||
static SurfaceData loadSurface(const std::string& file_path);
|
static auto loadSurface(const std::string& file_path) -> SurfaceData;
|
||||||
|
|
||||||
// Carga una paleta desde un archivo
|
// Carga una paleta desde un archivo
|
||||||
void loadPalette(const std::string& file_path);
|
void loadPalette(const std::string& file_path);
|
||||||
@@ -95,14 +95,14 @@ class Surface {
|
|||||||
void copyToTexture(SDL_Renderer* renderer, SDL_Texture* texture, SDL_FRect* src_rect, SDL_FRect* dest_rect);
|
void copyToTexture(SDL_Renderer* renderer, SDL_Texture* texture, SDL_FRect* src_rect, SDL_FRect* dest_rect);
|
||||||
|
|
||||||
// Realiza un efecto de fundido en las paletas
|
// Realiza un efecto de fundido en las paletas
|
||||||
bool fadePalette();
|
auto fadePalette() -> bool;
|
||||||
bool fadeSubPalette(Uint32 delay = 0);
|
auto fadeSubPalette(Uint32 delay = 0) -> bool;
|
||||||
|
|
||||||
// Pone un pixel en la SurfaceData
|
// Pone un pixel en la SurfaceData
|
||||||
void putPixel(int x, int y, Uint8 color);
|
void putPixel(int x, int y, Uint8 color);
|
||||||
|
|
||||||
// Obtiene el color de un pixel de la surface_data
|
// Obtiene el color de un pixel de la surface_data
|
||||||
Uint8 getPixel(int x, int y);
|
auto getPixel(int x, int y) -> Uint8;
|
||||||
|
|
||||||
// Dibuja un rectangulo relleno
|
// Dibuja un rectangulo relleno
|
||||||
void fillRect(const SDL_FRect* rect, Uint8 color);
|
void fillRect(const SDL_FRect* rect, Uint8 color);
|
||||||
@@ -114,15 +114,15 @@ class Surface {
|
|||||||
void drawLine(float x1, float y1, float x2, float y2, Uint8 color);
|
void drawLine(float x1, float y1, float x2, float y2, Uint8 color);
|
||||||
|
|
||||||
// Metodos para gestionar surface_data_
|
// Metodos para gestionar surface_data_
|
||||||
std::shared_ptr<SurfaceData> getSurfaceData() const { return surface_data_; }
|
[[nodiscard]] auto getSurfaceData() const -> std::shared_ptr<SurfaceData> { return surface_data_; }
|
||||||
void setSurfaceData(std::shared_ptr<SurfaceData> new_data) { surface_data_ = new_data; }
|
void setSurfaceData(std::shared_ptr<SurfaceData> new_data) { surface_data_ = std::move(new_data); }
|
||||||
|
|
||||||
// Obtien ancho y alto
|
// Obtien ancho y alto
|
||||||
float getWidth() const { return surface_data_->width; }
|
[[nodiscard]] auto getWidth() const -> float { return surface_data_->width; }
|
||||||
float getHeight() const { return surface_data_->height; }
|
[[nodiscard]] auto getHeight() const -> float { return surface_data_->height; }
|
||||||
|
|
||||||
// Color transparente
|
// Color transparente
|
||||||
Uint8 getTransparentColor() const { return transparent_color_; }
|
[[nodiscard]] auto getTransparentColor() const -> Uint8 { return transparent_color_; }
|
||||||
void setTransparentColor(Uint8 color = 255) { transparent_color_ = color; }
|
void setTransparentColor(Uint8 color = 255) { transparent_color_ = color; }
|
||||||
|
|
||||||
// Paleta
|
// Paleta
|
||||||
|
|||||||
@@ -1,20 +1,20 @@
|
|||||||
#include "core/rendering/surface_animated_sprite.hpp"
|
#include "core/rendering/surface_animated_sprite.hpp"
|
||||||
|
|
||||||
#include <stddef.h> // Para size_t
|
#include <cstddef> // Para size_t
|
||||||
|
|
||||||
#include <fstream> // Para basic_ostream, basic_istream, operator<<, basic...
|
#include <fstream> // Para basic_ostream, basic_istream, operator<<, basic...
|
||||||
#include <iostream> // Para cout, cerr
|
#include <iostream> // Para cout, cerr
|
||||||
#include <sstream> // Para basic_stringstream
|
#include <sstream> // Para basic_stringstream
|
||||||
#include <stdexcept> // Para runtime_error
|
#include <stdexcept> // Para runtime_error
|
||||||
|
#include <utility>
|
||||||
|
|
||||||
#include "core/rendering/surface.hpp" // Para Surface
|
#include "core/rendering/surface.hpp" // Para Surface
|
||||||
#include "utils/utils.hpp" // Para printWithDots
|
#include "utils/utils.hpp" // Para printWithDots
|
||||||
|
|
||||||
// Carga las animaciones en un vector(Animations) desde un fichero
|
// Carga las animaciones en un vector(Animations) desde un fichero
|
||||||
Animations loadAnimationsFromFile(const std::string& file_path) {
|
auto loadAnimationsFromFile(const std::string& file_path) -> Animations {
|
||||||
std::ifstream file(file_path);
|
std::ifstream file(file_path);
|
||||||
if (!file) {
|
if (!file) {
|
||||||
std::cerr << "Error: Fichero no encontrado " << file_path << std::endl;
|
std::cerr << "Error: Fichero no encontrado " << file_path << '\n';
|
||||||
throw std::runtime_error("Fichero no encontrado: " + file_path);
|
throw std::runtime_error("Fichero no encontrado: " + file_path);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -33,7 +33,7 @@ Animations loadAnimationsFromFile(const std::string& file_path) {
|
|||||||
|
|
||||||
// Constructor
|
// Constructor
|
||||||
SurfaceAnimatedSprite::SurfaceAnimatedSprite(std::shared_ptr<Surface> surface, const std::string& file_path)
|
SurfaceAnimatedSprite::SurfaceAnimatedSprite(std::shared_ptr<Surface> surface, const std::string& file_path)
|
||||||
: SurfaceMovingSprite(surface) {
|
: SurfaceMovingSprite(std::move(surface)) {
|
||||||
// Carga las animaciones
|
// Carga las animaciones
|
||||||
if (!file_path.empty()) {
|
if (!file_path.empty()) {
|
||||||
Animations v = loadAnimationsFromFile(file_path);
|
Animations v = loadAnimationsFromFile(file_path);
|
||||||
@@ -43,14 +43,14 @@ SurfaceAnimatedSprite::SurfaceAnimatedSprite(std::shared_ptr<Surface> surface, c
|
|||||||
|
|
||||||
// Constructor
|
// Constructor
|
||||||
SurfaceAnimatedSprite::SurfaceAnimatedSprite(std::shared_ptr<Surface> surface, const Animations& animations)
|
SurfaceAnimatedSprite::SurfaceAnimatedSprite(std::shared_ptr<Surface> surface, const Animations& animations)
|
||||||
: SurfaceMovingSprite(surface) {
|
: SurfaceMovingSprite(std::move(surface)) {
|
||||||
if (!animations.empty()) {
|
if (!animations.empty()) {
|
||||||
setAnimations(animations);
|
setAnimations(animations);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Obtiene el indice de la animación a partir del nombre
|
// Obtiene el indice de la animación a partir del nombre
|
||||||
int SurfaceAnimatedSprite::getIndex(const std::string& name) {
|
auto SurfaceAnimatedSprite::getIndex(const std::string& name) -> int {
|
||||||
auto index = -1;
|
auto index = -1;
|
||||||
|
|
||||||
for (const auto& a : animations_) {
|
for (const auto& a : animations_) {
|
||||||
@@ -59,7 +59,7 @@ int SurfaceAnimatedSprite::getIndex(const std::string& name) {
|
|||||||
return index;
|
return index;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
std::cout << "** Warning: could not find \"" << name.c_str() << "\" animation" << std::endl;
|
std::cout << "** Warning: could not find \"" << name.c_str() << "\" animation" << '\n';
|
||||||
return -1;
|
return -1;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -94,7 +94,7 @@ void SurfaceAnimatedSprite::animate() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Comprueba si ha terminado la animación
|
// Comprueba si ha terminado la animación
|
||||||
bool SurfaceAnimatedSprite::animationIsCompleted() {
|
auto SurfaceAnimatedSprite::animationIsCompleted() -> bool {
|
||||||
return animations_[current_animation_].completed;
|
return animations_[current_animation_].completed;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -136,8 +136,8 @@ void SurfaceAnimatedSprite::resetAnimation() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Helper: Parsea los parámetros de configuración globales (frame_width, frame_height)
|
// Helper: Parsea los parámetros de configuración globales (frame_width, frame_height)
|
||||||
bool parseGlobalParameter(const std::string& line, float& frame_width, float& frame_height) {
|
auto parseGlobalParameter(const std::string& line, float& frame_width, float& frame_height) -> bool {
|
||||||
size_t pos = line.find("=");
|
size_t pos = line.find('=');
|
||||||
if (pos == std::string::npos) {
|
if (pos == std::string::npos) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
@@ -154,7 +154,7 @@ bool parseGlobalParameter(const std::string& line, float& frame_width, float& fr
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
std::cout << "Warning: unknown parameter " << key << std::endl;
|
std::cout << "Warning: unknown parameter " << key << '\n';
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -177,10 +177,7 @@ void parseAnimationFrames(const std::string& value, AnimationData& animation,
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Helper: Parsea un parámetro de animación individual
|
// Helper: Parsea un parámetro de animación individual
|
||||||
bool parseAnimationParameter(const std::string& key, const std::string& value,
|
auto parseAnimationParameter(const std::string& key, const std::string& value, AnimationData& animation, float frame_width, float frame_height, int frames_per_row, int max_tiles) -> bool {
|
||||||
AnimationData& animation,
|
|
||||||
float frame_width, float frame_height,
|
|
||||||
int frames_per_row, int max_tiles) {
|
|
||||||
if (key == "name") {
|
if (key == "name") {
|
||||||
animation.name = value;
|
animation.name = value;
|
||||||
return true;
|
return true;
|
||||||
@@ -198,21 +195,19 @@ bool parseAnimationParameter(const std::string& key, const std::string& value,
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
std::cout << "Warning: unknown parameter " << key << std::endl;
|
std::cout << "Warning: unknown parameter " << key << '\n';
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Helper: Parsea una animación completa
|
// Helper: Parsea una animación completa
|
||||||
AnimationData parseAnimation(const Animations& animations, size_t& index,
|
auto parseAnimation(const Animations& animations, size_t& index, float frame_width, float frame_height, int frames_per_row, int max_tiles) -> AnimationData {
|
||||||
float frame_width, float frame_height,
|
|
||||||
int frames_per_row, int max_tiles) {
|
|
||||||
AnimationData animation;
|
AnimationData animation;
|
||||||
std::string line;
|
std::string line;
|
||||||
|
|
||||||
do {
|
do {
|
||||||
index++;
|
index++;
|
||||||
line = animations.at(index);
|
line = animations.at(index);
|
||||||
size_t pos = line.find("=");
|
size_t pos = line.find('=');
|
||||||
|
|
||||||
if (pos != std::string::npos) {
|
if (pos != std::string::npos) {
|
||||||
std::string key = line.substr(0, pos);
|
std::string key = line.substr(0, pos);
|
||||||
@@ -234,7 +229,7 @@ void SurfaceAnimatedSprite::setAnimations(const Animations& animations) {
|
|||||||
|
|
||||||
size_t index = 0;
|
size_t index = 0;
|
||||||
while (index < animations.size()) {
|
while (index < animations.size()) {
|
||||||
std::string line = animations.at(index);
|
const std::string& line = animations.at(index);
|
||||||
|
|
||||||
// Parsea el fichero para buscar variables y valores
|
// Parsea el fichero para buscar variables y valores
|
||||||
if (line != "[animation]") {
|
if (line != "[animation]") {
|
||||||
|
|||||||
@@ -4,6 +4,7 @@
|
|||||||
|
|
||||||
#include <memory> // Para shared_ptr
|
#include <memory> // Para shared_ptr
|
||||||
#include <string> // Para string
|
#include <string> // Para string
|
||||||
|
#include <utility>
|
||||||
#include <vector> // Para vector
|
#include <vector> // Para vector
|
||||||
|
|
||||||
#include "core/rendering/surface_moving_sprite.hpp" // Para SMovingSprite
|
#include "core/rendering/surface_moving_sprite.hpp" // Para SMovingSprite
|
||||||
@@ -12,24 +13,21 @@ class Surface; // lines 9-9
|
|||||||
struct AnimationData {
|
struct AnimationData {
|
||||||
std::string name; // Nombre de la animacion
|
std::string name; // Nombre de la animacion
|
||||||
std::vector<SDL_FRect> frames; // Cada uno de los frames que componen la animación
|
std::vector<SDL_FRect> frames; // Cada uno de los frames que componen la animación
|
||||||
int speed; // Velocidad de la animación
|
int speed{5}; // Velocidad de la animación
|
||||||
int loop; // Indica a que frame vuelve la animación al terminar. -1 para que no vuelva
|
int loop{0}; // Indica a que frame vuelve la animación al terminar. -1 para que no vuelva
|
||||||
bool completed; // Indica si ha finalizado la animación
|
bool completed{false}; // Indica si ha finalizado la animación
|
||||||
int current_frame; // Frame actual
|
int current_frame{0}; // Frame actual
|
||||||
int counter; // Contador para las animaciones
|
int counter{0}; // Contador para las animaciones
|
||||||
|
|
||||||
AnimationData()
|
AnimationData()
|
||||||
: speed(5),
|
|
||||||
loop(0),
|
{}
|
||||||
completed(false),
|
|
||||||
current_frame(0),
|
|
||||||
counter(0) {}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
using Animations = std::vector<std::string>;
|
using Animations = std::vector<std::string>;
|
||||||
|
|
||||||
// Carga las animaciones en un vector(Animations) desde un fichero
|
// Carga las animaciones en un vector(Animations) desde un fichero
|
||||||
Animations loadAnimationsFromFile(const std::string& file_path);
|
auto loadAnimationsFromFile(const std::string& file_path) -> Animations;
|
||||||
|
|
||||||
class SurfaceAnimatedSprite : public SurfaceMovingSprite {
|
class SurfaceAnimatedSprite : public SurfaceMovingSprite {
|
||||||
protected:
|
protected:
|
||||||
@@ -48,19 +46,19 @@ class SurfaceAnimatedSprite : public SurfaceMovingSprite {
|
|||||||
SurfaceAnimatedSprite(std::shared_ptr<Surface> surface, const std::string& file_path);
|
SurfaceAnimatedSprite(std::shared_ptr<Surface> surface, const std::string& file_path);
|
||||||
SurfaceAnimatedSprite(std::shared_ptr<Surface> surface, const Animations& animations);
|
SurfaceAnimatedSprite(std::shared_ptr<Surface> surface, const Animations& animations);
|
||||||
explicit SurfaceAnimatedSprite(std::shared_ptr<Surface> surface)
|
explicit SurfaceAnimatedSprite(std::shared_ptr<Surface> surface)
|
||||||
: SurfaceMovingSprite(surface) {}
|
: SurfaceMovingSprite(std::move(surface)) {}
|
||||||
|
|
||||||
// Destructor
|
// Destructor
|
||||||
virtual ~SurfaceAnimatedSprite() override = default;
|
~SurfaceAnimatedSprite() override = default;
|
||||||
|
|
||||||
// Actualiza las variables del objeto
|
// Actualiza las variables del objeto
|
||||||
void update() override;
|
void update() override;
|
||||||
|
|
||||||
// Comprueba si ha terminado la animación
|
// Comprueba si ha terminado la animación
|
||||||
bool animationIsCompleted();
|
auto animationIsCompleted() -> bool;
|
||||||
|
|
||||||
// Obtiene el indice de la animación a partir del nombre
|
// Obtiene el indice de la animación a partir del nombre
|
||||||
int getIndex(const std::string& name);
|
auto getIndex(const std::string& name) -> int;
|
||||||
|
|
||||||
// Establece la animacion actual
|
// Establece la animacion actual
|
||||||
void setCurrentAnimation(const std::string& name = "default");
|
void setCurrentAnimation(const std::string& name = "default");
|
||||||
@@ -73,5 +71,5 @@ class SurfaceAnimatedSprite : public SurfaceMovingSprite {
|
|||||||
void setCurrentAnimationFrame(int num);
|
void setCurrentAnimationFrame(int num);
|
||||||
|
|
||||||
// Obtiene el numero de frames de la animación actual
|
// Obtiene el numero de frames de la animación actual
|
||||||
int getCurrentAnimationSize() { return static_cast<int>(animations_[current_animation_].frames.size()); }
|
auto getCurrentAnimationSize() -> int { return static_cast<int>(animations_[current_animation_].frames.size()); }
|
||||||
};
|
};
|
||||||
@@ -1,22 +1,24 @@
|
|||||||
#include "core/rendering/surface_moving_sprite.hpp"
|
#include "core/rendering/surface_moving_sprite.hpp"
|
||||||
|
|
||||||
|
#include <utility>
|
||||||
|
|
||||||
#include "core/rendering/surface.hpp" // Para Surface
|
#include "core/rendering/surface.hpp" // Para Surface
|
||||||
|
|
||||||
// Constructor
|
// Constructor
|
||||||
SurfaceMovingSprite::SurfaceMovingSprite(std::shared_ptr<Surface> surface, SDL_FRect pos, SDL_FlipMode flip)
|
SurfaceMovingSprite::SurfaceMovingSprite(std::shared_ptr<Surface> surface, SDL_FRect pos, SDL_FlipMode flip)
|
||||||
: SurfaceSprite(surface, pos),
|
: SurfaceSprite(std::move(surface), pos),
|
||||||
x_(pos.x),
|
x_(pos.x),
|
||||||
y_(pos.y),
|
y_(pos.y),
|
||||||
flip_(flip) { SurfaceSprite::pos_ = pos; }
|
flip_(flip) { SurfaceSprite::pos_ = pos; }
|
||||||
|
|
||||||
SurfaceMovingSprite::SurfaceMovingSprite(std::shared_ptr<Surface> surface, SDL_FRect pos)
|
SurfaceMovingSprite::SurfaceMovingSprite(std::shared_ptr<Surface> surface, SDL_FRect pos)
|
||||||
: SurfaceSprite(surface, pos),
|
: SurfaceSprite(std::move(surface), pos),
|
||||||
x_(pos.x),
|
x_(pos.x),
|
||||||
y_(pos.y),
|
y_(pos.y),
|
||||||
flip_(SDL_FLIP_NONE) { SurfaceSprite::pos_ = pos; }
|
flip_(SDL_FLIP_NONE) { SurfaceSprite::pos_ = pos; }
|
||||||
|
|
||||||
SurfaceMovingSprite::SurfaceMovingSprite(std::shared_ptr<Surface> surface)
|
SurfaceMovingSprite::SurfaceMovingSprite(std::shared_ptr<Surface> surface)
|
||||||
: SurfaceSprite(surface),
|
: SurfaceSprite(std::move(surface)),
|
||||||
x_(0.0F),
|
x_(0.0F),
|
||||||
y_(0.0F),
|
y_(0.0F),
|
||||||
flip_(SDL_FLIP_NONE) { SurfaceSprite::clear(); }
|
flip_(SDL_FLIP_NONE) { SurfaceSprite::clear(); }
|
||||||
|
|||||||
@@ -32,7 +32,7 @@ class SurfaceMovingSprite : public SurfaceSprite {
|
|||||||
explicit SurfaceMovingSprite(std::shared_ptr<Surface> surface);
|
explicit SurfaceMovingSprite(std::shared_ptr<Surface> surface);
|
||||||
|
|
||||||
// Destructor
|
// Destructor
|
||||||
virtual ~SurfaceMovingSprite() override = default;
|
~SurfaceMovingSprite() override = default;
|
||||||
|
|
||||||
// Actualiza las variables internas del objeto
|
// Actualiza las variables internas del objeto
|
||||||
virtual void update();
|
virtual void update();
|
||||||
@@ -45,12 +45,12 @@ class SurfaceMovingSprite : public SurfaceSprite {
|
|||||||
void render(Uint8 source_color, Uint8 target_color) override;
|
void render(Uint8 source_color, Uint8 target_color) override;
|
||||||
|
|
||||||
// Obtiene la variable
|
// Obtiene la variable
|
||||||
float getPosX() const { return x_; }
|
[[nodiscard]] auto getPosX() const -> float { return x_; }
|
||||||
float getPosY() const { return y_; }
|
[[nodiscard]] auto getPosY() const -> float { return y_; }
|
||||||
float getVelX() const { return vx_; }
|
[[nodiscard]] auto getVelX() const -> float { return vx_; }
|
||||||
float getVelY() const { return vy_; }
|
[[nodiscard]] auto getVelY() const -> float { return vy_; }
|
||||||
float getAccelX() const { return ax_; }
|
[[nodiscard]] auto getAccelX() const -> float { return ax_; }
|
||||||
float getAccelY() const { return ay_; }
|
[[nodiscard]] auto getAccelY() const -> float { return ay_; }
|
||||||
|
|
||||||
// Establece la variable
|
// Establece la variable
|
||||||
void setVelX(float value) { vx_ = value; }
|
void setVelX(float value) { vx_ = value; }
|
||||||
@@ -65,7 +65,7 @@ class SurfaceMovingSprite : public SurfaceSprite {
|
|||||||
void flip() { flip_ = (flip_ == SDL_FLIP_HORIZONTAL) ? SDL_FLIP_NONE : SDL_FLIP_HORIZONTAL; }
|
void flip() { flip_ = (flip_ == SDL_FLIP_HORIZONTAL) ? SDL_FLIP_NONE : SDL_FLIP_HORIZONTAL; }
|
||||||
|
|
||||||
// Obtiene el valor de la variable
|
// Obtiene el valor de la variable
|
||||||
SDL_FlipMode getFlip() { return flip_; }
|
auto getFlip() -> SDL_FlipMode { return flip_; }
|
||||||
|
|
||||||
// Establece la posición y_ el tamaño del objeto
|
// Establece la posición y_ el tamaño del objeto
|
||||||
void setPos(SDL_FRect rect);
|
void setPos(SDL_FRect rect);
|
||||||
|
|||||||
@@ -1,20 +1,22 @@
|
|||||||
#include "core/rendering/surface_sprite.hpp"
|
#include "core/rendering/surface_sprite.hpp"
|
||||||
|
|
||||||
|
#include <utility>
|
||||||
|
|
||||||
#include "core/rendering/surface.hpp" // Para Surface
|
#include "core/rendering/surface.hpp" // Para Surface
|
||||||
|
|
||||||
// Constructor
|
// Constructor
|
||||||
SurfaceSprite::SurfaceSprite(std::shared_ptr<Surface> surface, float x, float y, float w, float h)
|
SurfaceSprite::SurfaceSprite(std::shared_ptr<Surface> surface, float x, float y, float w, float h)
|
||||||
: surface_(surface),
|
: surface_(std::move(std::move(surface))),
|
||||||
pos_((SDL_FRect){x, y, w, h}),
|
pos_((SDL_FRect){x, y, w, h}),
|
||||||
clip_((SDL_FRect){0.0F, 0.0F, pos_.w, pos_.h}) {}
|
clip_((SDL_FRect){0.0F, 0.0F, pos_.w, pos_.h}) {}
|
||||||
|
|
||||||
SurfaceSprite::SurfaceSprite(std::shared_ptr<Surface> surface, SDL_FRect rect)
|
SurfaceSprite::SurfaceSprite(std::shared_ptr<Surface> surface, SDL_FRect rect)
|
||||||
: surface_(surface),
|
: surface_(std::move(std::move(surface))),
|
||||||
pos_(rect),
|
pos_(rect),
|
||||||
clip_((SDL_FRect){0, 0, pos_.w, pos_.h}) {}
|
clip_((SDL_FRect){0, 0, pos_.w, pos_.h}) {}
|
||||||
|
|
||||||
SurfaceSprite::SurfaceSprite(std::shared_ptr<Surface> surface)
|
SurfaceSprite::SurfaceSprite(std::shared_ptr<Surface> surface)
|
||||||
: surface_(surface),
|
: surface_(std::move(std::move(surface))),
|
||||||
pos_((SDL_FRect){0.0F, 0.0F, surface_->getWidth(), surface_->getHeight()}),
|
pos_((SDL_FRect){0.0F, 0.0F, surface_->getWidth(), surface_->getHeight()}),
|
||||||
clip_(pos_) {}
|
clip_(pos_) {}
|
||||||
|
|
||||||
@@ -41,6 +43,6 @@ void SurfaceSprite::setPosition(SDL_FPoint p) {
|
|||||||
|
|
||||||
// Reinicia las variables a cero
|
// Reinicia las variables a cero
|
||||||
void SurfaceSprite::clear() {
|
void SurfaceSprite::clear() {
|
||||||
pos_ = {0, 0, 0, 0};
|
pos_ = {.x = 0, .y = 0, .w = 0, .h = 0};
|
||||||
clip_ = {0, 0, 0, 0};
|
clip_ = {.x = 0, .y = 0, .w = 0, .h = 0};
|
||||||
}
|
}
|
||||||
@@ -3,6 +3,7 @@
|
|||||||
#include <SDL3/SDL.h>
|
#include <SDL3/SDL.h>
|
||||||
|
|
||||||
#include <memory> // Para shared_ptr
|
#include <memory> // Para shared_ptr
|
||||||
|
#include <utility>
|
||||||
class Surface; // lines 5-5
|
class Surface; // lines 5-5
|
||||||
|
|
||||||
// Clase SurfaceSprite
|
// Clase SurfaceSprite
|
||||||
@@ -30,14 +31,14 @@ class SurfaceSprite {
|
|||||||
virtual void clear();
|
virtual void clear();
|
||||||
|
|
||||||
// Obtiene la posición y el tamaño
|
// Obtiene la posición y el tamaño
|
||||||
float getX() const { return pos_.x; }
|
[[nodiscard]] auto getX() const -> float { return pos_.x; }
|
||||||
float getY() const { return pos_.y; }
|
[[nodiscard]] auto getY() const -> float { return pos_.y; }
|
||||||
float getWidth() const { return pos_.w; }
|
[[nodiscard]] auto getWidth() const -> float { return pos_.w; }
|
||||||
float getHeight() const { return pos_.h; }
|
[[nodiscard]] auto getHeight() const -> float { return pos_.h; }
|
||||||
|
|
||||||
// Devuelve el rectangulo donde está el sprite
|
// Devuelve el rectangulo donde está el sprite
|
||||||
SDL_FRect getPosition() const { return pos_; }
|
[[nodiscard]] auto getPosition() const -> SDL_FRect { return pos_; }
|
||||||
SDL_FRect& getRect() { return pos_; }
|
auto getRect() -> SDL_FRect& { return pos_; }
|
||||||
|
|
||||||
// Establece la posición y el tamaño
|
// Establece la posición y el tamaño
|
||||||
void setX(float x) { pos_.x = x; }
|
void setX(float x) { pos_.x = x; }
|
||||||
@@ -55,15 +56,15 @@ class SurfaceSprite {
|
|||||||
void incY(float value) { pos_.y += value; }
|
void incY(float value) { pos_.y += value; }
|
||||||
|
|
||||||
// Obtiene el rectangulo que se dibuja de la surface
|
// Obtiene el rectangulo que se dibuja de la surface
|
||||||
SDL_FRect getClip() const { return clip_; }
|
[[nodiscard]] auto getClip() const -> SDL_FRect { return clip_; }
|
||||||
|
|
||||||
// Establece el rectangulo que se dibuja de la surface
|
// Establece el rectangulo que se dibuja de la surface
|
||||||
void setClip(SDL_FRect rect) { clip_ = rect; }
|
void setClip(SDL_FRect rect) { clip_ = rect; }
|
||||||
void setClip(float x, float y, float w, float h) { clip_ = (SDL_FRect){x, y, w, h}; }
|
void setClip(float x, float y, float w, float h) { clip_ = (SDL_FRect){x, y, w, h}; }
|
||||||
|
|
||||||
// Obtiene un puntero a la surface
|
// Obtiene un puntero a la surface
|
||||||
std::shared_ptr<Surface> getSurface() const { return surface_; }
|
[[nodiscard]] auto getSurface() const -> std::shared_ptr<Surface> { return surface_; }
|
||||||
|
|
||||||
// Establece la surface a utilizar
|
// Establece la surface a utilizar
|
||||||
void setSurface(std::shared_ptr<Surface> surface) { surface_ = surface; }
|
void setSurface(std::shared_ptr<Surface> surface) { surface_ = std::move(surface); }
|
||||||
};
|
};
|
||||||
@@ -1,8 +1,8 @@
|
|||||||
#include "core/rendering/text.hpp"
|
#include "core/rendering/text.hpp"
|
||||||
|
|
||||||
#include <SDL3/SDL.h>
|
#include <SDL3/SDL.h>
|
||||||
#include <stddef.h> // Para size_t
|
|
||||||
|
|
||||||
|
#include <cstddef> // Para size_t
|
||||||
#include <fstream> // Para basic_ifstream, basic_istream, basic_ostream
|
#include <fstream> // Para basic_ifstream, basic_istream, basic_ostream
|
||||||
#include <iostream> // Para cerr
|
#include <iostream> // Para cerr
|
||||||
#include <stdexcept> // Para runtime_error
|
#include <stdexcept> // Para runtime_error
|
||||||
@@ -13,14 +13,14 @@
|
|||||||
#include "utils/utils.hpp" // Para getFileName, stringToColor, printWithDots
|
#include "utils/utils.hpp" // Para getFileName, stringToColor, printWithDots
|
||||||
|
|
||||||
// Llena una estructuta TextFile desde un fichero
|
// Llena una estructuta TextFile desde un fichero
|
||||||
std::shared_ptr<TextFile> loadTextFile(const std::string& file_path) {
|
auto loadTextFile(const std::string& file_path) -> std::shared_ptr<TextFile> {
|
||||||
auto tf = std::make_shared<TextFile>();
|
auto tf = std::make_shared<TextFile>();
|
||||||
|
|
||||||
// Inicializa a cero el vector con las coordenadas
|
// Inicializa a cero el vector con las coordenadas
|
||||||
for (int i = 0; i < 128; ++i) {
|
for (auto& i : tf->offset) {
|
||||||
tf->offset[i].x = 0;
|
i.x = 0;
|
||||||
tf->offset[i].y = 0;
|
i.y = 0;
|
||||||
tf->offset[i].w = 0;
|
i.w = 0;
|
||||||
tf->box_width = 0;
|
tf->box_width = 0;
|
||||||
tf->box_height = 0;
|
tf->box_height = 0;
|
||||||
}
|
}
|
||||||
@@ -61,7 +61,7 @@ std::shared_ptr<TextFile> loadTextFile(const std::string& file_path) {
|
|||||||
|
|
||||||
// El fichero no se puede abrir
|
// El fichero no se puede abrir
|
||||||
else {
|
else {
|
||||||
std::cerr << "Error: Fichero no encontrado " << getFileName(file_path) << std::endl;
|
std::cerr << "Error: Fichero no encontrado " << getFileName(file_path) << '\n';
|
||||||
throw std::runtime_error("Fichero no encontrado: " + getFileName(file_path));
|
throw std::runtime_error("Fichero no encontrado: " + getFileName(file_path));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -75,7 +75,7 @@ std::shared_ptr<TextFile> loadTextFile(const std::string& file_path) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Constructor
|
// Constructor
|
||||||
Text::Text(std::shared_ptr<Surface> surface, const std::string& text_file) {
|
Text::Text(const std::shared_ptr<Surface>& surface, const std::string& text_file) {
|
||||||
// Carga los offsets desde el fichero
|
// Carga los offsets desde el fichero
|
||||||
auto tf = loadTextFile(text_file);
|
auto tf = loadTextFile(text_file);
|
||||||
|
|
||||||
@@ -96,7 +96,7 @@ Text::Text(std::shared_ptr<Surface> surface, const std::string& text_file) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Constructor
|
// Constructor
|
||||||
Text::Text(std::shared_ptr<Surface> surface, std::shared_ptr<TextFile> text_file) {
|
Text::Text(const std::shared_ptr<Surface>& surface, const std::shared_ptr<TextFile>& text_file) {
|
||||||
// Inicializa variables desde la estructura
|
// Inicializa variables desde la estructura
|
||||||
box_height_ = text_file->box_height;
|
box_height_ = text_file->box_height;
|
||||||
box_width_ = text_file->box_width;
|
box_width_ = text_file->box_width;
|
||||||
@@ -132,7 +132,7 @@ void Text::write(int x, int y, const std::string& text, int kerning, int lenght)
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Escribe el texto en una surface
|
// Escribe el texto en una surface
|
||||||
std::shared_ptr<Surface> Text::writeToSurface(const std::string& text, int zoom, int kerning) {
|
auto Text::writeToSurface(const std::string& text, int zoom, int kerning) -> std::shared_ptr<Surface> {
|
||||||
auto width = lenght(text, kerning) * zoom;
|
auto width = lenght(text, kerning) * zoom;
|
||||||
auto height = box_height_ * zoom;
|
auto height = box_height_ * zoom;
|
||||||
auto surface = std::make_shared<Surface>(width, height);
|
auto surface = std::make_shared<Surface>(width, height);
|
||||||
@@ -146,7 +146,7 @@ std::shared_ptr<Surface> Text::writeToSurface(const std::string& text, int zoom,
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Escribe el texto con extras en una surface
|
// Escribe el texto con extras en una surface
|
||||||
std::shared_ptr<Surface> Text::writeDXToSurface(Uint8 flags, const std::string& text, int kerning, Uint8 text_color, Uint8 shadow_distance, Uint8 shadow_color, int lenght) {
|
auto Text::writeDXToSurface(Uint8 flags, const std::string& text, int kerning, Uint8 text_color, Uint8 shadow_distance, Uint8 shadow_color, int lenght) -> std::shared_ptr<Surface> {
|
||||||
auto width = Text::lenght(text, kerning) + shadow_distance;
|
auto width = Text::lenght(text, kerning) + shadow_distance;
|
||||||
auto height = box_height_ + shadow_distance;
|
auto height = box_height_ + shadow_distance;
|
||||||
auto surface = std::make_shared<Surface>(width, height);
|
auto surface = std::make_shared<Surface>(width, height);
|
||||||
@@ -223,7 +223,7 @@ void Text::writeDX(Uint8 flags, int x, int y, const std::string& text, int kerni
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Obtiene la longitud en pixels de una cadena
|
// Obtiene la longitud en pixels de una cadena
|
||||||
int Text::lenght(const std::string& text, int kerning) const {
|
auto Text::lenght(const std::string& text, int kerning) const -> int {
|
||||||
int shift = 0;
|
int shift = 0;
|
||||||
for (size_t i = 0; i < text.length(); ++i) {
|
for (size_t i = 0; i < text.length(); ++i) {
|
||||||
shift += (offset_[static_cast<int>(text[i])].w + kerning);
|
shift += (offset_[static_cast<int>(text[i])].w + kerning);
|
||||||
@@ -234,7 +234,7 @@ int Text::lenght(const std::string& text, int kerning) const {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Devuelve el valor de la variable
|
// Devuelve el valor de la variable
|
||||||
int Text::getCharacterSize() const {
|
auto Text::getCharacterSize() const -> int {
|
||||||
return box_width_;
|
return box_width_;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -24,7 +24,7 @@ struct TextFile {
|
|||||||
};
|
};
|
||||||
|
|
||||||
// Llena una estructuta TextFile desde un fichero
|
// Llena una estructuta TextFile desde un fichero
|
||||||
std::shared_ptr<TextFile> loadTextFile(const std::string& file_path);
|
auto loadTextFile(const std::string& file_path) -> std::shared_ptr<TextFile>;
|
||||||
|
|
||||||
// Clase texto. Pinta texto en pantalla a partir de un bitmap
|
// Clase texto. Pinta texto en pantalla a partir de un bitmap
|
||||||
class Text {
|
class Text {
|
||||||
@@ -40,8 +40,8 @@ class Text {
|
|||||||
|
|
||||||
public:
|
public:
|
||||||
// Constructor
|
// Constructor
|
||||||
Text(std::shared_ptr<Surface> surface, const std::string& text_file);
|
Text(const std::shared_ptr<Surface>& surface, const std::string& text_file);
|
||||||
Text(std::shared_ptr<Surface> surface, std::shared_ptr<TextFile> text_file);
|
Text(const std::shared_ptr<Surface>& surface, const std::shared_ptr<TextFile>& text_file);
|
||||||
|
|
||||||
// Destructor
|
// Destructor
|
||||||
~Text() = default;
|
~Text() = default;
|
||||||
@@ -50,10 +50,10 @@ class Text {
|
|||||||
void write(int x, int y, const std::string& text, int kerning = 1, int lenght = -1);
|
void write(int x, int y, const std::string& text, int kerning = 1, int lenght = -1);
|
||||||
|
|
||||||
// Escribe el texto en una textura
|
// Escribe el texto en una textura
|
||||||
std::shared_ptr<Surface> writeToSurface(const std::string& text, int zoom = 1, int kerning = 1);
|
auto writeToSurface(const std::string& text, int zoom = 1, int kerning = 1) -> std::shared_ptr<Surface>;
|
||||||
|
|
||||||
// Escribe el texto con extras en una textura
|
// Escribe el texto con extras en una textura
|
||||||
std::shared_ptr<Surface> writeDXToSurface(Uint8 flags, const std::string& text, int kerning = 1, Uint8 text_color = Uint8(), Uint8 shadow_distance = 1, Uint8 shadow_color = Uint8(), int lenght = -1);
|
auto 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) -> std::shared_ptr<Surface>;
|
||||||
|
|
||||||
// Escribe el texto con colores
|
// Escribe el texto con colores
|
||||||
void writeColored(int x, int y, const std::string& text, Uint8 color, int kerning = 1, int lenght = -1);
|
void writeColored(int x, int y, const std::string& text, Uint8 color, int kerning = 1, int lenght = -1);
|
||||||
@@ -68,10 +68,10 @@ class Text {
|
|||||||
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);
|
void writeDX(Uint8 flags, int x, int y, const std::string& text, int kerning = 1, Uint8 text_color = Uint8(), Uint8 shadow_distance = 1, Uint8 shadow_color = Uint8(), int lenght = -1);
|
||||||
|
|
||||||
// Obtiene la longitud en pixels de una cadena
|
// Obtiene la longitud en pixels de una cadena
|
||||||
int lenght(const std::string& text, int kerning = 1) const;
|
[[nodiscard]] auto lenght(const std::string& text, int kerning = 1) const -> int;
|
||||||
|
|
||||||
// Devuelve el valor de la variable
|
// Devuelve el valor de la variable
|
||||||
int getCharacterSize() const;
|
[[nodiscard]] auto getCharacterSize() const -> int;
|
||||||
|
|
||||||
// Establece si se usa un tamaño fijo de letra
|
// Establece si se usa un tamaño fijo de letra
|
||||||
void setFixedWidth(bool value);
|
void setFixedWidth(bool value);
|
||||||
|
|||||||
@@ -6,6 +6,7 @@
|
|||||||
#include <iostream> // Para basic_ostream, operator<<, endl, cout
|
#include <iostream> // Para basic_ostream, operator<<, endl, cout
|
||||||
#include <stdexcept> // Para runtime_error
|
#include <stdexcept> // Para runtime_error
|
||||||
#include <string> // Para char_traits, operator<<, string, opera...
|
#include <string> // Para char_traits, operator<<, string, opera...
|
||||||
|
#include <utility>
|
||||||
#include <vector> // Para vector
|
#include <vector> // Para vector
|
||||||
|
|
||||||
#include "utils/utils.hpp" // Para getFileName, Color, printWithDots
|
#include "utils/utils.hpp" // Para getFileName, Color, printWithDots
|
||||||
@@ -14,13 +15,13 @@
|
|||||||
#include "external/stb_image.h" // para stbi_failure_reason, stbi_image_free
|
#include "external/stb_image.h" // para stbi_failure_reason, stbi_image_free
|
||||||
|
|
||||||
// Constructor
|
// Constructor
|
||||||
Texture::Texture(SDL_Renderer* renderer, const std::string& path)
|
Texture::Texture(SDL_Renderer* renderer, std::string path)
|
||||||
: renderer_(renderer),
|
: renderer_(renderer),
|
||||||
path_(path) {
|
path_(std::move(path)) {
|
||||||
// Carga el fichero en la textura
|
// Carga el fichero en la textura
|
||||||
if (!path_.empty()) {
|
if (!path_.empty()) {
|
||||||
// Obtiene la extensión
|
// Obtiene la extensión
|
||||||
const std::string EXTENSION = path_.substr(path_.find_last_of(".") + 1);
|
const std::string EXTENSION = path_.substr(path_.find_last_of('.') + 1);
|
||||||
|
|
||||||
// .png
|
// .png
|
||||||
if (EXTENSION == "png") {
|
if (EXTENSION == "png") {
|
||||||
@@ -36,7 +37,7 @@ Texture::~Texture() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Carga una imagen desde un fichero
|
// Carga una imagen desde un fichero
|
||||||
bool Texture::loadFromFile(const std::string& file_path) {
|
auto Texture::loadFromFile(const std::string& file_path) -> bool {
|
||||||
if (file_path.empty()) {
|
if (file_path.empty()) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
@@ -47,7 +48,7 @@ bool Texture::loadFromFile(const std::string& file_path) {
|
|||||||
int orig_format;
|
int orig_format;
|
||||||
unsigned char* data = stbi_load(file_path.c_str(), &width, &height, &orig_format, req_format);
|
unsigned char* data = stbi_load(file_path.c_str(), &width, &height, &orig_format, req_format);
|
||||||
if (data == nullptr) {
|
if (data == nullptr) {
|
||||||
std::cerr << "Error: Fichero no encontrado " << getFileName(file_path) << std::endl;
|
std::cerr << "Error: Fichero no encontrado " << getFileName(file_path) << '\n';
|
||||||
throw std::runtime_error("Fichero no encontrado: " + getFileName(file_path));
|
throw std::runtime_error("Fichero no encontrado: " + getFileName(file_path));
|
||||||
}
|
}
|
||||||
printWithDots("Image : ", getFileName(file_path), "[ LOADED ]");
|
printWithDots("Image : ", getFileName(file_path), "[ LOADED ]");
|
||||||
@@ -67,12 +68,12 @@ bool Texture::loadFromFile(const std::string& file_path) {
|
|||||||
// Carga la imagen desde una ruta específica
|
// Carga la imagen desde una ruta específica
|
||||||
auto* loaded_surface = SDL_CreateSurfaceFrom(width, height, pixel_format, static_cast<void*>(data), pitch);
|
auto* loaded_surface = SDL_CreateSurfaceFrom(width, height, pixel_format, static_cast<void*>(data), pitch);
|
||||||
if (loaded_surface == nullptr) {
|
if (loaded_surface == nullptr) {
|
||||||
std::cout << "Unable to load image " << file_path << std::endl;
|
std::cout << "Unable to load image " << file_path << '\n';
|
||||||
} else {
|
} else {
|
||||||
// Crea la textura desde los pixels de la surface
|
// Crea la textura desde los pixels de la surface
|
||||||
new_texture = SDL_CreateTextureFromSurface(renderer_, loaded_surface);
|
new_texture = SDL_CreateTextureFromSurface(renderer_, loaded_surface);
|
||||||
if (new_texture == nullptr) {
|
if (new_texture == nullptr) {
|
||||||
std::cout << "Unable to create texture from " << file_path << "! SDL Error: " << SDL_GetError() << std::endl;
|
std::cout << "Unable to create texture from " << file_path << "! SDL Error: " << SDL_GetError() << '\n';
|
||||||
} else {
|
} else {
|
||||||
// Obtiene las dimensiones de la imagen
|
// Obtiene las dimensiones de la imagen
|
||||||
width_ = loaded_surface->w;
|
width_ = loaded_surface->w;
|
||||||
@@ -153,10 +154,10 @@ void Texture::render(float x, float y, SDL_FRect* clip, float zoom_w, float zoom
|
|||||||
void Texture::setAsRenderTarget(SDL_Renderer* renderer) { SDL_SetRenderTarget(renderer, texture_); }
|
void Texture::setAsRenderTarget(SDL_Renderer* renderer) { SDL_SetRenderTarget(renderer, texture_); }
|
||||||
|
|
||||||
// Recarga la textura
|
// Recarga la textura
|
||||||
bool Texture::reLoad() { return loadFromFile(path_); }
|
auto Texture::reLoad() -> bool { return loadFromFile(path_); }
|
||||||
|
|
||||||
// Obtiene la textura
|
// Obtiene la textura
|
||||||
SDL_Texture* Texture::getSDLTexture() { return texture_; }
|
auto Texture::getSDLTexture() -> SDL_Texture* { return texture_; }
|
||||||
|
|
||||||
// Obtiene el renderizador
|
// Obtiene el renderizador
|
||||||
SDL_Renderer* Texture::getRenderer() { return renderer_; }
|
auto Texture::getRenderer() -> SDL_Renderer* { return renderer_; }
|
||||||
@@ -23,13 +23,13 @@ class Texture {
|
|||||||
|
|
||||||
public:
|
public:
|
||||||
// Constructor
|
// Constructor
|
||||||
explicit Texture(SDL_Renderer* renderer, const std::string& path = std::string());
|
explicit Texture(SDL_Renderer* renderer, std::string path = std::string());
|
||||||
|
|
||||||
// Destructor
|
// Destructor
|
||||||
~Texture();
|
~Texture();
|
||||||
|
|
||||||
// Carga una imagen desde un fichero
|
// Carga una imagen desde un fichero
|
||||||
bool loadFromFile(const std::string& path);
|
auto loadFromFile(const std::string& path) -> bool;
|
||||||
|
|
||||||
// Crea una textura en blanco
|
// Crea una textura en blanco
|
||||||
auto createBlank(int width, int height, SDL_PixelFormat format = SDL_PIXELFORMAT_RGBA8888, SDL_TextureAccess access = SDL_TEXTUREACCESS_STREAMING) -> bool;
|
auto createBlank(int width, int height, SDL_PixelFormat format = SDL_PIXELFORMAT_RGBA8888, SDL_TextureAccess access = SDL_TEXTUREACCESS_STREAMING) -> bool;
|
||||||
@@ -51,17 +51,17 @@ class Texture {
|
|||||||
void setAsRenderTarget(SDL_Renderer* renderer);
|
void setAsRenderTarget(SDL_Renderer* renderer);
|
||||||
|
|
||||||
// Obtiene el ancho de la imagen
|
// Obtiene el ancho de la imagen
|
||||||
int getWidth() const { return width_; }
|
[[nodiscard]] auto getWidth() const -> int { return width_; }
|
||||||
|
|
||||||
// Obtiene el alto de la imagen
|
// Obtiene el alto de la imagen
|
||||||
int getHeight() const { return height_; }
|
[[nodiscard]] auto getHeight() const -> int { return height_; }
|
||||||
|
|
||||||
// Recarga la textura
|
// Recarga la textura
|
||||||
bool reLoad();
|
auto reLoad() -> bool;
|
||||||
|
|
||||||
// Obtiene la textura
|
// Obtiene la textura
|
||||||
SDL_Texture* getSDLTexture();
|
auto getSDLTexture() -> SDL_Texture*;
|
||||||
|
|
||||||
// Obtiene el renderizador
|
// Obtiene el renderizador
|
||||||
SDL_Renderer* getRenderer();
|
auto getRenderer() -> SDL_Renderer*;
|
||||||
};
|
};
|
||||||
@@ -21,7 +21,7 @@ void Asset::destroy() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// [SINGLETON] Con este método obtenemos el objeto asset y podemos trabajar con él
|
// [SINGLETON] Con este método obtenemos el objeto asset y podemos trabajar con él
|
||||||
Asset* Asset::get() {
|
auto Asset::get() -> Asset* {
|
||||||
return Asset::asset;
|
return Asset::asset;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -32,23 +32,23 @@ void Asset::add(const std::string& file, AssetType type, bool required, bool abs
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Devuelve la ruta completa a un fichero a partir de una cadena
|
// Devuelve la ruta completa a un fichero a partir de una cadena
|
||||||
std::string Asset::get(const std::string& text) const {
|
auto Asset::get(const std::string& text) const -> std::string {
|
||||||
auto it = std::find_if(file_list_.begin(), file_list_.end(), [&text](const auto& f) {
|
auto it = std::ranges::find_if(file_list_, [&text](const auto& f) {
|
||||||
return getFileName(f.file) == text;
|
return getFileName(f.file) == text;
|
||||||
});
|
});
|
||||||
|
|
||||||
if (it != file_list_.end()) {
|
if (it != file_list_.end()) {
|
||||||
return it->file;
|
return it->file;
|
||||||
}
|
}
|
||||||
std::cout << "Warning: file " << text << " not found" << std::endl;
|
std::cout << "Warning: file " << text << " not found" << '\n';
|
||||||
return "";
|
return "";
|
||||||
}
|
}
|
||||||
|
|
||||||
// Comprueba que existen todos los elementos
|
// Comprueba que existen todos los elementos
|
||||||
bool Asset::check() const {
|
auto Asset::check() const -> bool {
|
||||||
bool success = true;
|
bool success = true;
|
||||||
|
|
||||||
std::cout << "\n** CHECKING FILES" << std::endl;
|
std::cout << "\n** CHECKING FILES" << '\n';
|
||||||
|
|
||||||
// std::cout << "Executable path is: " << executable_path_ << std::endl;
|
// std::cout << "Executable path is: " << executable_path_ << std::endl;
|
||||||
// std::cout << "Sample filepath: " << file_list_.back().file << std::endl;
|
// std::cout << "Sample filepath: " << file_list_.back().file << std::endl;
|
||||||
@@ -66,7 +66,7 @@ bool Asset::check() const {
|
|||||||
|
|
||||||
// Si hay ficheros de ese tipo, comprueba si existen
|
// Si hay ficheros de ese tipo, comprueba si existen
|
||||||
if (any) {
|
if (any) {
|
||||||
std::cout << "\n>> " << getTypeName(static_cast<AssetType>(type)).c_str() << " FILES" << std::endl;
|
std::cout << "\n>> " << getTypeName(static_cast<AssetType>(type)).c_str() << " FILES" << '\n';
|
||||||
|
|
||||||
for (const auto& f : file_list_) {
|
for (const auto& f : file_list_) {
|
||||||
if (f.required && f.type == static_cast<AssetType>(type)) {
|
if (f.required && f.type == static_cast<AssetType>(type)) {
|
||||||
@@ -74,19 +74,19 @@ bool Asset::check() const {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (success) {
|
if (success) {
|
||||||
std::cout << " All files are OK." << std::endl;
|
std::cout << " All files are OK." << '\n';
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Resultado
|
// Resultado
|
||||||
std::cout << (success ? "\n** CHECKING FILES COMPLETED.\n" : "\n** CHECKING FILES FAILED.\n") << std::endl;
|
std::cout << (success ? "\n** CHECKING FILES COMPLETED.\n" : "\n** CHECKING FILES FAILED.\n") << '\n';
|
||||||
|
|
||||||
return success;
|
return success;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Comprueba que existe un fichero
|
// Comprueba que existe un fichero
|
||||||
bool Asset::checkFile(const std::string& path) {
|
auto Asset::checkFile(const std::string& path) -> bool {
|
||||||
std::ifstream file(path);
|
std::ifstream file(path);
|
||||||
bool success = file.good();
|
bool success = file.good();
|
||||||
file.close();
|
file.close();
|
||||||
@@ -99,7 +99,7 @@ bool Asset::checkFile(const std::string& path) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Devuelve el nombre del tipo de recurso
|
// Devuelve el nombre del tipo de recurso
|
||||||
std::string Asset::getTypeName(AssetType type) {
|
auto Asset::getTypeName(AssetType type) -> std::string {
|
||||||
switch (type) {
|
switch (type) {
|
||||||
case AssetType::DATA:
|
case AssetType::DATA:
|
||||||
return "DATA";
|
return "DATA";
|
||||||
@@ -144,10 +144,10 @@ std::string Asset::getTypeName(AssetType type) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Devuelve la lista de recursos de un tipo
|
// Devuelve la lista de recursos de un tipo
|
||||||
std::vector<std::string> Asset::getListByType(AssetType type) const {
|
auto Asset::getListByType(AssetType type) const -> std::vector<std::string> {
|
||||||
std::vector<std::string> list;
|
std::vector<std::string> list;
|
||||||
|
|
||||||
for (auto f : file_list_) {
|
for (const auto& f : file_list_) {
|
||||||
if (f.type == type) {
|
if (f.type == type) {
|
||||||
list.push_back(f.file);
|
list.push_back(f.file);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
#include <string> // para string, basic_string
|
#include <string> // para string, basic_string
|
||||||
|
#include <utility>
|
||||||
#include <vector> // para vector
|
#include <vector> // para vector
|
||||||
|
|
||||||
#include "utils/utils.hpp"
|
#include "utils/utils.hpp"
|
||||||
@@ -31,8 +32,8 @@ class Asset {
|
|||||||
bool required; // Indica si es un fichero que debe de existir
|
bool required; // Indica si es un fichero que debe de existir
|
||||||
|
|
||||||
// Constructor
|
// Constructor
|
||||||
AssetItem(const std::string& file_path, AssetType asset_type, bool is_required)
|
AssetItem(std::string file_path, AssetType asset_type, bool is_required)
|
||||||
: file(file_path),
|
: file(std::move(file_path)),
|
||||||
type(asset_type),
|
type(asset_type),
|
||||||
required(is_required) {}
|
required(is_required) {}
|
||||||
};
|
};
|
||||||
@@ -43,10 +44,10 @@ class Asset {
|
|||||||
std::string executable_path_; // Ruta al ejecutable
|
std::string executable_path_; // Ruta al ejecutable
|
||||||
|
|
||||||
// Comprueba que existe un fichero
|
// Comprueba que existe un fichero
|
||||||
static bool checkFile(const std::string& path);
|
static auto checkFile(const std::string& path) -> bool;
|
||||||
|
|
||||||
// Devuelve el nombre del tipo de recurso
|
// Devuelve el nombre del tipo de recurso
|
||||||
static std::string getTypeName(AssetType type);
|
static auto getTypeName(AssetType type) -> std::string;
|
||||||
|
|
||||||
// Constructor
|
// Constructor
|
||||||
explicit Asset(const std::string& executable_path)
|
explicit Asset(const std::string& executable_path)
|
||||||
@@ -63,17 +64,17 @@ class Asset {
|
|||||||
static void destroy();
|
static void destroy();
|
||||||
|
|
||||||
// [SINGLETON] Con este método obtenemos el objeto y podemos trabajar con él
|
// [SINGLETON] Con este método obtenemos el objeto y podemos trabajar con él
|
||||||
static Asset* get();
|
static auto get() -> Asset*;
|
||||||
|
|
||||||
// Añade un elemento a la lista
|
// Añade un elemento a la lista
|
||||||
void add(const std::string& file, AssetType type, bool required = true, bool absolute = false);
|
void add(const std::string& file, AssetType type, bool required = true, bool absolute = false);
|
||||||
|
|
||||||
// Devuelve la ruta completa a un fichero a partir de una cadena
|
// Devuelve la ruta completa a un fichero a partir de una cadena
|
||||||
std::string get(const std::string& text) const;
|
[[nodiscard]] auto get(const std::string& text) const -> std::string;
|
||||||
|
|
||||||
// Comprueba que existen todos los elementos
|
// Comprueba que existen todos los elementos
|
||||||
bool check() const;
|
[[nodiscard]] auto check() const -> bool;
|
||||||
|
|
||||||
// Devuelve la lista de recursos de un tipo
|
// Devuelve la lista de recursos de un tipo
|
||||||
std::vector<std::string> getListByType(AssetType type) const;
|
[[nodiscard]] auto getListByType(AssetType type) const -> std::vector<std::string>;
|
||||||
};
|
};
|
||||||
@@ -32,7 +32,7 @@ class Debug {
|
|||||||
static void destroy();
|
static void destroy();
|
||||||
|
|
||||||
// [SINGLETON] Con este método obtenemos el objeto y podemos trabajar con él
|
// [SINGLETON] Con este método obtenemos el objeto y podemos trabajar con él
|
||||||
static Debug* get();
|
static auto get() -> Debug*;
|
||||||
|
|
||||||
// Dibuja en pantalla
|
// Dibuja en pantalla
|
||||||
void render();
|
void render();
|
||||||
@@ -41,12 +41,12 @@ class Debug {
|
|||||||
void setPos(SDL_FPoint p);
|
void setPos(SDL_FPoint p);
|
||||||
|
|
||||||
// Getters
|
// Getters
|
||||||
bool getEnabled() const { return enabled_; }
|
[[nodiscard]] auto getEnabled() const -> bool { return enabled_; }
|
||||||
|
|
||||||
// Setters
|
// Setters
|
||||||
void add(std::string text) { slot_.push_back(text); }
|
void add(const std::string& text) { slot_.push_back(text); }
|
||||||
void clear() { slot_.clear(); }
|
void clear() { slot_.clear(); }
|
||||||
void addToLog(std::string text) { log_.push_back(text); }
|
void addToLog(const std::string& text) { log_.push_back(text); }
|
||||||
void clearLog() { log_.clear(); }
|
void clearLog() { log_.clear(); }
|
||||||
void setEnabled(bool value) { enabled_ = value; }
|
void setEnabled(bool value) { enabled_ = value; }
|
||||||
void toggleEnabled() { enabled_ = !enabled_; }
|
void toggleEnabled() { enabled_ = !enabled_; }
|
||||||
|
|||||||
@@ -1,13 +1,11 @@
|
|||||||
#include "game/scene_manager.hpp" // Para SceneManager
|
|
||||||
|
|
||||||
#include "core/system/director.hpp"
|
#include "core/system/director.hpp"
|
||||||
|
|
||||||
#include <SDL3/SDL.h>
|
#include <SDL3/SDL.h>
|
||||||
#include <errno.h> // Para errno, EEXIST, EACCES, ENAMETOO...
|
|
||||||
#include <stdio.h> // Para printf, perror
|
|
||||||
#include <sys/stat.h> // Para mkdir, stat, S_IRWXU
|
#include <sys/stat.h> // Para mkdir, stat, S_IRWXU
|
||||||
#include <unistd.h> // Para getuid
|
#include <unistd.h> // Para getuid
|
||||||
|
|
||||||
|
#include <cerrno> // Para errno, EEXIST, EACCES, ENAMETOO...
|
||||||
|
#include <cstdio> // Para printf, perror
|
||||||
#include <cstdlib> // Para exit, EXIT_FAILURE, srand
|
#include <cstdlib> // Para exit, EXIT_FAILURE, srand
|
||||||
#include <iostream> // Para basic_ostream, operator<<, cout
|
#include <iostream> // Para basic_ostream, operator<<, cout
|
||||||
#include <memory> // Para make_unique, unique_ptr
|
#include <memory> // Para make_unique, unique_ptr
|
||||||
@@ -21,6 +19,7 @@
|
|||||||
#include "core/system/debug.hpp" // Para Debug
|
#include "core/system/debug.hpp" // Para Debug
|
||||||
#include "game/gameplay/cheevos.hpp" // Para Cheevos
|
#include "game/gameplay/cheevos.hpp" // Para Cheevos
|
||||||
#include "game/options.hpp" // Para Options, options, OptionsVideo
|
#include "game/options.hpp" // Para Options, options, OptionsVideo
|
||||||
|
#include "game/scene_manager.hpp" // Para SceneManager
|
||||||
#include "game/scenes/credits.hpp" // Para Credits
|
#include "game/scenes/credits.hpp" // Para Credits
|
||||||
#include "game/scenes/ending.hpp" // Para Ending
|
#include "game/scenes/ending.hpp" // Para Ending
|
||||||
#include "game/scenes/ending2.hpp" // Para Ending2
|
#include "game/scenes/ending2.hpp" // Para Ending2
|
||||||
@@ -37,14 +36,14 @@
|
|||||||
#endif
|
#endif
|
||||||
|
|
||||||
// Constructor
|
// Constructor
|
||||||
Director::Director(int argc, const char* argv[]) {
|
Director::Director(std::vector<std::string> const& args) {
|
||||||
std::cout << "Game start" << std::endl;
|
std::cout << "Game start" << '\n';
|
||||||
|
|
||||||
// Crea e inicializa las opciones del programa
|
// Crea e inicializa las opciones del programa
|
||||||
Options::init();
|
Options::init();
|
||||||
|
|
||||||
// Comprueba los parametros del programa
|
// Comprueba los parametros del programa
|
||||||
executable_path_ = checkProgramArguments(argc, argv);
|
executable_path_ = checkProgramArguments(args);
|
||||||
|
|
||||||
// Crea el objeto que controla los ficheros de recursos
|
// Crea el objeto que controla los ficheros de recursos
|
||||||
Asset::init(executable_path_);
|
Asset::init(executable_path_);
|
||||||
@@ -92,14 +91,14 @@ Director::~Director() {
|
|||||||
|
|
||||||
SDL_Quit();
|
SDL_Quit();
|
||||||
|
|
||||||
std::cout << "\nBye!" << std::endl;
|
std::cout << "\nBye!" << '\n';
|
||||||
}
|
}
|
||||||
|
|
||||||
// Comprueba los parametros del programa
|
// Comprueba los parametros del programa
|
||||||
std::string Director::checkProgramArguments(int argc, const char* argv[]) {
|
auto Director::checkProgramArguments(std::vector<std::string> const& args) -> std::string {
|
||||||
// Iterar sobre los argumentos del programa
|
// Iterar sobre los argumentos del programa (saltando args[0] que es el ejecutable)
|
||||||
for (int i = 1; i < argc; ++i) {
|
for (std::size_t i = 1; i < args.size(); ++i) {
|
||||||
std::string argument(argv[i]);
|
const std::string& argument = args[i];
|
||||||
|
|
||||||
if (argument == "--console") {
|
if (argument == "--console") {
|
||||||
Options::console = true;
|
Options::console = true;
|
||||||
@@ -114,7 +113,7 @@ std::string Director::checkProgramArguments(int argc, const char* argv[]) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return argv[0];
|
return args[0];
|
||||||
}
|
}
|
||||||
|
|
||||||
// Crea la carpeta del sistema donde guardar datos
|
// Crea la carpeta del sistema donde guardar datos
|
||||||
@@ -141,7 +140,7 @@ void Director::createSystemFolder(const std::string& folder) {
|
|||||||
}
|
}
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
struct stat st = {0};
|
struct stat st = {.st_dev = 0};
|
||||||
if (stat(system_folder_.c_str(), &st) == -1) {
|
if (stat(system_folder_.c_str(), &st) == -1) {
|
||||||
errno = 0;
|
errno = 0;
|
||||||
#ifdef _WIN32
|
#ifdef _WIN32
|
||||||
@@ -239,7 +238,7 @@ void Director::initInput() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Crea el indice de ficheros
|
// Crea el indice de ficheros
|
||||||
bool Director::setFileList() {
|
auto Director::setFileList() -> bool {
|
||||||
#ifdef MACOS_BUNDLE
|
#ifdef MACOS_BUNDLE
|
||||||
const std::string prefix = "/../Resources";
|
const std::string prefix = "/../Resources";
|
||||||
#else
|
#else
|
||||||
@@ -527,7 +526,7 @@ void Director::runGame() {
|
|||||||
game->run();
|
game->run();
|
||||||
}
|
}
|
||||||
|
|
||||||
int Director::run() {
|
auto Director::run() -> int {
|
||||||
// Bucle principal
|
// Bucle principal
|
||||||
while (SceneManager::current != SceneManager::Scene::QUIT) {
|
while (SceneManager::current != SceneManager::Scene::QUIT) {
|
||||||
switch (SceneManager::current) {
|
switch (SceneManager::current) {
|
||||||
|
|||||||
@@ -3,23 +3,24 @@
|
|||||||
#include <SDL3/SDL.h>
|
#include <SDL3/SDL.h>
|
||||||
|
|
||||||
#include <string> // Para string
|
#include <string> // Para string
|
||||||
|
#include <vector> // Para vector
|
||||||
|
|
||||||
class Director {
|
class Director {
|
||||||
public:
|
public:
|
||||||
Director(int argc, const char* argv[]); // Constructor
|
Director(std::vector<std::string> const& args); // Constructor
|
||||||
~Director(); // Destructor
|
~Director(); // Destructor
|
||||||
static int run(); // Bucle principal
|
static auto run() -> int; // Bucle principal
|
||||||
|
|
||||||
private:
|
private:
|
||||||
// --- Variables ---
|
// --- Variables ---
|
||||||
std::string executable_path_; // Path del ejecutable
|
std::string executable_path_; // Path del ejecutable
|
||||||
std::string system_folder_; // Carpeta del sistema donde guardar datos
|
std::string system_folder_; // Carpeta del sistema donde guardar datos
|
||||||
static std::string checkProgramArguments(int argc, const char* argv[]); // Comprueba los parametros del programa
|
static auto checkProgramArguments(std::vector<std::string> const& args) -> std::string; // Comprueba los parametros del programa
|
||||||
|
|
||||||
// --- Funciones ---
|
// --- Funciones ---
|
||||||
void createSystemFolder(const std::string& folder); // Crea la carpeta del sistema donde guardar datos
|
void createSystemFolder(const std::string& folder); // Crea la carpeta del sistema donde guardar datos
|
||||||
static void initInput(); // Inicializa el objeto Input
|
static void initInput(); // Inicializa el objeto Input
|
||||||
bool setFileList(); // Crea el indice de ficheros
|
auto setFileList() -> bool; // Crea el indice de ficheros
|
||||||
static void runLogo(); // Ejecuta la seccion de juego con el logo
|
static void runLogo(); // Ejecuta la seccion de juego con el logo
|
||||||
static void runLoadingScreen(); // Ejecuta la seccion de juego de la pantalla de carga
|
static void runLoadingScreen(); // Ejecuta la seccion de juego de la pantalla de carga
|
||||||
static void runTitle(); // Ejecuta la seccion de juego con el titulo y los menus
|
static void runTitle(); // Ejecuta la seccion de juego con el titulo y los menus
|
||||||
|
|||||||
@@ -1,7 +1,8 @@
|
|||||||
#include "game/entities/enemy.hpp"
|
#include "game/entities/enemy.hpp"
|
||||||
|
|
||||||
#include <SDL3/SDL.h>
|
#include <SDL3/SDL.h>
|
||||||
#include <stdlib.h> // Para rand
|
|
||||||
|
#include <cstdlib> // Para rand
|
||||||
|
|
||||||
#include "core/rendering/surface_animated_sprite.hpp" // Para SAnimatedSprite
|
#include "core/rendering/surface_animated_sprite.hpp" // Para SAnimatedSprite
|
||||||
#include "core/resources/resource.hpp" // Para Resource
|
#include "core/resources/resource.hpp" // Para Resource
|
||||||
@@ -87,11 +88,11 @@ void Enemy::checkPath() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Devuelve el rectangulo que contiene al enemigo
|
// Devuelve el rectangulo que contiene al enemigo
|
||||||
SDL_FRect Enemy::getRect() {
|
auto Enemy::getRect() -> SDL_FRect {
|
||||||
return sprite_->getRect();
|
return sprite_->getRect();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Obtiene el rectangulo de colision del enemigo
|
// Obtiene el rectangulo de colision del enemigo
|
||||||
SDL_FRect& Enemy::getCollider() {
|
auto Enemy::getCollider() -> SDL_FRect& {
|
||||||
return collider_;
|
return collider_;
|
||||||
}
|
}
|
||||||
@@ -59,8 +59,8 @@ class Enemy {
|
|||||||
void update();
|
void update();
|
||||||
|
|
||||||
// Devuelve el rectangulo que contiene al enemigo
|
// Devuelve el rectangulo que contiene al enemigo
|
||||||
SDL_FRect getRect();
|
auto getRect() -> SDL_FRect;
|
||||||
|
|
||||||
// Obtiene el rectangulo de colision del enemigo
|
// Obtiene el rectangulo de colision del enemigo
|
||||||
SDL_FRect& getCollider();
|
auto getCollider() -> SDL_FRect&;
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -4,7 +4,7 @@
|
|||||||
#include "core/resources/resource.hpp" // Para Resource
|
#include "core/resources/resource.hpp" // Para Resource
|
||||||
|
|
||||||
// Constructor
|
// Constructor
|
||||||
Item::Item(ItemData item)
|
Item::Item(const ItemData &item)
|
||||||
: sprite_(std::make_shared<SurfaceSprite>(Resource::get()->getSurface(item.tile_set_file), item.x, item.y, ITEM_SIZE, ITEM_SIZE)),
|
: sprite_(std::make_shared<SurfaceSprite>(Resource::get()->getSurface(item.tile_set_file), item.x, item.y, ITEM_SIZE, ITEM_SIZE)),
|
||||||
change_color_speed_(4) {
|
change_color_speed_(4) {
|
||||||
// Inicia variables
|
// Inicia variables
|
||||||
@@ -21,13 +21,13 @@ Item::Item(ItemData item)
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Pinta el objeto en pantalla
|
// Pinta el objeto en pantalla
|
||||||
void Item::render() {
|
void Item::render() const {
|
||||||
const int INDEX = (counter_ / change_color_speed_) % color_.size();
|
const int INDEX = (counter_ / change_color_speed_) % color_.size();
|
||||||
sprite_->render(1, color_.at(INDEX));
|
sprite_->render(1, color_.at(INDEX));
|
||||||
}
|
}
|
||||||
|
|
||||||
// Obtiene su ubicación
|
// Obtiene su ubicación
|
||||||
SDL_FPoint Item::getPos() {
|
auto Item::getPos() -> SDL_FPoint {
|
||||||
const SDL_FPoint P = {sprite_->getX(), sprite_->getY()};
|
const SDL_FPoint P = {sprite_->getX(), sprite_->getY()};
|
||||||
return P;
|
return P;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,21 +9,15 @@ class SurfaceSprite;
|
|||||||
|
|
||||||
struct ItemData {
|
struct ItemData {
|
||||||
std::string tile_set_file; // Ruta al fichero con los gráficos del item
|
std::string tile_set_file; // Ruta al fichero con los gráficos del item
|
||||||
float x; // Posición del item en pantalla
|
float x{0}; // Posición del item en pantalla
|
||||||
float y; // Posición del item en pantalla
|
float y{0}; // Posición del item en pantalla
|
||||||
int tile; // Número de tile dentro de la textura
|
int tile{0}; // Número de tile dentro de la textura
|
||||||
int counter; // Contador inicial. Es el que lo hace cambiar de color
|
int counter{0}; // Contador inicial. Es el que lo hace cambiar de color
|
||||||
Uint8 color1; // Uno de los dos colores que se utiliza para el item
|
Uint8 color1{}; // Uno de los dos colores que se utiliza para el item
|
||||||
Uint8 color2; // Uno de los dos colores que se utiliza para el item
|
Uint8 color2{}; // Uno de los dos colores que se utiliza para el item
|
||||||
|
|
||||||
// Constructor
|
// Constructor
|
||||||
ItemData()
|
ItemData() = default;
|
||||||
: x(0),
|
|
||||||
y(0),
|
|
||||||
tile(0),
|
|
||||||
counter(0),
|
|
||||||
color1(),
|
|
||||||
color2() {}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
class Item {
|
class Item {
|
||||||
@@ -42,22 +36,22 @@ class Item {
|
|||||||
|
|
||||||
public:
|
public:
|
||||||
// Constructor
|
// Constructor
|
||||||
explicit Item(ItemData item);
|
explicit Item(const ItemData &item);
|
||||||
|
|
||||||
// Destructor
|
// Destructor
|
||||||
~Item() = default;
|
~Item() = default;
|
||||||
|
|
||||||
// Pinta el objeto en pantalla
|
// Pinta el objeto en pantalla
|
||||||
void render();
|
void render() const;
|
||||||
|
|
||||||
// Actualiza las variables del objeto
|
// Actualiza las variables del objeto
|
||||||
void update() { counter_++; }
|
void update() { counter_++; }
|
||||||
|
|
||||||
// Obtiene el rectangulo de colision del objeto
|
// Obtiene el rectangulo de colision del objeto
|
||||||
SDL_FRect& getCollider() { return collider_; }
|
auto getCollider() -> SDL_FRect& { return collider_; }
|
||||||
|
|
||||||
// Obtiene su ubicación
|
// Obtiene su ubicación
|
||||||
SDL_FPoint getPos();
|
auto getPos() -> SDL_FPoint;
|
||||||
|
|
||||||
// Asigna los colores del objeto
|
// Asigna los colores del objeto
|
||||||
void setColors(Uint8 col1, Uint8 col2);
|
void setColors(Uint8 col1, Uint8 col2);
|
||||||
|
|||||||
@@ -32,10 +32,10 @@ Player::Player(const PlayerData& player)
|
|||||||
feet_.resize(feet_.size() + 2, {0, 0});
|
feet_.resize(feet_.size() + 2, {0, 0});
|
||||||
|
|
||||||
#ifdef _DEBUG
|
#ifdef _DEBUG
|
||||||
debug_rect_x_ = {0, 0, 0, 0};
|
debug_rect_x_ = {.x = 0, .y = 0, .w = 0, .h = 0};
|
||||||
debug_rect_y_ = {0, 0, 0, 0};
|
debug_rect_y_ = {.x = 0, .y = 0, .w = 0, .h = 0};
|
||||||
debug_color_ = static_cast<Uint8>(PaletteColor::GREEN);
|
debug_color_ = static_cast<Uint8>(PaletteColor::GREEN);
|
||||||
debug_point_ = {0, 0};
|
debug_point_ = {.x = 0, .y = 0};
|
||||||
#endif
|
#endif
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -241,7 +241,7 @@ void Player::moveHorizontalLeft() {
|
|||||||
|
|
||||||
// Si ha tocado alguna rampa mientras camina (sin saltar), asciende
|
// Si ha tocado alguna rampa mientras camina (sin saltar), asciende
|
||||||
if (state_ != PlayerState::JUMPING) {
|
if (state_ != PlayerState::JUMPING) {
|
||||||
const LineVertical LEFT_SIDE = {static_cast<int>(x_), static_cast<int>(y_) + static_cast<int>(HEIGHT) - 2, static_cast<int>(y_) + static_cast<int>(HEIGHT) - 1}; // Comprueba solo los dos pixels de abajo
|
const LineVertical LEFT_SIDE = {.x = static_cast<int>(x_), .y1 = static_cast<int>(y_) + static_cast<int>(HEIGHT) - 2, .y2 = static_cast<int>(y_) + static_cast<int>(HEIGHT) - 1}; // Comprueba solo los dos pixels de abajo
|
||||||
const int LY = room_->checkLeftSlopes(&LEFT_SIDE);
|
const int LY = room_->checkLeftSlopes(&LEFT_SIDE);
|
||||||
if (LY > -1) {
|
if (LY > -1) {
|
||||||
y_ = LY - HEIGHT;
|
y_ = LY - HEIGHT;
|
||||||
@@ -261,7 +261,7 @@ void Player::moveHorizontalRight() {
|
|||||||
proj.x = x_ + WIDTH;
|
proj.x = x_ + WIDTH;
|
||||||
proj.y = y_;
|
proj.y = y_;
|
||||||
proj.h = HEIGHT;
|
proj.h = HEIGHT;
|
||||||
proj.w = ceil(vx_); // Para evitar que tenga un ancho de 0 pixels
|
proj.w = std::ceil(vx_); // Para evitar que tenga un ancho de 0 pixels
|
||||||
|
|
||||||
#ifdef _DEBUG
|
#ifdef _DEBUG
|
||||||
debug_rect_x_ = proj;
|
debug_rect_x_ = proj;
|
||||||
@@ -281,7 +281,7 @@ void Player::moveHorizontalRight() {
|
|||||||
|
|
||||||
// Si ha tocado alguna rampa mientras camina (sin saltar), asciende
|
// Si ha tocado alguna rampa mientras camina (sin saltar), asciende
|
||||||
if (state_ != PlayerState::JUMPING) {
|
if (state_ != PlayerState::JUMPING) {
|
||||||
const LineVertical RIGHT_SIDE = {static_cast<int>(x_) + static_cast<int>(WIDTH) - 1, static_cast<int>(y_) + static_cast<int>(HEIGHT) - 2, static_cast<int>(y_) + static_cast<int>(HEIGHT) - 1}; // Comprueba solo los dos pixels de abajo
|
const LineVertical RIGHT_SIDE = {.x = static_cast<int>(x_) + static_cast<int>(WIDTH) - 1, .y1 = static_cast<int>(y_) + static_cast<int>(HEIGHT) - 2, .y2 = static_cast<int>(y_) + static_cast<int>(HEIGHT) - 1}; // Comprueba solo los dos pixels de abajo
|
||||||
const int RY = room_->checkRightSlopes(&RIGHT_SIDE);
|
const int RY = room_->checkRightSlopes(&RIGHT_SIDE);
|
||||||
if (RY > -1) {
|
if (RY > -1) {
|
||||||
y_ = RY - HEIGHT;
|
y_ = RY - HEIGHT;
|
||||||
@@ -327,7 +327,7 @@ void Player::moveVerticalDown() {
|
|||||||
SDL_FRect proj;
|
SDL_FRect proj;
|
||||||
proj.x = x_;
|
proj.x = x_;
|
||||||
proj.y = y_ + HEIGHT;
|
proj.y = y_ + HEIGHT;
|
||||||
proj.h = ceil(vy_); // Para evitar que tenga una altura de 0 pixels
|
proj.h = std::ceil(vy_); // Para evitar que tenga una altura de 0 pixels
|
||||||
proj.w = WIDTH;
|
proj.w = WIDTH;
|
||||||
|
|
||||||
#ifdef _DEBUG
|
#ifdef _DEBUG
|
||||||
@@ -347,8 +347,8 @@ void Player::moveVerticalDown() {
|
|||||||
// Si no hay colisión con los muros, comprueba la colisión con las rampas
|
// Si no hay colisión con los muros, comprueba la colisión con las rampas
|
||||||
if (state_ != PlayerState::JUMPING) { // Las rampas no se miran si se está saltando
|
if (state_ != PlayerState::JUMPING) { // Las rampas no se miran si se está saltando
|
||||||
auto rect = toSDLRect(proj);
|
auto rect = toSDLRect(proj);
|
||||||
const LineVertical LEFT_SIDE = {rect.x, rect.y, rect.y + rect.h - 1};
|
const LineVertical LEFT_SIDE = {.x = rect.x, .y1 = rect.y, .y2 = rect.y + rect.h - 1};
|
||||||
const LineVertical RIGHT_SIDE = {rect.x + rect.w - 1, rect.y, rect.y + rect.h - 1};
|
const LineVertical RIGHT_SIDE = {.x = rect.x + rect.w - 1, .y1 = rect.y, .y2 = rect.y + rect.h - 1};
|
||||||
const float POINT = std::max(room_->checkRightSlopes(&RIGHT_SIDE), room_->checkLeftSlopes(&LEFT_SIDE));
|
const float POINT = std::max(room_->checkRightSlopes(&RIGHT_SIDE), room_->checkLeftSlopes(&LEFT_SIDE));
|
||||||
if (POINT > -1) {
|
if (POINT > -1) {
|
||||||
// No está saltando y hay colisión con una rampa
|
// No está saltando y hay colisión con una rampa
|
||||||
@@ -357,7 +357,7 @@ void Player::moveVerticalDown() {
|
|||||||
setState(PlayerState::STANDING);
|
setState(PlayerState::STANDING);
|
||||||
#ifdef _DEBUG
|
#ifdef _DEBUG
|
||||||
debug_color_ = static_cast<Uint8>(PaletteColor::YELLOW);
|
debug_color_ = static_cast<Uint8>(PaletteColor::YELLOW);
|
||||||
debug_point_ = {x_ + (WIDTH / 2), POINT};
|
debug_point_ = {.x = x_ + (WIDTH / 2), .y = POINT};
|
||||||
#endif
|
#endif
|
||||||
} else {
|
} else {
|
||||||
// No está saltando y no hay colisón con una rampa
|
// No está saltando y no hay colisón con una rampa
|
||||||
@@ -377,7 +377,7 @@ void Player::moveVerticalDown() {
|
|||||||
|
|
||||||
// Recalcula la posición del jugador y su animación
|
// Recalcula la posición del jugador y su animación
|
||||||
void Player::move() {
|
void Player::move() {
|
||||||
last_position_ = {x_, y_}; // Guarda la posicion actual antes de modificarla
|
last_position_ = {.x = x_, .y = y_}; // Guarda la posicion actual antes de modificarla
|
||||||
applyGravity(); // Aplica gravedad al jugador
|
applyGravity(); // Aplica gravedad al jugador
|
||||||
checkState(); // Comprueba el estado del jugador
|
checkState(); // Comprueba el estado del jugador
|
||||||
|
|
||||||
@@ -463,7 +463,7 @@ void Player::playFallSound() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Comprueba si el jugador tiene suelo debajo de los pies
|
// Comprueba si el jugador tiene suelo debajo de los pies
|
||||||
bool Player::isOnFloor() {
|
auto Player::isOnFloor() -> bool {
|
||||||
bool on_floor = false;
|
bool on_floor = false;
|
||||||
bool on_slope_l = false;
|
bool on_slope_l = false;
|
||||||
bool on_slope_r = false;
|
bool on_slope_r = false;
|
||||||
@@ -498,7 +498,7 @@ bool Player::isOnFloor() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Comprueba si el jugador esta sobre una superficie automática
|
// Comprueba si el jugador esta sobre una superficie automática
|
||||||
bool Player::isOnAutoSurface() {
|
auto Player::isOnAutoSurface() -> bool {
|
||||||
bool on_auto_surface = false;
|
bool on_auto_surface = false;
|
||||||
|
|
||||||
updateFeet();
|
updateFeet();
|
||||||
@@ -518,7 +518,7 @@ bool Player::isOnAutoSurface() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Comprueba si el jugador está sobre una rampa hacia abajo
|
// Comprueba si el jugador está sobre una rampa hacia abajo
|
||||||
bool Player::isOnDownSlope() {
|
auto Player::isOnDownSlope() -> bool {
|
||||||
bool on_slope = false;
|
bool on_slope = false;
|
||||||
|
|
||||||
updateFeet();
|
updateFeet();
|
||||||
@@ -542,7 +542,7 @@ bool Player::isOnDownSlope() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Comprueba que el jugador no toque ningun tile de los que matan
|
// Comprueba que el jugador no toque ningun tile de los que matan
|
||||||
bool Player::checkKillingTiles() {
|
auto Player::checkKillingTiles() -> bool {
|
||||||
// Actualiza los puntos de colisión
|
// Actualiza los puntos de colisión
|
||||||
updateColliderPoints();
|
updateColliderPoints();
|
||||||
|
|
||||||
@@ -571,25 +571,25 @@ void Player::setColor() {
|
|||||||
// Actualiza los puntos de colisión
|
// Actualiza los puntos de colisión
|
||||||
void Player::updateColliderPoints() {
|
void Player::updateColliderPoints() {
|
||||||
const SDL_FRect RECT = getRect();
|
const SDL_FRect RECT = getRect();
|
||||||
collider_points_[0] = {RECT.x, RECT.y};
|
collider_points_[0] = {.x = RECT.x, .y = RECT.y};
|
||||||
collider_points_[1] = {RECT.x + 7, RECT.y};
|
collider_points_[1] = {.x = RECT.x + 7, .y = RECT.y};
|
||||||
collider_points_[2] = {RECT.x + 7, RECT.y + 7};
|
collider_points_[2] = {.x = RECT.x + 7, .y = RECT.y + 7};
|
||||||
collider_points_[3] = {RECT.x, RECT.y + 7};
|
collider_points_[3] = {.x = RECT.x, .y = RECT.y + 7};
|
||||||
collider_points_[4] = {RECT.x, RECT.y + 8};
|
collider_points_[4] = {.x = RECT.x, .y = RECT.y + 8};
|
||||||
collider_points_[5] = {RECT.x + 7, RECT.y + 8};
|
collider_points_[5] = {.x = RECT.x + 7, .y = RECT.y + 8};
|
||||||
collider_points_[6] = {RECT.x + 7, RECT.y + 15};
|
collider_points_[6] = {.x = RECT.x + 7, .y = RECT.y + 15};
|
||||||
collider_points_[7] = {RECT.x, RECT.y + 15};
|
collider_points_[7] = {.x = RECT.x, .y = RECT.y + 15};
|
||||||
}
|
}
|
||||||
|
|
||||||
// Actualiza los puntos de los pies
|
// Actualiza los puntos de los pies
|
||||||
void Player::updateFeet() {
|
void Player::updateFeet() {
|
||||||
const SDL_FPoint P = {x_, y_};
|
const SDL_FPoint P = {x_, y_};
|
||||||
|
|
||||||
under_feet_[0] = {P.x, P.y + HEIGHT};
|
under_feet_[0] = {.x = P.x, .y = P.y + HEIGHT};
|
||||||
under_feet_[1] = {P.x + 7, P.y + HEIGHT};
|
under_feet_[1] = {.x = P.x + 7, .y = P.y + HEIGHT};
|
||||||
|
|
||||||
feet_[0] = {P.x, P.y + HEIGHT - 1};
|
feet_[0] = {.x = P.x, .y = P.y + HEIGHT - 1};
|
||||||
feet_[1] = {P.x + 7, P.y + HEIGHT - 1};
|
feet_[1] = {.x = P.x + 7, .y = P.y + HEIGHT - 1};
|
||||||
}
|
}
|
||||||
|
|
||||||
// Cambia el estado del jugador
|
// Cambia el estado del jugador
|
||||||
|
|||||||
@@ -4,6 +4,7 @@
|
|||||||
|
|
||||||
#include <memory> // Para shared_ptr, __shared_ptr_access
|
#include <memory> // Para shared_ptr, __shared_ptr_access
|
||||||
#include <string> // Para string
|
#include <string> // Para string
|
||||||
|
#include <utility>
|
||||||
#include <vector> // Para vector
|
#include <vector> // Para vector
|
||||||
|
|
||||||
#include "core/rendering/surface_animated_sprite.hpp" // Para SAnimatedSprite
|
#include "core/rendering/surface_animated_sprite.hpp" // Para SAnimatedSprite
|
||||||
@@ -57,9 +58,9 @@ struct PlayerData {
|
|||||||
// Constructor
|
// Constructor
|
||||||
PlayerData(PlayerSpawn spawn, std::string texture_path, std::string animations_path, std::shared_ptr<Room> room)
|
PlayerData(PlayerSpawn spawn, std::string texture_path, std::string animations_path, std::shared_ptr<Room> room)
|
||||||
: spawn(spawn),
|
: spawn(spawn),
|
||||||
texture_path(texture_path),
|
texture_path(std::move(std::move(texture_path))),
|
||||||
animations_path(animations_path),
|
animations_path(std::move(std::move(animations_path))),
|
||||||
room(room) {}
|
room(std::move(std::move(room))) {}
|
||||||
};
|
};
|
||||||
|
|
||||||
class Player {
|
class Player {
|
||||||
@@ -145,16 +146,16 @@ class Player {
|
|||||||
void playFallSound();
|
void playFallSound();
|
||||||
|
|
||||||
// Comprueba si el jugador tiene suelo debajo de los pies
|
// Comprueba si el jugador tiene suelo debajo de los pies
|
||||||
bool isOnFloor();
|
auto isOnFloor() -> bool;
|
||||||
|
|
||||||
// Comprueba si el jugador esta sobre una superficie automática
|
// Comprueba si el jugador esta sobre una superficie automática
|
||||||
bool isOnAutoSurface();
|
auto isOnAutoSurface() -> bool;
|
||||||
|
|
||||||
// Comprueba si el jugador está sobre una rampa hacia abajo
|
// Comprueba si el jugador está sobre una rampa hacia abajo
|
||||||
bool isOnDownSlope();
|
auto isOnDownSlope() -> bool;
|
||||||
|
|
||||||
// Comprueba que el jugador no toque ningun tile de los que matan
|
// Comprueba que el jugador no toque ningun tile de los que matan
|
||||||
bool checkKillingTiles();
|
auto checkKillingTiles() -> bool;
|
||||||
|
|
||||||
// Actualiza los puntos de colisión
|
// Actualiza los puntos de colisión
|
||||||
void updateColliderPoints();
|
void updateColliderPoints();
|
||||||
@@ -196,31 +197,31 @@ public:
|
|||||||
void update();
|
void update();
|
||||||
|
|
||||||
// Indica si el jugador esta en uno de los cuatro bordes de la pantalla
|
// Indica si el jugador esta en uno de los cuatro bordes de la pantalla
|
||||||
bool getOnBorder() const { return is_on_border_; }
|
[[nodiscard]] auto getOnBorder() const -> bool { return is_on_border_; }
|
||||||
|
|
||||||
// Indica en cual de los cuatro bordes se encuentra
|
// Indica en cual de los cuatro bordes se encuentra
|
||||||
RoomBorder getBorder() const { return border_; }
|
[[nodiscard]] auto getBorder() const -> RoomBorder { return border_; }
|
||||||
|
|
||||||
// Cambia al jugador de un borde al opuesto. Util para el cambio de pantalla
|
// Cambia al jugador de un borde al opuesto. Util para el cambio de pantalla
|
||||||
void switchBorders();
|
void switchBorders();
|
||||||
|
|
||||||
// Obtiene el rectangulo que delimita al jugador
|
// Obtiene el rectangulo que delimita al jugador
|
||||||
SDL_FRect getRect() { return {x_, y_, WIDTH, HEIGHT}; }
|
auto getRect() -> SDL_FRect { return {x_, y_, WIDTH, HEIGHT}; }
|
||||||
|
|
||||||
// Obtiene el rectangulo de colision del jugador
|
// Obtiene el rectangulo de colision del jugador
|
||||||
SDL_FRect& getCollider() { return collider_box_; }
|
auto getCollider() -> SDL_FRect& { return collider_box_; }
|
||||||
|
|
||||||
// Obtiene el estado de reaparición del jugador
|
// Obtiene el estado de reaparición del jugador
|
||||||
PlayerSpawn getSpawnParams() { return {x_, y_, vx_, vy_, jump_init_pos_, state_, sprite_->getFlip()}; }
|
auto getSpawnParams() -> PlayerSpawn { return {x_, y_, vx_, vy_, jump_init_pos_, state_, sprite_->getFlip()}; }
|
||||||
|
|
||||||
// Establece el color del jugador
|
// Establece el color del jugador
|
||||||
void setColor();
|
void setColor();
|
||||||
|
|
||||||
// Establece la habitación en la que se encuentra el jugador
|
// Establece la habitación en la que se encuentra el jugador
|
||||||
void setRoom(std::shared_ptr<Room> room) { room_ = room; }
|
void setRoom(std::shared_ptr<Room> room) { room_ = std::move(room); }
|
||||||
|
|
||||||
// Comprueba si el jugador esta vivo
|
// Comprueba si el jugador esta vivo
|
||||||
bool isAlive() const { return is_alive_; }
|
[[nodiscard]] auto isAlive() const -> bool { return is_alive_; }
|
||||||
|
|
||||||
// Pone el jugador en modo pausa
|
// Pone el jugador en modo pausa
|
||||||
void setPaused(bool value) { is_paused_ = value; }
|
void setPaused(bool value) { is_paused_ = value; }
|
||||||
|
|||||||
@@ -1,10 +1,11 @@
|
|||||||
#include "game/gameplay/cheevos.hpp"
|
#include "game/gameplay/cheevos.hpp"
|
||||||
|
|
||||||
#include <SDL3/SDL.h>
|
#include <SDL3/SDL.h>
|
||||||
#include <stddef.h> // Para NULL
|
|
||||||
|
|
||||||
|
#include <cstddef> // Para NULL
|
||||||
#include <fstream> // Para basic_ostream, operator<<, basic_ofstream
|
#include <fstream> // Para basic_ostream, operator<<, basic_ofstream
|
||||||
#include <iostream> // Para cout, cerr
|
#include <iostream> // Para cout, cerr
|
||||||
|
#include <utility>
|
||||||
|
|
||||||
#include "game/options.hpp" // Para Options, options
|
#include "game/options.hpp" // Para Options, options
|
||||||
#include "game/ui/notifier.hpp" // Para Notifier
|
#include "game/ui/notifier.hpp" // Para Notifier
|
||||||
@@ -23,13 +24,13 @@ void Cheevos::destroy() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// [SINGLETON] Con este método obtenemos el objeto y podemos trabajar con él
|
// [SINGLETON] Con este método obtenemos el objeto y podemos trabajar con él
|
||||||
Cheevos* Cheevos::get() {
|
auto Cheevos::get() -> Cheevos* {
|
||||||
return Cheevos::cheevos;
|
return Cheevos::cheevos;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Constructor
|
// Constructor
|
||||||
Cheevos::Cheevos(const std::string& file)
|
Cheevos::Cheevos(std::string file)
|
||||||
: file_(file) {
|
: file_(std::move(file)) {
|
||||||
init();
|
init();
|
||||||
loadFromFile();
|
loadFromFile();
|
||||||
}
|
}
|
||||||
@@ -57,7 +58,7 @@ void Cheevos::init() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Busca un logro por id y devuelve el indice
|
// Busca un logro por id y devuelve el indice
|
||||||
int Cheevos::find(int id) {
|
auto Cheevos::find(int id) -> int {
|
||||||
for (int i = 0; i < (int)cheevos_list_.size(); ++i) {
|
for (int i = 0; i < (int)cheevos_list_.size(); ++i) {
|
||||||
if (cheevos_list_[i].id == id) {
|
if (cheevos_list_[i].id == id) {
|
||||||
return i;
|
return i;
|
||||||
@@ -103,7 +104,7 @@ void Cheevos::loadFromFile() {
|
|||||||
// El fichero no existe
|
// El fichero no existe
|
||||||
if (!file) {
|
if (!file) {
|
||||||
if (Options::console) {
|
if (Options::console) {
|
||||||
std::cout << "Warning: Unable to open " << file_ << "! Creating new file..." << std::endl;
|
std::cout << "Warning: Unable to open " << file_ << "! Creating new file..." << '\n';
|
||||||
}
|
}
|
||||||
|
|
||||||
// Crea el fichero en modo escritura (binario)
|
// Crea el fichero en modo escritura (binario)
|
||||||
@@ -111,7 +112,7 @@ void Cheevos::loadFromFile() {
|
|||||||
|
|
||||||
if (new_file) {
|
if (new_file) {
|
||||||
if (Options::console) {
|
if (Options::console) {
|
||||||
std::cout << "New " << file_ << " created!" << std::endl;
|
std::cout << "New " << file_ << " created!" << '\n';
|
||||||
}
|
}
|
||||||
|
|
||||||
// Guarda la información
|
// Guarda la información
|
||||||
@@ -120,14 +121,14 @@ void Cheevos::loadFromFile() {
|
|||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
if (Options::console) {
|
if (Options::console) {
|
||||||
std::cerr << "Error: Unable to create " << file_ << "!" << std::endl;
|
std::cerr << "Error: Unable to create " << file_ << "!" << '\n';
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// El fichero existe
|
// El fichero existe
|
||||||
else {
|
else {
|
||||||
if (Options::console) {
|
if (Options::console) {
|
||||||
std::cout << "Reading " << file_ << std::endl;
|
std::cout << "Reading " << file_ << '\n';
|
||||||
}
|
}
|
||||||
|
|
||||||
// Carga los datos
|
// Carga los datos
|
||||||
@@ -143,21 +144,21 @@ void Cheevos::saveToFile() {
|
|||||||
SDL_IOStream* file = SDL_IOFromFile(this->file_.c_str(), "w+b");
|
SDL_IOStream* file = SDL_IOFromFile(this->file_.c_str(), "w+b");
|
||||||
if (file != nullptr) {
|
if (file != nullptr) {
|
||||||
// Guarda la información
|
// Guarda la información
|
||||||
for (int i = 0; i < (int)cheevos_list_.size(); ++i) {
|
for (auto& i : cheevos_list_) {
|
||||||
SDL_WriteIO(file, &cheevos_list_[i].completed, sizeof(bool));
|
SDL_WriteIO(file, &i.completed, sizeof(bool));
|
||||||
}
|
}
|
||||||
|
|
||||||
// Cierra el fichero
|
// Cierra el fichero
|
||||||
SDL_CloseIO(file);
|
SDL_CloseIO(file);
|
||||||
} else {
|
} else {
|
||||||
if (Options::console) {
|
if (Options::console) {
|
||||||
std::cout << "Error: Unable to save file! " << SDL_GetError() << std::endl;
|
std::cout << "Error: Unable to save file! " << SDL_GetError() << '\n';
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Devuelve el número total de logros desbloqueados
|
// Devuelve el número total de logros desbloqueados
|
||||||
int Cheevos::getTotalUnlockedAchievements() {
|
auto Cheevos::getTotalUnlockedAchievements() -> int {
|
||||||
int count = 0;
|
int count = 0;
|
||||||
for (const auto& cheevo : cheevos_list_) {
|
for (const auto& cheevo : cheevos_list_) {
|
||||||
if (cheevo.completed) {
|
if (cheevo.completed) {
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
#include <string> // Para string
|
#include <string> // Para string
|
||||||
|
#include <utility>
|
||||||
#include <vector> // Para vector
|
#include <vector> // Para vector
|
||||||
|
|
||||||
// Struct para los logros
|
// Struct para los logros
|
||||||
@@ -20,10 +21,10 @@ struct Achievement {
|
|||||||
obtainable(true) {}
|
obtainable(true) {}
|
||||||
|
|
||||||
// Constructor parametrizado
|
// Constructor parametrizado
|
||||||
Achievement(int id, const std::string& caption, const std::string& description, int icon, bool completed = false, bool obtainable = true)
|
Achievement(int id, std::string caption, std::string description, int icon, bool completed = false, bool obtainable = true)
|
||||||
: id(id),
|
: id(id),
|
||||||
caption(caption),
|
caption(std::move(caption)),
|
||||||
description(description),
|
description(std::move(description)),
|
||||||
icon(icon),
|
icon(icon),
|
||||||
completed(completed),
|
completed(completed),
|
||||||
obtainable(obtainable) {}
|
obtainable(obtainable) {}
|
||||||
@@ -43,7 +44,7 @@ class Cheevos {
|
|||||||
void init();
|
void init();
|
||||||
|
|
||||||
// Busca un logro por id y devuelve el índice
|
// Busca un logro por id y devuelve el índice
|
||||||
int find(int id);
|
auto find(int id) -> int;
|
||||||
|
|
||||||
// Carga el estado de los logros desde un fichero
|
// Carga el estado de los logros desde un fichero
|
||||||
void loadFromFile();
|
void loadFromFile();
|
||||||
@@ -52,7 +53,7 @@ class Cheevos {
|
|||||||
void saveToFile();
|
void saveToFile();
|
||||||
|
|
||||||
// Constructor
|
// Constructor
|
||||||
explicit Cheevos(const std::string& file);
|
explicit Cheevos(std::string file);
|
||||||
|
|
||||||
// Destructor
|
// Destructor
|
||||||
~Cheevos();
|
~Cheevos();
|
||||||
@@ -65,7 +66,7 @@ class Cheevos {
|
|||||||
static void destroy();
|
static void destroy();
|
||||||
|
|
||||||
// [SINGLETON] Con este método obtenemos el objeto y podemos trabajar con él
|
// [SINGLETON] Con este método obtenemos el objeto y podemos trabajar con él
|
||||||
static Cheevos* get();
|
static auto get() -> Cheevos*;
|
||||||
|
|
||||||
// Desbloquea un logro
|
// Desbloquea un logro
|
||||||
void unlock(int id);
|
void unlock(int id);
|
||||||
@@ -80,11 +81,11 @@ class Cheevos {
|
|||||||
void enable(bool value) { enabled_ = value; }
|
void enable(bool value) { enabled_ = value; }
|
||||||
|
|
||||||
// Lista los logros
|
// Lista los logros
|
||||||
const std::vector<Achievement>& list() const { return cheevos_list_; }
|
[[nodiscard]] auto list() const -> const std::vector<Achievement>& { return cheevos_list_; }
|
||||||
|
|
||||||
// Devuelve el número total de logros desbloqueados
|
// Devuelve el número total de logros desbloqueados
|
||||||
int getTotalUnlockedAchievements();
|
auto getTotalUnlockedAchievements() -> int;
|
||||||
|
|
||||||
// Devuelve el número total de logros
|
// Devuelve el número total de logros
|
||||||
int size() { return cheevos_list_.size(); }
|
auto size() -> int { return cheevos_list_.size(); }
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -14,12 +14,12 @@ void ItemTracker::destroy() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// [SINGLETON] Con este método obtenemos el objeto y podemos trabajar con él
|
// [SINGLETON] Con este método obtenemos el objeto y podemos trabajar con él
|
||||||
ItemTracker* ItemTracker::get() {
|
auto ItemTracker::get() -> ItemTracker* {
|
||||||
return ItemTracker::item_tracker;
|
return ItemTracker::item_tracker;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Comprueba si el objeto ya ha sido cogido
|
// Comprueba si el objeto ya ha sido cogido
|
||||||
bool ItemTracker::hasBeenPicked(const std::string& name, SDL_FPoint pos) {
|
auto ItemTracker::hasBeenPicked(const std::string& name, SDL_FPoint pos) -> bool {
|
||||||
// Primero busca si ya hay una entrada con ese nombre
|
// Primero busca si ya hay una entrada con ese nombre
|
||||||
if (const int INDEX = findByName(name); INDEX != -1) {
|
if (const int INDEX = findByName(name); INDEX != -1) {
|
||||||
// Luego busca si existe ya una entrada con esa posición
|
// Luego busca si existe ya una entrada con esa posición
|
||||||
@@ -47,7 +47,7 @@ void ItemTracker::addItem(const std::string& name, SDL_FPoint pos) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Busca una entrada en la lista por nombre
|
// Busca una entrada en la lista por nombre
|
||||||
int ItemTracker::findByName(const std::string& name) {
|
auto ItemTracker::findByName(const std::string& name) -> int {
|
||||||
int i = 0;
|
int i = 0;
|
||||||
|
|
||||||
for (const auto& l : item_list_) {
|
for (const auto& l : item_list_) {
|
||||||
@@ -61,7 +61,7 @@ int ItemTracker::findByName(const std::string& name) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Busca una entrada en la lista por posición
|
// Busca una entrada en la lista por posición
|
||||||
int ItemTracker::findByPos(int index, SDL_FPoint pos) {
|
auto ItemTracker::findByPos(int index, SDL_FPoint pos) -> int {
|
||||||
int i = 0;
|
int i = 0;
|
||||||
|
|
||||||
for (const auto& l : item_list_[index].pos) {
|
for (const auto& l : item_list_[index].pos) {
|
||||||
|
|||||||
@@ -3,6 +3,7 @@
|
|||||||
#include <SDL3/SDL.h>
|
#include <SDL3/SDL.h>
|
||||||
|
|
||||||
#include <string> // Para string, basic_string
|
#include <string> // Para string, basic_string
|
||||||
|
#include <utility>
|
||||||
#include <vector> // Para vector
|
#include <vector> // Para vector
|
||||||
|
|
||||||
struct ItemTrackerData {
|
struct ItemTrackerData {
|
||||||
@@ -10,8 +11,8 @@ struct ItemTrackerData {
|
|||||||
std::vector<SDL_FPoint> pos; // Lista de objetos cogidos de la habitación
|
std::vector<SDL_FPoint> pos; // Lista de objetos cogidos de la habitación
|
||||||
|
|
||||||
// Constructor
|
// Constructor
|
||||||
ItemTrackerData(const std::string& name, const SDL_FPoint& position)
|
ItemTrackerData(std::string name, const SDL_FPoint& position)
|
||||||
: name(name) {
|
: name(std::move(name)) {
|
||||||
pos.push_back(position);
|
pos.push_back(position);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@@ -25,10 +26,10 @@ class ItemTracker {
|
|||||||
std::vector<ItemTrackerData> item_list_; // Lista con todos los objetos recogidos
|
std::vector<ItemTrackerData> item_list_; // Lista con todos los objetos recogidos
|
||||||
|
|
||||||
// Busca una entrada en la lista por nombre
|
// Busca una entrada en la lista por nombre
|
||||||
int findByName(const std::string& name);
|
auto findByName(const std::string& name) -> int;
|
||||||
|
|
||||||
// Busca una entrada en la lista por posición
|
// Busca una entrada en la lista por posición
|
||||||
int findByPos(int index, SDL_FPoint pos);
|
auto findByPos(int index, SDL_FPoint pos) -> int;
|
||||||
|
|
||||||
// Constructor
|
// Constructor
|
||||||
ItemTracker() = default;
|
ItemTracker() = default;
|
||||||
@@ -44,10 +45,10 @@ class ItemTracker {
|
|||||||
static void destroy();
|
static void destroy();
|
||||||
|
|
||||||
// [SINGLETON] Con este método obtenemos el objeto y podemos trabajar con él
|
// [SINGLETON] Con este método obtenemos el objeto y podemos trabajar con él
|
||||||
static ItemTracker* get();
|
static auto get() -> ItemTracker*;
|
||||||
|
|
||||||
// Comprueba si el objeto ya ha sido cogido
|
// Comprueba si el objeto ya ha sido cogido
|
||||||
bool hasBeenPicked(const std::string& name, SDL_FPoint pos);
|
auto hasBeenPicked(const std::string& name, SDL_FPoint pos) -> bool;
|
||||||
|
|
||||||
// Añade el objeto a la lista de objetos cogidos
|
// Añade el objeto a la lista de objetos cogidos
|
||||||
void addItem(const std::string& name, SDL_FPoint pos);
|
void addItem(const std::string& name, SDL_FPoint pos);
|
||||||
|
|||||||
@@ -5,6 +5,7 @@
|
|||||||
#include <fstream> // Para basic_ostream, operator<<, basic_istream
|
#include <fstream> // Para basic_ostream, operator<<, basic_istream
|
||||||
#include <iostream> // Para cout, cerr
|
#include <iostream> // Para cout, cerr
|
||||||
#include <sstream> // Para basic_stringstream
|
#include <sstream> // Para basic_stringstream
|
||||||
|
#include <utility>
|
||||||
|
|
||||||
#include "core/rendering/screen.hpp" // Para Screen
|
#include "core/rendering/screen.hpp" // Para Screen
|
||||||
#include "core/rendering/surface.hpp" // Para Surface
|
#include "core/rendering/surface.hpp" // Para Surface
|
||||||
@@ -19,7 +20,7 @@
|
|||||||
#include "utils/utils.hpp" // Para LineHorizontal, LineDiagonal, LineVertical
|
#include "utils/utils.hpp" // Para LineHorizontal, LineDiagonal, LineVertical
|
||||||
|
|
||||||
// Carga las variables y texturas desde un fichero de mapa de tiles
|
// Carga las variables y texturas desde un fichero de mapa de tiles
|
||||||
std::vector<int> loadRoomTileFile(const std::string& file_path, bool verbose) {
|
auto loadRoomTileFile(const std::string& file_path, bool verbose) -> std::vector<int> {
|
||||||
std::vector<int> tile_map_file;
|
std::vector<int> tile_map_file;
|
||||||
const std::string FILENAME = file_path.substr(file_path.find_last_of("\\/") + 1);
|
const std::string FILENAME = file_path.substr(file_path.find_last_of("\\/") + 1);
|
||||||
std::ifstream file(file_path);
|
std::ifstream file(file_path);
|
||||||
@@ -47,14 +48,14 @@ std::vector<int> loadRoomTileFile(const std::string& file_path, bool verbose) {
|
|||||||
|
|
||||||
// Cierra el fichero
|
// Cierra el fichero
|
||||||
if (verbose) {
|
if (verbose) {
|
||||||
std::cout << "TileMap loaded: " << FILENAME.c_str() << std::endl;
|
std::cout << "TileMap loaded: " << FILENAME.c_str() << '\n';
|
||||||
}
|
}
|
||||||
file.close();
|
file.close();
|
||||||
}
|
}
|
||||||
|
|
||||||
else { // El fichero no se puede abrir
|
else { // El fichero no se puede abrir
|
||||||
if (verbose) {
|
if (verbose) {
|
||||||
std::cout << "Warning: Unable to open " << FILENAME.c_str() << " file" << std::endl;
|
std::cout << "Warning: Unable to open " << FILENAME.c_str() << " file" << '\n';
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -62,8 +63,8 @@ std::vector<int> loadRoomTileFile(const std::string& file_path, bool verbose) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Parsea una línea en key y value separados por '='
|
// Parsea una línea en key y value separados por '='
|
||||||
std::pair<std::string, std::string> parseKeyValue(const std::string& line) {
|
auto parseKeyValue(const std::string& line) -> std::pair<std::string, std::string> {
|
||||||
int pos = line.find("=");
|
int pos = line.find('=');
|
||||||
std::string key = line.substr(0, pos);
|
std::string key = line.substr(0, pos);
|
||||||
std::string value = line.substr(pos + 1, line.length());
|
std::string value = line.substr(pos + 1, line.length());
|
||||||
return {key, value};
|
return {key, value};
|
||||||
@@ -72,12 +73,12 @@ std::pair<std::string, std::string> parseKeyValue(const std::string& line) {
|
|||||||
// Muestra un warning de parámetro desconocido
|
// Muestra un warning de parámetro desconocido
|
||||||
void logUnknownParameter(const std::string& file_name, const std::string& key, bool verbose) {
|
void logUnknownParameter(const std::string& file_name, const std::string& key, bool verbose) {
|
||||||
if (verbose) {
|
if (verbose) {
|
||||||
std::cout << "Warning: file " << file_name.c_str() << "\n, unknown parameter \"" << key.c_str() << "\"" << std::endl;
|
std::cout << "Warning: file " << file_name.c_str() << "\n, unknown parameter \"" << key.c_str() << "\"" << '\n';
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Carga un bloque [enemy]...[/enemy] desde un archivo
|
// Carga un bloque [enemy]...[/enemy] desde un archivo
|
||||||
EnemyData loadEnemyFromFile(std::ifstream& file, const std::string& file_name, bool verbose) {
|
auto loadEnemyFromFile(std::ifstream& file, const std::string& file_name, bool verbose) -> EnemyData {
|
||||||
EnemyData enemy;
|
EnemyData enemy;
|
||||||
enemy.flip = false;
|
enemy.flip = false;
|
||||||
enemy.mirror = false;
|
enemy.mirror = false;
|
||||||
@@ -97,7 +98,7 @@ EnemyData loadEnemyFromFile(std::ifstream& file, const std::string& file_name, b
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Carga un bloque [item]...[/item] desde un archivo
|
// Carga un bloque [item]...[/item] desde un archivo
|
||||||
ItemData loadItemFromFile(std::ifstream& file, const std::string& file_name, bool verbose) {
|
auto loadItemFromFile(std::ifstream& file, const std::string& file_name, bool verbose) -> ItemData {
|
||||||
ItemData item;
|
ItemData item;
|
||||||
item.counter = 0;
|
item.counter = 0;
|
||||||
item.color1 = stringToColor("yellow");
|
item.color1 = stringToColor("yellow");
|
||||||
@@ -117,14 +118,14 @@ ItemData loadItemFromFile(std::ifstream& file, const std::string& file_name, boo
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Carga las variables desde un fichero de mapa
|
// Carga las variables desde un fichero de mapa
|
||||||
RoomData loadRoomFile(const std::string& file_path, bool verbose) {
|
auto loadRoomFile(const std::string& file_path, bool verbose) -> RoomData {
|
||||||
RoomData room;
|
RoomData room;
|
||||||
room.item_color1 = "yellow";
|
room.item_color1 = "yellow";
|
||||||
room.item_color2 = "magenta";
|
room.item_color2 = "magenta";
|
||||||
room.conveyor_belt_direction = 1;
|
room.conveyor_belt_direction = 1;
|
||||||
|
|
||||||
const std::string FILE_NAME = file_path.substr(file_path.find_last_of("\\/") + 1);
|
const std::string FILE_NAME = file_path.substr(file_path.find_last_of("\\/") + 1);
|
||||||
room.number = FILE_NAME.substr(0, FILE_NAME.find_last_of("."));
|
room.number = FILE_NAME.substr(0, FILE_NAME.find_last_of('.'));
|
||||||
|
|
||||||
std::ifstream file(file_path);
|
std::ifstream file(file_path);
|
||||||
|
|
||||||
@@ -152,20 +153,20 @@ RoomData loadRoomFile(const std::string& file_path, bool verbose) {
|
|||||||
|
|
||||||
// Cierra el fichero
|
// Cierra el fichero
|
||||||
if (verbose) {
|
if (verbose) {
|
||||||
std::cout << "Room loaded: " << FILE_NAME.c_str() << std::endl;
|
std::cout << "Room loaded: " << FILE_NAME.c_str() << '\n';
|
||||||
}
|
}
|
||||||
file.close();
|
file.close();
|
||||||
}
|
}
|
||||||
// El fichero no se puede abrir
|
// El fichero no se puede abrir
|
||||||
else {
|
else {
|
||||||
std::cout << "Warning: Unable to open " << FILE_NAME.c_str() << " file" << std::endl;
|
std::cout << "Warning: Unable to open " << FILE_NAME.c_str() << " file" << '\n';
|
||||||
}
|
}
|
||||||
|
|
||||||
return room;
|
return room;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Asigna variables a una estructura RoomData
|
// Asigna variables a una estructura RoomData
|
||||||
bool setRoom(RoomData* room, const std::string& key, const std::string& value) {
|
auto setRoom(RoomData* room, const std::string& key, const std::string& value) -> bool {
|
||||||
// Indicador de éxito en la asignación
|
// Indicador de éxito en la asignación
|
||||||
bool success = true;
|
bool success = true;
|
||||||
|
|
||||||
@@ -200,7 +201,7 @@ bool setRoom(RoomData* room, const std::string& key, const std::string& value) {
|
|||||||
success = false;
|
success = false;
|
||||||
}
|
}
|
||||||
} catch (const std::exception& e) {
|
} catch (const std::exception& e) {
|
||||||
std::cerr << "Error al asignar la clave " << key << " con valor " << value << ": " << e.what() << std::endl;
|
std::cerr << "Error al asignar la clave " << key << " con valor " << value << ": " << e.what() << '\n';
|
||||||
success = false;
|
success = false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -208,7 +209,7 @@ bool setRoom(RoomData* room, const std::string& key, const std::string& value) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Asigna variables a una estructura EnemyData
|
// Asigna variables a una estructura EnemyData
|
||||||
bool setEnemy(EnemyData* enemy, const std::string& key, const std::string& value) {
|
auto setEnemy(EnemyData* enemy, const std::string& key, const std::string& value) -> bool {
|
||||||
// Indicador de éxito en la asignación
|
// Indicador de éxito en la asignación
|
||||||
bool success = true;
|
bool success = true;
|
||||||
|
|
||||||
@@ -251,7 +252,7 @@ bool setEnemy(EnemyData* enemy, const std::string& key, const std::string& value
|
|||||||
success = false;
|
success = false;
|
||||||
}
|
}
|
||||||
} catch (const std::exception& e) {
|
} catch (const std::exception& e) {
|
||||||
std::cerr << "Error al asignar la clave " << key << " con valor " << value << ": " << e.what() << std::endl;
|
std::cerr << "Error al asignar la clave " << key << " con valor " << value << ": " << e.what() << '\n';
|
||||||
success = false;
|
success = false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -259,7 +260,7 @@ bool setEnemy(EnemyData* enemy, const std::string& key, const std::string& value
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Asigna variables a una estructura ItemData
|
// Asigna variables a una estructura ItemData
|
||||||
bool setItem(ItemData* item, const std::string& key, const std::string& value) {
|
auto setItem(ItemData* item, const std::string& key, const std::string& value) -> bool {
|
||||||
// Indicador de éxito en la asignación
|
// Indicador de éxito en la asignación
|
||||||
bool success = true;
|
bool success = true;
|
||||||
|
|
||||||
@@ -280,7 +281,7 @@ bool setItem(ItemData* item, const std::string& key, const std::string& value) {
|
|||||||
success = false;
|
success = false;
|
||||||
}
|
}
|
||||||
} catch (const std::exception& e) {
|
} catch (const std::exception& e) {
|
||||||
std::cerr << "Error al asignar la clave " << key << " con valor " << value << ": " << e.what() << std::endl;
|
std::cerr << "Error al asignar la clave " << key << " con valor " << value << ": " << e.what() << '\n';
|
||||||
success = false;
|
success = false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -289,7 +290,7 @@ bool setItem(ItemData* item, const std::string& key, const std::string& value) {
|
|||||||
|
|
||||||
// Constructor
|
// Constructor
|
||||||
Room::Room(const std::string& room_path, std::shared_ptr<ScoreboardData> data)
|
Room::Room(const std::string& room_path, std::shared_ptr<ScoreboardData> data)
|
||||||
: data_(data) {
|
: data_(std::move(std::move(data))) {
|
||||||
auto room = Resource::get()->getRoom(room_path);
|
auto room = Resource::get()->getRoom(room_path);
|
||||||
initializeRoom(*room);
|
initializeRoom(*room);
|
||||||
|
|
||||||
@@ -482,19 +483,19 @@ void Room::update() {
|
|||||||
// Actualiza los tiles animados
|
// Actualiza los tiles animados
|
||||||
updateAnimatedTiles();
|
updateAnimatedTiles();
|
||||||
|
|
||||||
for (auto enemy : enemies_) {
|
for (const auto& enemy : enemies_) {
|
||||||
// Actualiza los enemigos
|
// Actualiza los enemigos
|
||||||
enemy->update();
|
enemy->update();
|
||||||
}
|
}
|
||||||
|
|
||||||
for (auto item : items_) {
|
for (const auto& item : items_) {
|
||||||
// Actualiza los items
|
// Actualiza los items
|
||||||
item->update();
|
item->update();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Devuelve la cadena del fichero de la habitación contigua segun el borde
|
// Devuelve la cadena del fichero de la habitación contigua segun el borde
|
||||||
std::string Room::getRoom(RoomBorder border) {
|
auto Room::getRoom(RoomBorder border) -> std::string {
|
||||||
switch (border) {
|
switch (border) {
|
||||||
case RoomBorder::TOP:
|
case RoomBorder::TOP:
|
||||||
return upper_room_;
|
return upper_room_;
|
||||||
@@ -519,13 +520,13 @@ std::string Room::getRoom(RoomBorder border) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Devuelve el tipo de tile que hay en ese pixel
|
// Devuelve el tipo de tile que hay en ese pixel
|
||||||
TileType Room::getTile(SDL_FPoint point) {
|
auto Room::getTile(SDL_FPoint point) -> TileType {
|
||||||
const int POS = ((point.y / TILE_SIZE) * MAP_WIDTH) + (point.x / TILE_SIZE);
|
const int POS = ((point.y / TILE_SIZE) * MAP_WIDTH) + (point.x / TILE_SIZE);
|
||||||
return getTile(POS);
|
return getTile(POS);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Devuelve el tipo de tile que hay en ese indice
|
// Devuelve el tipo de tile que hay en ese indice
|
||||||
TileType Room::getTile(int index) {
|
auto Room::getTile(int index) -> TileType {
|
||||||
// const bool onRange = (index > -1) && (index < mapWidth * mapHeight);
|
// const bool onRange = (index > -1) && (index < mapWidth * mapHeight);
|
||||||
const bool ON_RANGE = (index > -1) && (index < (int)tile_map_.size());
|
const bool ON_RANGE = (index > -1) && (index < (int)tile_map_.size());
|
||||||
|
|
||||||
@@ -565,14 +566,14 @@ TileType Room::getTile(int index) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Indica si hay colision con un enemigo a partir de un rectangulo
|
// Indica si hay colision con un enemigo a partir de un rectangulo
|
||||||
bool Room::enemyCollision(SDL_FRect& rect) {
|
auto Room::enemyCollision(SDL_FRect& rect) -> bool {
|
||||||
return std::ranges::any_of(enemies_, [&rect](const auto& enemy) {
|
return std::ranges::any_of(enemies_, [&rect](const auto& enemy) {
|
||||||
return checkCollision(rect, enemy->getCollider());
|
return checkCollision(rect, enemy->getCollider());
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// Indica si hay colision con un objeto a partir de un rectangulo
|
// Indica si hay colision con un objeto a partir de un rectangulo
|
||||||
bool Room::itemCollision(SDL_FRect& rect) {
|
auto Room::itemCollision(SDL_FRect& rect) -> bool {
|
||||||
for (int i = 0; i < static_cast<int>(items_.size()); ++i) {
|
for (int i = 0; i < static_cast<int>(items_.size()); ++i) {
|
||||||
if (checkCollision(rect, items_.at(i)->getCollider())) {
|
if (checkCollision(rect, items_.at(i)->getCollider())) {
|
||||||
ItemTracker::get()->addItem(name_, items_.at(i)->getPos());
|
ItemTracker::get()->addItem(name_, items_.at(i)->getPos());
|
||||||
@@ -588,7 +589,7 @@ bool Room::itemCollision(SDL_FRect& rect) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Obten la coordenada de la cuesta a partir de un punto perteneciente a ese tile
|
// Obten la coordenada de la cuesta a partir de un punto perteneciente a ese tile
|
||||||
int Room::getSlopeHeight(SDL_FPoint p, TileType slope) {
|
auto Room::getSlopeHeight(SDL_FPoint p, TileType slope) -> int {
|
||||||
// Calcula la base del tile
|
// Calcula la base del tile
|
||||||
int base = ((p.y / TILE_SIZE) * TILE_SIZE) + TILE_SIZE;
|
int base = ((p.y / TILE_SIZE) * TILE_SIZE) + TILE_SIZE;
|
||||||
#ifdef _DEBUG
|
#ifdef _DEBUG
|
||||||
@@ -618,7 +619,7 @@ int Room::getSlopeHeight(SDL_FPoint p, TileType slope) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Helper: recopila tiles inferiores (muros sin muro debajo)
|
// Helper: recopila tiles inferiores (muros sin muro debajo)
|
||||||
std::vector<int> Room::collectBottomTiles() {
|
auto Room::collectBottomTiles() -> std::vector<int> {
|
||||||
std::vector<int> tile;
|
std::vector<int> tile;
|
||||||
|
|
||||||
// Busca todos los tiles de tipo muro que no tengan debajo otro muro
|
// Busca todos los tiles de tipo muro que no tengan debajo otro muro
|
||||||
@@ -640,7 +641,7 @@ std::vector<int> Room::collectBottomTiles() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Helper: recopila tiles superiores (muros o pasables sin muro encima)
|
// Helper: recopila tiles superiores (muros o pasables sin muro encima)
|
||||||
std::vector<int> Room::collectTopTiles() {
|
auto Room::collectTopTiles() -> std::vector<int> {
|
||||||
std::vector<int> tile;
|
std::vector<int> tile;
|
||||||
|
|
||||||
// Busca todos los tiles de tipo muro o pasable que no tengan encima un muro
|
// Busca todos los tiles de tipo muro o pasable que no tengan encima un muro
|
||||||
@@ -867,7 +868,7 @@ void Room::setRightSlopes() {
|
|||||||
|
|
||||||
// Calcula las superficies automaticas
|
// Calcula las superficies automaticas
|
||||||
// Helper: recopila tiles animados (para superficies automaticas/conveyor belts)
|
// Helper: recopila tiles animados (para superficies automaticas/conveyor belts)
|
||||||
std::vector<int> Room::collectAnimatedTiles() {
|
auto Room::collectAnimatedTiles() -> std::vector<int> {
|
||||||
std::vector<int> tile;
|
std::vector<int> tile;
|
||||||
|
|
||||||
// Busca todos los tiles de tipo animado
|
// Busca todos los tiles de tipo animado
|
||||||
@@ -943,7 +944,7 @@ void Room::renderAnimatedTiles() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Comprueba las colisiones
|
// Comprueba las colisiones
|
||||||
int Room::checkRightSurfaces(SDL_FRect* rect) {
|
auto Room::checkRightSurfaces(SDL_FRect* rect) -> int {
|
||||||
for (const auto& s : right_walls_) {
|
for (const auto& s : right_walls_) {
|
||||||
if (checkCollision(s, *rect)) {
|
if (checkCollision(s, *rect)) {
|
||||||
return s.x;
|
return s.x;
|
||||||
@@ -954,7 +955,7 @@ int Room::checkRightSurfaces(SDL_FRect* rect) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Comprueba las colisiones
|
// Comprueba las colisiones
|
||||||
int Room::checkLeftSurfaces(SDL_FRect* rect) {
|
auto Room::checkLeftSurfaces(SDL_FRect* rect) -> int {
|
||||||
for (const auto& s : left_walls_) {
|
for (const auto& s : left_walls_) {
|
||||||
if (checkCollision(s, *rect)) {
|
if (checkCollision(s, *rect)) {
|
||||||
return s.x;
|
return s.x;
|
||||||
@@ -965,7 +966,7 @@ int Room::checkLeftSurfaces(SDL_FRect* rect) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Comprueba las colisiones
|
// Comprueba las colisiones
|
||||||
int Room::checkTopSurfaces(SDL_FRect* rect) {
|
auto Room::checkTopSurfaces(SDL_FRect* rect) -> int {
|
||||||
for (const auto& s : top_floors_) {
|
for (const auto& s : top_floors_) {
|
||||||
if (checkCollision(s, *rect)) {
|
if (checkCollision(s, *rect)) {
|
||||||
return s.y;
|
return s.y;
|
||||||
@@ -976,7 +977,7 @@ int Room::checkTopSurfaces(SDL_FRect* rect) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Comprueba las colisiones
|
// Comprueba las colisiones
|
||||||
int Room::checkBottomSurfaces(SDL_FRect* rect) {
|
auto Room::checkBottomSurfaces(SDL_FRect* rect) -> int {
|
||||||
for (const auto& s : bottom_floors_) {
|
for (const auto& s : bottom_floors_) {
|
||||||
if (checkCollision(s, *rect)) {
|
if (checkCollision(s, *rect)) {
|
||||||
return s.y;
|
return s.y;
|
||||||
@@ -987,7 +988,7 @@ int Room::checkBottomSurfaces(SDL_FRect* rect) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Comprueba las colisiones
|
// Comprueba las colisiones
|
||||||
int Room::checkAutoSurfaces(SDL_FRect* rect) {
|
auto Room::checkAutoSurfaces(SDL_FRect* rect) -> int {
|
||||||
for (const auto& s : conveyor_belt_floors_) {
|
for (const auto& s : conveyor_belt_floors_) {
|
||||||
if (checkCollision(s, *rect)) {
|
if (checkCollision(s, *rect)) {
|
||||||
return s.y;
|
return s.y;
|
||||||
@@ -998,21 +999,21 @@ int Room::checkAutoSurfaces(SDL_FRect* rect) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Comprueba las colisiones
|
// Comprueba las colisiones
|
||||||
bool Room::checkTopSurfaces(SDL_FPoint* p) {
|
auto Room::checkTopSurfaces(SDL_FPoint* p) -> bool {
|
||||||
return std::ranges::any_of(top_floors_, [&](const auto& s) {
|
return std::ranges::any_of(top_floors_, [&](const auto& s) {
|
||||||
return checkCollision(s, *p);
|
return checkCollision(s, *p);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// Comprueba las colisiones
|
// Comprueba las colisiones
|
||||||
bool Room::checkAutoSurfaces(SDL_FPoint* p) {
|
auto Room::checkAutoSurfaces(SDL_FPoint* p) -> bool {
|
||||||
return std::ranges::any_of(conveyor_belt_floors_, [&](const auto& s) {
|
return std::ranges::any_of(conveyor_belt_floors_, [&](const auto& s) {
|
||||||
return checkCollision(s, *p);
|
return checkCollision(s, *p);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// Comprueba las colisiones
|
// Comprueba las colisiones
|
||||||
int Room::checkLeftSlopes(const LineVertical* line) {
|
auto Room::checkLeftSlopes(const LineVertical* line) -> int {
|
||||||
for (const auto& slope : left_slopes_) {
|
for (const auto& slope : left_slopes_) {
|
||||||
const auto P = checkCollision(slope, *line);
|
const auto P = checkCollision(slope, *line);
|
||||||
if (P.x != -1) {
|
if (P.x != -1) {
|
||||||
@@ -1024,14 +1025,14 @@ int Room::checkLeftSlopes(const LineVertical* line) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Comprueba las colisiones
|
// Comprueba las colisiones
|
||||||
bool Room::checkLeftSlopes(SDL_FPoint* p) {
|
auto Room::checkLeftSlopes(SDL_FPoint* p) -> bool {
|
||||||
return std::ranges::any_of(left_slopes_, [&](const auto& slope) {
|
return std::ranges::any_of(left_slopes_, [&](const auto& slope) {
|
||||||
return checkCollision(*p, slope);
|
return checkCollision(*p, slope);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// Comprueba las colisiones
|
// Comprueba las colisiones
|
||||||
int Room::checkRightSlopes(const LineVertical* line) {
|
auto Room::checkRightSlopes(const LineVertical* line) -> int {
|
||||||
for (const auto& slope : right_slopes_) {
|
for (const auto& slope : right_slopes_) {
|
||||||
const auto P = checkCollision(slope, *line);
|
const auto P = checkCollision(slope, *line);
|
||||||
if (P.x != -1) {
|
if (P.x != -1) {
|
||||||
@@ -1043,7 +1044,7 @@ int Room::checkRightSlopes(const LineVertical* line) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Comprueba las colisiones
|
// Comprueba las colisiones
|
||||||
bool Room::checkRightSlopes(SDL_FPoint* p) {
|
auto Room::checkRightSlopes(SDL_FPoint* p) -> bool {
|
||||||
return std::ranges::any_of(right_slopes_, [&](const auto& slope) {
|
return std::ranges::any_of(right_slopes_, [&](const auto& slope) {
|
||||||
return checkCollision(*p, slope);
|
return checkCollision(*p, slope);
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -55,19 +55,19 @@ struct RoomData {
|
|||||||
};
|
};
|
||||||
|
|
||||||
// Carga las variables desde un fichero de mapa
|
// Carga las variables desde un fichero de mapa
|
||||||
RoomData loadRoomFile(const std::string& file_path, bool verbose = false);
|
auto loadRoomFile(const std::string& file_path, bool verbose = false) -> RoomData;
|
||||||
|
|
||||||
// Carga las variables y texturas desde un fichero de mapa de tiles
|
// Carga las variables y texturas desde un fichero de mapa de tiles
|
||||||
std::vector<int> loadRoomTileFile(const std::string& file_path, bool verbose = false);
|
auto loadRoomTileFile(const std::string& file_path, bool verbose = false) -> std::vector<int>;
|
||||||
|
|
||||||
// Asigna variables a una estructura RoomData
|
// Asigna variables a una estructura RoomData
|
||||||
bool setRoom(RoomData* room, const std::string& key, const std::string& value);
|
auto setRoom(RoomData* room, const std::string& key, const std::string& value) -> bool;
|
||||||
|
|
||||||
// Asigna variables a una estructura EnemyData
|
// Asigna variables a una estructura EnemyData
|
||||||
bool setEnemy(EnemyData* enemy, const std::string& key, const std::string& value);
|
auto setEnemy(EnemyData* enemy, const std::string& key, const std::string& value) -> bool;
|
||||||
|
|
||||||
// Asigna variables a una estructura ItemData
|
// Asigna variables a una estructura ItemData
|
||||||
bool setItem(ItemData* item, const std::string& key, const std::string& value);
|
auto setItem(ItemData* item, const std::string& key, const std::string& value) -> bool;
|
||||||
|
|
||||||
class Room {
|
class Room {
|
||||||
private:
|
private:
|
||||||
@@ -116,13 +116,13 @@ class Room {
|
|||||||
void fillMapTexture();
|
void fillMapTexture();
|
||||||
|
|
||||||
// Helper para recopilar tiles inferiores
|
// Helper para recopilar tiles inferiores
|
||||||
std::vector<int> collectBottomTiles();
|
auto collectBottomTiles() -> std::vector<int>;
|
||||||
|
|
||||||
// Helper para recopilar tiles superiores
|
// Helper para recopilar tiles superiores
|
||||||
std::vector<int> collectTopTiles();
|
auto collectTopTiles() -> std::vector<int>;
|
||||||
|
|
||||||
// Helper para recopilar tiles animados (para superficies automaticas)
|
// Helper para recopilar tiles animados (para superficies automaticas)
|
||||||
std::vector<int> collectAnimatedTiles();
|
auto collectAnimatedTiles() -> std::vector<int>;
|
||||||
|
|
||||||
// Helper para construir lineas horizontales a partir de tiles consecutivos
|
// Helper para construir lineas horizontales a partir de tiles consecutivos
|
||||||
static void buildHorizontalLines(const std::vector<int>& tiles, std::vector<LineHorizontal>& lines, bool is_bottom_surface);
|
static void buildHorizontalLines(const std::vector<int>& tiles, std::vector<LineHorizontal>& lines, bool is_bottom_surface);
|
||||||
@@ -158,7 +158,7 @@ class Room {
|
|||||||
void renderAnimatedTiles();
|
void renderAnimatedTiles();
|
||||||
|
|
||||||
// Devuelve el tipo de tile que hay en ese indice
|
// Devuelve el tipo de tile que hay en ese indice
|
||||||
TileType getTile(int index);
|
auto getTile(int index) -> TileType;
|
||||||
|
|
||||||
// Abre la jail para poder entrar
|
// Abre la jail para poder entrar
|
||||||
void openTheJail();
|
void openTheJail();
|
||||||
@@ -174,13 +174,13 @@ class Room {
|
|||||||
~Room() = default;
|
~Room() = default;
|
||||||
|
|
||||||
// Devuelve el nombre de la habitación
|
// Devuelve el nombre de la habitación
|
||||||
const std::string& getName() const { return name_; }
|
[[nodiscard]] auto getName() const -> const std::string& { return name_; }
|
||||||
|
|
||||||
// Devuelve el color de la habitación
|
// Devuelve el color de la habitación
|
||||||
Uint8 getBGColor() const { return stringToColor(bg_color_); }
|
[[nodiscard]] auto getBGColor() const -> Uint8 { return stringToColor(bg_color_); }
|
||||||
|
|
||||||
// Devuelve el color del borde
|
// Devuelve el color del borde
|
||||||
Uint8 getBorderColor() const { return stringToColor(border_color_); }
|
[[nodiscard]] auto getBorderColor() const -> Uint8 { return stringToColor(border_color_); }
|
||||||
|
|
||||||
// Dibuja el mapa en pantalla
|
// Dibuja el mapa en pantalla
|
||||||
void renderMap();
|
void renderMap();
|
||||||
@@ -195,59 +195,59 @@ class Room {
|
|||||||
void update();
|
void update();
|
||||||
|
|
||||||
// Devuelve la cadena del fichero de la habitación contigua segun el borde
|
// Devuelve la cadena del fichero de la habitación contigua segun el borde
|
||||||
std::string getRoom(RoomBorder border);
|
auto getRoom(RoomBorder border) -> std::string;
|
||||||
|
|
||||||
// Devuelve el tipo de tile que hay en ese pixel
|
// Devuelve el tipo de tile que hay en ese pixel
|
||||||
TileType getTile(SDL_FPoint point);
|
auto getTile(SDL_FPoint point) -> TileType;
|
||||||
|
|
||||||
// Indica si hay colision con un enemigo a partir de un rectangulo
|
// Indica si hay colision con un enemigo a partir de un rectangulo
|
||||||
bool enemyCollision(SDL_FRect& rect);
|
auto enemyCollision(SDL_FRect& rect) -> bool;
|
||||||
|
|
||||||
// Indica si hay colision con un objeto a partir de un rectangulo
|
// Indica si hay colision con un objeto a partir de un rectangulo
|
||||||
bool itemCollision(SDL_FRect& rect);
|
auto itemCollision(SDL_FRect& rect) -> bool;
|
||||||
|
|
||||||
// Obten el tamaño del tile
|
// Obten el tamaño del tile
|
||||||
static int getTileSize() { return TILE_SIZE; }
|
static auto getTileSize() -> int { return TILE_SIZE; }
|
||||||
|
|
||||||
// Obten la coordenada de la cuesta a partir de un punto perteneciente a ese tile
|
// Obten la coordenada de la cuesta a partir de un punto perteneciente a ese tile
|
||||||
static int getSlopeHeight(SDL_FPoint p, TileType slope);
|
static auto getSlopeHeight(SDL_FPoint p, TileType slope) -> int;
|
||||||
|
|
||||||
// Comprueba las colisiones
|
// Comprueba las colisiones
|
||||||
int checkRightSurfaces(SDL_FRect* rect);
|
auto checkRightSurfaces(SDL_FRect* rect) -> int;
|
||||||
|
|
||||||
// Comprueba las colisiones
|
// Comprueba las colisiones
|
||||||
int checkLeftSurfaces(SDL_FRect* rect);
|
auto checkLeftSurfaces(SDL_FRect* rect) -> int;
|
||||||
|
|
||||||
// Comprueba las colisiones
|
// Comprueba las colisiones
|
||||||
int checkTopSurfaces(SDL_FRect* rect);
|
auto checkTopSurfaces(SDL_FRect* rect) -> int;
|
||||||
|
|
||||||
// Comprueba las colisiones
|
// Comprueba las colisiones
|
||||||
int checkBottomSurfaces(SDL_FRect* rect);
|
auto checkBottomSurfaces(SDL_FRect* rect) -> int;
|
||||||
|
|
||||||
// Comprueba las colisiones
|
// Comprueba las colisiones
|
||||||
int checkAutoSurfaces(SDL_FRect* rect);
|
auto checkAutoSurfaces(SDL_FRect* rect) -> int;
|
||||||
|
|
||||||
// Comprueba las colisiones
|
// Comprueba las colisiones
|
||||||
bool checkTopSurfaces(SDL_FPoint* p);
|
auto checkTopSurfaces(SDL_FPoint* p) -> bool;
|
||||||
|
|
||||||
// Comprueba las colisiones
|
// Comprueba las colisiones
|
||||||
bool checkAutoSurfaces(SDL_FPoint* p);
|
auto checkAutoSurfaces(SDL_FPoint* p) -> bool;
|
||||||
|
|
||||||
// Comprueba las colisiones
|
// Comprueba las colisiones
|
||||||
int checkLeftSlopes(const LineVertical* line);
|
auto checkLeftSlopes(const LineVertical* line) -> int;
|
||||||
|
|
||||||
// Comprueba las colisiones
|
// Comprueba las colisiones
|
||||||
bool checkLeftSlopes(SDL_FPoint* p);
|
auto checkLeftSlopes(SDL_FPoint* p) -> bool;
|
||||||
|
|
||||||
// Comprueba las colisiones
|
// Comprueba las colisiones
|
||||||
int checkRightSlopes(const LineVertical* line);
|
auto checkRightSlopes(const LineVertical* line) -> int;
|
||||||
|
|
||||||
// Comprueba las colisiones
|
// Comprueba las colisiones
|
||||||
bool checkRightSlopes(SDL_FPoint* p);
|
auto checkRightSlopes(SDL_FPoint* p) -> bool;
|
||||||
|
|
||||||
// Pone el mapa en modo pausa
|
// Pone el mapa en modo pausa
|
||||||
void setPaused(bool value) { is_paused_ = value; };
|
void setPaused(bool value) { is_paused_ = value; };
|
||||||
|
|
||||||
// Obten la direccion de las superficies automaticas
|
// Obten la direccion de las superficies automaticas
|
||||||
int getAutoSurfaceDirection() const { return conveyor_belt_direction_; }
|
[[nodiscard]] auto getAutoSurfaceDirection() const -> int { return conveyor_belt_direction_; }
|
||||||
};
|
};
|
||||||
@@ -3,12 +3,12 @@
|
|||||||
#include <algorithm> // Para std::ranges::any_of
|
#include <algorithm> // Para std::ranges::any_of
|
||||||
|
|
||||||
// Comprueba si la habitación ya ha sido visitada
|
// Comprueba si la habitación ya ha sido visitada
|
||||||
bool RoomTracker::hasBeenVisited(const std::string& name) {
|
auto RoomTracker::hasBeenVisited(const std::string& name) -> bool {
|
||||||
return std::ranges::any_of(list_, [&name](const auto& l) { return l == name; });
|
return std::ranges::any_of(list_, [&name](const auto& l) { return l == name; });
|
||||||
}
|
}
|
||||||
|
|
||||||
// Añade la habitación a la lista
|
// Añade la habitación a la lista
|
||||||
bool RoomTracker::addRoom(const std::string& name) {
|
auto RoomTracker::addRoom(const std::string& name) -> bool {
|
||||||
// Comprueba si la habitación ya ha sido visitada
|
// Comprueba si la habitación ya ha sido visitada
|
||||||
if (!hasBeenVisited(name)) {
|
if (!hasBeenVisited(name)) {
|
||||||
// En caso contrario añádela a la lista
|
// En caso contrario añádela a la lista
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ class RoomTracker {
|
|||||||
std::vector<std::string> list_; // Lista con las habitaciones visitadas
|
std::vector<std::string> list_; // Lista con las habitaciones visitadas
|
||||||
|
|
||||||
// Comprueba si la habitación ya ha sido visitada
|
// Comprueba si la habitación ya ha sido visitada
|
||||||
bool hasBeenVisited(const std::string& name);
|
auto hasBeenVisited(const std::string& name) -> bool;
|
||||||
|
|
||||||
public:
|
public:
|
||||||
// Constructor
|
// Constructor
|
||||||
@@ -19,5 +19,5 @@ class RoomTracker {
|
|||||||
~RoomTracker() = default;
|
~RoomTracker() = default;
|
||||||
|
|
||||||
// Añade la habitación a la lista
|
// Añade la habitación a la lista
|
||||||
bool addRoom(const std::string& name);
|
auto addRoom(const std::string& name) -> bool;
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -2,6 +2,8 @@
|
|||||||
|
|
||||||
#include <SDL3/SDL.h>
|
#include <SDL3/SDL.h>
|
||||||
|
|
||||||
|
#include <utility>
|
||||||
|
|
||||||
#include "core/rendering/screen.hpp" // Para Screen
|
#include "core/rendering/screen.hpp" // Para Screen
|
||||||
#include "core/rendering/surface.hpp" // Para Surface
|
#include "core/rendering/surface.hpp" // Para Surface
|
||||||
#include "core/rendering/surface_animated_sprite.hpp" // Para SAnimatedSprite
|
#include "core/rendering/surface_animated_sprite.hpp" // Para SAnimatedSprite
|
||||||
@@ -14,7 +16,7 @@
|
|||||||
// Constructor
|
// Constructor
|
||||||
Scoreboard::Scoreboard(std::shared_ptr<ScoreboardData> data)
|
Scoreboard::Scoreboard(std::shared_ptr<ScoreboardData> data)
|
||||||
: item_surface_(Resource::get()->getSurface("items.gif")),
|
: item_surface_(Resource::get()->getSurface("items.gif")),
|
||||||
data_(data) {
|
data_(std::move(std::move(data))) {
|
||||||
const float SURFACE_WIDTH = Options::game.width;
|
const float SURFACE_WIDTH = Options::game.width;
|
||||||
constexpr float SURFACE_HEIGHT = 6.0F * BLOCK;
|
constexpr float SURFACE_HEIGHT = 6.0F * BLOCK;
|
||||||
|
|
||||||
@@ -25,7 +27,7 @@ Scoreboard::Scoreboard(std::shared_ptr<ScoreboardData> data)
|
|||||||
player_sprite_->setCurrentAnimation("walk_menu");
|
player_sprite_->setCurrentAnimation("walk_menu");
|
||||||
|
|
||||||
surface_ = std::make_shared<Surface>(SURFACE_WIDTH, SURFACE_HEIGHT);
|
surface_ = std::make_shared<Surface>(SURFACE_WIDTH, SURFACE_HEIGHT);
|
||||||
surface_dest_ = {0, Options::game.height - SURFACE_HEIGHT, SURFACE_WIDTH, SURFACE_HEIGHT};
|
surface_dest_ = {.x = 0, .y = Options::game.height - SURFACE_HEIGHT, .w = SURFACE_WIDTH, .h = SURFACE_HEIGHT};
|
||||||
|
|
||||||
// Inicializa las variables
|
// Inicializa las variables
|
||||||
counter_ = 0;
|
counter_ = 0;
|
||||||
@@ -65,7 +67,7 @@ void Scoreboard::update() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Obtiene el tiempo transcurrido de partida
|
// Obtiene el tiempo transcurrido de partida
|
||||||
Scoreboard::ClockData Scoreboard::getTime() {
|
auto Scoreboard::getTime() -> Scoreboard::ClockData {
|
||||||
const Uint32 TIME_ELAPSED = SDL_GetTicks() - data_->ini_clock - paused_time_elapsed_;
|
const Uint32 TIME_ELAPSED = SDL_GetTicks() - data_->ini_clock - paused_time_elapsed_;
|
||||||
|
|
||||||
ClockData time;
|
ClockData time;
|
||||||
@@ -109,7 +111,7 @@ void Scoreboard::updateItemsColor() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Devuelve la cantidad de minutos de juego transcurridos
|
// Devuelve la cantidad de minutos de juego transcurridos
|
||||||
int Scoreboard::getMinutes() {
|
auto Scoreboard::getMinutes() -> int {
|
||||||
return getTime().minutes;
|
return getTime().minutes;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -4,6 +4,7 @@
|
|||||||
|
|
||||||
#include <memory> // Para shared_ptr
|
#include <memory> // Para shared_ptr
|
||||||
#include <string> // Para string, basic_string
|
#include <string> // Para string, basic_string
|
||||||
|
#include <utility>
|
||||||
#include <vector> // Para vector
|
#include <vector> // Para vector
|
||||||
class SurfaceAnimatedSprite; // lines 10-10
|
class SurfaceAnimatedSprite; // lines 10-10
|
||||||
class Surface; // lines 11-11
|
class Surface; // lines 11-11
|
||||||
@@ -54,11 +55,11 @@ class Scoreboard {
|
|||||||
separator(":") {}
|
separator(":") {}
|
||||||
|
|
||||||
// Constructor parametrizado
|
// Constructor parametrizado
|
||||||
ClockData(int h, int m, int s, const std::string& sep)
|
ClockData(int h, int m, int s, std::string sep)
|
||||||
: hours(h),
|
: hours(h),
|
||||||
minutes(m),
|
minutes(m),
|
||||||
seconds(s),
|
seconds(s),
|
||||||
separator(sep) {}
|
separator(std::move(sep)) {}
|
||||||
};
|
};
|
||||||
|
|
||||||
// Objetos y punteros
|
// Objetos y punteros
|
||||||
@@ -79,7 +80,7 @@ class Scoreboard {
|
|||||||
SDL_FRect surface_dest_; // Rectangulo donde dibujar la surface del marcador
|
SDL_FRect surface_dest_; // Rectangulo donde dibujar la surface del marcador
|
||||||
|
|
||||||
// Obtiene el tiempo transcurrido de partida
|
// Obtiene el tiempo transcurrido de partida
|
||||||
ClockData getTime();
|
auto getTime() -> ClockData;
|
||||||
|
|
||||||
// Actualiza el color de la cantidad de items recogidos
|
// Actualiza el color de la cantidad de items recogidos
|
||||||
void updateItemsColor();
|
void updateItemsColor();
|
||||||
@@ -104,5 +105,5 @@ class Scoreboard {
|
|||||||
void setPaused(bool value);
|
void setPaused(bool value);
|
||||||
|
|
||||||
// Devuelve la cantidad de minutos de juego transcurridos
|
// Devuelve la cantidad de minutos de juego transcurridos
|
||||||
int getMinutes();
|
auto getMinutes() -> int;
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -2,13 +2,14 @@
|
|||||||
|
|
||||||
#include <fstream> // Para basic_ostream, basic_ifstream, basic_istream
|
#include <fstream> // Para basic_ostream, basic_ifstream, basic_istream
|
||||||
#include <sstream> // Para basic_stringstream
|
#include <sstream> // Para basic_stringstream
|
||||||
|
#include <utility>
|
||||||
|
|
||||||
#include "game/options.hpp" // Para Options, OptionsStats, options
|
#include "game/options.hpp" // Para Options, OptionsStats, options
|
||||||
|
|
||||||
// Constructor
|
// Constructor
|
||||||
Stats::Stats(const std::string& file, const std::string& buffer)
|
Stats::Stats(std::string file, std::string buffer)
|
||||||
: buffer_path_(buffer),
|
: buffer_path_(std::move(buffer)),
|
||||||
file_path_(file) {}
|
file_path_(std::move(file)) {}
|
||||||
|
|
||||||
// Destructor
|
// Destructor
|
||||||
Stats::~Stats() {
|
Stats::~Stats() {
|
||||||
@@ -75,7 +76,7 @@ void Stats::addVisit(const std::string& name) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Busca una entrada en la lista por nombre
|
// Busca una entrada en la lista por nombre
|
||||||
int Stats::findByName(const std::string& name, const std::vector<StatsData>& list) {
|
auto Stats::findByName(const std::string& name, const std::vector<StatsData>& list) -> int {
|
||||||
int i = 0;
|
int i = 0;
|
||||||
|
|
||||||
for (const auto& l : list) {
|
for (const auto& l : list) {
|
||||||
@@ -89,7 +90,7 @@ int Stats::findByName(const std::string& name, const std::vector<StatsData>& lis
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Carga las estadisticas desde un fichero
|
// Carga las estadisticas desde un fichero
|
||||||
bool Stats::loadFromFile(const std::string& file_path, std::vector<StatsData>& list) {
|
auto Stats::loadFromFile(const std::string& file_path, std::vector<StatsData>& list) -> bool {
|
||||||
list.clear();
|
list.clear();
|
||||||
|
|
||||||
// Indicador de éxito en la carga
|
// Indicador de éxito en la carga
|
||||||
@@ -144,9 +145,9 @@ void Stats::saveToFile(const std::string& file_path, const std::vector<StatsData
|
|||||||
std::ofstream file(file_path);
|
std::ofstream file(file_path);
|
||||||
|
|
||||||
// Escribe en el fichero
|
// Escribe en el fichero
|
||||||
file << "# ROOM NAME;VISITS;DEATHS" << std::endl;
|
file << "# ROOM NAME;VISITS;DEATHS" << '\n';
|
||||||
for (const auto& item : list) {
|
for (const auto& item : list) {
|
||||||
file << item.name << ";" << item.visited << ";" << item.died << std::endl;
|
file << item.name << ";" << item.visited << ";" << item.died << '\n';
|
||||||
}
|
}
|
||||||
|
|
||||||
// Cierra el fichero
|
// Cierra el fichero
|
||||||
|
|||||||
@@ -24,10 +24,10 @@ class Stats {
|
|||||||
std::string file_path_; // Fichero con las estadísticas completas
|
std::string file_path_; // Fichero con las estadísticas completas
|
||||||
|
|
||||||
// Busca una entrada en la lista por nombre
|
// Busca una entrada en la lista por nombre
|
||||||
static int findByName(const std::string& name, const std::vector<StatsData>& list);
|
static auto findByName(const std::string& name, const std::vector<StatsData>& list) -> int;
|
||||||
|
|
||||||
// Carga las estadisticas desde un fichero
|
// Carga las estadisticas desde un fichero
|
||||||
static bool loadFromFile(const std::string& file_path, std::vector<StatsData>& list);
|
static auto loadFromFile(const std::string& file_path, std::vector<StatsData>& list) -> bool;
|
||||||
|
|
||||||
// Guarda las estadisticas en un fichero
|
// Guarda las estadisticas en un fichero
|
||||||
static void saveToFile(const std::string& file_path, const std::vector<StatsData>& list);
|
static void saveToFile(const std::string& file_path, const std::vector<StatsData>& list);
|
||||||
@@ -39,8 +39,8 @@ class Stats {
|
|||||||
void updateListFromBuffer();
|
void updateListFromBuffer();
|
||||||
|
|
||||||
public:
|
public:
|
||||||
// Constructor
|
// Constructostd::string nst stdstd::string nst std::string& buffer);
|
||||||
Stats(const std::string& file, const std::string& buffer);
|
Stats(std::string file, std::string buffer);
|
||||||
|
|
||||||
// Destructor
|
// Destructor
|
||||||
~Stats();
|
~Stats();
|
||||||
|
|||||||
@@ -7,6 +7,7 @@
|
|||||||
#include <fstream> // Para basic_ostream, operator<<, basic_ofstream
|
#include <fstream> // Para basic_ostream, operator<<, basic_ofstream
|
||||||
#include <functional> // Para function
|
#include <functional> // Para function
|
||||||
#include <iostream> // Para cout, cerr
|
#include <iostream> // Para cout, cerr
|
||||||
|
#include <ranges>
|
||||||
#include <sstream> // Para basic_istringstream
|
#include <sstream> // Para basic_istringstream
|
||||||
#include <string> // Para char_traits, string, operator<<, hash
|
#include <string> // Para char_traits, string, operator<<, hash
|
||||||
#include <unordered_map> // Para unordered_map, operator==, _Node_const_i...
|
#include <unordered_map> // Para unordered_map, operator==, _Node_const_i...
|
||||||
@@ -16,11 +17,11 @@
|
|||||||
|
|
||||||
namespace Options {
|
namespace Options {
|
||||||
// Declaración de funciones internas
|
// Declaración de funciones internas
|
||||||
bool setOptions(const std::string& var, const std::string& value);
|
auto setOptions(const std::string& var, const std::string& value) -> bool;
|
||||||
std::string trimLine(const std::string& line);
|
auto trimLine(const std::string& line) -> std::string;
|
||||||
bool isCommentOrEmpty(const std::string& line);
|
auto isCommentOrEmpty(const std::string& line) -> bool;
|
||||||
bool processConfigLine(const std::string& line);
|
auto processConfigLine(const std::string& line) -> bool;
|
||||||
bool readConfigFile(const std::string& file_path);
|
auto readConfigFile(const std::string& file_path) -> bool;
|
||||||
|
|
||||||
// Crea e inicializa las opciones del programa
|
// Crea e inicializa las opciones del programa
|
||||||
void init() {
|
void init() {
|
||||||
@@ -32,19 +33,19 @@ void init() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Elimina espacios en blanco al inicio y final de una línea
|
// Elimina espacios en blanco al inicio y final de una línea
|
||||||
std::string trimLine(const std::string& line) {
|
auto trimLine(const std::string& line) -> std::string {
|
||||||
auto start = std::find_if(line.begin(), line.end(), [](int ch) { return !std::isspace(ch); });
|
auto start = std::ranges::find_if(line, [](int ch) { return !std::isspace(ch); });
|
||||||
auto end = std::find_if(line.rbegin(), line.rend(), [](int ch) { return !std::isspace(ch); }).base();
|
auto end = std::ranges::find_if(std::ranges::reverse_view(line), [](int ch) { return !std::isspace(ch); }).base();
|
||||||
return std::string(start, end);
|
return {start, end};
|
||||||
}
|
}
|
||||||
|
|
||||||
// Verifica si una línea es comentario o está vacía
|
// Verifica si una línea es comentario o está vacía
|
||||||
bool isCommentOrEmpty(const std::string& line) {
|
auto isCommentOrEmpty(const std::string& line) -> bool {
|
||||||
return line.empty() || line[0] == '#';
|
return line.empty() || line[0] == '#';
|
||||||
}
|
}
|
||||||
|
|
||||||
// Procesa una línea de configuración individual
|
// Procesa una línea de configuración individual
|
||||||
bool processConfigLine(const std::string& line) {
|
auto processConfigLine(const std::string& line) -> bool {
|
||||||
std::istringstream iss(line);
|
std::istringstream iss(line);
|
||||||
std::string key;
|
std::string key;
|
||||||
std::string value;
|
std::string value;
|
||||||
@@ -53,7 +54,7 @@ bool processConfigLine(const std::string& line) {
|
|||||||
if (!setOptions(key, value)) {
|
if (!setOptions(key, value)) {
|
||||||
if (console) {
|
if (console) {
|
||||||
std::cout << "Warning: file config.txt\n";
|
std::cout << "Warning: file config.txt\n";
|
||||||
std::cout << "unknown parameter " << key << std::endl;
|
std::cout << "unknown parameter " << key << '\n';
|
||||||
}
|
}
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
@@ -62,7 +63,7 @@ bool processConfigLine(const std::string& line) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Lee y procesa el fichero de configuración
|
// Lee y procesa el fichero de configuración
|
||||||
bool readConfigFile(const std::string& file_path) {
|
auto readConfigFile(const std::string& file_path) -> bool {
|
||||||
std::ifstream file(file_path);
|
std::ifstream file(file_path);
|
||||||
if (!file.good()) {
|
if (!file.good()) {
|
||||||
return false;
|
return false;
|
||||||
@@ -95,7 +96,7 @@ bool readConfigFile(const std::string& file_path) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Carga las opciones desde un fichero
|
// Carga las opciones desde un fichero
|
||||||
bool loadFromFile(const std::string& file_path) {
|
auto loadFromFile(const std::string& file_path) -> bool {
|
||||||
// Versión actual del fichero
|
// Versión actual del fichero
|
||||||
const std::string CONFIG_VERSION = version;
|
const std::string CONFIG_VERSION = version;
|
||||||
version = "";
|
version = "";
|
||||||
@@ -122,7 +123,7 @@ bool loadFromFile(const std::string& file_path) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Guarda las opciones en un fichero
|
// Guarda las opciones en un fichero
|
||||||
bool saveToFile(const std::string& file_path) {
|
auto saveToFile(const std::string& file_path) -> bool {
|
||||||
// Crea y abre el fichero de texto
|
// Crea y abre el fichero de texto
|
||||||
std::ofstream file(file_path);
|
std::ofstream file(file_path);
|
||||||
bool success = file.is_open(); // Verifica si el archivo se abrió correctamente
|
bool success = file.is_open(); // Verifica si el archivo se abrió correctamente
|
||||||
@@ -130,13 +131,13 @@ bool saveToFile(const std::string& file_path) {
|
|||||||
if (!success) // Si no se pudo abrir el archivo, muestra un mensaje de error y devuelve false
|
if (!success) // Si no se pudo abrir el archivo, muestra un mensaje de error y devuelve false
|
||||||
{
|
{
|
||||||
if (console) {
|
if (console) {
|
||||||
std::cerr << "Error: Unable to open file " << file_path << " for writing." << std::endl;
|
std::cerr << "Error: Unable to open file " << file_path << " for writing." << '\n';
|
||||||
}
|
}
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (console) {
|
if (console) {
|
||||||
std::cout << file_path << " open for writing" << std::endl;
|
std::cout << file_path << " open for writing" << '\n';
|
||||||
}
|
}
|
||||||
|
|
||||||
// Escribe en el fichero
|
// Escribe en el fichero
|
||||||
@@ -179,7 +180,7 @@ bool saveToFile(const std::string& file_path) {
|
|||||||
return success;
|
return success;
|
||||||
}
|
}
|
||||||
|
|
||||||
bool setOptions(const std::string& var, const std::string& value) {
|
auto setOptions(const std::string& var, const std::string& value) -> bool {
|
||||||
static const std::unordered_map<std::string, std::function<void(const std::string&)>> OPTION_HANDLERS = {
|
static const std::unordered_map<std::string, std::function<void(const std::string&)>> OPTION_HANDLERS = {
|
||||||
{"version", [](const std::string& v) { version = v; }},
|
{"version", [](const std::string& v) { version = v; }},
|
||||||
{"keys", [](const std::string& v) {
|
{"keys", [](const std::string& v) {
|
||||||
|
|||||||
@@ -4,6 +4,7 @@
|
|||||||
|
|
||||||
#include <algorithm>
|
#include <algorithm>
|
||||||
#include <string> // Para string, basic_string
|
#include <string> // Para string, basic_string
|
||||||
|
#include <utility>
|
||||||
|
|
||||||
#include "core/rendering/screen.hpp" // Para ScreenFilter
|
#include "core/rendering/screen.hpp" // Para ScreenFilter
|
||||||
#include "utils/utils.hpp" // Para Color, Palette
|
#include "utils/utils.hpp" // Para Color, Palette
|
||||||
@@ -15,7 +16,7 @@ namespace Options {
|
|||||||
// VOLUME HELPERS - Conversión de volumen 0-100 a 0-128
|
// VOLUME HELPERS - Conversión de volumen 0-100 a 0-128
|
||||||
// =============================================================================
|
// =============================================================================
|
||||||
namespace VolumeHelpers {
|
namespace VolumeHelpers {
|
||||||
constexpr int convertVolume(int volume_percent) {
|
constexpr auto convertVolume(int volume_percent) -> int {
|
||||||
return (volume_percent * 128) / 100;
|
return (volume_percent * 128) / 100;
|
||||||
}
|
}
|
||||||
} // namespace VolumeHelpers
|
} // namespace VolumeHelpers
|
||||||
@@ -77,7 +78,7 @@ struct Cheat {
|
|||||||
alternate_skin(alt_skin) {}
|
alternate_skin(alt_skin) {}
|
||||||
|
|
||||||
// Método para comprobar si alguno de los tres primeros trucos está activo
|
// Método para comprobar si alguno de los tres primeros trucos está activo
|
||||||
bool enabled() const {
|
[[nodiscard]] auto enabled() const -> bool {
|
||||||
return infinite_lives == State::ENABLED ||
|
return infinite_lives == State::ENABLED ||
|
||||||
invincible == State::ENABLED ||
|
invincible == State::ENABLED ||
|
||||||
jail_is_open == State::ENABLED;
|
jail_is_open == State::ENABLED;
|
||||||
@@ -96,10 +97,10 @@ struct Stats {
|
|||||||
items(0) {}
|
items(0) {}
|
||||||
|
|
||||||
// Constructor
|
// Constructor
|
||||||
Stats(int room_count, int item_count, const std::string& worst_nightmare_room)
|
Stats(int room_count, int item_count, std::string worst_nightmare_room)
|
||||||
: rooms(room_count),
|
: rooms(room_count),
|
||||||
items(item_count),
|
items(item_count),
|
||||||
worst_nightmare(worst_nightmare_room) {}
|
worst_nightmare(std::move(worst_nightmare_room)) {}
|
||||||
};
|
};
|
||||||
|
|
||||||
// Estructura con opciones de la ventana
|
// Estructura con opciones de la ventana
|
||||||
@@ -164,7 +165,7 @@ struct Video {
|
|||||||
palette(GameDefaults::PALETTE_NAME) {}
|
palette(GameDefaults::PALETTE_NAME) {}
|
||||||
|
|
||||||
// Constructor
|
// Constructor
|
||||||
Video(bool is_fullscreen, ScreenFilter screen_filter, bool vsync, bool use_shaders, bool int_scale, bool keep_aspect_ratio, Border video_border, const std::string& palette_name)
|
Video(bool is_fullscreen, ScreenFilter screen_filter, bool vsync, bool use_shaders, bool int_scale, bool keep_aspect_ratio, Border video_border, std::string palette_name)
|
||||||
: fullscreen(is_fullscreen),
|
: fullscreen(is_fullscreen),
|
||||||
filter(screen_filter),
|
filter(screen_filter),
|
||||||
vertical_sync(vsync),
|
vertical_sync(vsync),
|
||||||
@@ -172,7 +173,7 @@ struct Video {
|
|||||||
integer_scale(int_scale),
|
integer_scale(int_scale),
|
||||||
keep_aspect(keep_aspect_ratio),
|
keep_aspect(keep_aspect_ratio),
|
||||||
border(video_border),
|
border(video_border),
|
||||||
palette(palette_name) {}
|
palette(std::move(palette_name)) {}
|
||||||
};
|
};
|
||||||
|
|
||||||
// Estructura para las opciones de musica
|
// Estructura para las opciones de musica
|
||||||
@@ -269,7 +270,7 @@ inline ControlScheme keys{GameDefaults::CONTROL_SCHEME}; // Teclas usadas para
|
|||||||
|
|
||||||
// --- Funciones ---
|
// --- Funciones ---
|
||||||
void init(); // Crea e inicializa las opciones del programa
|
void init(); // Crea e inicializa las opciones del programa
|
||||||
bool loadFromFile(const std::string& file_path); // Carga las opciones desde un fichero
|
auto loadFromFile(const std::string& file_path) -> bool; // Carga las opciones desde un fichero
|
||||||
bool saveToFile(const std::string& file_path); // Guarda las opciones a un fichero
|
auto saveToFile(const std::string& file_path) -> bool; // Guarda las opciones a un fichero
|
||||||
|
|
||||||
} // namespace Options
|
} // namespace Options
|
||||||
@@ -439,7 +439,7 @@ void Ending::fillCoverTexture() {
|
|||||||
cover_surface_->clear(static_cast<Uint8>(PaletteColor::TRANSPARENT));
|
cover_surface_->clear(static_cast<Uint8>(PaletteColor::TRANSPARENT));
|
||||||
|
|
||||||
// Los primeros 8 pixels crea una malla
|
// Los primeros 8 pixels crea una malla
|
||||||
const Uint8 COLOR = static_cast<Uint8>(PaletteColor::BLACK);
|
const auto COLOR = static_cast<Uint8>(PaletteColor::BLACK);
|
||||||
auto surface = Screen::get()->getRendererSurface();
|
auto surface = Screen::get()->getRendererSurface();
|
||||||
for (int i = 0; i < 256; i += 2) {
|
for (int i = 0; i < 256; i += 2) {
|
||||||
surface->putPixel(i + 0, Options::game.height + 0, COLOR);
|
surface->putPixel(i + 0, Options::game.height + 0, COLOR);
|
||||||
|
|||||||
@@ -106,7 +106,7 @@ void Ending2::render() {
|
|||||||
renderTexts();
|
renderTexts();
|
||||||
|
|
||||||
// Dibuja una trama arriba y abajo
|
// Dibuja una trama arriba y abajo
|
||||||
Uint8 color = static_cast<Uint8>(PaletteColor::BLACK);
|
auto color = static_cast<Uint8>(PaletteColor::BLACK);
|
||||||
auto surface = Screen::get()->getRendererSurface();
|
auto surface = Screen::get()->getRendererSurface();
|
||||||
for (int i = 0; i < 256; i += 2) {
|
for (int i = 0; i < 256; i += 2) {
|
||||||
surface->putPixel(i + 0, 0, color);
|
surface->putPixel(i + 0, 0, color);
|
||||||
@@ -196,75 +196,75 @@ void Ending2::iniSpriteList() {
|
|||||||
sprite_list_.clear();
|
sprite_list_.clear();
|
||||||
|
|
||||||
// Añade los valores
|
// Añade los valores
|
||||||
sprite_list_.push_back("bin");
|
sprite_list_.emplace_back("bin");
|
||||||
sprite_list_.push_back("floppy");
|
sprite_list_.emplace_back("floppy");
|
||||||
sprite_list_.push_back("bird");
|
sprite_list_.emplace_back("bird");
|
||||||
sprite_list_.push_back("chip");
|
sprite_list_.emplace_back("chip");
|
||||||
sprite_list_.push_back("jeannine");
|
sprite_list_.emplace_back("jeannine");
|
||||||
sprite_list_.push_back("spark");
|
sprite_list_.emplace_back("spark");
|
||||||
sprite_list_.push_back("code");
|
sprite_list_.emplace_back("code");
|
||||||
sprite_list_.push_back("paco");
|
sprite_list_.emplace_back("paco");
|
||||||
sprite_list_.push_back("elsa");
|
sprite_list_.emplace_back("elsa");
|
||||||
sprite_list_.push_back("z80");
|
sprite_list_.emplace_back("z80");
|
||||||
|
|
||||||
sprite_list_.push_back("bell");
|
sprite_list_.emplace_back("bell");
|
||||||
sprite_list_.push_back("dong");
|
sprite_list_.emplace_back("dong");
|
||||||
|
|
||||||
sprite_list_.push_back("amstrad_cs");
|
sprite_list_.emplace_back("amstrad_cs");
|
||||||
sprite_list_.push_back("breakout");
|
sprite_list_.emplace_back("breakout");
|
||||||
|
|
||||||
sprite_list_.push_back("flying_arounder");
|
sprite_list_.emplace_back("flying_arounder");
|
||||||
sprite_list_.push_back("stopped_arounder");
|
sprite_list_.emplace_back("stopped_arounder");
|
||||||
sprite_list_.push_back("walking_arounder");
|
sprite_list_.emplace_back("walking_arounder");
|
||||||
sprite_list_.push_back("arounders_door");
|
sprite_list_.emplace_back("arounders_door");
|
||||||
sprite_list_.push_back("arounders_machine");
|
sprite_list_.emplace_back("arounders_machine");
|
||||||
|
|
||||||
sprite_list_.push_back("abad");
|
sprite_list_.emplace_back("abad");
|
||||||
sprite_list_.push_back("abad_bell");
|
sprite_list_.emplace_back("abad_bell");
|
||||||
sprite_list_.push_back("lord_abad");
|
sprite_list_.emplace_back("lord_abad");
|
||||||
|
|
||||||
sprite_list_.push_back("bat");
|
sprite_list_.emplace_back("bat");
|
||||||
sprite_list_.push_back("batman_bell");
|
sprite_list_.emplace_back("batman_bell");
|
||||||
sprite_list_.push_back("batman_fire");
|
sprite_list_.emplace_back("batman_fire");
|
||||||
sprite_list_.push_back("batman");
|
sprite_list_.emplace_back("batman");
|
||||||
|
|
||||||
sprite_list_.push_back("demon");
|
sprite_list_.emplace_back("demon");
|
||||||
sprite_list_.push_back("heavy");
|
sprite_list_.emplace_back("heavy");
|
||||||
sprite_list_.push_back("dimallas");
|
sprite_list_.emplace_back("dimallas");
|
||||||
sprite_list_.push_back("guitar");
|
sprite_list_.emplace_back("guitar");
|
||||||
|
|
||||||
sprite_list_.push_back("jailbattle_alien");
|
sprite_list_.emplace_back("jailbattle_alien");
|
||||||
sprite_list_.push_back("jailbattle_human");
|
sprite_list_.emplace_back("jailbattle_human");
|
||||||
|
|
||||||
sprite_list_.push_back("jailer_#1");
|
sprite_list_.emplace_back("jailer_#1");
|
||||||
sprite_list_.push_back("jailer_#2");
|
sprite_list_.emplace_back("jailer_#2");
|
||||||
sprite_list_.push_back("jailer_#3");
|
sprite_list_.emplace_back("jailer_#3");
|
||||||
sprite_list_.push_back("bry");
|
sprite_list_.emplace_back("bry");
|
||||||
sprite_list_.push_back("upv_student");
|
sprite_list_.emplace_back("upv_student");
|
||||||
|
|
||||||
sprite_list_.push_back("lamp");
|
sprite_list_.emplace_back("lamp");
|
||||||
sprite_list_.push_back("robot");
|
sprite_list_.emplace_back("robot");
|
||||||
sprite_list_.push_back("congo");
|
sprite_list_.emplace_back("congo");
|
||||||
sprite_list_.push_back("crosshair");
|
sprite_list_.emplace_back("crosshair");
|
||||||
sprite_list_.push_back("tree_thing");
|
sprite_list_.emplace_back("tree_thing");
|
||||||
|
|
||||||
sprite_list_.push_back("matatunos");
|
sprite_list_.emplace_back("matatunos");
|
||||||
sprite_list_.push_back("tuno");
|
sprite_list_.emplace_back("tuno");
|
||||||
|
|
||||||
sprite_list_.push_back("mummy");
|
sprite_list_.emplace_back("mummy");
|
||||||
sprite_list_.push_back("sam");
|
sprite_list_.emplace_back("sam");
|
||||||
|
|
||||||
sprite_list_.push_back("qvoid");
|
sprite_list_.emplace_back("qvoid");
|
||||||
sprite_list_.push_back("sigmasua");
|
sprite_list_.emplace_back("sigmasua");
|
||||||
|
|
||||||
sprite_list_.push_back("tv_panel");
|
sprite_list_.emplace_back("tv_panel");
|
||||||
sprite_list_.push_back("tv");
|
sprite_list_.emplace_back("tv");
|
||||||
|
|
||||||
sprite_list_.push_back("spider");
|
sprite_list_.emplace_back("spider");
|
||||||
sprite_list_.push_back("shock");
|
sprite_list_.emplace_back("shock");
|
||||||
sprite_list_.push_back("wave");
|
sprite_list_.emplace_back("wave");
|
||||||
|
|
||||||
sprite_list_.push_back("player");
|
sprite_list_.emplace_back("player");
|
||||||
}
|
}
|
||||||
|
|
||||||
// Carga todos los sprites desde una lista
|
// Carga todos los sprites desde una lista
|
||||||
@@ -283,29 +283,29 @@ void Ending2::loadSprites() {
|
|||||||
|
|
||||||
// Actualiza los sprites
|
// Actualiza los sprites
|
||||||
void Ending2::updateSprites() {
|
void Ending2::updateSprites() {
|
||||||
for (auto sprite : sprites_) {
|
for (const auto& sprite : sprites_) {
|
||||||
sprite->update();
|
sprite->update();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Actualiza los sprites de texto
|
// Actualiza los sprites de texto
|
||||||
void Ending2::updateTextSprites() {
|
void Ending2::updateTextSprites() {
|
||||||
for (auto sprite : sprite_texts_) {
|
for (const auto& sprite : sprite_texts_) {
|
||||||
sprite->update();
|
sprite->update();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Actualiza los sprites de texto del final
|
// Actualiza los sprites de texto del final
|
||||||
void Ending2::updateTexts() {
|
void Ending2::updateTexts() {
|
||||||
for (auto sprite : texts_) {
|
for (const auto& sprite : texts_) {
|
||||||
sprite->update();
|
sprite->update();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Dibuja los sprites
|
// Dibuja los sprites
|
||||||
void Ending2::renderSprites() {
|
void Ending2::renderSprites() {
|
||||||
const Uint8 COLOR_A = static_cast<Uint8>(PaletteColor::RED);
|
const auto COLOR_A = static_cast<Uint8>(PaletteColor::RED);
|
||||||
for (auto sprite : sprites_) {
|
for (const auto& sprite : sprites_) {
|
||||||
const bool A = sprite->getRect().y + sprite->getRect().h > 0;
|
const bool A = sprite->getRect().y + sprite->getRect().h > 0;
|
||||||
const bool B = sprite->getRect().y < Options::game.height;
|
const bool B = sprite->getRect().y < Options::game.height;
|
||||||
if (A && B) {
|
if (A && B) {
|
||||||
@@ -314,14 +314,14 @@ void Ending2::renderSprites() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Pinta el ultimo elemento de otro color
|
// Pinta el ultimo elemento de otro color
|
||||||
const Uint8 COLOR_B = static_cast<Uint8>(PaletteColor::WHITE);
|
const auto COLOR_B = static_cast<Uint8>(PaletteColor::WHITE);
|
||||||
sprites_.back()->render(1, COLOR_B);
|
sprites_.back()->render(1, COLOR_B);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Dibuja los sprites con el texto
|
// Dibuja los sprites con el texto
|
||||||
void Ending2::renderSpriteTexts() {
|
void Ending2::renderSpriteTexts() {
|
||||||
const Uint8 COLOR = static_cast<Uint8>(PaletteColor::WHITE);
|
const auto COLOR = static_cast<Uint8>(PaletteColor::WHITE);
|
||||||
for (auto sprite : sprite_texts_) {
|
for (const auto& sprite : sprite_texts_) {
|
||||||
const bool A = sprite->getRect().y + sprite->getRect().h > 0;
|
const bool A = sprite->getRect().y + sprite->getRect().h > 0;
|
||||||
const bool B = sprite->getRect().y < Options::game.height;
|
const bool B = sprite->getRect().y < Options::game.height;
|
||||||
if (A && B) {
|
if (A && B) {
|
||||||
@@ -332,7 +332,7 @@ void Ending2::renderSpriteTexts() {
|
|||||||
|
|
||||||
// Dibuja los sprites con el texto del final
|
// Dibuja los sprites con el texto del final
|
||||||
void Ending2::renderTexts() {
|
void Ending2::renderTexts() {
|
||||||
for (auto sprite : texts_) {
|
for (const auto& sprite : texts_) {
|
||||||
const bool A = sprite->getRect().y + sprite->getRect().h > 0;
|
const bool A = sprite->getRect().y + sprite->getRect().h > 0;
|
||||||
const bool B = sprite->getRect().y < Options::game.height;
|
const bool B = sprite->getRect().y < Options::game.height;
|
||||||
if (A && B) {
|
if (A && B) {
|
||||||
@@ -370,7 +370,7 @@ void Ending2::createSpriteTexts() {
|
|||||||
|
|
||||||
// Procesa y ajusta el texto del sprite actual
|
// Procesa y ajusta el texto del sprite actual
|
||||||
std::string txt = sprite_list_[i];
|
std::string txt = sprite_list_[i];
|
||||||
std::replace(txt.begin(), txt.end(), '_', ' '); // Reemplaza '_' por ' '
|
std::ranges::replace(txt, '_', ' '); // Reemplaza '_' por ' '
|
||||||
if (txt == "player") {
|
if (txt == "player") {
|
||||||
txt = "JAILDOCTOR"; // Reemplaza "player" por "JAILDOCTOR"
|
txt = "JAILDOCTOR"; // Reemplaza "player" por "JAILDOCTOR"
|
||||||
}
|
}
|
||||||
@@ -405,7 +405,7 @@ void Ending2::createSpriteTexts() {
|
|||||||
void Ending2::createTexts() {
|
void Ending2::createTexts() {
|
||||||
// Crea los primeros textos
|
// Crea los primeros textos
|
||||||
std::vector<std::string> list;
|
std::vector<std::string> list;
|
||||||
list.push_back("STARRING");
|
list.emplace_back("STARRING");
|
||||||
|
|
||||||
auto text = Resource::get()->getText("smb2");
|
auto text = Resource::get()->getText("smb2");
|
||||||
|
|
||||||
@@ -435,8 +435,8 @@ void Ending2::createTexts() {
|
|||||||
// El primer texto va a continuación del ultimo spriteText
|
// El primer texto va a continuación del ultimo spriteText
|
||||||
const int START = sprite_texts_.back()->getPosY() + (text->getCharacterSize() * 15);
|
const int START = sprite_texts_.back()->getPosY() + (text->getCharacterSize() * 15);
|
||||||
list.clear();
|
list.clear();
|
||||||
list.push_back("THANK YOU");
|
list.emplace_back("THANK YOU");
|
||||||
list.push_back("FOR PLAYING!");
|
list.emplace_back("FOR PLAYING!");
|
||||||
|
|
||||||
// Crea los sprites de texto a partir de la lista
|
// Crea los sprites de texto a partir de la lista
|
||||||
for (size_t i = 0; i < list.size(); ++i) {
|
for (size_t i = 0; i < list.size(); ++i) {
|
||||||
@@ -463,7 +463,7 @@ void Ending2::createTexts() {
|
|||||||
|
|
||||||
// Actualiza el fade final
|
// Actualiza el fade final
|
||||||
void Ending2::updateFinalFade() {
|
void Ending2::updateFinalFade() {
|
||||||
for (auto sprite : texts_) {
|
for (const auto& sprite : texts_) {
|
||||||
sprite->getSurface()->fadeSubPalette(0);
|
sprite->getSurface()->fadeSubPalette(0);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -33,7 +33,7 @@ class Ending2 {
|
|||||||
duration(state_duration) {}
|
duration(state_duration) {}
|
||||||
|
|
||||||
// Método para comprobar si el estado ha terminado y verifica el nombre del estado
|
// Método para comprobar si el estado ha terminado y verifica el nombre del estado
|
||||||
bool hasEnded(EndingState expected_state) const {
|
[[nodiscard]] auto hasEnded(EndingState expected_state) const -> bool {
|
||||||
// Comprobar si el estado actual coincide con el estado esperado
|
// Comprobar si el estado actual coincide con el estado esperado
|
||||||
if (state != expected_state) {
|
if (state != expected_state) {
|
||||||
return false; // Si no coincide, considerar que no ha terminado
|
return false; // Si no coincide, considerar que no ha terminado
|
||||||
|
|||||||
@@ -2,6 +2,7 @@
|
|||||||
|
|
||||||
#include <SDL3/SDL.h>
|
#include <SDL3/SDL.h>
|
||||||
|
|
||||||
|
#include <utility>
|
||||||
#include <vector> // Para vector
|
#include <vector> // Para vector
|
||||||
|
|
||||||
#include "core/input/global_inputs.hpp" // Para check
|
#include "core/input/global_inputs.hpp" // Para check
|
||||||
@@ -263,7 +264,7 @@ void Game::renderRoomName() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Cambia de habitación
|
// Cambia de habitación
|
||||||
bool Game::changeRoom(const std::string& room_path) {
|
auto Game::changeRoom(const std::string& room_path) -> bool {
|
||||||
// En las habitaciones los limites tienen la cadena del fichero o un 0 en caso de no limitar con nada
|
// En las habitaciones los limites tienen la cadena del fichero o un 0 en caso de no limitar con nada
|
||||||
if (room_path == "0") {
|
if (room_path == "0") {
|
||||||
return false;
|
return false;
|
||||||
@@ -313,7 +314,7 @@ void Game::checkPlayerIsOnBorder() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Comprueba las colisiones del jugador con los enemigos
|
// Comprueba las colisiones del jugador con los enemigos
|
||||||
bool Game::checkPlayerAndEnemies() {
|
auto Game::checkPlayerAndEnemies() -> bool {
|
||||||
const bool DEATH = room_->enemyCollision(player_->getCollider());
|
const bool DEATH = room_->enemyCollision(player_->getCollider());
|
||||||
if (DEATH) {
|
if (DEATH) {
|
||||||
killPlayer();
|
killPlayer();
|
||||||
@@ -415,7 +416,7 @@ void Game::setScoreBoardColor() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Comprueba si ha finalizado el juego
|
// Comprueba si ha finalizado el juego
|
||||||
bool Game::checkEndGame() {
|
auto Game::checkEndGame() -> bool {
|
||||||
const bool IS_ON_THE_ROOM = room_->getName() == "THE JAIL"; // Estar en la habitación que toca
|
const bool IS_ON_THE_ROOM = room_->getName() == "THE JAIL"; // Estar en la habitación que toca
|
||||||
const bool 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 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)
|
const bool IS_ON_THE_DOOR = player_->getRect().x <= 128; // Y en la ubicación que toca (En la puerta)
|
||||||
@@ -436,7 +437,7 @@ bool Game::checkEndGame() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Obtiene la cantidad total de items que hay en el mapeado del juego
|
// Obtiene la cantidad total de items que hay en el mapeado del juego
|
||||||
int Game::getTotalItems() {
|
auto Game::getTotalItems() -> int {
|
||||||
int items = 0;
|
int items = 0;
|
||||||
auto rooms = Resource::get()->getRooms();
|
auto rooms = Resource::get()->getRooms();
|
||||||
|
|
||||||
@@ -572,7 +573,7 @@ void Game::checkEndGameCheevos() {
|
|||||||
void Game::initPlayer(const PlayerSpawn& spawn_point, std::shared_ptr<Room> room) {
|
void Game::initPlayer(const PlayerSpawn& spawn_point, std::shared_ptr<Room> room) {
|
||||||
std::string player_texture = Options::cheats.alternate_skin == Options::Cheat::State::ENABLED ? "player2.gif" : "player.gif";
|
std::string player_texture = Options::cheats.alternate_skin == Options::Cheat::State::ENABLED ? "player2.gif" : "player.gif";
|
||||||
std::string player_animations = Options::cheats.alternate_skin == Options::Cheat::State::ENABLED ? "player2.ani" : "player.ani";
|
std::string player_animations = Options::cheats.alternate_skin == Options::Cheat::State::ENABLED ? "player2.ani" : "player.ani";
|
||||||
const PlayerData PLAYER(spawn_point, player_texture, player_animations, room);
|
const PlayerData PLAYER(spawn_point, player_texture, player_animations, std::move(room));
|
||||||
player_ = std::make_shared<Player>(PLAYER);
|
player_ = std::make_shared<Player>(PLAYER);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -582,7 +583,7 @@ void Game::createRoomNameTexture() {
|
|||||||
room_name_surface_ = std::make_shared<Surface>(Options::game.width, text->getCharacterSize() * 2);
|
room_name_surface_ = std::make_shared<Surface>(Options::game.width, text->getCharacterSize() * 2);
|
||||||
|
|
||||||
// Establece el destino de la textura
|
// Establece el destino de la textura
|
||||||
room_name_rect_ = {0.0F, PLAY_AREA_HEIGHT, Options::game.width, text->getCharacterSize() * 2.0F};
|
room_name_rect_ = {.x = 0.0F, .y = PLAY_AREA_HEIGHT, .w = Options::game.width, .h = text->getCharacterSize() * 2.0F};
|
||||||
}
|
}
|
||||||
|
|
||||||
// Hace sonar la música
|
// Hace sonar la música
|
||||||
|
|||||||
@@ -89,7 +89,7 @@ class Game {
|
|||||||
void renderRoomName();
|
void renderRoomName();
|
||||||
|
|
||||||
// Cambia de habitación
|
// Cambia de habitación
|
||||||
bool changeRoom(const std::string& room_path);
|
auto changeRoom(const std::string& room_path) -> bool;
|
||||||
|
|
||||||
// Comprueba el teclado
|
// Comprueba el teclado
|
||||||
void checkInput();
|
void checkInput();
|
||||||
@@ -98,7 +98,7 @@ class Game {
|
|||||||
void checkPlayerIsOnBorder();
|
void checkPlayerIsOnBorder();
|
||||||
|
|
||||||
// Comprueba las colisiones del jugador con los enemigos
|
// Comprueba las colisiones del jugador con los enemigos
|
||||||
bool checkPlayerAndEnemies();
|
auto checkPlayerAndEnemies() -> bool;
|
||||||
|
|
||||||
// Comprueba las colisiones del jugador con los objetos
|
// Comprueba las colisiones del jugador con los objetos
|
||||||
void checkPlayerAndItems();
|
void checkPlayerAndItems();
|
||||||
@@ -125,10 +125,10 @@ class Game {
|
|||||||
void setScoreBoardColor();
|
void setScoreBoardColor();
|
||||||
|
|
||||||
// Comprueba si ha finalizado el juego
|
// Comprueba si ha finalizado el juego
|
||||||
bool checkEndGame();
|
auto checkEndGame() -> bool;
|
||||||
|
|
||||||
// Obtiene la cantidad total de items que hay en el mapeado del juego
|
// Obtiene la cantidad total de items que hay en el mapeado del juego
|
||||||
static int getTotalItems();
|
static auto getTotalItems() -> int;
|
||||||
|
|
||||||
// Pone el juego en pausa
|
// Pone el juego en pausa
|
||||||
void togglePause();
|
void togglePause();
|
||||||
|
|||||||
@@ -20,10 +20,7 @@
|
|||||||
// Constructor
|
// Constructor
|
||||||
GameOver::GameOver()
|
GameOver::GameOver()
|
||||||
: player_sprite_(std::make_shared<SurfaceAnimatedSprite>(Resource::get()->getSurface("player_game_over.gif"), Resource::get()->getAnimations("player_game_over.ani"))),
|
: player_sprite_(std::make_shared<SurfaceAnimatedSprite>(Resource::get()->getSurface("player_game_over.gif"), Resource::get()->getAnimations("player_game_over.ani"))),
|
||||||
tv_sprite_(std::make_shared<SurfaceAnimatedSprite>(Resource::get()->getSurface("tv.gif"), Resource::get()->getAnimations("tv.ani"))),
|
tv_sprite_(std::make_shared<SurfaceAnimatedSprite>(Resource::get()->getSurface("tv.gif"), Resource::get()->getAnimations("tv.ani"))) {
|
||||||
pre_counter_(0),
|
|
||||||
counter_(0),
|
|
||||||
ticks_(0) {
|
|
||||||
SceneManager::current = SceneManager::Scene::GAME_OVER;
|
SceneManager::current = SceneManager::Scene::GAME_OVER;
|
||||||
SceneManager::options = SceneManager::Options::NONE;
|
SceneManager::options = SceneManager::Options::NONE;
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,8 @@
|
|||||||
#include "game/scenes/loading_screen.hpp"
|
#include "game/scenes/loading_screen.hpp"
|
||||||
|
|
||||||
#include <SDL3/SDL.h>
|
#include <SDL3/SDL.h>
|
||||||
#include <stdlib.h> // Para rand
|
|
||||||
|
#include <cstdlib> // Para rand
|
||||||
|
|
||||||
#include "core/audio/audio.hpp" // Para Audio
|
#include "core/audio/audio.hpp" // Para Audio
|
||||||
#include "core/input/global_inputs.hpp" // Para check
|
#include "core/input/global_inputs.hpp" // Para check
|
||||||
@@ -9,10 +10,10 @@
|
|||||||
#include "core/rendering/surface.hpp" // Para Surface
|
#include "core/rendering/surface.hpp" // Para Surface
|
||||||
#include "core/rendering/surface_sprite.hpp" // Para SSprite
|
#include "core/rendering/surface_sprite.hpp" // Para SSprite
|
||||||
#include "core/resources/resource.hpp" // Para Resource
|
#include "core/resources/resource.hpp" // Para Resource
|
||||||
|
#include "core/system/global_events.hpp" // Para check
|
||||||
#include "game/options.hpp" // Para Options, options, SectionState, Options...
|
#include "game/options.hpp" // Para Options, options, SectionState, Options...
|
||||||
#include "game/scene_manager.hpp" // Para SceneManager
|
#include "game/scene_manager.hpp" // Para SceneManager
|
||||||
#include "utils/defines.hpp" // Para GAME_SPEED
|
#include "utils/defines.hpp" // Para GAME_SPEED
|
||||||
#include "core/system/global_events.hpp" // Para check
|
|
||||||
#include "utils/utils.hpp" // Para stringToColor, PaletteColor
|
#include "utils/utils.hpp" // Para stringToColor, PaletteColor
|
||||||
|
|
||||||
// Constructor
|
// Constructor
|
||||||
@@ -252,7 +253,7 @@ void LoadingScreen::renderYellowBorder() {
|
|||||||
border->clear(static_cast<Uint8>(PaletteColor::BLUE));
|
border->clear(static_cast<Uint8>(PaletteColor::BLUE));
|
||||||
|
|
||||||
// Añade lineas amarillas
|
// Añade lineas amarillas
|
||||||
const Uint8 COLOR = static_cast<Uint8>(PaletteColor::YELLOW);
|
const auto COLOR = static_cast<Uint8>(PaletteColor::YELLOW);
|
||||||
const int WIDTH = Options::game.width + (Options::video.border.width * 2);
|
const int WIDTH = Options::game.width + (Options::video.border.width * 2);
|
||||||
const int HEIGHT = Options::game.height + (Options::video.border.height * 2);
|
const int HEIGHT = Options::game.height + (Options::video.border.height * 2);
|
||||||
bool draw_enabled = rand() % 2 == 0;
|
bool draw_enabled = rand() % 2 == 0;
|
||||||
@@ -279,7 +280,7 @@ void LoadingScreen::renderRedBorder() {
|
|||||||
border->clear(static_cast<Uint8>(PaletteColor::CYAN));
|
border->clear(static_cast<Uint8>(PaletteColor::CYAN));
|
||||||
|
|
||||||
// Añade lineas rojas
|
// Añade lineas rojas
|
||||||
const Uint8 COLOR = static_cast<Uint8>(PaletteColor::RED);
|
const auto COLOR = static_cast<Uint8>(PaletteColor::RED);
|
||||||
const int WIDTH = Options::game.width + (Options::video.border.width * 2);
|
const int WIDTH = Options::game.width + (Options::video.border.width * 2);
|
||||||
const int HEIGHT = Options::game.height + (Options::video.border.height * 2);
|
const int HEIGHT = Options::game.height + (Options::video.border.height * 2);
|
||||||
bool draw_enabled = true;
|
bool draw_enabled = true;
|
||||||
|
|||||||
@@ -83,7 +83,7 @@ void Logo::updateJAILGAMES(float delta_time) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Calcula el índice de color según el progreso (0.0-1.0)
|
// Calcula el índice de color según el progreso (0.0-1.0)
|
||||||
int Logo::getColorIndex(float progress) const {
|
auto Logo::getColorIndex(float progress) const -> int {
|
||||||
// Asegurar que progress esté en el rango [0.0, 1.0]
|
// Asegurar que progress esté en el rango [0.0, 1.0]
|
||||||
progress = std::clamp(progress, 0.0F, 1.0F);
|
progress = std::clamp(progress, 0.0F, 1.0F);
|
||||||
|
|
||||||
|
|||||||
@@ -60,7 +60,7 @@ class Logo {
|
|||||||
void updateTextureColors(); // Gestiona el color de las texturas
|
void updateTextureColors(); // Gestiona el color de las texturas
|
||||||
void updateState(float delta_time); // Actualiza el estado actual
|
void updateState(float delta_time); // Actualiza el estado actual
|
||||||
void transitionToState(LogoState new_state); // Transiciona a un nuevo estado
|
void transitionToState(LogoState new_state); // Transiciona a un nuevo estado
|
||||||
int getColorIndex(float progress) const; // Calcula el índice de color según el progreso (0.0-1.0)
|
[[nodiscard]] auto getColorIndex(float progress) const -> int; // Calcula el índice de color según el progreso (0.0-1.0)
|
||||||
static void endSection(); // Termina la sección
|
static void endSection(); // Termina la sección
|
||||||
void initColors(); // Inicializa el vector de colores
|
void initColors(); // Inicializa el vector de colores
|
||||||
void initSprites(); // Crea los sprites de cada linea
|
void initSprites(); // Crea los sprites de cada linea
|
||||||
|
|||||||
@@ -328,7 +328,7 @@ void Title::createCheevosTexture() {
|
|||||||
Screen::get()->setRendererSurface(cheevos_surface_);
|
Screen::get()->setRendererSurface(cheevos_surface_);
|
||||||
|
|
||||||
// Rellena la textura con color sólido
|
// Rellena la textura con color sólido
|
||||||
const Uint8 CHEEVOS_BG_COLOR = static_cast<Uint8>(PaletteColor::BLACK);
|
const auto CHEEVOS_BG_COLOR = static_cast<Uint8>(PaletteColor::BLACK);
|
||||||
cheevos_surface_->clear(CHEEVOS_BG_COLOR);
|
cheevos_surface_->clear(CHEEVOS_BG_COLOR);
|
||||||
|
|
||||||
// Escribe la lista de logros en la textura
|
// Escribe la lista de logros en la textura
|
||||||
@@ -358,7 +358,7 @@ void Title::createCheevosTexture() {
|
|||||||
|
|
||||||
// Crea el sprite para el listado de logros
|
// Crea el sprite para el listado de logros
|
||||||
cheevos_sprite_ = std::make_shared<SurfaceSprite>(cheevos_surface_, (GAMECANVAS_WIDTH - cheevos_surface_->getWidth()) / 2, CHEEVOS_TEXTURE_POS_Y, cheevos_surface_->getWidth(), cheevos_surface_->getHeight());
|
cheevos_sprite_ = std::make_shared<SurfaceSprite>(cheevos_surface_, (GAMECANVAS_WIDTH - cheevos_surface_->getWidth()) / 2, CHEEVOS_TEXTURE_POS_Y, cheevos_surface_->getWidth(), cheevos_surface_->getHeight());
|
||||||
cheevos_surface_view_ = {0, 0, cheevos_surface_->getWidth(), CHEEVOS_TEXTURE_VIEW_HEIGHT};
|
cheevos_surface_view_ = {.x = 0, .y = 0, .w = cheevos_surface_->getWidth(), .h = CHEEVOS_TEXTURE_VIEW_HEIGHT};
|
||||||
cheevos_sprite_->setClip(cheevos_surface_view_);
|
cheevos_sprite_->setClip(cheevos_surface_view_);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -55,41 +55,41 @@ void Notifier::update() {
|
|||||||
// Si la notificación anterior está "saliendo", no hagas nada
|
// Si la notificación anterior está "saliendo", no hagas nada
|
||||||
if (!notifications_.empty() && ¬ification != ¬ifications_.front()) {
|
if (!notifications_.empty() && ¬ification != ¬ifications_.front()) {
|
||||||
const auto& previous_notification = *(std::prev(¬ification));
|
const auto& previous_notification = *(std::prev(¬ification));
|
||||||
if (previous_notification.state == NotificationStatus::RISING) {
|
if (previous_notification.state == Status::RISING) {
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
switch (notification.state) {
|
switch (notification.state) {
|
||||||
case NotificationStatus::RISING: {
|
case Status::RISING: {
|
||||||
const int DIRECTION = 1;
|
const int DIRECTION = 1;
|
||||||
notification.rect.y += DIRECTION;
|
notification.rect.y += DIRECTION;
|
||||||
|
|
||||||
if (notification.rect.y == notification.y) {
|
if (notification.rect.y == notification.y) {
|
||||||
notification.state = NotificationStatus::STAY;
|
notification.state = Status::STAY;
|
||||||
notification.start_time = SDL_GetTicks();
|
notification.start_time = SDL_GetTicks();
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
case NotificationStatus::STAY: {
|
case Status::STAY: {
|
||||||
notification.elapsed_time = SDL_GetTicks() - notification.start_time;
|
notification.elapsed_time = SDL_GetTicks() - notification.start_time;
|
||||||
if (notification.elapsed_time >= notification.display_duration) {
|
if (notification.elapsed_time >= notification.display_duration) {
|
||||||
notification.state = NotificationStatus::VANISHING;
|
notification.state = Status::VANISHING;
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
case NotificationStatus::VANISHING: {
|
case Status::VANISHING: {
|
||||||
const int DIRECTION = -1;
|
const int DIRECTION = -1;
|
||||||
notification.rect.y += DIRECTION;
|
notification.rect.y += DIRECTION;
|
||||||
|
|
||||||
if (notification.rect.y == notification.y - notification.travel_dist) {
|
if (notification.rect.y == notification.y - notification.travel_dist) {
|
||||||
notification.state = NotificationStatus::FINISHED;
|
notification.state = Status::FINISHED;
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
case NotificationStatus::FINISHED:
|
case Status::FINISHED:
|
||||||
break;
|
break;
|
||||||
|
|
||||||
default:
|
default:
|
||||||
@@ -106,7 +106,7 @@ void Notifier::update() {
|
|||||||
void Notifier::clearFinishedNotifications() {
|
void Notifier::clearFinishedNotifications() {
|
||||||
notifications_.erase(
|
notifications_.erase(
|
||||||
std::remove_if(notifications_.begin(), notifications_.end(), [](const Notification& notification) {
|
std::remove_if(notifications_.begin(), notifications_.end(), [](const Notification& notification) {
|
||||||
return notification.state == NotificationStatus::FINISHED;
|
return notification.state == Status::FINISHED;
|
||||||
}),
|
}),
|
||||||
notifications_.end());
|
notifications_.end());
|
||||||
}
|
}
|
||||||
@@ -142,7 +142,7 @@ void Notifier::show(std::vector<std::string> texts, NotificationText text_is, Ui
|
|||||||
text_is = ICON_SPACE > 0 ? NotificationText::LEFT : text_is;
|
text_is = ICON_SPACE > 0 ? NotificationText::LEFT : text_is;
|
||||||
const float WIDTH = Options::game.width - (PADDING_OUT * 2);
|
const float WIDTH = Options::game.width - (PADDING_OUT * 2);
|
||||||
const float HEIGHT = (TEXT_SIZE * texts.size()) + (PADDING_IN_V * 2);
|
const float HEIGHT = (TEXT_SIZE * texts.size()) + (PADDING_IN_V * 2);
|
||||||
const auto SHAPE = NotificationShape::SQUARED;
|
const auto SHAPE = Shape::SQUARED;
|
||||||
|
|
||||||
// Posición horizontal
|
// Posición horizontal
|
||||||
float desp_h = ((Options::game.width / 2) - (WIDTH / 2));
|
float desp_h = ((Options::game.width / 2) - (WIDTH / 2));
|
||||||
@@ -179,7 +179,7 @@ void Notifier::show(std::vector<std::string> texts, NotificationText text_is, Ui
|
|||||||
|
|
||||||
// Dibuja el fondo de la notificación
|
// Dibuja el fondo de la notificación
|
||||||
SDL_FRect rect;
|
SDL_FRect rect;
|
||||||
if (SHAPE == NotificationShape::ROUNDED) {
|
if (SHAPE == Shape::ROUNDED) {
|
||||||
rect = {4, 0, WIDTH - (4 * 2), HEIGHT};
|
rect = {4, 0, WIDTH - (4 * 2), HEIGHT};
|
||||||
n.surface->fillRect(&rect, bg_color_);
|
n.surface->fillRect(&rect, bg_color_);
|
||||||
|
|
||||||
@@ -193,7 +193,7 @@ void Notifier::show(std::vector<std::string> texts, NotificationText text_is, Ui
|
|||||||
n.surface->fillRect(&rect, bg_color_);
|
n.surface->fillRect(&rect, bg_color_);
|
||||||
}
|
}
|
||||||
|
|
||||||
else if (SHAPE == NotificationShape::SQUARED) {
|
else if (SHAPE == Shape::SQUARED) {
|
||||||
n.surface->clear(bg_color_);
|
n.surface->clear(bg_color_);
|
||||||
SDL_FRect squared_rect = {0, 0, n.surface->getWidth(), n.surface->getHeight()};
|
SDL_FRect squared_rect = {0, 0, n.surface->getWidth(), n.surface->getHeight()};
|
||||||
n.surface->drawRectBorder(&squared_rect, static_cast<Uint8>(PaletteColor::CYAN));
|
n.surface->drawRectBorder(&squared_rect, static_cast<Uint8>(PaletteColor::CYAN));
|
||||||
@@ -245,7 +245,7 @@ bool Notifier::isActive() { return !notifications_.empty(); }
|
|||||||
void Notifier::clearNotifications() {
|
void Notifier::clearNotifications() {
|
||||||
for (auto& notification : notifications_) {
|
for (auto& notification : notifications_) {
|
||||||
if (notification.can_be_removed) {
|
if (notification.can_be_removed) {
|
||||||
notification.state = NotificationStatus::FINISHED;
|
notification.state = Status::FINISHED;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -28,50 +28,36 @@ class Notifier {
|
|||||||
// [SINGLETON] Objeto notifier
|
// [SINGLETON] Objeto notifier
|
||||||
static Notifier* notifier;
|
static Notifier* notifier;
|
||||||
|
|
||||||
enum class NotificationStatus {
|
enum class Status {
|
||||||
RISING,
|
RISING,
|
||||||
STAY,
|
STAY,
|
||||||
VANISHING,
|
VANISHING,
|
||||||
FINISHED,
|
FINISHED,
|
||||||
};
|
};
|
||||||
|
|
||||||
enum class NotificationShape {
|
enum class Shape {
|
||||||
ROUNDED,
|
ROUNDED,
|
||||||
SQUARED,
|
SQUARED,
|
||||||
};
|
};
|
||||||
|
|
||||||
struct Notification {
|
struct Notification {
|
||||||
std::shared_ptr<Surface> surface; // Superficie asociada a la notificación
|
std::shared_ptr<Surface> surface{nullptr}; // Superficie asociada a la notificación
|
||||||
std::shared_ptr<SurfaceSprite> sprite; // Sprite asociado para gráficos o animaciones
|
std::shared_ptr<SurfaceSprite> sprite{nullptr}; // Sprite asociado para gráficos o animaciones
|
||||||
std::vector<std::string> texts; // Lista de textos incluidos en la notificación
|
std::vector<std::string> texts; // Lista de textos incluidos en la notificación
|
||||||
NotificationStatus state; // Estado actual de la notificación (RISING, SHOWING, etc.)
|
Status state{Status::RISING}; // Estado actual de la notificación (RISING, SHOWING, etc.)
|
||||||
NotificationShape shape; // Forma de la notificación (ej. SQUARED o ROUNDED)
|
Shape shape{Shape::SQUARED}; // Forma de la notificación (ej. SQUARED o ROUNDED)
|
||||||
SDL_FRect rect; // Dimensiones y posición de la notificación en pantalla
|
SDL_FRect rect{0, 0, 0, 0}; // Dimensiones y posición de la notificación en pantalla
|
||||||
int y; // Posición actual en el eje Y
|
int y{0}; // Posición actual en el eje Y
|
||||||
int travel_dist; // Distancia a recorrer (por ejemplo, en animaciones)
|
int travel_dist{0}; // Distancia a recorrer (por ejemplo, en animaciones)
|
||||||
std::string code; // Código identificador único para esta notificación
|
std::string code; // Código identificador único para esta notificación
|
||||||
bool can_be_removed; // Indica si la notificación puede ser eliminada
|
bool can_be_removed{true}; // Indica si la notificación puede ser eliminada
|
||||||
int height; // Altura de la notificación
|
int height{0}; // Altura de la notificación
|
||||||
Uint32 start_time; // Momento en que se creó la notificación
|
Uint32 start_time{0}; // Momento en que se creó la notificación
|
||||||
Uint32 elapsed_time; // Tiempo transcurrido desde la creación
|
Uint32 elapsed_time{0}; // Tiempo transcurrido desde la creación
|
||||||
Uint32 display_duration; // Duración total para mostrar la notificación
|
Uint32 display_duration{0}; // Duración total para mostrar la notificación
|
||||||
|
|
||||||
// Constructor
|
// Constructor
|
||||||
explicit Notification()
|
explicit Notification() = default;
|
||||||
: surface(nullptr), // Inicializar superficie como nula
|
|
||||||
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), // 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
|
|
||||||
elapsed_time(0), // Tiempo transcurrido inicializado a 0
|
|
||||||
display_duration(0) // Duración inicializada a 0
|
|
||||||
{
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
std::shared_ptr<Surface> icon_surface_; // Textura para los iconos de las notificaciones
|
std::shared_ptr<Surface> icon_surface_; // Textura para los iconos de las notificaciones
|
||||||
|
|||||||
@@ -6,12 +6,17 @@ Empezado en Castalla el 01/07/2022.
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
#include <memory>
|
#include <memory>
|
||||||
|
#include <string>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
#include "core/system/director.hpp"
|
#include "core/system/director.hpp"
|
||||||
|
|
||||||
int main(int argc, char* argv[]) {
|
auto main(int argc, char* argv[]) -> int {
|
||||||
|
// Convierte argumentos a formato moderno C++
|
||||||
|
std::vector<std::string> args(argv, argv + argc);
|
||||||
|
|
||||||
// Crea el objeto Director
|
// Crea el objeto Director
|
||||||
auto director = std::make_unique<Director>(argc, const_cast<const char**>(argv));
|
auto director = std::make_unique<Director>(args);
|
||||||
|
|
||||||
// Bucle principal
|
// Bucle principal
|
||||||
return Director::run();
|
return Director::run();
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ DeltaTimer::DeltaTimer() noexcept
|
|||||||
time_scale_(1.0F) {
|
time_scale_(1.0F) {
|
||||||
}
|
}
|
||||||
|
|
||||||
float DeltaTimer::tick() noexcept {
|
auto DeltaTimer::tick() noexcept -> float {
|
||||||
const Uint64 NOW = SDL_GetPerformanceCounter();
|
const Uint64 NOW = SDL_GetPerformanceCounter();
|
||||||
const Uint64 DIFF = (NOW > last_counter_) ? (NOW - last_counter_) : 0;
|
const Uint64 DIFF = (NOW > last_counter_) ? (NOW - last_counter_) : 0;
|
||||||
last_counter_ = NOW;
|
last_counter_ = NOW;
|
||||||
@@ -14,7 +14,7 @@ float DeltaTimer::tick() noexcept {
|
|||||||
return static_cast<float>(SECONDS * static_cast<double>(time_scale_));
|
return static_cast<float>(SECONDS * static_cast<double>(time_scale_));
|
||||||
}
|
}
|
||||||
|
|
||||||
float DeltaTimer::peek() const noexcept {
|
auto DeltaTimer::peek() const noexcept -> float {
|
||||||
const Uint64 NOW = SDL_GetPerformanceCounter();
|
const Uint64 NOW = SDL_GetPerformanceCounter();
|
||||||
const Uint64 DIFF = (NOW > last_counter_) ? (NOW - last_counter_) : 0;
|
const Uint64 DIFF = (NOW > last_counter_) ? (NOW - last_counter_) : 0;
|
||||||
const double SECONDS = static_cast<double>(DIFF) / perf_freq_;
|
const double SECONDS = static_cast<double>(DIFF) / perf_freq_;
|
||||||
@@ -33,7 +33,6 @@ 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 {
|
auto DeltaTimer::getTimeScale() const noexcept -> float {
|
||||||
return time_scale_;
|
return time_scale_;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -8,17 +8,17 @@ public:
|
|||||||
DeltaTimer() noexcept;
|
DeltaTimer() noexcept;
|
||||||
|
|
||||||
// Calcula delta en segundos y actualiza el contador interno
|
// Calcula delta en segundos y actualiza el contador interno
|
||||||
float tick() noexcept;
|
auto tick() noexcept -> float;
|
||||||
|
|
||||||
// Devuelve el delta estimado desde el último tick sin actualizar el contador
|
// Devuelve el delta estimado desde el último tick sin actualizar el contador
|
||||||
float peek() const noexcept;
|
[[nodiscard]] auto peek() const noexcept -> float;
|
||||||
|
|
||||||
// Reinicia el contador al valor actual o al valor pasado (en performance counter ticks)
|
// Reinicia el contador al valor actual o al valor pasado (en performance counter ticks)
|
||||||
void reset(Uint64 counter = 0) noexcept;
|
void reset(Uint64 counter = 0) noexcept;
|
||||||
|
|
||||||
// Escala el tiempo retornado por tick/peek, por defecto 1.0f
|
// Escala el tiempo retornado por tick/peek, por defecto 1.0f
|
||||||
void setTimeScale(float scale) noexcept;
|
void setTimeScale(float scale) noexcept;
|
||||||
float getTimeScale() const noexcept;
|
[[nodiscard]] auto getTimeScale() const noexcept -> float;
|
||||||
|
|
||||||
private:
|
private:
|
||||||
Uint64 last_counter_;
|
Uint64 last_counter_;
|
||||||
|
|||||||
@@ -1,10 +1,9 @@
|
|||||||
#include "utils/utils.hpp"
|
#include "utils/utils.hpp"
|
||||||
|
|
||||||
#include <stdlib.h> // Para abs
|
|
||||||
|
|
||||||
#include <algorithm> // Para find, transform
|
#include <algorithm> // Para find, transform
|
||||||
#include <cctype> // Para tolower
|
#include <cctype> // Para tolower
|
||||||
#include <cmath> // Para round, abs
|
#include <cmath> // Para round, abs
|
||||||
|
#include <cstdlib> // Para abs
|
||||||
#include <exception> // Para exception
|
#include <exception> // Para exception
|
||||||
#include <filesystem> // Para path
|
#include <filesystem> // Para path
|
||||||
#include <iostream> // Para basic_ostream, cout, basic_ios, ios, endl
|
#include <iostream> // Para basic_ostream, cout, basic_ios, ios, endl
|
||||||
@@ -16,14 +15,14 @@
|
|||||||
#include "external/jail_audio.h" // Para JA_GetMusicState, JA_Music_state, JA_PlayMusic
|
#include "external/jail_audio.h" // Para JA_GetMusicState, JA_Music_state, JA_PlayMusic
|
||||||
|
|
||||||
// Calcula el cuadrado de la distancia entre dos puntos
|
// Calcula el cuadrado de la distancia entre dos puntos
|
||||||
double distanceSquared(int x1, int y1, int x2, int y2) {
|
auto distanceSquared(int x1, int y1, int x2, int y2) -> double {
|
||||||
const int DELTA_X = x2 - x1;
|
const int DELTA_X = x2 - x1;
|
||||||
const int DELTA_Y = y2 - y1;
|
const int DELTA_Y = y2 - y1;
|
||||||
return (DELTA_X * DELTA_X) + (DELTA_Y * DELTA_Y);
|
return (DELTA_X * DELTA_X) + (DELTA_Y * DELTA_Y);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Detector de colisiones entre dos circulos
|
// Detector de colisiones entre dos circulos
|
||||||
bool checkCollision(const Circle& a, const Circle& b) {
|
auto checkCollision(const Circle& a, const Circle& b) -> bool {
|
||||||
// Calcula el radio total al cuadrado
|
// Calcula el radio total al cuadrado
|
||||||
int total_radius_squared = a.r + b.r;
|
int total_radius_squared = a.r + b.r;
|
||||||
total_radius_squared = total_radius_squared * total_radius_squared;
|
total_radius_squared = total_radius_squared * total_radius_squared;
|
||||||
@@ -33,7 +32,7 @@ bool checkCollision(const Circle& a, const Circle& b) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Detector de colisiones entre un circulo y un rectangulo
|
// Detector de colisiones entre un circulo y un rectangulo
|
||||||
bool checkCollision(const Circle& a, const SDL_FRect& rect) {
|
auto checkCollision(const Circle& a, const SDL_FRect& rect) -> bool {
|
||||||
SDL_Rect b = toSDLRect(rect);
|
SDL_Rect b = toSDLRect(rect);
|
||||||
// Closest point on collision box
|
// Closest point on collision box
|
||||||
int c_x;
|
int c_x;
|
||||||
@@ -68,7 +67,7 @@ bool checkCollision(const Circle& a, const SDL_FRect& rect) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Detector de colisiones entre dos rectangulos
|
// Detector de colisiones entre dos rectangulos
|
||||||
bool checkCollision(const SDL_FRect& rect_a, const SDL_FRect& rect_b) {
|
auto checkCollision(const SDL_FRect& rect_a, const SDL_FRect& rect_b) -> bool {
|
||||||
SDL_Rect a = toSDLRect(rect_a);
|
SDL_Rect a = toSDLRect(rect_a);
|
||||||
SDL_Rect b = toSDLRect(rect_b);
|
SDL_Rect b = toSDLRect(rect_b);
|
||||||
// Calcula las caras del rectangulo a
|
// Calcula las caras del rectangulo a
|
||||||
@@ -105,7 +104,7 @@ bool checkCollision(const SDL_FRect& rect_a, const SDL_FRect& rect_b) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Detector de colisiones entre un punto y un rectangulo
|
// Detector de colisiones entre un punto y un rectangulo
|
||||||
bool checkCollision(const SDL_FPoint& point, const SDL_FRect& rect) {
|
auto checkCollision(const SDL_FPoint& point, const SDL_FRect& rect) -> bool {
|
||||||
SDL_Rect r = toSDLRect(rect);
|
SDL_Rect r = toSDLRect(rect);
|
||||||
SDL_Point p = toSDLPoint(point);
|
SDL_Point p = toSDLPoint(point);
|
||||||
|
|
||||||
@@ -134,7 +133,7 @@ bool checkCollision(const SDL_FPoint& point, const SDL_FRect& rect) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Detector de colisiones entre una linea horizontal y un rectangulo
|
// Detector de colisiones entre una linea horizontal y un rectangulo
|
||||||
bool checkCollision(const LineHorizontal& l, const SDL_FRect& rect) {
|
auto checkCollision(const LineHorizontal& l, const SDL_FRect& rect) -> bool {
|
||||||
SDL_Rect r = toSDLRect(rect);
|
SDL_Rect r = toSDLRect(rect);
|
||||||
// Comprueba si la linea esta por encima del rectangulo
|
// Comprueba si la linea esta por encima del rectangulo
|
||||||
if (l.y < r.y) {
|
if (l.y < r.y) {
|
||||||
@@ -161,7 +160,7 @@ bool checkCollision(const LineHorizontal& l, const SDL_FRect& rect) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Detector de colisiones entre una linea vertical y un rectangulo
|
// Detector de colisiones entre una linea vertical y un rectangulo
|
||||||
bool checkCollision(const LineVertical& l, const SDL_FRect& rect) {
|
auto checkCollision(const LineVertical& l, const SDL_FRect& rect) -> bool {
|
||||||
SDL_Rect r = toSDLRect(rect);
|
SDL_Rect r = toSDLRect(rect);
|
||||||
// Comprueba si la linea esta por la izquierda del rectangulo
|
// Comprueba si la linea esta por la izquierda del rectangulo
|
||||||
if (l.x < r.x) {
|
if (l.x < r.x) {
|
||||||
@@ -188,7 +187,7 @@ bool checkCollision(const LineVertical& l, const SDL_FRect& rect) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Detector de colisiones entre una linea horizontal y un punto
|
// Detector de colisiones entre una linea horizontal y un punto
|
||||||
bool checkCollision(const LineHorizontal& l, const SDL_FPoint& point) {
|
auto checkCollision(const LineHorizontal& l, const SDL_FPoint& point) -> bool {
|
||||||
SDL_Point p = toSDLPoint(point);
|
SDL_Point p = toSDLPoint(point);
|
||||||
|
|
||||||
// Comprueba si el punto esta sobre la linea
|
// Comprueba si el punto esta sobre la linea
|
||||||
@@ -216,7 +215,7 @@ bool checkCollision(const LineHorizontal& l, const SDL_FPoint& point) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Detector de colisiones entre dos lineas
|
// Detector de colisiones entre dos lineas
|
||||||
SDL_Point checkCollision(const Line& l1, const Line& l2) {
|
auto checkCollision(const Line& l1, const Line& l2) -> SDL_Point {
|
||||||
const float X1 = l1.x1;
|
const float X1 = l1.x1;
|
||||||
const float Y1 = l1.y1;
|
const float Y1 = l1.y1;
|
||||||
const float X2 = l1.x2;
|
const float X2 = l1.x2;
|
||||||
@@ -237,13 +236,13 @@ SDL_Point checkCollision(const Line& l1, const Line& l2) {
|
|||||||
const float X = X1 + (u_a * (X2 - X1));
|
const float X = X1 + (u_a * (X2 - X1));
|
||||||
const float Y = Y1 + (u_a * (Y2 - Y1));
|
const float Y = Y1 + (u_a * (Y2 - Y1));
|
||||||
|
|
||||||
return {static_cast<int>(round(X)), static_cast<int>(round(Y))};
|
return {static_cast<int>(std::round(X)), static_cast<int>(std::round(Y))};
|
||||||
}
|
}
|
||||||
return {-1, -1};
|
return {-1, -1};
|
||||||
}
|
}
|
||||||
|
|
||||||
// Detector de colisiones entre dos lineas
|
// Detector de colisiones entre dos lineas
|
||||||
SDL_Point checkCollision(const LineDiagonal& l1, const LineVertical& l2) {
|
auto checkCollision(const LineDiagonal& l1, const LineVertical& l2) -> SDL_Point {
|
||||||
const float X1 = l1.x1;
|
const float X1 = l1.x1;
|
||||||
const float Y1 = l1.y1;
|
const float Y1 = l1.y1;
|
||||||
const float X2 = l1.x2;
|
const float X2 = l1.x2;
|
||||||
@@ -284,7 +283,7 @@ void normalizeLine(LineDiagonal& l) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Detector de colisiones entre un punto y una linea diagonal
|
// Detector de colisiones entre un punto y una linea diagonal
|
||||||
bool checkCollision(const SDL_FPoint& point, const LineDiagonal& l) {
|
auto checkCollision(const SDL_FPoint& point, const LineDiagonal& l) -> bool {
|
||||||
SDL_Point p = toSDLPoint(point);
|
SDL_Point p = toSDLPoint(point);
|
||||||
|
|
||||||
// Comprueba si el punto está en alineado con la linea
|
// Comprueba si el punto está en alineado con la linea
|
||||||
@@ -317,7 +316,7 @@ bool checkCollision(const SDL_FPoint& point, const LineDiagonal& l) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Convierte una cadena a un indice de la paleta
|
// Convierte una cadena a un indice de la paleta
|
||||||
Uint8 stringToColor(const std::string& str) {
|
auto stringToColor(const std::string& str) -> Uint8 {
|
||||||
// Mapas de colores para cada paleta
|
// Mapas de colores para cada paleta
|
||||||
static const std::unordered_map<std::string, Uint8> PALETTE_MAP = {
|
static const std::unordered_map<std::string, Uint8> PALETTE_MAP = {
|
||||||
{"black", 0},
|
{"black", 0},
|
||||||
@@ -355,7 +354,7 @@ Uint8 stringToColor(const std::string& str) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Convierte una cadena a un entero de forma segura
|
// Convierte una cadena a un entero de forma segura
|
||||||
int safeStoi(const std::string& value, int default_value) {
|
auto safeStoi(const std::string& value, int default_value) -> int {
|
||||||
try {
|
try {
|
||||||
return std::stoi(value);
|
return std::stoi(value);
|
||||||
} catch (const std::exception&) {
|
} catch (const std::exception&) {
|
||||||
@@ -364,19 +363,19 @@ int safeStoi(const std::string& value, int default_value) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Convierte una cadena a un booleano
|
// Convierte una cadena a un booleano
|
||||||
bool stringToBool(const std::string& str) {
|
auto stringToBool(const std::string& str) -> bool {
|
||||||
std::string lower_str = str;
|
std::string lower_str = str;
|
||||||
std::transform(lower_str.begin(), lower_str.end(), lower_str.begin(), ::tolower);
|
std::ranges::transform(lower_str, lower_str.begin(), ::tolower);
|
||||||
return (lower_str == "true" || lower_str == "1" || lower_str == "yes" || lower_str == "on");
|
return (lower_str == "true" || lower_str == "1" || lower_str == "yes" || lower_str == "on");
|
||||||
}
|
}
|
||||||
|
|
||||||
// Convierte un booleano a una cadena
|
// Convierte un booleano a una cadena
|
||||||
std::string boolToString(bool value) {
|
auto boolToString(bool value) -> std::string {
|
||||||
return value ? "1" : "0";
|
return value ? "1" : "0";
|
||||||
}
|
}
|
||||||
|
|
||||||
// Compara dos colores
|
// Compara dos colores
|
||||||
bool colorAreEqual(Color color1, Color color2) {
|
auto colorAreEqual(Color color1, Color color2) -> bool {
|
||||||
const bool R = color1.r == color2.r;
|
const bool R = color1.r == color2.r;
|
||||||
const bool G = color1.g == color2.g;
|
const bool G = color1.g == color2.g;
|
||||||
const bool B = color1.b == color2.b;
|
const bool B = color1.b == color2.b;
|
||||||
@@ -385,26 +384,26 @@ bool colorAreEqual(Color color1, Color color2) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Función para convertir un string a minúsculas
|
// Función para convertir un string a minúsculas
|
||||||
std::string toLower(const std::string& str) {
|
auto toLower(const std::string& str) -> std::string {
|
||||||
std::string lower_str = str;
|
std::string lower_str = str;
|
||||||
std::transform(lower_str.begin(), lower_str.end(), lower_str.begin(), ::tolower);
|
std::ranges::transform(lower_str, lower_str.begin(), ::tolower);
|
||||||
return lower_str;
|
return lower_str;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Función para convertir un string a mayúsculas
|
// Función para convertir un string a mayúsculas
|
||||||
std::string toUpper(const std::string& str) {
|
auto toUpper(const std::string& str) -> std::string {
|
||||||
std::string upper_str = str;
|
std::string upper_str = str;
|
||||||
std::transform(upper_str.begin(), upper_str.end(), upper_str.begin(), ::toupper);
|
std::ranges::transform(upper_str, upper_str.begin(), ::toupper);
|
||||||
return upper_str;
|
return upper_str;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Obtiene el nombre de un fichero a partir de una ruta completa
|
// Obtiene el nombre de un fichero a partir de una ruta completa
|
||||||
std::string getFileName(const std::string& path) {
|
auto getFileName(const std::string& path) -> std::string {
|
||||||
return std::filesystem::path(path).filename().string();
|
return std::filesystem::path(path).filename().string();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Obtiene la ruta eliminando el nombre del fichero
|
// Obtiene la ruta eliminando el nombre del fichero
|
||||||
std::string getPath(const std::string& full_path) {
|
auto getPath(const std::string& full_path) -> std::string {
|
||||||
std::filesystem::path path(full_path);
|
std::filesystem::path path(full_path);
|
||||||
return path.parent_path().string();
|
return path.parent_path().string();
|
||||||
}
|
}
|
||||||
@@ -418,12 +417,12 @@ void printWithDots(const std::string& text1, const std::string& text2, const std
|
|||||||
std::cout.fill('.');
|
std::cout.fill('.');
|
||||||
std::cout << text2;
|
std::cout << text2;
|
||||||
|
|
||||||
std::cout << text3 << std::endl;
|
std::cout << text3 << '\n';
|
||||||
}
|
}
|
||||||
|
|
||||||
// Comprueba si una vector contiene una cadena
|
// Comprueba si una vector contiene una cadena
|
||||||
bool stringInVector(const std::vector<std::string>& vec, const std::string& str) {
|
auto stringInVector(const std::vector<std::string>& vec, const std::string& str) -> bool {
|
||||||
return std::find(vec.begin(), vec.end(), str) != vec.end();
|
return std::ranges::find(vec, str) != vec.end();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Hace sonar la música
|
// Hace sonar la música
|
||||||
|
|||||||
@@ -80,73 +80,73 @@ struct Color {
|
|||||||
};
|
};
|
||||||
|
|
||||||
// Calcula el cuadrado de la distancia entre dos puntos
|
// Calcula el cuadrado de la distancia entre dos puntos
|
||||||
double distanceSquared(int x1, int y1, int x2, int y2);
|
auto distanceSquared(int x1, int y1, int x2, int y2) -> double;
|
||||||
|
|
||||||
// Detector de colisiones entre dos circulos
|
// Detector de colisiones entre dos circulos
|
||||||
bool checkCollision(const Circle& a, const Circle& b);
|
auto checkCollision(const Circle& a, const Circle& b) -> bool;
|
||||||
|
|
||||||
// Detector de colisiones entre un circulo y un rectangulo
|
// Detector de colisiones entre un circulo y un rectangulo
|
||||||
bool checkCollision(const Circle& a, const SDL_FRect& rect);
|
auto checkCollision(const Circle& a, const SDL_FRect& rect) -> bool;
|
||||||
|
|
||||||
// Detector de colisiones entre un dos rectangulos
|
// Detector de colisiones entre un dos rectangulos
|
||||||
bool checkCollision(const SDL_FRect& a, const SDL_FRect& b);
|
auto checkCollision(const SDL_FRect& a, const SDL_FRect& b) -> bool;
|
||||||
|
|
||||||
// Detector de colisiones entre un punto y un rectangulo
|
// Detector de colisiones entre un punto y un rectangulo
|
||||||
bool checkCollision(const SDL_FPoint& p, const SDL_FRect& r);
|
auto checkCollision(const SDL_FPoint& p, const SDL_FRect& r) -> bool;
|
||||||
|
|
||||||
// Detector de colisiones entre una linea horizontal y un rectangulo
|
// Detector de colisiones entre una linea horizontal y un rectangulo
|
||||||
bool checkCollision(const LineHorizontal& l, const SDL_FRect& r);
|
auto checkCollision(const LineHorizontal& l, const SDL_FRect& r) -> bool;
|
||||||
|
|
||||||
// Detector de colisiones entre una linea vertical y un rectangulo
|
// Detector de colisiones entre una linea vertical y un rectangulo
|
||||||
bool checkCollision(const LineVertical& l, const SDL_FRect& r);
|
auto checkCollision(const LineVertical& l, const SDL_FRect& r) -> bool;
|
||||||
|
|
||||||
// Detector de colisiones entre una linea horizontal y un punto
|
// Detector de colisiones entre una linea horizontal y un punto
|
||||||
bool checkCollision(const LineHorizontal& l, const SDL_FPoint& p);
|
auto checkCollision(const LineHorizontal& l, const SDL_FPoint& p) -> bool;
|
||||||
|
|
||||||
// Detector de colisiones entre dos lineas
|
// Detector de colisiones entre dos lineas
|
||||||
SDL_Point checkCollision(const Line& l1, const Line& l2);
|
auto checkCollision(const Line& l1, const Line& l2) -> SDL_Point;
|
||||||
|
|
||||||
// Detector de colisiones entre dos lineas
|
// Detector de colisiones entre dos lineas
|
||||||
SDL_Point checkCollision(const LineDiagonal& l1, const LineVertical& l2);
|
auto checkCollision(const LineDiagonal& l1, const LineVertical& l2) -> SDL_Point;
|
||||||
|
|
||||||
// Detector de colisiones entre un punto y una linea diagonal
|
// Detector de colisiones entre un punto y una linea diagonal
|
||||||
bool checkCollision(const SDL_FPoint& p, const LineDiagonal& l);
|
auto checkCollision(const SDL_FPoint& p, const LineDiagonal& l) -> bool;
|
||||||
|
|
||||||
// Normaliza una linea diagonal
|
// Normaliza una linea diagonal
|
||||||
void normalizeLine(LineDiagonal& l);
|
void normalizeLine(LineDiagonal& l);
|
||||||
|
|
||||||
// Devuelve un Color a partir de un string
|
// Devuelve un Color a partir de un string
|
||||||
Uint8 stringToColor(const std::string& str);
|
auto stringToColor(const std::string& str) -> Uint8;
|
||||||
|
|
||||||
// Convierte una cadena a un entero de forma segura
|
// Convierte una cadena a un entero de forma segura
|
||||||
int safeStoi(const std::string& value, int default_value = 0);
|
auto safeStoi(const std::string& value, int default_value = 0) -> int;
|
||||||
|
|
||||||
// Convierte una cadena a un booleano
|
// Convierte una cadena a un booleano
|
||||||
bool stringToBool(const std::string& str);
|
auto stringToBool(const std::string& str) -> bool;
|
||||||
|
|
||||||
// Convierte un booleano a una cadena
|
// Convierte un booleano a una cadena
|
||||||
std::string boolToString(bool value);
|
auto boolToString(bool value) -> std::string;
|
||||||
|
|
||||||
// Compara dos colores
|
// Compara dos colores
|
||||||
bool colorAreEqual(Color color1, Color color2);
|
auto colorAreEqual(Color color1, Color color2) -> bool;
|
||||||
|
|
||||||
// Convierte una cadena a minusculas
|
// Convierte una cadena a minusculas
|
||||||
std::string toLower(const std::string& str);
|
auto toLower(const std::string& str) -> std::string;
|
||||||
|
|
||||||
// Convierte una cadena a mayúsculas
|
// Convierte una cadena a mayúsculas
|
||||||
std::string toUpper(const std::string& str);
|
auto toUpper(const std::string& str) -> std::string;
|
||||||
|
|
||||||
// Obtiene el nombre de un fichero a partir de una ruta
|
// Obtiene el nombre de un fichero a partir de una ruta
|
||||||
std::string getFileName(const std::string& path);
|
auto getFileName(const std::string& path) -> std::string;
|
||||||
|
|
||||||
// Obtiene la ruta eliminando el nombre del fichero
|
// Obtiene la ruta eliminando el nombre del fichero
|
||||||
std::string getPath(const std::string& full_path);
|
auto getPath(const std::string& full_path) -> std::string;
|
||||||
|
|
||||||
// Imprime por pantalla una linea de texto de tamaño fijo rellena con puntos
|
// Imprime por pantalla una linea de texto de tamaño fijo rellena con puntos
|
||||||
void printWithDots(const std::string& text1, const std::string& text2, const std::string& text3);
|
void printWithDots(const std::string& text1, const std::string& text2, const std::string& text3);
|
||||||
|
|
||||||
// Comprueba si una vector contiene una cadena
|
// Comprueba si una vector contiene una cadena
|
||||||
bool stringInVector(const std::vector<std::string>& vec, const std::string& str);
|
auto stringInVector(const std::vector<std::string>& vec, const std::string& str) -> bool;
|
||||||
|
|
||||||
// Hace sonar la música
|
// Hace sonar la música
|
||||||
void playMusic(const std::string& music_path);
|
void playMusic(const std::string& music_path);
|
||||||
@@ -154,7 +154,7 @@ void playMusic(const std::string& music_path);
|
|||||||
// Rellena una textura de un color
|
// Rellena una textura de un color
|
||||||
void fillTextureWithColor(SDL_Renderer* renderer, SDL_Texture* texture, Uint8 r, Uint8 g, Uint8 b, Uint8 a);
|
void fillTextureWithColor(SDL_Renderer* renderer, SDL_Texture* texture, Uint8 r, Uint8 g, Uint8 b, Uint8 a);
|
||||||
|
|
||||||
inline SDL_Rect toSDLRect(const SDL_FRect& frect) {
|
inline auto toSDLRect(const SDL_FRect& frect) -> SDL_Rect {
|
||||||
SDL_Rect rect;
|
SDL_Rect rect;
|
||||||
rect.x = static_cast<int>(frect.x);
|
rect.x = static_cast<int>(frect.x);
|
||||||
rect.y = static_cast<int>(frect.y);
|
rect.y = static_cast<int>(frect.y);
|
||||||
@@ -163,7 +163,7 @@ inline SDL_Rect toSDLRect(const SDL_FRect& frect) {
|
|||||||
return rect;
|
return rect;
|
||||||
}
|
}
|
||||||
|
|
||||||
inline SDL_Point toSDLPoint(const SDL_FPoint& fpoint) {
|
inline auto toSDLPoint(const SDL_FPoint& fpoint) -> SDL_Point {
|
||||||
SDL_Point point;
|
SDL_Point point;
|
||||||
point.x = static_cast<int>(fpoint.x);
|
point.x = static_cast<int>(fpoint.x);
|
||||||
point.y = static_cast<int>(fpoint.y);
|
point.y = static_cast<int>(fpoint.y);
|
||||||
|
|||||||
Reference in New Issue
Block a user