diff --git a/source/cheevos.cpp b/source/cheevos.cpp index 69ba47a..c34c7fb 100644 --- a/source/cheevos.cpp +++ b/source/cheevos.cpp @@ -1,14 +1,13 @@ #include "cheevos.h" -#include // Para SDL_GetError -#include // Para SDL_RWFromFile, SDL_RWclose, SDL_RWwrite -#include // Para NULL +#include +#include // Para NULL #include // Para basic_ostream, operator<<, basic_ofstream #include // Para cout, cerr -#include "notifier.h" // Para Notifier -#include "options.h" // Para Options, options +#include "options.h" // Para Options, options +#include "ui/notifier.h" // Para Notifier // [SINGLETON] Cheevos* Cheevos::cheevos_ = nullptr; diff --git a/source/debug.h b/source/debug.h index 1b52a6b..729aae5 100644 --- a/source/debug.h +++ b/source/debug.h @@ -1,6 +1,6 @@ #pragma once -#include // Para SDL_Point +#include #include // Para string #include // Para vector diff --git a/source/director.cpp b/source/director.cpp index 6628d67..879977d 100644 --- a/source/director.cpp +++ b/source/director.cpp @@ -1,44 +1,34 @@ #include "director.h" -#include // Para SDL_Init, SDL_Quit, SDL_INIT_EV... -#include // Para AUDIO_S16 -#include // Para SDL_BLENDMODE_BLEND -#include // Para SDL_GetError -#include // Para SDL_DISABLE -#include // Para SDL_CONTROLLER_BUTTON_B, SDL_CO... -#include // Para SDL_SetHint, SDL_HINT_RENDER_DR... -#include // Para SDL_ShowCursor -#include // Para SDL_SCANCODE_A, SDL_SCANCODE_ES... -#include // Para Uint32 -#include // Para SDL_GetTicks -#include // Para errno, EEXIST, EACCES, ENAMETOO... -#include // Para printf, perror -#include // Para mkdir, stat, S_IRWXU -#include // Para getuid +#include +#include // Para errno, EEXIST, EACCES, ENAMETOO... +#include // Para printf, perror +#include // Para mkdir, stat, S_IRWXU +#include // Para getuid #include // Para exit, EXIT_FAILURE, srand #include // Para basic_ostream, operator<<, cout #include // Para make_unique, unique_ptr #include // Para operator+, allocator, char_traits -#include "asset.h" // Para Asset, AssetType -#include "cheevos.h" // Para Cheevos -#include "credits.h" // Para Credits -#include "debug.h" // Para Debug -#include "defines.h" // Para WINDOW_CAPTION -#include "ending.h" // Para Ending -#include "ending2.h" // Para Ending2 -#include "game.h" // Para Game, GameMode -#include "game_over.h" // Para GameOver -#include "input.h" // Para Input, InputAction -#include "jail_audio.h" // Para JA_SetMusicVolume, JA_SetSoundV... -#include "loading_screen.h" // Para LoadingScreen -#include "logo.h" // Para Logo -#include "notifier.h" // Para Notifier -#include "options.h" // Para Options, options, OptionsVideo -#include "resource.h" // Para Resource -#include "screen.h" // Para Screen -#include "title.h" // Para Title +#include "asset.h" // Para Asset, AssetType +#include "cheevos.h" // Para Cheevos +#include "credits.h" // Para Credits +#include "debug.h" // Para Debug +#include "defines.h" // Para WINDOW_CAPTION +#include "ending.h" // Para Ending +#include "ending2.h" // Para Ending2 +#include "external/jail_audio.h" // Para JA_SetMusicVolume, JA_SetSoundV... +#include "game.h" // Para Game, GameMode +#include "game_over.h" // Para GameOver +#include "input.h" // Para Input, InputAction +#include "loading_screen.h" // Para LoadingScreen +#include "logo.h" // Para Logo +#include "options.h" // Para Options, options, OptionsVideo +#include "resource.h" // Para Resource +#include "screen.h" // Para Screen +#include "title.h" // Para Title +#include "ui/notifier.h" // Para Notifier #ifndef _WIN32 #include diff --git a/source/director.h b/source/director.h index 585cac1..0b06b53 100644 --- a/source/director.h +++ b/source/director.h @@ -1,7 +1,6 @@ #pragma once -#include // Para SDL_Renderer -#include // Para SDL_Window +#include #include // Para string diff --git a/source/enemy.cpp b/source/enemy.cpp index 6ba1987..5dfaefc 100644 --- a/source/enemy.cpp +++ b/source/enemy.cpp @@ -1,11 +1,11 @@ #include "enemy.h" -#include // Para SDL_RendererFlip, SDL_FLIP_NONE, SDL_... -#include // Para rand +#include +#include // Para rand -#include "resource.h" // Para Resource -#include "s_animated_sprite.h" // Para SAnimatedSprite -#include "utils.h" // Para stringToColor +#include "resource.h" // Para Resource +#include "sprite/surface_animated_sprite.h" // Para SAnimatedSprite +#include "utils.h" // Para stringToColor // Constructor Enemy::Enemy(const EnemyData& enemy) diff --git a/source/enemy.h b/source/enemy.h index d7301de..18d64a7 100644 --- a/source/enemy.h +++ b/source/enemy.h @@ -1,7 +1,6 @@ #pragma once -#include // Para SDL_Rect -#include // Para Uint8 +#include #include // Para shared_ptr #include // Para string diff --git a/source/external/jail_audio.cpp b/source/external/jail_audio.cpp index ca3a0c5..d699f07 100644 --- a/source/external/jail_audio.cpp +++ b/source/external/jail_audio.cpp @@ -1,7 +1,6 @@ -#include "jail_audio.h" +#include "external/jail_audio.h" -#include // Para SDL_RWFromMem -#include // Para SDL_GetTicks +#include #include // Para uint8_t, uint32_t #include // Para NULL, fseek, fclose, fopen, fread, ftell #include // Para free, malloc diff --git a/source/external/jail_audio.h b/source/external/jail_audio.h index 4dcce55..a242bae 100644 --- a/source/external/jail_audio.h +++ b/source/external/jail_audio.h @@ -1,7 +1,6 @@ #pragma once -#include // Para SDL_AudioFormat -#include // Para Uint32, Uint8 +#include struct JA_Music_t; // lines 5-5 struct JA_Sound_t; // lines 6-6 diff --git a/source/external/jail_shader.cpp b/source/external/jail_shader.cpp index 13a975d..0c89e0e 100644 --- a/source/external/jail_shader.cpp +++ b/source/external/jail_shader.cpp @@ -1,7 +1,6 @@ -#include "jail_shader.h" +#include "external/jail_shader.h" -#include // Para SDL_Point -#include // Para SDL_bool +#include #include // Para strncmp #include // Para basic_ostream, operator<<, endl, cout diff --git a/source/external/jail_shader.h b/source/external/jail_shader.h index 18ae60d..3a928c2 100644 --- a/source/external/jail_shader.h +++ b/source/external/jail_shader.h @@ -1,7 +1,6 @@ #pragma once -#include // Para SDL_Texture -#include // Para SDL_Window +#include #include diff --git a/source/global_events.h b/source/global_events.h index d74cb0c..ad08cf2 100644 --- a/source/global_events.h +++ b/source/global_events.h @@ -1,6 +1,6 @@ #pragma once -#include +#include namespace globalEvents { // Comprueba los eventos que se pueden producir en cualquier sección del juego diff --git a/source/global_inputs.cpp b/source/global_inputs.cpp index 77e8c87..a50c7fd 100644 --- a/source/global_inputs.cpp +++ b/source/global_inputs.cpp @@ -1,16 +1,15 @@ #include "global_inputs.h" -#include // Para SDL_RenderSetIntegerScale -#include // Para SDL_FALSE, SDL_TRUE +#include #include // Para allocator, operator+, char_traits, string #include // Para vector -#include "input.h" // Para Input, InputAction, INPUT_DO_NOT_ALLOW_REPEAT -#include "notifier.h" // Para Notifier, NotificationText -#include "options.h" // Para Options, options, OptionsVideo, Section -#include "screen.h" // Para Screen -#include "utils.h" // Para stringInVector +#include "input.h" // Para Input, InputAction, INPUT_DO_NOT_ALLOW_REPEAT +#include "options.h" // Para Options, options, OptionsVideo, Section +#include "screen.h" // Para Screen +#include "ui/notifier.h" // Para Notifier, NotificationText +#include "utils.h" // Para stringInVector namespace globalInputs { void quit() { diff --git a/source/input.cpp b/source/input.cpp index ba92b79..0b1ad35 100644 --- a/source/input.cpp +++ b/source/input.cpp @@ -1,9 +1,6 @@ #include "input.h" -#include // Para SDL_INIT_GAMECONTROLLER, SDL_InitSubS... -#include // Para SDL_GetError -#include // Para SDL_ENABLE -#include // Para SDL_GetKeyboardState +#include #include // Para find #include // Para basic_ostream, operator<<, cout, endl diff --git a/source/input.h b/source/input.h index bb0afda..194804b 100644 --- a/source/input.h +++ b/source/input.h @@ -1,8 +1,6 @@ #pragma once -#include // Para SDL_GameControllerButton, SDL_G... -#include // Para SDL_Scancode -#include // Para Uint8 +#include #include // Para string, basic_string #include // Para vector diff --git a/source/item.cpp b/source/item.cpp index ca00aa2..0dd88d6 100644 --- a/source/item.cpp +++ b/source/item.cpp @@ -1,12 +1,12 @@ #include "item.h" -#include "resource.h" // Para Resource -#include "s_sprite.h" // Para SSprite + +#include "resource.h" // Para Resource +#include "sprite/surface_sprite.h" // Para SSprite // Constructor Item::Item(ItemData item) : sprite_(std::make_shared(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 sprite_->setClip((item.tile % 10) * ITEM_SIZE_, (item.tile / 10) * ITEM_SIZE_, ITEM_SIZE_, ITEM_SIZE_); collider_ = sprite_->getRect(); @@ -21,22 +21,19 @@ Item::Item(ItemData item) } // Pinta el objeto en pantalla -void Item::render() -{ +void Item::render() { const int INDEX = (counter_ / change_color_speed) % color_.size(); sprite_->render(1, color_.at(INDEX)); } // Obtiene su ubicación -SDL_Point Item::getPos() -{ +SDL_Point Item::getPos() { const SDL_Point p = {sprite_->getX(), sprite_->getY()}; return p; } // Asigna los colores del objeto -void Item::setColors(Uint8 col1, Uint8 col2) -{ +void Item::setColors(Uint8 col1, Uint8 col2) { // Reinicializa el vector de colores color_.clear(); diff --git a/source/item.h b/source/item.h index 5e4fa00..943cd46 100644 --- a/source/item.h +++ b/source/item.h @@ -1,7 +1,6 @@ #pragma once -#include // Para SDL_Rect, SDL_Point -#include // Para Uint8 +#include #include // Para shared_ptr #include // Para string diff --git a/source/item_tracker.h b/source/item_tracker.h index a473b26..db4f69d 100644 --- a/source/item_tracker.h +++ b/source/item_tracker.h @@ -1,6 +1,6 @@ #pragma once -#include // Para SDL_Point +#include #include // Para string, basic_string #include // Para vector diff --git a/source/mouse.cpp b/source/mouse.cpp index 230f63f..7169b8a 100644 --- a/source/mouse.cpp +++ b/source/mouse.cpp @@ -1,7 +1,5 @@ #include "mouse.h" -#include // Para SDL_ShowCursor -#include // Para SDL_GetTicks namespace Mouse { Uint32 cursor_hide_time = 3000; // Tiempo en milisegundos para ocultar el cursor diff --git a/source/mouse.h b/source/mouse.h index 573e7b8..0b1a9ce 100644 --- a/source/mouse.h +++ b/source/mouse.h @@ -1,7 +1,6 @@ #pragma once -#include // Para SDL_Event -#include // Para Uint32 +#include namespace Mouse { extern Uint32 cursor_hide_time; // Tiempo en milisegundos para ocultar el cursor diff --git a/source/options.cpp b/source/options.cpp index 66902ff..16634c7 100644 --- a/source/options.cpp +++ b/source/options.cpp @@ -1,6 +1,6 @@ #include "options.h" -#include // Para SDL_WINDOW_FULLSCREEN_DESKTOP +#include #include // Para find_if #include // Para isspace diff --git a/source/options.h b/source/options.h index 326152f..2b1e575 100644 --- a/source/options.h +++ b/source/options.h @@ -1,6 +1,6 @@ #pragma once -#include // Para Uint32 +#include #include #include // Para string, basic_string diff --git a/source/player.cpp b/source/player.cpp index 9d5c4fe..04ab49d 100644 --- a/source/player.cpp +++ b/source/player.cpp @@ -1,20 +1,21 @@ // IWYU pragma: no_include #include "player.h" -#include // Para max, min -#include // Para ceil, abs -#include "debug.h" // Para Debug -#include "defines.h" // Para RoomBorder::BOTTOM, RoomBorder::LEFT, RoomBorder::RIGHT -#include "input.h" // Para Input, InputAction -#include "jail_audio.h" // Para JA_PlaySound -#include "options.h" // Para Cheat, Options, options -#include "resource.h" // Para Resource -#include "room.h" // Para Room, TileType -#include "s_animated_sprite.h" // Para SAnimatedSprite + +#include // Para max, min +#include // Para ceil, abs + +#include "debug.h" // Para Debug +#include "defines.h" // Para RoomBorder::BOTTOM, RoomBorder::LEFT, RoomBorder::RIGHT +#include "external/jail_audio.h" // Para JA_PlaySound +#include "input.h" // Para Input, InputAction +#include "options.h" // Para Cheat, Options, options +#include "resource.h" // Para Resource +#include "room.h" // Para Room, TileType +#include "sprite/surface_animated_sprite.h" // Para SAnimatedSprite // Constructor -Player::Player(const PlayerData &player) - : room_(player.room) -{ +Player::Player(const PlayerData& player) + : room_(player.room) { // Inicializa algunas variables initSprite(player.texture_path, player.animations_path); setColor(); @@ -38,8 +39,7 @@ Player::Player(const PlayerData &player) } // Pinta el jugador en pantalla -void Player::render() -{ +void Player::render() { sprite_->render(1, color_); #ifdef DEBUG @@ -48,77 +48,61 @@ void Player::render() } // Actualiza las variables del objeto -void Player::update() -{ - if (!is_paused_) - { - checkInput(); // Comprueba las entradas y modifica variables - move(); // Recalcula la posición del jugador - animate(); // Establece la animación del jugador - checkBorders(); // Comprueba si está situado en alguno de los cuatro bordes de la habitación - checkJumpEnd(); // Comprueba si ha finalizado el salto al alcanzar la altura de inicio - checkKillingTiles(); // Comprueba que el jugador no toque ningun tile de los que matan} +void Player::update() { + if (!is_paused_) { + checkInput(); // Comprueba las entradas y modifica variables + move(); // Recalcula la posición del jugador + animate(); // Establece la animación del jugador + checkBorders(); // Comprueba si está situado en alguno de los cuatro bordes de la habitación + checkJumpEnd(); // Comprueba si ha finalizado el salto al alcanzar la altura de inicio + checkKillingTiles(); // Comprueba que el jugador no toque ningun tile de los que matan} } } // Comprueba las entradas y modifica variables -void Player::checkInput() -{ +void Player::checkInput() { // Solo comprueba las entradas de dirección cuando está sobre una superficie - if (state_ != PlayerState::STANDING) - { + if (state_ != PlayerState::STANDING) { return; } - if (!auto_movement_) - { + if (!auto_movement_) { // Comprueba las entradas de desplazamiento lateral solo en el caso de no estar enganchado a una superficie automatica - if (Input::get()->checkInput(InputAction::LEFT)) - { + if (Input::get()->checkInput(InputAction::LEFT)) { vx_ = -0.6f; sprite_->setFlip(SDL_FLIP_HORIZONTAL); } - else if (Input::get()->checkInput(InputAction::RIGHT)) - { + else if (Input::get()->checkInput(InputAction::RIGHT)) { vx_ = 0.6f; sprite_->setFlip(SDL_FLIP_NONE); } - else - { + else { // No se pulsa ninguna dirección vx_ = 0.0f; - if (isOnAutoSurface()) - { + if (isOnAutoSurface()) { // Si deja de moverse sobre una superficie se engancha auto_movement_ = true; } } - } - else - { // El movimiento lo proporciona la superficie + } else { // El movimiento lo proporciona la superficie vx_ = 0.6f * room_->getAutoSurfaceDirection(); - if (vx_ > 0.0f) - { + if (vx_ > 0.0f) { sprite_->setFlip(SDL_FLIP_NONE); - } - else - { + } else { sprite_->setFlip(SDL_FLIP_HORIZONTAL); } } - if (Input::get()->checkInput(InputAction::JUMP)) - { + if (Input::get()->checkInput(InputAction::JUMP)) { // Solo puede saltar si ademas de estar (state == s_standing) // Esta sobre el suelo, rampa o suelo que se mueve // Esto es para evitar el salto desde el vacio al cambiar de pantalla verticalmente // Ya que se coloca el estado s_standing al cambiar de pantalla - if (isOnFloor() || isOnAutoSurface()) - { + if (isOnFloor() || isOnAutoSurface()) { setState(PlayerState::JUMPING); vy_ = -MAX_VY_; jump_init_pos_ = y_; @@ -128,61 +112,50 @@ void Player::checkInput() } // Comprueba si está situado en alguno de los cuatro bordes de la habitación -void Player::checkBorders() -{ - if (x_ < PLAY_AREA_LEFT) - { +void Player::checkBorders() { + if (x_ < PLAY_AREA_LEFT) { border_ = RoomBorder::LEFT; is_on_border_ = true; } - else if (x_ + WIDTH_ > PLAY_AREA_RIGHT) - { + else if (x_ + WIDTH_ > PLAY_AREA_RIGHT) { border_ = RoomBorder::RIGHT; is_on_border_ = true; } - else if (y_ < PLAY_AREA_TOP) - { + else if (y_ < PLAY_AREA_TOP) { border_ = RoomBorder::TOP; is_on_border_ = true; } - else if (y_ + HEIGHT_ > PLAY_AREA_BOTTOM) - { + else if (y_ + HEIGHT_ > PLAY_AREA_BOTTOM) { border_ = RoomBorder::BOTTOM; is_on_border_ = true; } - else - { + else { is_on_border_ = false; } } // Comprueba el estado del jugador -void Player::checkState() -{ +void Player::checkState() { // Actualiza las variables en función del estado - if (state_ == PlayerState::FALLING) - { + if (state_ == PlayerState::FALLING) { vx_ = 0.0f; vy_ = MAX_VY_; falling_counter_++; playFallSound(); } - else if (state_ == PlayerState::STANDING) - { - if (previous_state_ == PlayerState::FALLING && falling_counter_ > MAX_FALLING_HEIGHT_) - { // Si cae de muy alto, el jugador muere + else if (state_ == PlayerState::STANDING) { + if (previous_state_ == PlayerState::FALLING && falling_counter_ > MAX_FALLING_HEIGHT_) { // Si cae de muy alto, el jugador muere is_alive_ = false; } vy_ = 0.0f; jumping_counter_ = 0; falling_counter_ = 0; - if (!isOnFloor() && !isOnAutoSurface() && !isOnDownSlope()) - { + if (!isOnFloor() && !isOnAutoSurface() && !isOnDownSlope()) { setState(PlayerState::FALLING); vx_ = 0.0f; vy_ = MAX_VY_; @@ -191,8 +164,7 @@ void Player::checkState() } } - else if (state_ == PlayerState::JUMPING) - { + else if (state_ == PlayerState::JUMPING) { falling_counter_ = 0; jumping_counter_++; playJumpSound(); @@ -200,30 +172,28 @@ void Player::checkState() } // Cambia al jugador de un borde al opuesto. Util para el cambio de pantalla -void Player::switchBorders() -{ - switch (border_) - { - case RoomBorder::TOP: - y_ = PLAY_AREA_BOTTOM - HEIGHT_ - BLOCK; - setState(PlayerState::STANDING); - break; +void Player::switchBorders() { + switch (border_) { + case RoomBorder::TOP: + y_ = PLAY_AREA_BOTTOM - HEIGHT_ - BLOCK; + setState(PlayerState::STANDING); + break; - case RoomBorder::BOTTOM: - y_ = PLAY_AREA_TOP; - setState(PlayerState::STANDING); - break; + case RoomBorder::BOTTOM: + y_ = PLAY_AREA_TOP; + setState(PlayerState::STANDING); + break; - case RoomBorder::RIGHT: - x_ = PLAY_AREA_LEFT; - break; + case RoomBorder::RIGHT: + x_ = PLAY_AREA_LEFT; + break; - case RoomBorder::LEFT: - x_ = PLAY_AREA_RIGHT - WIDTH_; - break; + case RoomBorder::LEFT: + x_ = PLAY_AREA_RIGHT - WIDTH_; + break; - default: - break; + default: + break; } is_on_border_ = false; @@ -232,42 +202,37 @@ void Player::switchBorders() } // Aplica gravedad al jugador -void Player::applyGravity() -{ +void Player::applyGravity() { constexpr float GRAVITY_FORCE = 0.035f; // La gravedad solo se aplica cuando el jugador esta saltando // Nunca mientras cae o esta de pie - if (state_ == PlayerState::JUMPING) - { + if (state_ == PlayerState::JUMPING) { vy_ += GRAVITY_FORCE; - if (vy_ > MAX_VY_) - { + if (vy_ > MAX_VY_) { vy_ = MAX_VY_; } } } // Recalcula la posición del jugador y su animación -void Player::move() -{ - last_position_ = {static_cast(x_), static_cast(y_)}; // Guarda la posicion actual antes de modificarla - applyGravity(); // Aplica gravedad al jugador - checkState(); // Comprueba el estado del jugador +void Player::move() { + last_position_ = {static_cast(x_), static_cast(y_)}; // Guarda la posicion actual antes de modificarla + applyGravity(); // Aplica gravedad al jugador + checkState(); // Comprueba el estado del jugador #ifdef DEBUG debug_color_ = static_cast(PaletteColor::GREEN); #endif // Se mueve hacia la izquierda - if (vx_ < 0.0f) - { + if (vx_ < 0.0f) { // Crea el rectangulo de proyección en el eje X para ver si colisiona SDL_Rect proj; proj.x = static_cast(x_ + vx_); proj.y = static_cast(y_); proj.h = HEIGHT_; - proj.w = static_cast(std::ceil(std::fabs(vx_))); // Para evitar que tenga un ancho de 0 pixels + proj.w = static_cast(std::ceil(std::fabs(vx_))); // Para evitar que tenga un ancho de 0 pixels #ifdef DEBUG debug_rect_x_ = proj; @@ -277,44 +242,37 @@ void Player::move() const int POS = room_->checkRightSurfaces(&proj); // Calcula la nueva posición - if (POS == -1) - { + if (POS == -1) { // Si no hay colisión x_ += vx_; - } - else - { + } else { // Si hay colisión lo mueve hasta donde no colisiona x_ = POS + 1; } // Si ha tocado alguna rampa mientras camina (sin saltar), asciende - if (state_ != PlayerState::JUMPING) - { - const LineVertical LEFT_SIDE = {static_cast(x_), static_cast(y_) + HEIGHT_ - 2, static_cast(y_) + HEIGHT_ - 1}; // Comprueba solo los dos pixels de abajo + if (state_ != PlayerState::JUMPING) { + const LineVertical LEFT_SIDE = {static_cast(x_), static_cast(y_) + HEIGHT_ - 2, static_cast(y_) + HEIGHT_ - 1}; // Comprueba solo los dos pixels de abajo const int LY = room_->checkLeftSlopes(&LEFT_SIDE); - if (LY > -1) - { + if (LY > -1) { y_ = LY - HEIGHT_; } } // Si está bajando la rampa, recoloca al jugador - if (isOnDownSlope() && state_ != PlayerState::JUMPING) - { + if (isOnDownSlope() && state_ != PlayerState::JUMPING) { y_ += 1; } } // Se mueve hacia la derecha - else if (vx_ > 0.0f) - { + else if (vx_ > 0.0f) { // Crea el rectangulo de proyección en el eje X para ver si colisiona SDL_Rect proj; proj.x = static_cast(x_) + WIDTH_; proj.y = static_cast(y_); proj.h = HEIGHT_; - proj.w = ceil(vx_); // Para evitar que tenga un ancho de 0 pixels + proj.w = ceil(vx_); // Para evitar que tenga un ancho de 0 pixels #ifdef DEBUG debug_rect_x_ = proj; @@ -324,38 +282,31 @@ void Player::move() const int POS = room_->checkLeftSurfaces(&proj); // Calcula la nueva posición - if (POS == -1) - { + if (POS == -1) { // Si no hay colisión x_ += vx_; - } - else - { + } else { // Si hay colisión lo mueve hasta donde no colisiona x_ = POS - WIDTH_; } // Si ha tocado alguna rampa mientras camina (sin saltar), asciende - if (state_ != PlayerState::JUMPING) - { - const LineVertical RIGHT_SIDE = {static_cast(x_) + WIDTH_ - 1, static_cast(y_) + HEIGHT_ - 2, static_cast(y_) + HEIGHT_ - 1}; // Comprueba solo los dos pixels de abajo + if (state_ != PlayerState::JUMPING) { + const LineVertical RIGHT_SIDE = {static_cast(x_) + WIDTH_ - 1, static_cast(y_) + HEIGHT_ - 2, static_cast(y_) + HEIGHT_ - 1}; // Comprueba solo los dos pixels de abajo const int RY = room_->checkRightSlopes(&RIGHT_SIDE); - if (RY > -1) - { + if (RY > -1) { y_ = RY - HEIGHT_; } } // Si está bajando la rampa, recoloca al jugador - if (isOnDownSlope() && state_ != PlayerState::JUMPING) - { + if (isOnDownSlope() && state_ != PlayerState::JUMPING) { y_ += 1; } } // Si ha salido del suelo, el jugador cae - if (state_ == PlayerState::STANDING && !isOnFloor()) - { + if (state_ == PlayerState::STANDING && !isOnFloor()) { setState(PlayerState::FALLING); // Deja de estar enganchado a la superficie automatica @@ -363,20 +314,18 @@ void Player::move() } // Si ha salido de una superficie automatica, detiene el movimiento automatico - if (state_ == PlayerState::STANDING && isOnFloor() && !isOnAutoSurface()) - { + if (state_ == PlayerState::STANDING && isOnFloor() && !isOnAutoSurface()) { // Deja de estar enganchado a la superficie automatica auto_movement_ = false; } // Se mueve hacia arriba - if (vy_ < 0.0f) - { + if (vy_ < 0.0f) { // Crea el rectangulo de proyección en el eje Y para ver si colisiona SDL_Rect proj; proj.x = static_cast(x_); proj.y = static_cast(y_ + vy_); - proj.h = static_cast(std::ceil(std::fabs(vy_))); // Para evitar que tenga una altura de 0 pixels + proj.h = static_cast(std::ceil(std::fabs(vy_))); // Para evitar que tenga una altura de 0 pixels proj.w = WIDTH_; #ifdef DEBUG @@ -387,13 +336,10 @@ void Player::move() const int POS = room_->checkBottomSurfaces(&proj); // Calcula la nueva posición - if (POS == -1) - { + if (POS == -1) { // Si no hay colisión y_ += vy_; - } - else - { + } else { // Si hay colisión lo mueve hasta donde no colisiona y entra en caída y_ = POS + 1; setState(PlayerState::FALLING); @@ -401,13 +347,12 @@ void Player::move() } // Se mueve hacia abajo - else if (vy_ > 0.0f) - { + else if (vy_ > 0.0f) { // Crea el rectangulo de proyección en el eje Y para ver si colisiona SDL_Rect proj; proj.x = static_cast(x_); proj.y = static_cast(y_) + HEIGHT_; - proj.h = ceil(vy_); // Para evitar que tenga una altura de 0 pixels + proj.h = ceil(vy_); // Para evitar que tenga una altura de 0 pixels proj.w = WIDTH_; #ifdef DEBUG @@ -416,25 +361,20 @@ void Player::move() // Comprueba la colisión con las superficies normales y las automáticas const int POS = std::max(room_->checkTopSurfaces(&proj), room_->checkAutoSurfaces(&proj)); - if (POS > -1) - { + if (POS > -1) { // Si hay colisión lo mueve hasta donde no colisiona y pasa a estar sobre la superficie y_ = POS - HEIGHT_; setState(PlayerState::STANDING); // Deja de estar enganchado a la superficie automatica auto_movement_ = false; - } - else - { + } else { // 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 const LineVertical LEFT_SIDE = {proj.x, proj.y, proj.y + proj.h - 1}; const LineVertical RIGHT_SIDE = {proj.x + proj.w - 1, proj.y, proj.y + proj.h - 1}; const int 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 // Calcula la nueva posición y_ = POINT - HEIGHT_; @@ -443,9 +383,7 @@ void Player::move() debug_color_ = static_cast(PaletteColor::YELLOW); debug_point_ = {(int)x_ + (WIDTH_ / 2), POINT}; #endif - } - else - { + } else { // No está saltando y no hay colisón con una rampa // Calcula la nueva posición y_ += vy_; @@ -453,9 +391,7 @@ void Player::move() debug_color_ = static_cast(PaletteColor::RED); #endif } - } - else - { + } else { // Esta saltando y no hay colisión con los muros // Calcula la nueva posición y_ += vy_; @@ -463,8 +399,8 @@ void Player::move() } } - placeSprite(); // Coloca el sprite en la nueva posición - collider_box_ = getRect(); // Actualiza el rectangulo de colisión + placeSprite(); // Coloca el sprite en la nueva posición + collider_box_ = getRect(); // Actualiza el rectangulo de colisión #ifdef DEBUG Debug::get()->add("RECT_X: " + std::to_string(debug_rect_x_.x) + "," + std::to_string(debug_rect_x_.y) + "," + std::to_string(debug_rect_x_.w) + "," + std::to_string(debug_rect_x_.h)); @@ -473,23 +409,17 @@ void Player::move() } // Establece la animación del jugador -void Player::animate() -{ - if (vx_ != 0) - { +void Player::animate() { + if (vx_ != 0) { sprite_->update(); } } // Comprueba si ha finalizado el salto al alcanzar la altura de inicio -void Player::checkJumpEnd() -{ - if (state_ == PlayerState::JUMPING) - { - if (vy_ > 0) - { - if (y_ >= jump_init_pos_) - { +void Player::checkJumpEnd() { + if (state_ == PlayerState::JUMPING) { + if (vy_ > 0) { + if (y_ >= jump_init_pos_) { // Si alcanza la altura de salto inicial, pasa al estado de caída setState(PlayerState::FALLING); vy_ = MAX_VY_; @@ -500,10 +430,8 @@ void Player::checkJumpEnd() } // Calcula y reproduce el sonido de salto -void Player::playJumpSound() -{ - if (jumping_counter_ % 4 == 0) - { +void Player::playJumpSound() { + if (jumping_counter_ % 4 == 0) { JA_PlaySound(jumping_sound_[jumping_counter_ / 4]); } @@ -513,10 +441,8 @@ void Player::playJumpSound() } // Calcula y reproduce el sonido de caer -void Player::playFallSound() -{ - if (falling_counter_ % 4 == 0) - { +void Player::playFallSound() { + if (falling_counter_ % 4 == 0) { JA_PlaySound(falling_sound_[std::min((falling_counter_ / 4), (int)falling_sound_.size() - 1)]); } @@ -526,8 +452,7 @@ void Player::playFallSound() } // Comprueba si el jugador tiene suelo debajo de los pies -bool Player::isOnFloor() -{ +bool Player::isOnFloor() { bool on_floor = false; bool on_slope_l = false; bool on_slope_r = false; @@ -535,8 +460,7 @@ bool Player::isOnFloor() updateFeet(); // Comprueba las superficies - for (auto f : under_feet_) - { + for (auto f : under_feet_) { on_floor |= room_->checkTopSurfaces(&f); on_floor |= room_->checkAutoSurfaces(&f); } @@ -546,18 +470,15 @@ bool Player::isOnFloor() on_slope_r = room_->checkRightSlopes(&under_feet_[1]); #ifdef DEBUG - if (on_floor) - { + if (on_floor) { Debug::get()->add("ON_FLOOR"); } - if (on_slope_l) - { + if (on_slope_l) { Debug::get()->add("ON_SLOPE_L: " + std::to_string(under_feet_[0].x) + "," + std::to_string(under_feet_[0].y)); } - if (on_slope_r) - { + if (on_slope_r) { Debug::get()->add("ON_SLOPE_R: " + std::to_string(under_feet_[1].x) + "," + std::to_string(under_feet_[1].y)); } #endif @@ -566,21 +487,18 @@ bool Player::isOnFloor() } // Comprueba si el jugador esta sobre una superficie automática -bool Player::isOnAutoSurface() -{ +bool Player::isOnAutoSurface() { bool on_auto_surface = false; updateFeet(); // Comprueba las superficies - for (auto f : under_feet_) - { + for (auto f : under_feet_) { on_auto_surface |= room_->checkAutoSurfaces(&f); } #ifdef DEBUG - if (on_auto_surface) - { + if (on_auto_surface) { Debug::get()->add("ON_AUTO_SURFACE"); } #endif @@ -589,8 +507,7 @@ bool Player::isOnAutoSurface() } // Comprueba si el jugador está sobre una rampa hacia abajo -bool Player::isOnDownSlope() -{ +bool Player::isOnDownSlope() { bool on_slope = false; updateFeet(); @@ -605,8 +522,7 @@ bool Player::isOnDownSlope() on_slope |= room_->checkRightSlopes(&under_feet_[1]); #ifdef DEBUG - if (on_slope) - { + if (on_slope) { Debug::get()->add("ON_DOWN_SLOPE"); } #endif @@ -615,44 +531,34 @@ bool Player::isOnDownSlope() } // Comprueba que el jugador no toque ningun tile de los que matan -bool Player::checkKillingTiles() -{ +bool Player::checkKillingTiles() { // Actualiza los puntos de colisión updateColliderPoints(); // Comprueba si hay contacto y retorna en cuanto se encuentra colisión - for (const auto &c : collider_points_) - { - if (room_->getTile(c) == TileType::KILL) - { - is_alive_ = false; // Mata al jugador inmediatamente - return true; // Retorna en cuanto se detecta una colisión + for (const auto& c : collider_points_) { + if (room_->getTile(c) == TileType::KILL) { + is_alive_ = false; // Mata al jugador inmediatamente + return true; // Retorna en cuanto se detecta una colisión } } - return false; // No se encontró ninguna colisión + return false; // No se encontró ninguna colisión } // Establece el color del jugador -void Player::setColor() -{ - if (options.cheats.invincible == Cheat::CheatState::ENABLED) - { +void Player::setColor() { + if (options.cheats.invincible == Cheat::CheatState::ENABLED) { color_ = static_cast(PaletteColor::CYAN); - } - else if (options.cheats.infinite_lives == Cheat::CheatState::ENABLED) - { + } else if (options.cheats.infinite_lives == Cheat::CheatState::ENABLED) { color_ = static_cast(PaletteColor::YELLOW); - } - else - { + } else { color_ = static_cast(PaletteColor::WHITE); } } // Actualiza los puntos de colisión -void Player::updateColliderPoints() -{ +void Player::updateColliderPoints() { const SDL_Rect rect = getRect(); collider_points_[0] = {rect.x, rect.y}; collider_points_[1] = {rect.x + 7, rect.y}; @@ -665,8 +571,7 @@ void Player::updateColliderPoints() } // Actualiza los puntos de los pies -void Player::updateFeet() -{ +void Player::updateFeet() { const SDL_Point p = {static_cast(x_), static_cast(y_)}; under_feet_[0] = {p.x, p.y + HEIGHT_}; @@ -677,8 +582,7 @@ void Player::updateFeet() } // Cambia el estado del jugador -void Player::setState(PlayerState value) -{ +void Player::setState(PlayerState value) { previous_state_ = state_; state_ = value; @@ -686,26 +590,22 @@ void Player::setState(PlayerState value) } // Inicializa los sonidos de salto y caida -void Player::initSounds() -{ +void Player::initSounds() { jumping_sound_.clear(); falling_sound_.clear(); - for (int i = 1; i <= 24; ++i) - { + for (int i = 1; i <= 24; ++i) { std::string soundFile = "jump" + std::to_string(i) + ".wav"; jumping_sound_.push_back(Resource::get()->getSound(soundFile)); - if (i >= 11) - { + if (i >= 11) { falling_sound_.push_back(Resource::get()->getSound(soundFile)); } } } // Aplica los valores de spawn al jugador -void Player::applySpawnValues(const PlayerSpawn &spawn) -{ +void Player::applySpawnValues(const PlayerSpawn& spawn) { x_ = spawn.x; y_ = spawn.y; vx_ = spawn.vx; @@ -716,8 +616,7 @@ void Player::applySpawnValues(const PlayerSpawn &spawn) } // Inicializa el sprite del jugador -void Player::initSprite(const std::string &surface_path, const std::string &animations_path) -{ +void Player::initSprite(const std::string& surface_path, const std::string& animations_path) { auto surface = Resource::get()->getSurface(surface_path); auto animations = Resource::get()->getAnimations(animations_path); @@ -729,27 +628,23 @@ void Player::initSprite(const std::string &surface_path, const std::string &anim #ifdef DEBUG // Pinta la información de debug del jugador -void Player::renderDebugInfo() -{ - if (Debug::get()->getEnabled()) - { - auto surface = Screen::get()->getRendererSurface(); +void Player::renderDebugInfo() { + if (Debug::get()->getEnabled()) { + auto surface = Screen::get()->getRendererSurface(); // Pinta los underfeet - surface->putPixel(under_feet_[0].x, under_feet_[0].y,static_cast(PaletteColor::BRIGHT_MAGENTA)); - surface->putPixel(under_feet_[1].x, under_feet_[1].y,static_cast(PaletteColor::BRIGHT_MAGENTA)); + surface->putPixel(under_feet_[0].x, under_feet_[0].y, static_cast(PaletteColor::BRIGHT_MAGENTA)); + surface->putPixel(under_feet_[1].x, under_feet_[1].y, static_cast(PaletteColor::BRIGHT_MAGENTA)); // Pinta rectangulo del jugador SDL_Rect rect = getRect(); surface->drawRectBorder(&rect, static_cast(PaletteColor::BRIGHT_CYAN)); // Pinta el rectangulo de movimiento - if (vx_ != 0.0f) - { + if (vx_ != 0.0f) { surface->fillRect(&debug_rect_x_, static_cast(PaletteColor::BRIGHT_RED)); } - if (vy_ != 0.0f) - { + if (vy_ != 0.0f) { surface->fillRect(&debug_rect_y_, static_cast(PaletteColor::BRIGHT_RED)); } @@ -757,4 +652,4 @@ void Player::renderDebugInfo() surface->putPixel(debug_point_.x, debug_point_.y, rand() % 16); } } -#endif // DEBUG \ No newline at end of file +#endif // DEBUG \ No newline at end of file diff --git a/source/player.h b/source/player.h index 6fdc104..49f8e50 100644 --- a/source/player.h +++ b/source/player.h @@ -1,8 +1,6 @@ #pragma once -#include // Para SDL_Rect, SDL_Point -#include // Para SDL_RendererFlip, SDL_FLIP_NONE -#include // Para Uint8 +#include #include // Para shared_ptr, __shared_ptr_access #include // Para string @@ -10,9 +8,9 @@ #include "defines.h" // Para BORDER_TOP, BLOCK #include "room.h" -#include "s_animated_sprite.h" // Para SAnimatedSprite -#include "utils.h" // Para Color -struct JA_Sound_t; // lines 13-13 +#include "sprite/surface_animated_sprite.h" // Para SAnimatedSprite +#include "utils.h" // Para Color +struct JA_Sound_t; // lines 13-13 enum class PlayerState { STANDING, diff --git a/source/resource.cpp b/source/resource.cpp index 12c0100..ed8acd9 100644 --- a/source/resource.cpp +++ b/source/resource.cpp @@ -1,24 +1,21 @@ #include "resource.h" -#include // Para SDL_PollEvent, SDL_Event, SDL_KEYDOWN -#include // Para SDLK_ESCAPE -#include // Para SDL_Rect -#include // Para Uint8 -#include // Para exit, size_t +#include +#include // Para exit, size_t #include // Para find_if #include // Para basic_ostream, operator<<, endl, cout #include // Para runtime_error -#include "asset.h" // Para AssetType, Asset -#include "jail_audio.h" // Para JA_DeleteMusic, JA_DeleteSound, JA_Loa... -#include "options.h" // Para Options, OptionsGame, options -#include "room.h" // Para RoomData, loadRoomFile, loadRoomTileFile -#include "screen.h" // Para Screen -#include "text.h" // Para Text, loadTextFile -#include "utils.h" // Para getFileName, printWithDots, PaletteColor -struct JA_Music_t; // lines 17-17 -struct JA_Sound_t; // lines 18-18 +#include "asset.h" // Para AssetType, Asset +#include "external/jail_audio.h" // Para JA_DeleteMusic, JA_DeleteSound, JA_Loa... +#include "options.h" // Para Options, OptionsGame, options +#include "room.h" // Para RoomData, loadRoomFile, loadRoomTileFile +#include "screen.h" // Para Screen +#include "text.h" // Para Text, loadTextFile +#include "utils.h" // Para getFileName, printWithDots, PaletteColor +struct JA_Music_t; // lines 17-17 +struct JA_Sound_t; // lines 18-18 // [SINGLETON] Hay que definir las variables estáticas, desde el .h sólo la hemos declarado Resource* Resource::resource_ = nullptr; diff --git a/source/resource.h b/source/resource.h index 8433daa..8806705 100644 --- a/source/resource.h +++ b/source/resource.h @@ -1,258 +1,257 @@ #pragma once -#include // Para shared_ptr -#include // Para string -#include // Para vector -#include "s_animated_sprite.h" // Para AnimationsFileBuffer -#include "room.h" // Para room_t -#include "text.h" // Para Text, TextFile -#include "surface.h" // Para Surface -struct JA_Music_t; // lines 11-11 -struct JA_Sound_t; // lines 12-12 +#include // Para shared_ptr +#include // Para string +#include // Para vector + +#include "room.h" // Para room_t +#include "sprite/surface_animated_sprite.h" // Para AnimationsFileBuffer +#include "surface.h" // Para Surface +#include "text.h" // Para Text, TextFile +struct JA_Music_t; // lines 11-11 +struct JA_Sound_t; // lines 12-12 // Estructura para almacenar ficheros de sonido y su nombre -struct ResourceSound -{ - std::string name; // Nombre del sonido - JA_Sound_t *sound; // Objeto con el sonido +struct ResourceSound { + std::string name; // Nombre del sonido + JA_Sound_t* sound; // Objeto con el sonido - // Constructor - ResourceSound(const std::string &name, JA_Sound_t *sound) - : name(name), sound(sound) {} + // Constructor + ResourceSound(const std::string& name, JA_Sound_t* sound) + : name(name), + sound(sound) {} }; // Estructura para almacenar ficheros musicales y su nombre -struct ResourceMusic -{ - std::string name; // Nombre de la musica - JA_Music_t *music; // Objeto con la música +struct ResourceMusic { + std::string name; // Nombre de la musica + JA_Music_t* music; // Objeto con la música - // Constructor - ResourceMusic(const std::string &name, JA_Music_t *music) - : name(name), music(music) {} + // Constructor + ResourceMusic(const std::string& name, JA_Music_t* music) + : name(name), + music(music) {} }; // Estructura para almacenar objetos Surface y su nombre -struct ResourceSurface -{ - std::string name; // Nombre de la surface - std::shared_ptr surface; // Objeto con la surface +struct ResourceSurface { + std::string name; // Nombre de la surface + std::shared_ptr surface; // Objeto con la surface - // Constructor - ResourceSurface(const std::string &name, std::shared_ptr surface) - : name(name), surface(surface) {} + // Constructor + ResourceSurface(const std::string& name, std::shared_ptr surface) + : name(name), + surface(surface) {} }; // Estructura para almacenar objetos Palette y su nombre -struct ResourcePalette -{ - std::string name; // Nombre de la surface - Palette palette; // Paleta +struct ResourcePalette { + std::string name; // Nombre de la surface + Palette palette; // Paleta - // Constructor - ResourcePalette(const std::string &name, Palette palette) - : name(name), palette(palette) {} + // Constructor + ResourcePalette(const std::string& name, Palette palette) + : name(name), + palette(palette) {} }; // Estructura para almacenar ficheros TextFile y su nombre -struct ResourceTextFile -{ - std::string name; // Nombre del fichero - std::shared_ptr text_file; // Objeto con los descriptores de la fuente de texto +struct ResourceTextFile { + std::string name; // Nombre del fichero + std::shared_ptr text_file; // Objeto con los descriptores de la fuente de texto - // Constructor - ResourceTextFile(const std::string &name, std::shared_ptr text_file) - : name(name), text_file(text_file) {} + // Constructor + ResourceTextFile(const std::string& name, std::shared_ptr text_file) + : name(name), + text_file(text_file) {} }; // Estructura para almacenar objetos Text y su nombre -struct ResourceText -{ - std::string name; // Nombre del objeto - std::shared_ptr text; // Objeto +struct ResourceText { + std::string name; // Nombre del objeto + std::shared_ptr text; // Objeto - // Constructor - ResourceText(const std::string &name, std::shared_ptr text) - : name(name), text(text) {} + // Constructor + ResourceText(const std::string& name, std::shared_ptr text) + : name(name), + text(text) {} }; // Estructura para almacenar ficheros animaciones y su nombre -struct ResourceAnimation -{ - std::string name; // Nombre del fichero - Animations animation; // Objeto con las animaciones +struct ResourceAnimation { + std::string name; // Nombre del fichero + Animations animation; // Objeto con las animaciones - // Constructor - ResourceAnimation(const std::string &name, const Animations &animation) - : name(name), animation(animation) {} + // Constructor + ResourceAnimation(const std::string& name, const Animations& animation) + : name(name), + animation(animation) {} }; // Estructura para almacenar ficheros con el mapa de tiles de una habitación y su nombre -struct ResourceTileMap -{ - std::string name; // Nombre del mapa de tiles - std::vector tileMap; // Vector con los indices del mapa de tiles +struct ResourceTileMap { + std::string name; // Nombre del mapa de tiles + std::vector tileMap; // Vector con los indices del mapa de tiles - // Constructor - ResourceTileMap(const std::string &name, const std::vector &tileMap) - : name(name), tileMap(tileMap) {} + // Constructor + ResourceTileMap(const std::string& name, const std::vector& tileMap) + : name(name), + tileMap(tileMap) {} }; // Estructura para almacenar habitaciones y su nombre -struct ResourceRoom -{ - std::string name; // Nombre de la habitación - std::shared_ptr room; // Habitación +struct ResourceRoom { + std::string name; // Nombre de la habitación + std::shared_ptr room; // Habitación - // Constructor - ResourceRoom(const std::string &name, std::shared_ptr room) - : name(name), room(room) {} + // Constructor + ResourceRoom(const std::string& name, std::shared_ptr room) + : name(name), + room(room) {} }; // Estructura para llevar la cuenta de los recursos cargados -struct ResourceCount -{ - int total; // Número total de recursos - int loaded; // Número de recursos cargados +struct ResourceCount { + int total; // Número total de recursos + int loaded; // Número de recursos cargados - // Constructor - ResourceCount() - : total(0), loaded(0) {} + // Constructor + ResourceCount() + : total(0), + loaded(0) {} - // Constructor - ResourceCount(int total, int loaded) - : total(total), loaded(loaded) {} + // Constructor + ResourceCount(int total, int loaded) + : total(total), + loaded(loaded) {} - // Añade una cantidad a los recursos cargados - void add(int amount) - { - loaded += amount; - } + // Añade una cantidad a los recursos cargados + void add(int amount) { + loaded += amount; + } - // Obtiene el porcentaje de recursos cargados - float getPercentage() - { - return static_cast(loaded) / static_cast(total); - } + // Obtiene el porcentaje de recursos cargados + float getPercentage() { + return static_cast(loaded) / static_cast(total); + } }; -class Resource -{ -private: - // [SINGLETON] Objeto resource privado para Don Melitón - static Resource *resource_; +class Resource { + private: + // [SINGLETON] Objeto resource privado para Don Melitón + static Resource* resource_; - std::vector sounds_; // Vector con los sonidos - std::vector musics_; // Vector con las musicas - std::vector surfaces_; // Vector con las surfaces - std::vector palettes_; // Vector con las paletas - std::vector text_files_; // Vector con los ficheros de texto - std::vector texts_; // Vector con los objetos de texto - std::vector animations_; // Vector con las animaciones - std::vector tile_maps_; // Vector con los mapas de tiles - std::vector rooms_; // Vector con las habitaciones + std::vector sounds_; // Vector con los sonidos + std::vector musics_; // Vector con las musicas + std::vector surfaces_; // Vector con las surfaces + std::vector palettes_; // Vector con las paletas + std::vector text_files_; // Vector con los ficheros de texto + std::vector texts_; // Vector con los objetos de texto + std::vector animations_; // Vector con las animaciones + std::vector tile_maps_; // Vector con los mapas de tiles + std::vector rooms_; // Vector con las habitaciones - ResourceCount count_; // Contador de recursos + ResourceCount count_; // Contador de recursos - // Carga los sonidos - void loadSounds(); + // Carga los sonidos + void loadSounds(); - // Carga las musicas - void loadMusics(); + // Carga las musicas + void loadMusics(); - // Carga las surfaces - void loadSurfaces(); + // Carga las surfaces + void loadSurfaces(); - // Carga las paletas - void loadPalettes(); + // Carga las paletas + void loadPalettes(); - // Carga los ficheros de texto - void loadTextFiles(); + // Carga los ficheros de texto + void loadTextFiles(); - // Carga las animaciones - void loadAnimations(); + // Carga las animaciones + void loadAnimations(); - // Carga los mapas de tiles - void loadTileMaps(); + // Carga los mapas de tiles + void loadTileMaps(); - // Carga las habitaciones - void loadRooms(); + // Carga las habitaciones + void loadRooms(); - // Crea los objetos de texto - void createText(); + // Crea los objetos de texto + void createText(); - // Vacia todos los vectores de recursos - void clear(); + // Vacia todos los vectores de recursos + void clear(); - // Carga todos los recursos - void load(); + // Carga todos los recursos + void load(); - // Vacía el vector de sonidos - void clearSounds(); + // Vacía el vector de sonidos + void clearSounds(); - // Vacía el vector de musicas - void clearMusics(); + // Vacía el vector de musicas + void clearMusics(); - // Calcula el numero de recursos para cargar - void calculateTotal(); + // Calcula el numero de recursos para cargar + void calculateTotal(); - // Muestra el progreso de carga - void renderProgress(); + // Muestra el progreso de carga + void renderProgress(); - // Comprueba los eventos - void checkEvents(); + // Comprueba los eventos + void checkEvents(); - // Actualiza el progreso de carga - void updateLoadingProgress(int steps = 5); + // Actualiza el progreso de carga + void updateLoadingProgress(int steps = 5); - // [SINGLETON] Ahora el constructor y el destructor son privados, para no poder crear objetos resource desde fuera + // [SINGLETON] Ahora el constructor y el destructor son privados, para no poder crear objetos resource desde fuera - // Constructor - Resource(); + // Constructor + Resource(); - // Destructor - ~Resource() = default; + // Destructor + ~Resource() = default; -public: - // [SINGLETON] Crearemos el objeto resource con esta función estática - static void init(); + public: + // [SINGLETON] Crearemos el objeto resource con esta función estática + static void init(); - // [SINGLETON] Destruiremos el objeto resource con esta función estática - static void destroy(); + // [SINGLETON] Destruiremos el objeto resource con esta función estática + static void destroy(); - // [SINGLETON] Con este método obtenemos el objeto resource y podemos trabajar con él - static Resource *get(); + // [SINGLETON] Con este método obtenemos el objeto resource y podemos trabajar con él + static Resource* get(); - // Obtiene el sonido a partir de un nombre - JA_Sound_t *getSound(const std::string &name); + // Obtiene el sonido a partir de un nombre + JA_Sound_t* getSound(const std::string& name); - // Obtiene la música a partir de un nombre - JA_Music_t *getMusic(const std::string &name); + // Obtiene la música a partir de un nombre + JA_Music_t* getMusic(const std::string& name); - // Obtiene la surface a partir de un nombre - std::shared_ptr getSurface(const std::string &name); + // Obtiene la surface a partir de un nombre + std::shared_ptr getSurface(const std::string& name); - // Obtiene la paleta a partir de un nombre - Palette getPalette(const std::string &name); + // Obtiene la paleta a partir de un nombre + Palette getPalette(const std::string& name); - // Obtiene el fichero de texto a partir de un nombre - std::shared_ptr getTextFile(const std::string &name); + // Obtiene el fichero de texto a partir de un nombre + std::shared_ptr getTextFile(const std::string& name); - // Obtiene el objeto de texto a partir de un nombre - std::shared_ptr getText(const std::string &name); + // Obtiene el objeto de texto a partir de un nombre + std::shared_ptr getText(const std::string& name); - // Obtiene la animación a partir de un nombre - Animations &getAnimations(const std::string &name); + // Obtiene la animación a partir de un nombre + Animations& getAnimations(const std::string& name); - // Obtiene el mapa de tiles a partir de un nombre - std::vector &getTileMap(const std::string &name); + // Obtiene el mapa de tiles a partir de un nombre + std::vector& getTileMap(const std::string& name); - // Obtiene la habitación a partir de un nombre - std::shared_ptr getRoom(const std::string &name); + // Obtiene la habitación a partir de un nombre + std::shared_ptr getRoom(const std::string& name); - // Obtiene todas las habitaciones - std::vector &getRooms(); + // Obtiene todas las habitaciones + std::vector& getRooms(); - // Recarga todos los recursos - void reload(); + // Recarga todos los recursos + void reload(); }; \ No newline at end of file diff --git a/source/room.cpp b/source/room.cpp index 4a5913d..f7fc555 100644 --- a/source/room.cpp +++ b/source/room.cpp @@ -1,44 +1,40 @@ #include "room.h" -#include // Para exception -#include // Para basic_ostream, operator<<, basic_istream -#include // Para cout, cerr -#include // Para basic_stringstream -#include "debug.h" // Para Debug -#include "defines.h" // Para BLOCK, PLAY_AREA_HEIGHT, PLAY_AREA_WIDTH -#include "item_tracker.h" // Para ItemTracker -#include "jail_audio.h" // Para JA_PlaySound -#include "options.h" // Para Options, OptionsStats, options -#include "resource.h" // Para Resource -#include "s_sprite.h" // Para SSprite -#include "scoreboard.h" // Para ScoreboardData -#include "screen.h" // Para Screen -#include "surface.h" // Para Surface -#include "utils.h" // Para LineHorizontal, LineDiagonal, LineVertical + +#include // Para exception +#include // Para basic_ostream, operator<<, basic_istream +#include // Para cout, cerr +#include // Para basic_stringstream + +#include "debug.h" // Para Debug +#include "defines.h" // Para BLOCK, PLAY_AREA_HEIGHT, PLAY_AREA_WIDTH +#include "external/jail_audio.h" // Para JA_PlaySound +#include "item_tracker.h" // Para ItemTracker +#include "options.h" // Para Options, OptionsStats, options +#include "resource.h" // Para Resource +#include "scoreboard.h" // Para ScoreboardData +#include "screen.h" // Para Screen +#include "sprite/surface_sprite.h" // Para SSprite +#include "surface.h" // Para Surface +#include "utils.h" // Para LineHorizontal, LineDiagonal, LineVertical // Carga las variables y texturas desde un fichero de mapa de tiles -std::vector loadRoomTileFile(const std::string &file_path, bool verbose) -{ +std::vector loadRoomTileFile(const std::string& file_path, bool verbose) { std::vector tileMapFile; const std::string filename = file_path.substr(file_path.find_last_of("\\/") + 1); std::ifstream file(file_path); // El fichero se puede abrir - if (file.good()) - { + if (file.good()) { std::string line; // Procesa el fichero linea a linea - while (std::getline(file, line)) - { // Lee el fichero linea a linea - if (line.find("data encoding") != std::string::npos) - { + while (std::getline(file, line)) { // Lee el fichero linea a linea + if (line.find("data encoding") != std::string::npos) { // Lee la primera linea std::getline(file, line); - while (line != "") - { // Procesa lineas mientras haya + while (line != "") { // Procesa lineas mientras haya std::stringstream ss(line); std::string tmp; - while (getline(ss, tmp, ',')) - { + while (getline(ss, tmp, ',')) { tileMapFile.push_back(std::stoi(tmp) - 1); } @@ -49,17 +45,14 @@ std::vector loadRoomTileFile(const std::string &file_path, bool verbose) } // Cierra el fichero - if (verbose) - { + if (verbose) { std::cout << "TileMap loaded: " << filename.c_str() << std::endl; } file.close(); } - else - { // El fichero no se puede abrir - if (verbose) - { + else { // El fichero no se puede abrir + if (verbose) { std::cout << "Warning: Unable to open " << filename.c_str() << " file" << std::endl; } } @@ -68,8 +61,7 @@ std::vector loadRoomTileFile(const std::string &file_path, bool verbose) } // Carga las variables desde un fichero de mapa -RoomData loadRoomFile(const std::string &file_path, bool verbose) -{ +RoomData loadRoomFile(const std::string& file_path, bool verbose) { RoomData room; room.item_color1 = "yellow"; room.item_color2 = "magenta"; @@ -81,22 +73,18 @@ RoomData loadRoomFile(const std::string &file_path, bool verbose) std::ifstream file(file_path); // El fichero se puede abrir - if (file.good()) - { + if (file.good()) { std::string line; // Procesa el fichero linea a linea - while (std::getline(file, line)) - { + while (std::getline(file, line)) { // Si la linea contiene el texto [enemy] se realiza el proceso de carga de un enemigo - if (line == "[enemy]") - { + if (line == "[enemy]") { EnemyData enemy; enemy.flip = false; enemy.mirror = false; enemy.frame = -1; - do - { + do { std::getline(file, line); // Encuentra la posición del caracter '=' @@ -106,8 +94,7 @@ RoomData loadRoomFile(const std::string &file_path, bool verbose) std::string key = line.substr(0, pos); std::string value = line.substr(pos + 1, line.length()); if (!setEnemy(&enemy, key, value)) - if (verbose) - { + if (verbose) { std::cout << "Warning: file " << fileName.c_str() << "\n, unknown parameter \"" << line.substr(0, pos).c_str() << "\"" << std::endl; } } while (line != "[/enemy]"); @@ -117,15 +104,13 @@ RoomData loadRoomFile(const std::string &file_path, bool verbose) } // Si la linea contiene el texto [item] se realiza el proceso de carga de un item - else if (line == "[item]") - { + else if (line == "[item]") { ItemData item; item.counter = 0; item.color1 = stringToColor("yellow"); item.color2 = stringToColor("magenta"); - do - { + do { std::getline(file, line); // Encuentra la posición del caracter '=' @@ -134,10 +119,8 @@ RoomData loadRoomFile(const std::string &file_path, bool verbose) // Procesa las dos subcadenas std::string key = line.substr(0, pos); std::string value = line.substr(pos + 1, line.length()); - if (!setItem(&item, key, value)) - { - if (verbose) - { + if (!setItem(&item, key, value)) { + if (verbose) { std::cout << "Warning: file " << fileName.c_str() << "\n, unknown parameter \"" << line.substr(0, pos).c_str() << "\"" << std::endl; } } @@ -148,18 +131,15 @@ RoomData loadRoomFile(const std::string &file_path, bool verbose) } // En caso contrario se parsea el fichero para buscar las variables y los valores - else - { + else { // Encuentra la posición del caracter '=' int pos = line.find("="); // Procesa las dos subcadenas std::string key = line.substr(0, pos); std::string value = line.substr(pos + 1, line.length()); - if (!setRoom(&room, key, value)) - { - if (verbose) - { + if (!setRoom(&room, key, value)) { + if (verbose) { std::cout << "Warning: file " << fileName.c_str() << "\n, unknown parameter \"" << line.substr(0, pos).c_str() << "\"" << std::endl; } } @@ -167,15 +147,13 @@ RoomData loadRoomFile(const std::string &file_path, bool verbose) } // Cierra el fichero - if (verbose) - { + if (verbose) { std::cout << "Room loaded: " << fileName.c_str() << std::endl; } file.close(); } // El fichero no se puede abrir - else - { + else { { std::cout << "Warning: Unable to open " << fileName.c_str() << " file" << std::endl; } @@ -185,72 +163,41 @@ RoomData loadRoomFile(const std::string &file_path, bool verbose) } // Asigna variables a una estructura RoomData -bool setRoom(RoomData *room, const std::string &key, const std::string &value) -{ +bool setRoom(RoomData* room, const std::string& key, const std::string& value) { // Indicador de éxito en la asignación bool success = true; - try - { - if (key == "tileMapFile") - { + try { + if (key == "tileMapFile") { room->tile_map_file = value; - } - else if (key == "name") - { + } else if (key == "name") { room->name = value; - } - else if (key == "bgColor") - { + } else if (key == "bgColor") { room->bg_color = value; - } - else if (key == "border") - { + } else if (key == "border") { room->border_color = value; - } - else if (key == "itemColor1") - { + } else if (key == "itemColor1") { room->item_color1 = value; - } - else if (key == "itemColor2") - { + } else if (key == "itemColor2") { room->item_color2 = value; - } - else if (key == "tileSetFile") - { + } else if (key == "tileSetFile") { room->tile_set_file = value; - } - else if (key == "roomUp") - { + } else if (key == "roomUp") { room->upper_room = value; - } - else if (key == "roomDown") - { + } else if (key == "roomDown") { room->lower_room = value; - } - else if (key == "roomLeft") - { + } else if (key == "roomLeft") { room->left_room = value; - } - else if (key == "roomRight") - { + } else if (key == "roomRight") { room->right_room = value; - } - else if (key == "autoSurface") - { + } else if (key == "autoSurface") { room->conveyor_belt_direction = (value == "right") ? 1 : -1; - } - else if (key == "" || key.substr(0, 1) == "#") - { + } else if (key == "" || key.substr(0, 1) == "#") { // No se realiza ninguna acción para estas claves - } - else - { + } else { 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; success = false; } @@ -259,88 +206,49 @@ bool setRoom(RoomData *room, const std::string &key, const std::string &value) } // Asigna variables a una estructura EnemyData -bool setEnemy(EnemyData *enemy, const std::string &key, const std::string &value) -{ +bool setEnemy(EnemyData* enemy, const std::string& key, const std::string& value) { // Indicador de éxito en la asignación bool success = true; - try - { - if (key == "tileSetFile") - { + try { + if (key == "tileSetFile") { enemy->surface_path = value; - } - else if (key == "animation") - { + } else if (key == "animation") { enemy->animation_path = value; - } - else if (key == "width") - { + } else if (key == "width") { enemy->w = std::stoi(value); - } - else if (key == "height") - { + } else if (key == "height") { enemy->h = std::stoi(value); - } - else if (key == "x") - { + } else if (key == "x") { enemy->x = std::stof(value) * BLOCK; - } - else if (key == "y") - { + } else if (key == "y") { enemy->y = std::stof(value) * BLOCK; - } - else if (key == "vx") - { + } else if (key == "vx") { enemy->vx = std::stof(value); - } - else if (key == "vy") - { + } else if (key == "vy") { enemy->vy = std::stof(value); - } - else if (key == "x1") - { + } else if (key == "x1") { enemy->x1 = std::stoi(value) * BLOCK; - } - else if (key == "x2") - { + } else if (key == "x2") { enemy->x2 = std::stoi(value) * BLOCK; - } - else if (key == "y1") - { + } else if (key == "y1") { enemy->y1 = std::stoi(value) * BLOCK; - } - else if (key == "y2") - { + } else if (key == "y2") { enemy->y2 = std::stoi(value) * BLOCK; - } - else if (key == "flip") - { + } else if (key == "flip") { enemy->flip = stringToBool(value); - } - else if (key == "mirror") - { + } else if (key == "mirror") { enemy->mirror = stringToBool(value); - } - else if (key == "color") - { + } else if (key == "color") { enemy->color = value; - } - else if (key == "frame") - { + } else if (key == "frame") { enemy->frame = std::stoi(value); - } - else if (key == "[/enemy]" || key == "tileSetFile" || key.substr(0, 1) == "#") - { + } else if (key == "[/enemy]" || key == "tileSetFile" || key.substr(0, 1) == "#") { // No se realiza ninguna acción para estas claves - } - else - { + } else { 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; success = false; } @@ -349,44 +257,27 @@ bool setEnemy(EnemyData *enemy, const std::string &key, const std::string &value } // Asigna variables a una estructura ItemData -bool setItem(ItemData *item, const std::string &key, const std::string &value) -{ +bool setItem(ItemData* item, const std::string& key, const std::string& value) { // Indicador de éxito en la asignación bool success = true; - try - { - if (key == "tileSetFile") - { + try { + if (key == "tileSetFile") { item->tile_set_file = value; - } - else if (key == "counter") - { + } else if (key == "counter") { item->counter = std::stoi(value); - } - else if (key == "x") - { + } else if (key == "x") { item->x = std::stof(value) * BLOCK; - } - else if (key == "y") - { + } else if (key == "y") { item->y = std::stof(value) * BLOCK; - } - else if (key == "tile") - { + } else if (key == "tile") { item->tile = std::stof(value); - } - else if (key == "[/item]") - { + } else if (key == "[/item]") { // No se realiza ninguna acción para esta clave - } - else - { + } else { 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; success = false; } @@ -395,9 +286,8 @@ bool setItem(ItemData *item, const std::string &key, const std::string &value) } // Constructor -Room::Room(const std::string &room_path, std::shared_ptr data) - : data_(data) -{ +Room::Room(const std::string& room_path, std::shared_ptr data) + : data_(data) { auto room = Resource::get()->getRoom(room_path); initializeRoom(*room); @@ -420,8 +310,7 @@ Room::Room(const std::string &room_path, std::shared_ptr data) Screen::get()->setBorderColor(stringToColor(border_color_)); } -void Room::initializeRoom(const RoomData &room) -{ +void Room::initializeRoom(const RoomData& room) { // Asignar valores a las variables miembro number_ = room.number; name_ = room.name; @@ -443,18 +332,15 @@ void Room::initializeRoom(const RoomData &room) counter_ = 0; // Crear los enemigos - for (auto &enemy_data : room.enemies) - { + for (auto& enemy_data : room.enemies) { enemies_.emplace_back(std::make_shared(enemy_data)); } // Crear los items - for (const auto &item : room.items) - { + for (const auto& item : room.items) { const SDL_Point itemPos = {item.x, item.y}; - if (!ItemTracker::get()->hasBeenPicked(room.name, itemPos)) - { + if (!ItemTracker::get()->hasBeenPicked(room.name, itemPos)) { // Crear una copia local de los datos del item ItemData itemCopy = item; itemCopy.color1 = stringToColor(item_color1_); @@ -467,8 +353,7 @@ void Room::initializeRoom(const RoomData &room) } // Crea la textura con el mapeado de la habitación -void Room::fillMapTexture() -{ +void Room::fillMapTexture() { const Uint8 color = stringToColor(bg_color_); auto previuos_renderer = Screen::get()->getRendererSurface(); Screen::get()->setRendererSurface(map_surface_); @@ -478,8 +363,7 @@ void Room::fillMapTexture() SDL_Rect clip = {0, 0, TILE_SIZE_, TILE_SIZE_}; for (int y = 0; y < MAP_HEIGHT_; ++y) - for (int x = 0; x < MAP_WIDTH_; ++x) - { + for (int x = 0; x < MAP_WIDTH_; ++x) { // Tiled pone los tiles vacios del mapa como cero y empieza a contar de 1 a n. // Al cargar el mapa en memoria, se resta uno, por tanto los tiles vacios son -1 // Tampoco hay que dibujar los tiles animados que estan en la fila 19 (indices) @@ -487,8 +371,7 @@ void Room::fillMapTexture() const bool A = (tile_map_[INDEX] >= 18 * tile_set_width_) && (tile_map_[INDEX] < 19 * tile_set_width_); const bool B = tile_map_[INDEX] > -1; - if (B && !A) - { + if (B && !A) { clip.x = (tile_map_[INDEX] % tile_set_width_) * TILE_SIZE_; clip.y = (tile_map_[INDEX] / tile_set_width_) * TILE_SIZE_; surface_->render(x * TILE_SIZE_, y * TILE_SIZE_, &clip); @@ -496,89 +379,72 @@ void Room::fillMapTexture() } #ifdef DEBUG - if (Debug::get()->getEnabled()) - { + if (Debug::get()->getEnabled()) { auto surface = Screen::get()->getRendererSurface(); // BottomSurfaces - if (true) - { - for (auto l : bottom_floors_) - { + if (true) { + for (auto l : bottom_floors_) { surface->drawLine(l.x1, l.y, l.x2, l.y, static_cast(PaletteColor::BLUE)); } } // TopSurfaces - if (true) - { - for (auto l : top_floors_) - { + if (true) { + for (auto l : top_floors_) { surface->drawLine(l.x1, l.y, l.x2, l.y, static_cast(PaletteColor::RED)); } } // LeftSurfaces - if (true) - { - for (auto l : left_walls_) - { + if (true) { + for (auto l : left_walls_) { surface->drawLine(l.x, l.y1, l.x, l.y2, static_cast(PaletteColor::GREEN)); } } // RightSurfaces - if (true) - { - for (auto l : right_walls_) - { + if (true) { + for (auto l : right_walls_) { surface->drawLine(l.x, l.y1, l.x, l.y2, static_cast(PaletteColor::MAGENTA)); } } // LeftSlopes - if (true) - { - for (auto l : left_slopes_) - { + if (true) { + for (auto l : left_slopes_) { surface->drawLine(l.x1, l.y1, l.x2, l.y2, static_cast(PaletteColor::CYAN)); } } // RightSlopes - if (true) - { - for (auto l : right_slopes_) - { + if (true) { + for (auto l : right_slopes_) { surface->drawLine(l.x1, l.y1, l.x2, l.y2, static_cast(PaletteColor::YELLOW)); } } // AutoSurfaces - if (true) - { - for (auto l : conveyor_belt_floors_) - { + if (true) { + for (auto l : conveyor_belt_floors_) { surface->drawLine(l.x1, l.y, l.x2, l.y, static_cast(PaletteColor::WHITE)); } } } -#endif // DEBUG +#endif // DEBUG Screen::get()->setRendererSurface(previuos_renderer); } // Dibuja el mapa en pantalla -void Room::renderMap() -{ +void Room::renderMap() { // Dibuja la textura con el mapa en pantalla SDL_Rect dest = {0, 0, PLAY_AREA_WIDTH, PLAY_AREA_HEIGHT}; map_surface_->render(nullptr, &dest); // Dibuja los tiles animados #ifdef DEBUG - if (!Debug::get()->getEnabled()) - { + if (!Debug::get()->getEnabled()) { renderAnimatedTiles(); } #else @@ -587,28 +453,22 @@ void Room::renderMap() } // Dibuja los enemigos en pantalla -void Room::renderEnemies() -{ - for (const auto &enemy : enemies_) - { +void Room::renderEnemies() { + for (const auto& enemy : enemies_) { enemy->render(); } } // Dibuja los objetos en pantalla -void Room::renderItems() -{ - for (const auto &item : items_) - { +void Room::renderItems() { + for (const auto& item : items_) { item->render(); } } // Actualiza las variables y objetos de la habitación -void Room::update() -{ - if (is_paused_) - { +void Room::update() { + if (is_paused_) { // Si está en modo pausa no se actualiza nada return; } @@ -619,94 +479,81 @@ void Room::update() // Actualiza los tiles animados updateAnimatedTiles(); - for (auto enemy : enemies_) - { + for (auto enemy : enemies_) { // Actualiza los enemigos enemy->update(); } - for (auto item : items_) - { + for (auto item : items_) { // Actualiza los items item->update(); } } // Devuelve la cadena del fichero de la habitación contigua segun el borde -std::string Room::getRoom(RoomBorder border) -{ - switch (border) - { - case RoomBorder::TOP: - return upper_room_; - break; +std::string Room::getRoom(RoomBorder border) { + switch (border) { + case RoomBorder::TOP: + return upper_room_; + break; - case RoomBorder::BOTTOM: - return lower_room_; - break; + case RoomBorder::BOTTOM: + return lower_room_; + break; - case RoomBorder::RIGHT: - return right_room_; - break; + case RoomBorder::RIGHT: + return right_room_; + break; - case RoomBorder::LEFT: - return left_room_; - break; + case RoomBorder::LEFT: + return left_room_; + break; - default: - break; + default: + break; } return ""; } // Devuelve el tipo de tile que hay en ese pixel -TileType Room::getTile(SDL_Point point) -{ +TileType Room::getTile(SDL_Point point) { const int pos = ((point.y / TILE_SIZE_) * MAP_WIDTH_) + (point.x / TILE_SIZE_); return getTile(pos); } // Devuelve el tipo de tile que hay en ese indice -TileType Room::getTile(int index) -{ +TileType Room::getTile(int index) { // const bool onRange = (index > -1) && (index < mapWidth * mapHeight); const bool onRange = (index > -1) && (index < (int)tile_map_.size()); - if (onRange) - { + if (onRange) { // Las filas 0-8 son de tiles t_wall - if ((tile_map_[index] >= 0) && (tile_map_[index] < 9 * tile_set_width_)) - { + if ((tile_map_[index] >= 0) && (tile_map_[index] < 9 * tile_set_width_)) { return TileType::WALL; } // Las filas 9-17 son de tiles t_passable - else if ((tile_map_[index] >= 9 * tile_set_width_) && (tile_map_[index] < 18 * tile_set_width_)) - { + else if ((tile_map_[index] >= 9 * tile_set_width_) && (tile_map_[index] < 18 * tile_set_width_)) { return TileType::PASSABLE; } // Las filas 18-20 es de tiles t_animated - else if ((tile_map_[index] >= 18 * tile_set_width_) && (tile_map_[index] < 21 * tile_set_width_)) - { + else if ((tile_map_[index] >= 18 * tile_set_width_) && (tile_map_[index] < 21 * tile_set_width_)) { return TileType::ANIMATED; } // La fila 21 es de tiles t_slope_r - else if ((tile_map_[index] >= 21 * tile_set_width_) && (tile_map_[index] < 22 * tile_set_width_)) - { + else if ((tile_map_[index] >= 21 * tile_set_width_) && (tile_map_[index] < 22 * tile_set_width_)) { return TileType::SLOPE_R; } // La fila 22 es de tiles t_slope_l - else if ((tile_map_[index] >= 22 * tile_set_width_) && (tile_map_[index] < 23 * tile_set_width_)) - { + else if ((tile_map_[index] >= 22 * tile_set_width_) && (tile_map_[index] < 23 * tile_set_width_)) { return TileType::SLOPE_L; } // La fila 23 es de tiles t_kill - else if ((tile_map_[index] >= 23 * tile_set_width_) && (tile_map_[index] < 24 * tile_set_width_)) - { + else if ((tile_map_[index] >= 23 * tile_set_width_) && (tile_map_[index] < 24 * tile_set_width_)) { return TileType::KILL; } } @@ -715,12 +562,9 @@ TileType Room::getTile(int index) } // Indica si hay colision con un enemigo a partir de un rectangulo -bool Room::enemyCollision(SDL_Rect &rect) -{ - for (const auto &enemy : enemies_) - { - if (checkCollision(rect, enemy->getCollider())) - { +bool Room::enemyCollision(SDL_Rect& rect) { + for (const auto& enemy : enemies_) { + if (checkCollision(rect, enemy->getCollider())) { return true; } } @@ -728,12 +572,9 @@ bool Room::enemyCollision(SDL_Rect &rect) } // Indica si hay colision con un objeto a partir de un rectangulo -bool Room::itemCollision(SDL_Rect &rect) -{ - for (int i = 0; i < static_cast(items_.size()); ++i) - { - if (checkCollision(rect, items_.at(i)->getCollider())) - { +bool Room::itemCollision(SDL_Rect& rect) { + for (int i = 0; i < static_cast(items_.size()); ++i) { + if (checkCollision(rect, items_.at(i)->getCollider())) { ItemTracker::get()->addItem(name_, items_.at(i)->getPos()); items_.erase(items_.begin() + i); JA_PlaySound(Resource::get()->getSound("item.wav")); @@ -747,8 +588,7 @@ bool Room::itemCollision(SDL_Rect &rect) } // Obten la coordenada de la cuesta a partir de un punto perteneciente a ese tile -int Room::getSlopeHeight(SDL_Point p, TileType slope) -{ +int Room::getSlopeHeight(SDL_Point p, TileType slope) { // Calcula la base del tile int base = ((p.y / TILE_SIZE_) * TILE_SIZE_) + TILE_SIZE_; #ifdef DEBUG @@ -756,21 +596,18 @@ int Room::getSlopeHeight(SDL_Point p, TileType slope) #endif // Calcula cuanto se ha entrado en el tile horizontalmente - const int pos = (p.x % TILE_SIZE_); // Esto da un valor entre 0 y 7 + const int pos = (p.x % TILE_SIZE_); // Esto da un valor entre 0 y 7 #ifdef DEBUG Debug::get()->add("POS = " + std::to_string(pos)); #endif // Se resta a la base la cantidad de pixeles pos en funcion de la rampa - if (slope == TileType::SLOPE_R) - { + if (slope == TileType::SLOPE_R) { base -= pos + 1; #ifdef DEBUG Debug::get()->add("BASE_R = " + std::to_string(base)); #endif - } - else - { + } else { base -= (TILE_SIZE_ - pos); #ifdef DEBUG Debug::get()->add("BASE_L = " + std::to_string(base)); @@ -781,21 +618,17 @@ int Room::getSlopeHeight(SDL_Point p, TileType slope) } // Calcula las superficies inferiores -void Room::setBottomSurfaces() -{ +void Room::setBottomSurfaces() { std::vector tile; // Busca todos los tiles de tipo muro que no tengan debajo otro muro // Hay que recorrer la habitación por filas (excepto los de la última fila) - for (int i = 0; i < (int)tile_map_.size() - MAP_WIDTH_; ++i) - { - if (getTile(i) == TileType::WALL && getTile(i + MAP_WIDTH_) != TileType::WALL) - { + for (int i = 0; i < (int)tile_map_.size() - MAP_WIDTH_; ++i) { + if (getTile(i) == TileType::WALL && getTile(i + MAP_WIDTH_) != TileType::WALL) { tile.push_back(i); // Si llega al final de la fila, introduce un separador - if (i % MAP_WIDTH_ == MAP_WIDTH_ - 1) - { + if (i % MAP_WIDTH_ == MAP_WIDTH_ - 1) { tile.push_back(-1); } } @@ -805,24 +638,19 @@ void Room::setBottomSurfaces() tile.push_back(-1); // Recorre el vector de tiles buscando tiles consecutivos para localizar las superficies - if ((int)tile.size() > 1) - { + if ((int)tile.size() > 1) { int i = 0; - do - { + do { LineHorizontal line; line.x1 = (tile[i] % MAP_WIDTH_) * TILE_SIZE_; line.y = ((tile[i] / MAP_WIDTH_) * TILE_SIZE_) + TILE_SIZE_ - 1; int last_one = i; i++; - if (i <= (int)tile.size() - 1) - { - while (tile[i] == tile[i - 1] + 1) - { + if (i <= (int)tile.size() - 1) { + while (tile[i] == tile[i - 1] + 1) { last_one = i; - if (i == (int)tile.size() - 1) - { + if (i == (int)tile.size() - 1) { break; } i++; @@ -831,10 +659,8 @@ void Room::setBottomSurfaces() line.x2 = ((tile[last_one] % MAP_WIDTH_) * TILE_SIZE_) + TILE_SIZE_ - 1; bottom_floors_.push_back(line); - if (i <= (int)tile.size() - 1) - { - if (tile[i] == -1) - { // Si el siguiente elemento es un separador, hay que saltarlo + if (i <= (int)tile.size() - 1) { + if (tile[i] == -1) { // Si el siguiente elemento es un separador, hay que saltarlo i++; } } @@ -843,21 +669,17 @@ void Room::setBottomSurfaces() } // Calcula las superficies superiores -void Room::setTopSurfaces() -{ +void Room::setTopSurfaces() { std::vector tile; // Busca todos los tiles de tipo muro o pasable que no tengan encima un muro // Hay que recorrer la habitación por filas (excepto los de la primera fila) - for (int i = MAP_WIDTH_; i < (int)tile_map_.size(); ++i) - { - if ((getTile(i) == TileType::WALL || getTile(i) == TileType::PASSABLE) && getTile(i - MAP_WIDTH_) != TileType::WALL) - { + for (int i = MAP_WIDTH_; i < (int)tile_map_.size(); ++i) { + if ((getTile(i) == TileType::WALL || getTile(i) == TileType::PASSABLE) && getTile(i - MAP_WIDTH_) != TileType::WALL) { tile.push_back(i); // Si llega al final de la fila, introduce un separador - if (i % MAP_WIDTH_ == MAP_WIDTH_ - 1) - { + if (i % MAP_WIDTH_ == MAP_WIDTH_ - 1) { tile.push_back(-1); } } @@ -867,24 +689,19 @@ void Room::setTopSurfaces() tile.push_back(-1); // Recorre el vector de tiles buscando tiles consecutivos para localizar las superficies - if ((int)tile.size() > 1) - { + if ((int)tile.size() > 1) { int i = 0; - do - { + do { LineHorizontal line; line.x1 = (tile[i] % MAP_WIDTH_) * TILE_SIZE_; line.y = (tile[i] / MAP_WIDTH_) * TILE_SIZE_; int last_one = i; i++; - if (i <= (int)tile.size() - 1) - { - while (tile[i] == tile[i - 1] + 1) - { + if (i <= (int)tile.size() - 1) { + while (tile[i] == tile[i - 1] + 1) { last_one = i; - if (i == (int)tile.size() - 1) - { + if (i == (int)tile.size() - 1) { break; } i++; @@ -893,10 +710,8 @@ void Room::setTopSurfaces() line.x2 = ((tile[last_one] % MAP_WIDTH_) * TILE_SIZE_) + TILE_SIZE_ - 1; top_floors_.push_back(line); - if (i <= (int)tile.size() - 1) - { - if (tile[i] == -1) - { // Si el siguiente elemento es un separador, hay que saltarlo + if (i <= (int)tile.size() - 1) { + if (tile[i] == -1) { // Si el siguiente elemento es un separador, hay que saltarlo i++; } } @@ -905,19 +720,15 @@ void Room::setTopSurfaces() } // Calcula las superficies laterales izquierdas -void Room::setLeftSurfaces() -{ +void Room::setLeftSurfaces() { std::vector tile; // Busca todos los tiles de tipo muro que no tienen a su izquierda un tile de tipo muro // Hay que recorrer la habitación por columnas (excepto los de la primera columna) - for (int i = 1; i < MAP_WIDTH_; ++i) - { - for (int j = 0; j < MAP_HEIGHT_; ++j) - { + for (int i = 1; i < MAP_WIDTH_; ++i) { + for (int j = 0; j < MAP_HEIGHT_; ++j) { const int pos = (j * MAP_WIDTH_ + i); - if (getTile(pos) == TileType::WALL && getTile(pos - 1) != TileType::WALL) - { + if (getTile(pos) == TileType::WALL && getTile(pos - 1) != TileType::WALL) { tile.push_back(pos); } } @@ -929,18 +740,14 @@ void Room::setLeftSurfaces() // Recorre el vector de tiles buscando tiles consecutivos // (Los tiles de la misma columna, la diferencia entre ellos es de mapWidth) // para localizar las superficies - if ((int)tile.size() > 1) - { + if ((int)tile.size() > 1) { int i = 0; - do - { + do { LineVertical line; line.x = (tile[i] % MAP_WIDTH_) * TILE_SIZE_; line.y1 = ((tile[i] / MAP_WIDTH_) * TILE_SIZE_); - while (tile[i] + MAP_WIDTH_ == tile[i + 1]) - { - if (i == (int)tile.size() - 1) - { + while (tile[i] + MAP_WIDTH_ == tile[i + 1]) { + if (i == (int)tile.size() - 1) { break; } i++; @@ -953,19 +760,15 @@ void Room::setLeftSurfaces() } // Calcula las superficies laterales derechas -void Room::setRightSurfaces() -{ +void Room::setRightSurfaces() { std::vector tile; // Busca todos los tiles de tipo muro que no tienen a su derecha un tile de tipo muro // Hay que recorrer la habitación por columnas (excepto los de la última columna) - for (int i = 0; i < MAP_WIDTH_ - 1; ++i) - { - for (int j = 0; j < MAP_HEIGHT_; ++j) - { + for (int i = 0; i < MAP_WIDTH_ - 1; ++i) { + for (int j = 0; j < MAP_HEIGHT_; ++j) { const int pos = (j * MAP_WIDTH_ + i); - if (getTile(pos) == TileType::WALL && getTile(pos + 1) != TileType::WALL) - { + if (getTile(pos) == TileType::WALL && getTile(pos + 1) != TileType::WALL) { tile.push_back(pos); } } @@ -977,18 +780,14 @@ void Room::setRightSurfaces() // Recorre el vector de tiles buscando tiles consecutivos // (Los tiles de la misma columna, la diferencia entre ellos es de mapWidth) // para localizar las superficies - if ((int)tile.size() > 1) - { + if ((int)tile.size() > 1) { int i = 0; - do - { + do { LineVertical line; line.x = ((tile[i] % MAP_WIDTH_) * TILE_SIZE_) + TILE_SIZE_ - 1; line.y1 = ((tile[i] / MAP_WIDTH_) * TILE_SIZE_); - while (tile[i] + MAP_WIDTH_ == tile[i + 1]) - { - if (i == (int)tile.size() - 1) - { + while (tile[i] + MAP_WIDTH_ == tile[i + 1]) { + if (i == (int)tile.size() - 1) { break; } i++; @@ -1001,14 +800,11 @@ void Room::setRightSurfaces() } // Encuentra todas las rampas que suben hacia la izquierda -void Room::setLeftSlopes() -{ +void Room::setLeftSlopes() { // Recorre la habitación entera por filas buscando tiles de tipo t_slope_l std::vector found; - for (int i = 0; i < (int)tile_map_.size(); ++i) - { - if (getTile(i) == TileType::SLOPE_L) - { + for (int i = 0; i < (int)tile_map_.size(); ++i) { + if (getTile(i) == TileType::SLOPE_L) { found.push_back(i); } } @@ -1017,18 +813,15 @@ void Room::setLeftSlopes() // que seran i + mapWidth + 1. Conforme se añaden se eliminan y se vuelve a escudriñar el vector de // tiles encontrados hasta que esté vacío - while (found.size() > 0) - { + while (found.size() > 0) { LineDiagonal line; line.x1 = (found[0] % MAP_WIDTH_) * TILE_SIZE_; line.y1 = (found[0] / MAP_WIDTH_) * TILE_SIZE_; int lookingFor = found[0] + MAP_WIDTH_ + 1; int lastOneFound = found[0]; found.erase(found.begin()); - for (int i = 0; i < (int)found.size(); ++i) - { - if (found[i] == lookingFor) - { + for (int i = 0; i < (int)found.size(); ++i) { + if (found[i] == lookingFor) { lastOneFound = lookingFor; lookingFor += MAP_WIDTH_ + 1; found.erase(found.begin() + i); @@ -1042,14 +835,11 @@ void Room::setLeftSlopes() } // Encuentra todas las rampas que suben hacia la derecha -void Room::setRightSlopes() -{ +void Room::setRightSlopes() { // Recorre la habitación entera por filas buscando tiles de tipo t_slope_r std::vector found; - for (int i = 0; i < (int)tile_map_.size(); ++i) - { - if (getTile(i) == TileType::SLOPE_R) - { + for (int i = 0; i < (int)tile_map_.size(); ++i) { + if (getTile(i) == TileType::SLOPE_R) { found.push_back(i); } } @@ -1058,18 +848,15 @@ void Room::setRightSlopes() // que seran i + mapWidth - 1. Conforme se añaden se eliminan y se vuelve a escudriñar el vector de // tiles encontrados hasta que esté vacío - while (found.size() > 0) - { + while (found.size() > 0) { LineDiagonal line; line.x1 = ((found[0] % MAP_WIDTH_) * TILE_SIZE_) + TILE_SIZE_ - 1; line.y1 = (found[0] / MAP_WIDTH_) * TILE_SIZE_; int lookingFor = found[0] + MAP_WIDTH_ - 1; int lastOneFound = found[0]; found.erase(found.begin()); - for (int i = 0; i < (int)found.size(); ++i) - { - if (found[i] == lookingFor) - { + for (int i = 0; i < (int)found.size(); ++i) { + if (found[i] == lookingFor) { lastOneFound = lookingFor; lookingFor += MAP_WIDTH_ - 1; found.erase(found.begin() + i); @@ -1083,45 +870,36 @@ void Room::setRightSlopes() } // Calcula las superficies automaticas -void Room::setAutoSurfaces() -{ +void Room::setAutoSurfaces() { std::vector tile; // Busca todos los tiles de tipo animado // Hay que recorrer la habitación por filas (excepto los de la primera fila) - for (int i = MAP_WIDTH_; i < (int)tile_map_.size(); ++i) - { - if (getTile(i) == TileType::ANIMATED) - { + for (int i = MAP_WIDTH_; i < (int)tile_map_.size(); ++i) { + if (getTile(i) == TileType::ANIMATED) { tile.push_back(i); // Si llega al final de la fila, introduce un separador - if (i % MAP_WIDTH_ == MAP_WIDTH_ - 1) - { + if (i % MAP_WIDTH_ == MAP_WIDTH_ - 1) { tile.push_back(-1); } } } // Recorre el vector de tiles buscando tiles consecutivos para localizar las superficies - if ((int)tile.size() > 0) - { + if ((int)tile.size() > 0) { int i = 0; - do - { + do { LineHorizontal line; line.x1 = (tile[i] % MAP_WIDTH_) * TILE_SIZE_; line.y = (tile[i] / MAP_WIDTH_) * TILE_SIZE_; int last_one = i; i++; - if (i <= (int)tile.size() - 1) - { - while (tile[i] == tile[i - 1] + 1) - { + if (i <= (int)tile.size() - 1) { + while (tile[i] == tile[i - 1] + 1) { last_one = i; - if (i == (int)tile.size() - 1) - { + if (i == (int)tile.size() - 1) { break; } i++; @@ -1130,10 +908,8 @@ void Room::setAutoSurfaces() line.x2 = ((tile[last_one] % MAP_WIDTH_) * TILE_SIZE_) + TILE_SIZE_ - 1; conveyor_belt_floors_.push_back(line); - if (i <= (int)tile.size() - 1) - { - if (tile[i] == -1) - { // Si el siguiente elemento es un separador, hay que saltarlo + if (i <= (int)tile.size() - 1) { + if (tile[i] == -1) { // Si el siguiente elemento es un separador, hay que saltarlo i++; } } @@ -1142,13 +918,10 @@ void Room::setAutoSurfaces() } // Localiza todos los tiles animados de la habitación -void Room::setAnimatedTiles() -{ +void Room::setAnimatedTiles() { // Recorre la habitación entera por filas buscando tiles de tipo t_animated - for (int i = 0; i < (int)tile_map_.size(); ++i) - { - if (getTile(i) == TileType::ANIMATED) - { + for (int i = 0; i < (int)tile_map_.size(); ++i) { + if (getTile(i) == TileType::ANIMATED) { // La i es la ubicación const int x = (i % MAP_WIDTH_) * TILE_SIZE_; const int y = (i / MAP_WIDTH_) * TILE_SIZE_; @@ -1167,21 +940,16 @@ void Room::setAnimatedTiles() } // Actualiza los tiles animados -void Room::updateAnimatedTiles() -{ +void Room::updateAnimatedTiles() { const int numFrames = 4; int offset = 0; - if (conveyor_belt_direction_ == -1) - { + if (conveyor_belt_direction_ == -1) { offset = ((counter_ / 3) % numFrames * TILE_SIZE_); - } - else - { + } else { offset = ((numFrames - 1 - ((counter_ / 3) % numFrames)) * TILE_SIZE_); } - for (auto &a : animated_tiles_) - { + for (auto& a : animated_tiles_) { SDL_Rect rect = a.sprite->getClip(); rect.x = a.x_orig + offset; a.sprite->setClip(rect); @@ -1189,21 +957,16 @@ void Room::updateAnimatedTiles() } // Pinta los tiles animados en pantalla -void Room::renderAnimatedTiles() -{ - for (const auto &a : animated_tiles_) - { +void Room::renderAnimatedTiles() { + for (const auto& a : animated_tiles_) { a.sprite->render(); } } // Comprueba las colisiones -int Room::checkRightSurfaces(SDL_Rect *rect) -{ - for (const auto &s : right_walls_) - { - if (checkCollision(s, *rect)) - { +int Room::checkRightSurfaces(SDL_Rect* rect) { + for (const auto& s : right_walls_) { + if (checkCollision(s, *rect)) { return s.x; } } @@ -1212,12 +975,9 @@ int Room::checkRightSurfaces(SDL_Rect *rect) } // Comprueba las colisiones -int Room::checkLeftSurfaces(SDL_Rect *rect) -{ - for (const auto &s : left_walls_) - { - if (checkCollision(s, *rect)) - { +int Room::checkLeftSurfaces(SDL_Rect* rect) { + for (const auto& s : left_walls_) { + if (checkCollision(s, *rect)) { return s.x; } } @@ -1226,12 +986,9 @@ int Room::checkLeftSurfaces(SDL_Rect *rect) } // Comprueba las colisiones -int Room::checkTopSurfaces(SDL_Rect *rect) -{ - for (const auto &s : top_floors_) - { - if (checkCollision(s, *rect)) - { +int Room::checkTopSurfaces(SDL_Rect* rect) { + for (const auto& s : top_floors_) { + if (checkCollision(s, *rect)) { return s.y; } } @@ -1240,12 +997,9 @@ int Room::checkTopSurfaces(SDL_Rect *rect) } // Comprueba las colisiones -int Room::checkBottomSurfaces(SDL_Rect *rect) -{ - for (const auto &s : bottom_floors_) - { - if (checkCollision(s, *rect)) - { +int Room::checkBottomSurfaces(SDL_Rect* rect) { + for (const auto& s : bottom_floors_) { + if (checkCollision(s, *rect)) { return s.y; } } @@ -1254,12 +1008,9 @@ int Room::checkBottomSurfaces(SDL_Rect *rect) } // Comprueba las colisiones -int Room::checkAutoSurfaces(SDL_Rect *rect) -{ - for (const auto &s : conveyor_belt_floors_) - { - if (checkCollision(s, *rect)) - { +int Room::checkAutoSurfaces(SDL_Rect* rect) { + for (const auto& s : conveyor_belt_floors_) { + if (checkCollision(s, *rect)) { return s.y; } } @@ -1268,12 +1019,9 @@ int Room::checkAutoSurfaces(SDL_Rect *rect) } // Comprueba las colisiones -bool Room::checkTopSurfaces(SDL_Point *p) -{ - for (const auto &s : top_floors_) - { - if (checkCollision(s, *p)) - { +bool Room::checkTopSurfaces(SDL_Point* p) { + for (const auto& s : top_floors_) { + if (checkCollision(s, *p)) { return true; } } @@ -1282,12 +1030,9 @@ bool Room::checkTopSurfaces(SDL_Point *p) } // Comprueba las colisiones -bool Room::checkAutoSurfaces(SDL_Point *p) -{ - for (const auto &s : conveyor_belt_floors_) - { - if (checkCollision(s, *p)) - { +bool Room::checkAutoSurfaces(SDL_Point* p) { + for (const auto& s : conveyor_belt_floors_) { + if (checkCollision(s, *p)) { return true; } } @@ -1296,13 +1041,10 @@ bool Room::checkAutoSurfaces(SDL_Point *p) } // Comprueba las colisiones -int Room::checkLeftSlopes(const LineVertical *line) -{ - for (const auto &slope : left_slopes_) - { +int Room::checkLeftSlopes(const LineVertical* line) { + for (const auto& slope : left_slopes_) { const SDL_Point p = checkCollision(slope, *line); - if (p.x != -1) - { + if (p.x != -1) { return p.y; } } @@ -1311,12 +1053,9 @@ int Room::checkLeftSlopes(const LineVertical *line) } // Comprueba las colisiones -bool Room::checkLeftSlopes(SDL_Point *p) -{ - for (const auto &slope : left_slopes_) - { - if (checkCollision(*p, slope)) - { +bool Room::checkLeftSlopes(SDL_Point* p) { + for (const auto& slope : left_slopes_) { + if (checkCollision(*p, slope)) { return true; } } @@ -1325,13 +1064,10 @@ bool Room::checkLeftSlopes(SDL_Point *p) } // Comprueba las colisiones -int Room::checkRightSlopes(const LineVertical *line) -{ - for (const auto &slope : right_slopes_) - { +int Room::checkRightSlopes(const LineVertical* line) { + for (const auto& slope : right_slopes_) { const SDL_Point p = checkCollision(slope, *line); - if (p.x != -1) - { + if (p.x != -1) { return p.y; } } @@ -1340,12 +1076,9 @@ int Room::checkRightSlopes(const LineVertical *line) } // Comprueba las colisiones -bool Room::checkRightSlopes(SDL_Point *p) -{ - for (const auto &slope : right_slopes_) - { - if (checkCollision(*p, slope)) - { +bool Room::checkRightSlopes(SDL_Point* p) { + for (const auto& slope : right_slopes_) { + if (checkCollision(*p, slope)) { return true; } } @@ -1354,33 +1087,27 @@ bool Room::checkRightSlopes(SDL_Point *p) } // Abre la Jail si se da el caso -void Room::openTheJail() -{ - if (data_->jail_is_open && name_ == "THE JAIL") - { +void Room::openTheJail() { + if (data_->jail_is_open && name_ == "THE JAIL") { // Elimina el último enemigo (Bry debe ser el último enemigo definido en el fichero) - if (!enemies_.empty()) - { + if (!enemies_.empty()) { enemies_.pop_back(); } // Abre las puertas constexpr int TILE_A = 16 + (13 * 32); constexpr int TILE_B = 16 + (14 * 32); - if (TILE_A < tile_map_.size()) - { + if (TILE_A < tile_map_.size()) { tile_map_[TILE_A] = -1; } - if (TILE_B < tile_map_.size()) - { + if (TILE_B < tile_map_.size()) { tile_map_[TILE_B] = -1; } } } // Inicializa las superficies de colision -void Room::initRoomSurfaces() -{ +void Room::initRoomSurfaces() { setBottomSurfaces(); setTopSurfaces(); setLeftSurfaces(); diff --git a/source/room.h b/source/room.h index 9c57eec..6112f21 100644 --- a/source/room.h +++ b/source/room.h @@ -1,7 +1,7 @@ #pragma once -#include // Para SDL_Rect, SDL_Point -#include // Para Uint8 +#include + #include // Para shared_ptr #include // Para string diff --git a/source/scoreboard.cpp b/source/scoreboard.cpp index 1137233..6ab3761 100644 --- a/source/scoreboard.cpp +++ b/source/scoreboard.cpp @@ -1,16 +1,15 @@ #include "scoreboard.h" -#include // Para SDL_Rect -#include // Para SDL_GetTicks +#include -#include "defines.h" // Para BLOCK -#include "options.h" // Para Options, options, Cheat, OptionsGame -#include "resource.h" // Para Resource -#include "s_animated_sprite.h" // Para SAnimatedSprite -#include "screen.h" // Para Screen -#include "surface.h" // Para Surface -#include "text.h" // Para Text -#include "utils.h" // Para stringToColor +#include "defines.h" // Para BLOCK +#include "options.h" // Para Options, options, Cheat, OptionsGame +#include "resource.h" // Para Resource +#include "screen.h" // Para Screen +#include "sprite/surface_animated_sprite.h" // Para SAnimatedSprite +#include "surface.h" // Para Surface +#include "text.h" // Para Text +#include "utils.h" // Para stringToColor // Constructor Scoreboard::Scoreboard(std::shared_ptr data) diff --git a/source/scoreboard.h b/source/scoreboard.h index 3231f7e..118d9ca 100644 --- a/source/scoreboard.h +++ b/source/scoreboard.h @@ -1,7 +1,6 @@ #pragma once -#include // Para SDL_Rect -#include // Para Uint32, Uint8 +#include #include // Para shared_ptr #include // Para string, basic_string diff --git a/source/screen.cpp b/source/screen.cpp index 81f9a19..fa2a5b8 100644 --- a/source/screen.cpp +++ b/source/screen.cpp @@ -1,11 +1,7 @@ #include "screen.h" -#include // Para SDL_GetError -#include // Para SDL_DISABLE, SDL_ENABLE -#include // Para SDL_ShowCursor -#include // Para SDL_PIXELFORMAT_ARGB8888, SDL_PIXELFORM... -#include // Para SDL_GetTicks -#include // Para toupper +#include +#include // Para toupper #include // Para max, min, transform #include // Para basic_ostream, operator<<, endl, basic_... @@ -13,14 +9,14 @@ #include // Para istreambuf_iterator, operator== #include // Para char_traits, string, operator+, operator== -#include "asset.h" // Para Asset, AssetType -#include "jail_shader.h" // Para init, render -#include "mouse.h" // Para updateCursorVisibility -#include "notifier.h" // Para Notifier -#include "options.h" // Para Options, options, OptionsVideo, Border -#include "resource.h" // Para Resource -#include "surface.h" // Para Surface, readPalFile -#include "text.h" // Para Text +#include "asset.h" // Para Asset, AssetType +#include "external/jail_shader.h" // Para init, render +#include "mouse.h" // Para updateCursorVisibility +#include "options.h" // Para Options, options, OptionsVideo, Border +#include "resource.h" // Para Resource +#include "surface.h" // Para Surface, readPalFile +#include "text.h" // Para Text +#include "ui/notifier.h" // Para Notifier // [SINGLETON] Screen* Screen::screen_ = nullptr; @@ -253,7 +249,9 @@ void Screen::adjustWindowSize() { } // Ajusta el tamaño lógico del renderizador -void Screen::adjustRenderLogicalSize() { SDL_RenderSetLogicalSize(renderer_, window_width_, window_height_); } +void Screen::adjustRenderLogicalSize() { + SDL_SetRenderLogicalPresentation(renderer_, window_width_, window_height_); +} // Obtiene el tamaño máximo de zoom posible para la ventana int Screen::getMaxZoom() { diff --git a/source/screen.h b/source/screen.h index dd3e988..8894dba 100644 --- a/source/screen.h +++ b/source/screen.h @@ -1,11 +1,7 @@ #pragma once -#include // Para SDL_BlendMode -#include // Para SDL_Rect -#include // Para SDL_Renderer, SDL_Texture -#include // Para Uint8, Uint32 -#include // Para SDL_Window -#include // Para size_t +#include +#include // Para size_t #include // Para shared_ptr, __shared_ptr_access #include // Para string diff --git a/source/sections/credits.cpp b/source/sections/credits.cpp index 076054b..eb32d48 100644 --- a/source/sections/credits.cpp +++ b/source/sections/credits.cpp @@ -1,21 +1,19 @@ #include "credits.h" -#include // Para SDL_PollEvent, SDL_Event -#include // Para SDL_Rect -#include // Para SDL_GetTicks +#include #include // Para min -#include "defines.h" // Para GAME_SPEED, PLAY_AREA_CENTER_X, PLAY_... -#include "global_events.h" // Para check -#include "global_inputs.h" // Para check -#include "options.h" // Para Options, options, OptionsGame, Sectio... -#include "resource.h" // Para Resource -#include "s_animated_sprite.h" // Para SAnimatedSprite -#include "screen.h" // Para Screen -#include "surface.h" // Para Surface -#include "text.h" // Para Text, TEXT_CENTER, TEXT_COLOR -#include "utils.h" // Para PaletteColor +#include "defines.h" // Para GAME_SPEED, PLAY_AREA_CENTER_X, PLAY_... +#include "global_events.h" // Para check +#include "global_inputs.h" // Para check +#include "options.h" // Para Options, options, OptionsGame, Sectio... +#include "resource.h" // Para Resource +#include "screen.h" // Para Screen +#include "sprite/surface_animated_sprite.h" // Para SAnimatedSprite +#include "surface.h" // Para Surface +#include "text.h" // Para Text, TEXT_CENTER, TEXT_COLOR +#include "utils.h" // Para PaletteColor // Constructor Credits::Credits() diff --git a/source/sections/credits.h b/source/sections/credits.h index 8985bb8..1a43004 100644 --- a/source/sections/credits.h +++ b/source/sections/credits.h @@ -1,6 +1,6 @@ #pragma once -#include // Para Uint32, Uint8 +#include #include // Para shared_ptr #include // Para string diff --git a/source/sections/ending.cpp b/source/sections/ending.cpp index 1653021..62b0887 100644 --- a/source/sections/ending.cpp +++ b/source/sections/ending.cpp @@ -1,22 +1,20 @@ #include "ending.h" -#include // Para SDL_PollEvent, SDL_Event -#include // Para SDL_Rect -#include // Para SDL_GetTicks +#include #include // Para min -#include "defines.h" // Para GAME_SPEED -#include "global_events.h" // Para check -#include "global_inputs.h" // Para check -#include "jail_audio.h" // Para JA_SetVolume, JA_PlayMusic, JA_StopMusic -#include "options.h" // Para Options, options, OptionsGame, SectionS... -#include "resource.h" // Para Resource -#include "s_sprite.h" // Para SSprite -#include "screen.h" // Para Screen -#include "surface.h" // Para Surface -#include "text.h" // Para Text, TEXT_STROKE -#include "utils.h" // Para PaletteColor +#include "defines.h" // Para GAME_SPEED +#include "external/jail_audio.h" // Para JA_SetVolume, JA_PlayMusic, JA_StopMusic +#include "global_events.h" // Para check +#include "global_inputs.h" // Para check +#include "options.h" // Para Options, options, OptionsGame, SectionS... +#include "resource.h" // Para Resource +#include "screen.h" // Para Screen +#include "sprite/surface_sprite.h" // Para SSprite +#include "surface.h" // Para Surface +#include "text.h" // Para Text, TEXT_STROKE +#include "utils.h" // Para PaletteColor // Constructor Ending::Ending() diff --git a/source/sections/ending.h b/source/sections/ending.h index 66d250a..1a0d362 100644 --- a/source/sections/ending.h +++ b/source/sections/ending.h @@ -1,6 +1,6 @@ #pragma once -#include // Para Uint32 +#include #include // Para shared_ptr #include // Para string diff --git a/source/sections/ending2.cpp b/source/sections/ending2.cpp index 283fe0b..b27fa57 100644 --- a/source/sections/ending2.cpp +++ b/source/sections/ending2.cpp @@ -1,23 +1,21 @@ #include "ending2.h" -#include // Para SDL_PollEvent, SDL_Event -#include // Para SDL_Rect -#include // Para SDL_GetTicks +#include #include // Para max, replace -#include "defines.h" // Para GAMECANVAS_CENTER_X, GAMECANVAS_CENTER_Y -#include "global_events.h" // Para check -#include "global_inputs.h" // Para check -#include "jail_audio.h" // Para JA_SetVolume, JA_PlayMusic, JA_StopMusic -#include "options.h" // Para Options, options, OptionsGame, Sectio... -#include "resource.h" // Para Resource -#include "s_animated_sprite.h" // Para SAnimatedSprite -#include "s_moving_sprite.h" // Para SMovingSprite -#include "screen.h" // Para Screen -#include "surface.h" // Para Surface -#include "text.h" // Para Text -#include "utils.h" // Para PaletteColor, stringToColor +#include "defines.h" // Para GAMECANVAS_CENTER_X, GAMECANVAS_CENTER_Y +#include "external/jail_audio.h" // Para JA_SetVolume, JA_PlayMusic, JA_StopMusic +#include "global_events.h" // Para check +#include "global_inputs.h" // Para check +#include "options.h" // Para Options, options, OptionsGame, Sectio... +#include "resource.h" // Para Resource +#include "screen.h" // Para Screen +#include "sprite/surface_animated_sprite.h" // Para SAnimatedSprite +#include "sprite/surface_moving_sprite.h" // Para SMovingSprite +#include "surface.h" // Para Surface +#include "text.h" // Para Text +#include "utils.h" // Para PaletteColor, stringToColor // Constructor Ending2::Ending2() diff --git a/source/sections/ending2.h b/source/sections/ending2.h index c8f3150..1a4b48f 100644 --- a/source/sections/ending2.h +++ b/source/sections/ending2.h @@ -1,6 +1,6 @@ #pragma once -#include // Para Uint32, Uint8 +#include #include // Para shared_ptr #include // Para string diff --git a/source/sections/game.cpp b/source/sections/game.cpp index 252f229..835a66d 100644 --- a/source/sections/game.cpp +++ b/source/sections/game.cpp @@ -1,31 +1,29 @@ #include "game.h" -#include // Para SDL_FLIP_HORIZONTAL -#include // Para SDL_SCANCODE_7, SDL_SCANCODE_A, SDL_S... -#include // Para SDL_GetTicks +#include #include // Para vector -#include "asset.h" // Para Asset -#include "cheevos.h" // Para Cheevos -#include "debug.h" // Para Debug -#include "defines.h" // Para BLOCK, PLAY_AREA_HEIGHT, RoomBorder::BOTTOM -#include "global_events.h" // Para check -#include "global_inputs.h" // Para check -#include "input.h" // Para Input, InputAction, INPUT_DO_NOT_ALLOW_REPEAT -#include "item_tracker.h" // Para ItemTracker -#include "jail_audio.h" // Para JA_PauseMusic, JA_GetMusicState, JA_P... -#include "notifier.h" // Para Notifier, NotificationText, CHEEVO_NO... -#include "options.h" // Para Options, options, Cheat, SectionState -#include "resource.h" // Para ResourceRoom, Resource -#include "room.h" // Para Room, RoomData -#include "room_tracker.h" // Para RoomTracker -#include "scoreboard.h" // Para ScoreboardData, Scoreboard -#include "screen.h" // Para Screen -#include "stats.h" // Para Stats -#include "surface.h" // Para Surface -#include "text.h" // Para Text, TEXT_CENTER, TEXT_COLOR -#include "utils.h" // Para PaletteColor, stringToColor +#include "asset.h" // Para Asset +#include "cheevos.h" // Para Cheevos +#include "debug.h" // Para Debug +#include "defines.h" // Para BLOCK, PLAY_AREA_HEIGHT, RoomBorder::BOTTOM +#include "external/jail_audio.h" // Para JA_PauseMusic, JA_GetMusicState, JA_P... +#include "global_events.h" // Para check +#include "global_inputs.h" // Para check +#include "input.h" // Para Input, InputAction, INPUT_DO_NOT_ALLOW_REPEAT +#include "item_tracker.h" // Para ItemTracker +#include "options.h" // Para Options, options, Cheat, SectionState +#include "resource.h" // Para ResourceRoom, Resource +#include "room.h" // Para Room, RoomData +#include "room_tracker.h" // Para RoomTracker +#include "scoreboard.h" // Para ScoreboardData, Scoreboard +#include "screen.h" // Para Screen +#include "stats.h" // Para Stats +#include "surface.h" // Para Surface +#include "text.h" // Para Text, TEXT_CENTER, TEXT_COLOR +#include "ui/notifier.h" // Para Notifier, NotificationText, CHEEVO_NO... +#include "utils.h" // Para PaletteColor, stringToColor // Constructor Game::Game(GameMode mode) diff --git a/source/sections/game.h b/source/sections/game.h index e91b8db..4036cf5 100644 --- a/source/sections/game.h +++ b/source/sections/game.h @@ -1,8 +1,6 @@ #pragma once -#include // Para SDL_Event -#include // Para SDL_Rect -#include // Para Uint32 +#include #include // Para initializer_list #include // Para shared_ptr diff --git a/source/sections/game_over.cpp b/source/sections/game_over.cpp index 94377f8..a987707 100644 --- a/source/sections/game_over.cpp +++ b/source/sections/game_over.cpp @@ -1,21 +1,20 @@ #include "game_over.h" -#include // Para SDL_PollEvent, SDL_Event -#include // Para SDL_GetTicks +#include #include // Para min, max #include // Para basic_string, operator+, to_string -#include "defines.h" // Para GAMECANVAS_CENTER_X, GAME_SPEED -#include "global_events.h" // Para check -#include "global_inputs.h" // Para check -#include "jail_audio.h" // Para JA_PlayMusic -#include "options.h" // Para Options, options, OptionsStats, Secti... -#include "resource.h" // Para Resource -#include "s_animated_sprite.h" // Para SAnimatedSprite -#include "screen.h" // Para Screen -#include "text.h" // Para TEXT_CENTER, TEXT_COLOR, Text -#include "utils.h" // Para PaletteColor, stringToColor +#include "defines.h" // Para GAMECANVAS_CENTER_X, GAME_SPEED +#include "external/jail_audio.h" // Para JA_PlayMusic +#include "global_events.h" // Para check +#include "global_inputs.h" // Para check +#include "options.h" // Para Options, options, OptionsStats, Secti... +#include "resource.h" // Para Resource +#include "screen.h" // Para Screen +#include "sprite/surface_animated_sprite.h" // Para SAnimatedSprite +#include "text.h" // Para TEXT_CENTER, TEXT_COLOR, Text +#include "utils.h" // Para PaletteColor, stringToColor // Constructor GameOver::GameOver() diff --git a/source/sections/game_over.h b/source/sections/game_over.h index 054bb5f..7884ac5 100644 --- a/source/sections/game_over.h +++ b/source/sections/game_over.h @@ -1,6 +1,6 @@ #pragma once -#include // Para Uint8, Uint32 +#include #include // Para shared_ptr #include // Para vector diff --git a/source/sections/loading_screen.cpp b/source/sections/loading_screen.cpp index 78f5968..d53d0da 100644 --- a/source/sections/loading_screen.cpp +++ b/source/sections/loading_screen.cpp @@ -1,19 +1,18 @@ #include "loading_screen.h" -#include // Para SDL_PollEvent, SDL_Event -#include // Para SDL_GetTicks -#include // Para rand +#include +#include // Para rand -#include "defines.h" // Para GAME_SPEED -#include "global_events.h" // Para check -#include "global_inputs.h" // Para check -#include "jail_audio.h" // Para JA_PlayMusic, JA_SetVolume, JA_StopMusic -#include "options.h" // Para Options, options, SectionState, Options... -#include "resource.h" // Para Resource -#include "s_sprite.h" // Para SSprite -#include "screen.h" // Para Screen -#include "surface.h" // Para Surface -#include "utils.h" // Para stringToColor, PaletteColor +#include "defines.h" // Para GAME_SPEED +#include "external/jail_audio.h" // Para JA_PlayMusic, JA_SetVolume, JA_StopMusic +#include "global_events.h" // Para check +#include "global_inputs.h" // Para check +#include "options.h" // Para Options, options, SectionState, Options... +#include "resource.h" // Para Resource +#include "screen.h" // Para Screen +#include "sprite/surface_sprite.h" // Para SSprite +#include "surface.h" // Para Surface +#include "utils.h" // Para stringToColor, PaletteColor // Constructor LoadingScreen::LoadingScreen() diff --git a/source/sections/loading_screen.h b/source/sections/loading_screen.h index 1fd5067..8c79c79 100644 --- a/source/sections/loading_screen.h +++ b/source/sections/loading_screen.h @@ -1,7 +1,6 @@ #pragma once -#include // Para SDL_Rect -#include // Para Uint32 +#include #include // Para shared_ptr class SSprite; // lines 7-7 diff --git a/source/sections/logo.cpp b/source/sections/logo.cpp index 59006e2..9989fce 100644 --- a/source/sections/logo.cpp +++ b/source/sections/logo.cpp @@ -1,17 +1,16 @@ #include "logo.h" -#include // Para SDL_PollEvent, SDL_Event -#include // Para SDL_GetTicks +#include -#include "defines.h" // Para GAME_SPEED -#include "global_events.h" // Para check -#include "global_inputs.h" // Para check -#include "options.h" // Para Options, SectionState, options, Section -#include "resource.h" // Para Resource -#include "s_sprite.h" // Para SSprite -#include "screen.h" // Para Screen -#include "surface.h" // Para Surface -#include "utils.h" // Para PaletteColor +#include "defines.h" // Para GAME_SPEED +#include "global_events.h" // Para check +#include "global_inputs.h" // Para check +#include "options.h" // Para Options, SectionState, options, Section +#include "resource.h" // Para Resource +#include "screen.h" // Para Screen +#include "sprite/surface_sprite.h" // Para SSprite +#include "surface.h" // Para Surface +#include "utils.h" // Para PaletteColor // Constructor Logo::Logo() diff --git a/source/sections/logo.h b/source/sections/logo.h index a1e2e03..6b4e4da 100644 --- a/source/sections/logo.h +++ b/source/sections/logo.h @@ -1,6 +1,6 @@ #pragma once -#include // Para Uint8, Uint32 +#include #include // Para shared_ptr #include // Para vector diff --git a/source/sections/title.cpp b/source/sections/title.cpp index 710f5b9..4c5c992 100644 --- a/source/sections/title.cpp +++ b/source/sections/title.cpp @@ -1,23 +1,21 @@ #include "title.h" -#include // Para SDL_PollEvent, SDL_Event, SDL_KEYDOWN -#include // Para SDL_SCANCODE_1, SDL_SCANCODE_2 -#include // Para SDL_GetTicks +#include #include // Para clamp -#include "cheevos.h" // Para Cheevos, Achievement -#include "defines.h" // Para PLAY_AREA_CENTER_X, GAMECANVAS_WIDTH -#include "global_events.h" // Para check -#include "global_inputs.h" // Para check -#include "input.h" // Para Input, InputAction, INPUT_DO_NOT_ALLOW_REPEAT, REP... -#include "options.h" // Para Options, options, SectionState, Section -#include "resource.h" // Para Resource -#include "s_sprite.h" // Para SSprite -#include "screen.h" // Para Screen -#include "surface.h" // Para Surface -#include "text.h" // Para Text, TEXT_CENTER, TEXT_COLOR -#include "utils.h" // Para stringToColor, PaletteColor, playMusic +#include "cheevos.h" // Para Cheevos, Achievement +#include "defines.h" // Para PLAY_AREA_CENTER_X, GAMECANVAS_WIDTH +#include "global_events.h" // Para check +#include "global_inputs.h" // Para check +#include "input.h" // Para Input, InputAction, INPUT_DO_NOT_ALLOW_REPEAT, REP... +#include "options.h" // Para Options, options, SectionState, Section +#include "resource.h" // Para Resource +#include "screen.h" // Para Screen +#include "sprite/surface_sprite.h" // Para SSprite +#include "surface.h" // Para Surface +#include "text.h" // Para Text, TEXT_CENTER, TEXT_COLOR +#include "utils.h" // Para stringToColor, PaletteColor, playMusic // Constructor Title::Title() diff --git a/source/sections/title.h b/source/sections/title.h index aed0f0f..d35f779 100644 --- a/source/sections/title.h +++ b/source/sections/title.h @@ -1,7 +1,6 @@ #pragma once -#include // Para SDL_Rect -#include // Para Uint32 +#include #include // Para shared_ptr #include // Para string diff --git a/source/sprite/surface_animated_sprite.cpp b/source/sprite/surface_animated_sprite.cpp index 25fa1a2..6854b82 100644 --- a/source/sprite/surface_animated_sprite.cpp +++ b/source/sprite/surface_animated_sprite.cpp @@ -1,269 +1,236 @@ -#include "s_animated_sprite.h" -#include // Para size_t -#include // Para basic_ostream, basic_istream, operator<<, basic... -#include // Para cout, cerr -#include // Para basic_stringstream -#include // Para runtime_error -#include "surface.h" // Para Surface -#include "utils.h" // Para printWithDots +#include "sprite/surface_animated_sprite.h" + +#include // Para size_t + +#include // Para basic_ostream, basic_istream, operator<<, basic... +#include // Para cout, cerr +#include // Para basic_stringstream +#include // Para runtime_error + +#include "surface.h" // Para Surface +#include "utils.h" // Para printWithDots // Carga las animaciones en un vector(Animations) desde un fichero -Animations loadAnimationsFromFile(const std::string &file_path) -{ - std::ifstream file(file_path); - if (!file) - { - std::cerr << "Error: Fichero no encontrado " << file_path << std::endl; - throw std::runtime_error("Fichero no encontrado: " + file_path); - } +Animations loadAnimationsFromFile(const std::string& file_path) { + std::ifstream file(file_path); + if (!file) { + std::cerr << "Error: Fichero no encontrado " << file_path << std::endl; + throw std::runtime_error("Fichero no encontrado: " + file_path); + } - printWithDots("Animation : ", file_path.substr(file_path.find_last_of("\\/") + 1), "[ LOADED ]"); + printWithDots("Animation : ", file_path.substr(file_path.find_last_of("\\/") + 1), "[ LOADED ]"); - std::vector buffer; - std::string line; - while (std::getline(file, line)) - { - if (!line.empty()) - buffer.push_back(line); - } + std::vector buffer; + std::string line; + while (std::getline(file, line)) { + if (!line.empty()) + buffer.push_back(line); + } - return buffer; + return buffer; } // Constructor -SAnimatedSprite::SAnimatedSprite(std::shared_ptr surface, const std::string &file_path) - : SMovingSprite(surface) -{ - // Carga las animaciones - if (!file_path.empty()) - { - Animations v = loadAnimationsFromFile(file_path); - setAnimations(v); - } +SAnimatedSprite::SAnimatedSprite(std::shared_ptr surface, const std::string& file_path) + : SMovingSprite(surface) { + // Carga las animaciones + if (!file_path.empty()) { + Animations v = loadAnimationsFromFile(file_path); + setAnimations(v); + } } // Constructor -SAnimatedSprite::SAnimatedSprite(std::shared_ptr surface, const Animations &animations) - : SMovingSprite(surface) -{ - if (!animations.empty()) - { - setAnimations(animations); - } +SAnimatedSprite::SAnimatedSprite(std::shared_ptr surface, const Animations& animations) + : SMovingSprite(surface) { + if (!animations.empty()) { + setAnimations(animations); + } } // Obtiene el indice de la animación a partir del nombre -int SAnimatedSprite::getIndex(const std::string &name) -{ - auto index = -1; +int SAnimatedSprite::getIndex(const std::string& name) { + auto index = -1; - for (const auto &a : animations_) - { - index++; - if (a.name == name) - { - return index; - } - } - std::cout << "** Warning: could not find \"" << name.c_str() << "\" animation" << std::endl; - return -1; + for (const auto& a : animations_) { + index++; + if (a.name == name) { + return index; + } + } + std::cout << "** Warning: could not find \"" << name.c_str() << "\" animation" << std::endl; + return -1; } // Calcula el frame correspondiente a la animación -void SAnimatedSprite::animate() -{ - if (animations_[current_animation_].speed == 0) - { - return; - } +void SAnimatedSprite::animate() { + if (animations_[current_animation_].speed == 0) { + return; + } - // Calcula el frame actual a partir del contador - animations_[current_animation_].current_frame = animations_[current_animation_].counter / animations_[current_animation_].speed; + // Calcula el frame actual a partir del contador + animations_[current_animation_].current_frame = animations_[current_animation_].counter / animations_[current_animation_].speed; - // Si alcanza el final de la animación, reinicia el contador de la animación - // en función de la variable loop y coloca el nuevo frame - if (animations_[current_animation_].current_frame >= static_cast(animations_[current_animation_].frames.size())) - { - if (animations_[current_animation_].loop == -1) - { // Si no hay loop, deja el último frame - animations_[current_animation_].current_frame = animations_[current_animation_].frames.size(); - animations_[current_animation_].completed = true; - } - else - { // Si hay loop, vuelve al frame indicado - animations_[current_animation_].counter = 0; - animations_[current_animation_].current_frame = animations_[current_animation_].loop; - } - } - // En caso contrario - else - { - // Escoge el frame correspondiente de la animación - setClip(animations_[current_animation_].frames[animations_[current_animation_].current_frame]); + // Si alcanza el final de la animación, reinicia el contador de la animación + // en función de la variable loop y coloca el nuevo frame + if (animations_[current_animation_].current_frame >= static_cast(animations_[current_animation_].frames.size())) { + if (animations_[current_animation_].loop == -1) { // Si no hay loop, deja el último frame + animations_[current_animation_].current_frame = animations_[current_animation_].frames.size(); + animations_[current_animation_].completed = true; + } else { // Si hay loop, vuelve al frame indicado + animations_[current_animation_].counter = 0; + animations_[current_animation_].current_frame = animations_[current_animation_].loop; + } + } + // En caso contrario + else { + // Escoge el frame correspondiente de la animación + setClip(animations_[current_animation_].frames[animations_[current_animation_].current_frame]); - // Incrementa el contador de la animacion - animations_[current_animation_].counter++; - } + // Incrementa el contador de la animacion + animations_[current_animation_].counter++; + } } // Comprueba si ha terminado la animación -bool SAnimatedSprite::animationIsCompleted() -{ - return animations_[current_animation_].completed; +bool SAnimatedSprite::animationIsCompleted() { + return animations_[current_animation_].completed; } // Establece la animacion actual -void SAnimatedSprite::setCurrentAnimation(const std::string &name) -{ - const auto new_animation = getIndex(name); - if (current_animation_ != new_animation) - { - current_animation_ = new_animation; - animations_[current_animation_].current_frame = 0; - animations_[current_animation_].counter = 0; - animations_[current_animation_].completed = false; - setClip(animations_[current_animation_].frames[animations_[current_animation_].current_frame]); - } +void SAnimatedSprite::setCurrentAnimation(const std::string& name) { + const auto new_animation = getIndex(name); + if (current_animation_ != new_animation) { + current_animation_ = new_animation; + animations_[current_animation_].current_frame = 0; + animations_[current_animation_].counter = 0; + animations_[current_animation_].completed = false; + setClip(animations_[current_animation_].frames[animations_[current_animation_].current_frame]); + } } // Establece la animacion actual -void SAnimatedSprite::setCurrentAnimation(int index) -{ - const auto new_animation = index; - if (current_animation_ != new_animation) - { - current_animation_ = new_animation; - animations_[current_animation_].current_frame = 0; - animations_[current_animation_].counter = 0; - animations_[current_animation_].completed = false; - setClip(animations_[current_animation_].frames[animations_[current_animation_].current_frame]); - } +void SAnimatedSprite::setCurrentAnimation(int index) { + const auto new_animation = index; + if (current_animation_ != new_animation) { + current_animation_ = new_animation; + animations_[current_animation_].current_frame = 0; + animations_[current_animation_].counter = 0; + animations_[current_animation_].completed = false; + setClip(animations_[current_animation_].frames[animations_[current_animation_].current_frame]); + } } // Actualiza las variables del objeto -void SAnimatedSprite::update() -{ - animate(); - SMovingSprite::update(); +void SAnimatedSprite::update() { + animate(); + SMovingSprite::update(); } // Reinicia la animación -void SAnimatedSprite::resetAnimation() -{ - animations_[current_animation_].current_frame = 0; - animations_[current_animation_].counter = 0; - animations_[current_animation_].completed = false; +void SAnimatedSprite::resetAnimation() { + animations_[current_animation_].current_frame = 0; + animations_[current_animation_].counter = 0; + animations_[current_animation_].completed = false; } // Carga la animación desde un vector de cadenas -void SAnimatedSprite::setAnimations(const Animations &animations) -{ - int frame_width = 1; - int frame_height = 1; - int frames_per_row = 1; - int max_tiles = 1; +void SAnimatedSprite::setAnimations(const Animations& animations) { + int frame_width = 1; + int frame_height = 1; + int frames_per_row = 1; + int max_tiles = 1; - size_t index = 0; - while (index < animations.size()) - { - std::string line = animations.at(index); + size_t index = 0; + while (index < animations.size()) { + std::string line = animations.at(index); - // Parsea el fichero para buscar variables y valores - if (line != "[animation]") - { - // Encuentra la posición del caracter '=' - size_t pos = line.find("="); + // Parsea el fichero para buscar variables y valores + if (line != "[animation]") { + // Encuentra la posición del caracter '=' + size_t pos = line.find("="); - // Procesa las dos subcadenas - if (pos != std::string::npos) - { - std::string key = line.substr(0, pos); - int value = std::stoi(line.substr(pos + 1)); - if (key == "frame_width") - frame_width = value; - else if (key == "frame_height") - frame_height = value; - else - std::cout << "Warning: unknown parameter " << key << std::endl; + // Procesa las dos subcadenas + if (pos != std::string::npos) { + std::string key = line.substr(0, pos); + int value = std::stoi(line.substr(pos + 1)); + if (key == "frame_width") + frame_width = value; + else if (key == "frame_height") + frame_height = value; + else + std::cout << "Warning: unknown parameter " << key << std::endl; - frames_per_row = surface_->getWidth() / frame_width; - const int w = surface_->getWidth() / frame_width; - const int h = surface_->getHeight() / frame_height; - max_tiles = w * h; - } - } + frames_per_row = surface_->getWidth() / frame_width; + const int w = surface_->getWidth() / frame_width; + const int h = surface_->getHeight() / frame_height; + max_tiles = w * h; + } + } - // Si la linea contiene el texto [animation] se realiza el proceso de carga de una animación - if (line == "[animation]") - { - AnimationData animation; - do - { - index++; - line = animations.at(index); - size_t pos = line.find("="); + // Si la linea contiene el texto [animation] se realiza el proceso de carga de una animación + if (line == "[animation]") { + AnimationData animation; + do { + index++; + line = animations.at(index); + size_t pos = line.find("="); - if (pos != std::string::npos) - { - std::string key = line.substr(0, pos); - std::string value = line.substr(pos + 1); + if (pos != std::string::npos) { + std::string key = line.substr(0, pos); + std::string value = line.substr(pos + 1); - if (key == "name") - animation.name = value; - else if (key == "speed") - animation.speed = std::stoi(value); - else if (key == "loop") - animation.loop = std::stoi(value); - else if (key == "frames") - { - // Se introducen los valores separados por comas en un vector - std::stringstream ss(value); - std::string tmp; - SDL_Rect rect = {0, 0, frame_width, frame_height}; - while (getline(ss, tmp, ',')) - { - // Comprueba que el tile no sea mayor que el maximo indice permitido - const int num_tile = std::stoi(tmp); - if (num_tile <= max_tiles) - { - rect.x = (num_tile % frames_per_row) * frame_width; - rect.y = (num_tile / frames_per_row) * frame_height; - animation.frames.emplace_back(rect); - } - } - } + if (key == "name") + animation.name = value; + else if (key == "speed") + animation.speed = std::stoi(value); + else if (key == "loop") + animation.loop = std::stoi(value); + else if (key == "frames") { + // Se introducen los valores separados por comas en un vector + std::stringstream ss(value); + std::string tmp; + SDL_Rect rect = {0, 0, frame_width, frame_height}; + while (getline(ss, tmp, ',')) { + // Comprueba que el tile no sea mayor que el maximo indice permitido + const int num_tile = std::stoi(tmp); + if (num_tile <= max_tiles) { + rect.x = (num_tile % frames_per_row) * frame_width; + rect.y = (num_tile / frames_per_row) * frame_height; + animation.frames.emplace_back(rect); + } + } + } - else - std::cout << "Warning: unknown parameter " << key << std::endl; - } - } while (line != "[/animation]"); + else + std::cout << "Warning: unknown parameter " << key << std::endl; + } + } while (line != "[/animation]"); - // Añade la animación al vector de animaciones - animations_.emplace_back(animation); - } + // Añade la animación al vector de animaciones + animations_.emplace_back(animation); + } - // Una vez procesada la linea, aumenta el indice para pasar a la siguiente - index++; - } + // Una vez procesada la linea, aumenta el indice para pasar a la siguiente + index++; + } - // Pone un valor por defecto - setWidth(frame_width); - setHeight(frame_height); + // Pone un valor por defecto + setWidth(frame_width); + setHeight(frame_height); } // Establece el frame actual de la animación -void SAnimatedSprite::setCurrentAnimationFrame(int num) -{ - // Descarta valores fuera de rango - if (num < 0 || num >= static_cast(animations_[current_animation_].frames.size())) - { - num = 0; - } +void SAnimatedSprite::setCurrentAnimationFrame(int num) { + // Descarta valores fuera de rango + if (num < 0 || num >= static_cast(animations_[current_animation_].frames.size())) { + num = 0; + } - // Cambia el valor de la variable - animations_[current_animation_].current_frame = num; - animations_[current_animation_].counter = 0; + // Cambia el valor de la variable + animations_[current_animation_].current_frame = num; + animations_[current_animation_].counter = 0; - // Escoge el frame correspondiente de la animación - setClip(animations_[current_animation_].frames[animations_[current_animation_].current_frame]); + // Escoge el frame correspondiente de la animación + setClip(animations_[current_animation_].frames[animations_[current_animation_].current_frame]); } \ No newline at end of file diff --git a/source/sprite/surface_animated_sprite.h b/source/sprite/surface_animated_sprite.h index 0a83f4d..0fd65f7 100644 --- a/source/sprite/surface_animated_sprite.h +++ b/source/sprite/surface_animated_sprite.h @@ -1,13 +1,13 @@ #pragma once -#include // Para SDL_Rect +#include #include // Para shared_ptr #include // Para string #include // Para vector -#include "s_moving_sprite.h" // Para SMovingSprite -class Surface; // lines 9-9 +#include "sprite/surface_moving_sprite.h" // Para SMovingSprite +class Surface; // lines 9-9 struct AnimationData { std::string name; // Nombre de la animacion diff --git a/source/sprite/surface_moving_sprite.cpp b/source/sprite/surface_moving_sprite.cpp index 0cda10c..7ed57cb 100644 --- a/source/sprite/surface_moving_sprite.cpp +++ b/source/sprite/surface_moving_sprite.cpp @@ -1,102 +1,94 @@ -#include "s_moving_sprite.h" -#include "surface.h" // Para Surface +#include "sprite/surface_moving_sprite.h" + +#include "surface.h" // Para Surface // Constructor SMovingSprite::SMovingSprite(std::shared_ptr surface, SDL_Rect pos, SDL_RendererFlip flip) - : SSprite(surface, pos), - x_(pos.x), - y_(pos.y), - flip_(flip) { SSprite::pos_ = pos; } + : SSprite(surface, pos), + x_(pos.x), + y_(pos.y), + flip_(flip) { SSprite::pos_ = pos; } SMovingSprite::SMovingSprite(std::shared_ptr surface, SDL_Rect pos) - : SSprite(surface, pos), - x_(pos.x), - y_(pos.y), - flip_(SDL_FLIP_NONE) { SSprite::pos_ = pos; } + : SSprite(surface, pos), + x_(pos.x), + y_(pos.y), + flip_(SDL_FLIP_NONE) { SSprite::pos_ = pos; } SMovingSprite::SMovingSprite(std::shared_ptr surface) - : SSprite(surface), - x_(0.0f), - y_(0.0f), - flip_(SDL_FLIP_NONE) { SSprite::clear(); } + : SSprite(surface), + x_(0.0f), + y_(0.0f), + flip_(SDL_FLIP_NONE) { SSprite::clear(); } // Reinicia todas las variables -void SMovingSprite::clear() -{ - x_ = 0.0f; // Posición en el eje X - y_ = 0.0f; // Posición en el eje Y +void SMovingSprite::clear() { + x_ = 0.0f; // Posición en el eje X + y_ = 0.0f; // Posición en el eje Y - vx_ = 0.0f; // Velocidad en el eje X. Cantidad de pixeles a desplazarse - vy_ = 0.0f; // Velocidad en el eje Y. Cantidad de pixeles a desplazarse + vx_ = 0.0f; // Velocidad en el eje X. Cantidad de pixeles a desplazarse + vy_ = 0.0f; // Velocidad en el eje Y. Cantidad de pixeles a desplazarse - ax_ = 0.0f; // Aceleración en el eje X. Variación de la velocidad - ay_ = 0.0f; // Aceleración en el eje Y. Variación de la velocidad + ax_ = 0.0f; // Aceleración en el eje X. Variación de la velocidad + ay_ = 0.0f; // Aceleración en el eje Y. Variación de la velocidad - flip_ = SDL_FLIP_NONE; // Establece como se ha de voltear el sprite + flip_ = SDL_FLIP_NONE; // Establece como se ha de voltear el sprite - SSprite::clear(); + SSprite::clear(); } // Mueve el sprite -void SMovingSprite::move() -{ - x_ += vx_; - y_ += vy_; +void SMovingSprite::move() { + x_ += vx_; + y_ += vy_; - vx_ += ax_; - vy_ += ay_; + vx_ += ax_; + vy_ += ay_; - pos_.x = static_cast(x_); - pos_.y = static_cast(y_); + pos_.x = static_cast(x_); + pos_.y = static_cast(y_); } // Actualiza las variables internas del objeto -void SMovingSprite::update() -{ - move(); +void SMovingSprite::update() { + move(); } // Muestra el sprite por pantalla -void SMovingSprite::render() -{ - surface_->render(pos_.x, pos_.y, &clip_, flip_); +void SMovingSprite::render() { + surface_->render(pos_.x, pos_.y, &clip_, flip_); } // Muestra el sprite por pantalla -void SMovingSprite::render(Uint8 source_color, Uint8 target_color) -{ - surface_->renderWithColorReplace(pos_.x, pos_.y, source_color, target_color, &clip_, flip_); +void SMovingSprite::render(Uint8 source_color, Uint8 target_color) { + surface_->renderWithColorReplace(pos_.x, pos_.y, source_color, target_color, &clip_, flip_); } // Establece la posición y_ el tamaño del objeto -void SMovingSprite::setPos(SDL_Rect rect) -{ - x_ = static_cast(rect.x); - y_ = static_cast(rect.y); +void SMovingSprite::setPos(SDL_Rect rect) { + x_ = static_cast(rect.x); + y_ = static_cast(rect.y); - pos_ = rect; + pos_ = rect; } // Establece el valor de las variables -void SMovingSprite::setPos(float x, float y) -{ - x_ = x; - y_ = y; +void SMovingSprite::setPos(float x, float y) { + x_ = x; + y_ = y; - pos_.x = static_cast(x_); - pos_.y = static_cast(y_); + pos_.x = static_cast(x_); + pos_.y = static_cast(y_); } // Establece el valor de la variable -void SMovingSprite::setPosX(float value) -{ - x_ = value; - pos_.x = static_cast(x_); +void SMovingSprite::setPosX(float value) { + x_ = value; + pos_.x = static_cast(x_); } // Establece el valor de la variable -void SMovingSprite::setPosY(float value) -{ - y_ = value; - pos_.y = static_cast(y_); +void SMovingSprite::setPosY(float value) { + y_ = value; + pos_.y = static_cast(y_); } \ No newline at end of file diff --git a/source/sprite/surface_moving_sprite.h b/source/sprite/surface_moving_sprite.h index bea7e2d..87d6626 100644 --- a/source/sprite/surface_moving_sprite.h +++ b/source/sprite/surface_moving_sprite.h @@ -1,13 +1,11 @@ #pragma once -#include // Para SDL_Rect -#include // Para SDL_RendererFlip, SDL_FLIP_HORIZONTAL -#include // Para Uint8 +#include #include // Para shared_ptr -#include "s_sprite.h" // Para SSprite -class Surface; // lines 8-8 +#include "sprite/surface_sprite.h" // Para SSprite +class Surface; // lines 8-8 // Clase SMovingSprite. Añade movimiento y flip al sprite class SMovingSprite : public SSprite { diff --git a/source/sprite/surface_sprite.cpp b/source/sprite/surface_sprite.cpp index a211c38..c28b6eb 100644 --- a/source/sprite/surface_sprite.cpp +++ b/source/sprite/surface_sprite.cpp @@ -1,50 +1,46 @@ -#include "s_sprite.h" -#include "surface.h" // Para Surface +#include "sprite/surface_sprite.h" + +#include "surface.h" // Para Surface // Constructor SSprite::SSprite(std::shared_ptr surface, int x, int y, int w, int h) - : surface_(surface), - pos_((SDL_Rect){x, y, w, h}), - clip_((SDL_Rect){0, 0, pos_.w, pos_.h}) {} + : surface_(surface), + pos_((SDL_Rect){x, y, w, h}), + clip_((SDL_Rect){0, 0, pos_.w, pos_.h}) {} SSprite::SSprite(std::shared_ptr surface, SDL_Rect rect) - : surface_(surface), - pos_(rect), - clip_((SDL_Rect){0, 0, pos_.w, pos_.h}) {} + : surface_(surface), + pos_(rect), + clip_((SDL_Rect){0, 0, pos_.w, pos_.h}) {} SSprite::SSprite(std::shared_ptr surface) - : surface_(surface), - pos_({0, 0, surface_->getWidth(), surface_->getHeight()}), - clip_(pos_) {} + : surface_(surface), + pos_({0, 0, surface_->getWidth(), surface_->getHeight()}), + clip_(pos_) {} // Muestra el sprite por pantalla -void SSprite::render() -{ - surface_->render(pos_.x, pos_.y, &clip_); +void SSprite::render() { + surface_->render(pos_.x, pos_.y, &clip_); } -void SSprite::render(Uint8 source_color, Uint8 target_color) -{ - surface_->renderWithColorReplace(pos_.x, pos_.y, source_color, target_color, &clip_); +void SSprite::render(Uint8 source_color, Uint8 target_color) { + surface_->renderWithColorReplace(pos_.x, pos_.y, source_color, target_color, &clip_); } // Establece la posición del objeto -void SSprite::setPosition(int x, int y) -{ - pos_.x = x; - pos_.y = y; +void SSprite::setPosition(int x, int y) { + pos_.x = x; + pos_.y = y; } // Establece la posición del objeto -void SSprite::setPosition(SDL_Point p) -{ - pos_.x = p.x; - pos_.y = p.y; +void SSprite::setPosition(SDL_Point p) { + pos_.x = p.x; + pos_.y = p.y; } // Reinicia las variables a cero -void SSprite::clear() -{ - pos_ = {0, 0, 0, 0}; - clip_ = {0, 0, 0, 0}; +void SSprite::clear() { + pos_ = {0, 0, 0, 0}; + clip_ = {0, 0, 0, 0}; } \ No newline at end of file diff --git a/source/sprite/surface_sprite.h b/source/sprite/surface_sprite.h index 28910e0..e0d8213 100644 --- a/source/sprite/surface_sprite.h +++ b/source/sprite/surface_sprite.h @@ -1,7 +1,6 @@ #pragma once -#include // Para SDL_Rect, SDL_Point -#include // Para Uint8 +#include #include // Para shared_ptr class Surface; // lines 5-5 diff --git a/source/surface.cpp b/source/surface.cpp index 6b00a0a..183e3d2 100644 --- a/source/surface.cpp +++ b/source/surface.cpp @@ -1,8 +1,6 @@ // IWYU pragma: no_include #include "surface.h" - -#include // Para SDL_GetError -#include // Para SDL_GetTicks +#include #include // Para min, max, copy_n, fill #include // Para abs diff --git a/source/surface.h b/source/surface.h index 812ee80..3d75b6c 100644 --- a/source/surface.h +++ b/source/surface.h @@ -1,8 +1,6 @@ #pragma once -#include // Para SDL_Rect -#include // Para SDL_FLIP_NONE, SDL_RendererFlip, SDL_Re... -#include // Para Uint8, Uint16, Uint32 +#include #include // Para array #include // Para default_delete, shared_ptr, __shared_pt... diff --git a/source/text.cpp b/source/text.cpp index a837b00..0ec1093 100644 --- a/source/text.cpp +++ b/source/text.cpp @@ -1,16 +1,16 @@ #include "text.h" -#include // Para SDL_Rect -#include // Para size_t +#include +#include // Para size_t #include // Para basic_ifstream, basic_istream, basic_ostream #include // Para cerr #include // Para runtime_error -#include "s_sprite.h" // Para SSprite -#include "screen.h" // Para Screen -#include "surface.h" // Para Surface -#include "utils.h" // Para getFileName, stringToColor, printWithDots +#include "screen.h" // Para Screen +#include "sprite/surface_sprite.h" // Para SSprite +#include "surface.h" // Para Surface +#include "utils.h" // Para getFileName, stringToColor, printWithDots // Llena una estructuta TextFile desde un fichero std::shared_ptr loadTextFile(const std::string& file_path) { diff --git a/source/text.h b/source/text.h index 8df30c2..9e0ade0 100644 --- a/source/text.h +++ b/source/text.h @@ -1,12 +1,12 @@ #pragma once -#include // Para Uint8 +#include #include // Para shared_ptr, unique_ptr #include // Para string -#include "s_sprite.h" // Para SSprite -class Surface; // lines 8-8 +#include "sprite/surface_sprite.h" // Para SSprite +class Surface; // lines 8-8 constexpr int TEXT_COLOR = 1; constexpr int TEXT_SHADOW = 2; diff --git a/source/texture.cpp b/source/texture.cpp index 66193c3..0bff2ca 100644 --- a/source/texture.cpp +++ b/source/texture.cpp @@ -1,8 +1,7 @@ #include "texture.h" +#include -#include // Para SDL_GetError -#include // Para SDL_CreateRGBSurfaceWithFormatFrom #include // Para basic_ostream, operator<<, endl, cout #include // Para runtime_error @@ -12,7 +11,7 @@ #include "utils.h" // Para getFileName, Color, printWithDots #define STB_IMAGE_IMPLEMENTATION -#include "stb_image.h" // para stbi_failure_reason, stbi_image_free +#include "external/stb_image.h" // para stbi_failure_reason, stbi_image_free // Constructor Texture::Texture(SDL_Renderer* renderer, const std::string& path) @@ -53,7 +52,7 @@ bool Texture::loadFromFile(const std::string& file_path) { } int depth, pitch; - Uint32 pixel_format; + SDL_PixelFormat pixel_format; // STBI_rgb_alpha (RGBA) depth = 32; pitch = 4 * width; @@ -66,22 +65,22 @@ bool Texture::loadFromFile(const std::string& file_path) { SDL_Texture* newTexture = nullptr; // Carga la imagen desde una ruta específica - auto loadedSurface = SDL_CreateRGBSurfaceWithFormatFrom(static_cast(data), width, height, depth, pitch, pixel_format); - if (loadedSurface == nullptr) { + auto *loaded_surface = SDL_CreateSurfaceFrom(width, height, pixel_format, static_cast(data), pitch); + if (loaded_surface == nullptr) { std::cout << "Unable to load image " << file_path << std::endl; } else { // Crea la textura desde los pixels de la surface - newTexture = SDL_CreateTextureFromSurface(renderer_, loadedSurface); + newTexture = SDL_CreateTextureFromSurface(renderer_, loaded_surface); if (newTexture == nullptr) { std::cout << "Unable to create texture from " << file_path << "! SDL Error: " << SDL_GetError() << std::endl; } else { // Obtiene las dimensiones de la imagen - width_ = loadedSurface->w; - height_ = loadedSurface->h; + width_ = loaded_surface->w; + height_ = loaded_surface->h; } // Elimina la textura cargada - SDL_FreeSurface(loadedSurface); + SDL_DestroySurface(loaded_surface); } // Return success @@ -91,11 +90,11 @@ bool Texture::loadFromFile(const std::string& file_path) { } // Crea una textura en blanco -bool Texture::createBlank(int width, int height, SDL_PixelFormatEnum format, SDL_TextureAccess access) { +auto Texture::createBlank(int width, int height, SDL_PixelFormat format, SDL_TextureAccess access) -> bool { // Crea una textura sin inicializar texture_ = SDL_CreateTexture(renderer_, format, access, width, height); - if (!texture_) { - std::cout << "Unable to create blank texture! SDL Error: " << SDL_GetError() << std::endl; + if (texture_ == nullptr) { + SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Unable to create blank texture! SDL Error: %s", SDL_GetError()); } else { width_ = width; height_ = height; @@ -126,28 +125,28 @@ void Texture::setBlendMode(SDL_BlendMode blending) { SDL_SetTextureBlendMode(tex void Texture::setAlpha(Uint8 alpha) { SDL_SetTextureAlphaMod(texture_, alpha); } // Renderiza la textura en un punto específico -void Texture::render(int x, int y, SDL_Rect* clip, float zoomW, float zoomH, double angle, SDL_Point* center, SDL_RendererFlip flip) { +void Texture::render(int x, int y, SDL_FRect* clip, float zoomW, float zoomH, double angle, SDL_FPoint* center, SDL_FlipMode flip) { // Establece el destino de renderizado en la pantalla - SDL_Rect renderQuad = {x, y, width_, height_}; + SDL_FRect render_quad = {x, y, width_, height_}; // Obtiene las dimesiones del clip de renderizado if (clip != nullptr) { - renderQuad.w = clip->w; - renderQuad.h = clip->h; + render_quad.w = clip->w; + render_quad.h = clip->h; } // Calcula el zoom y las coordenadas if (zoomH != 1.0f || zoomW != 1.0f) { - renderQuad.x = renderQuad.x + (renderQuad.w / 2); - renderQuad.y = renderQuad.y + (renderQuad.h / 2); - renderQuad.w = renderQuad.w * zoomW; - renderQuad.h = renderQuad.h * zoomH; - renderQuad.x = renderQuad.x - (renderQuad.w / 2); - renderQuad.y = renderQuad.y - (renderQuad.h / 2); + render_quad.x = render_quad.x + (render_quad.w / 2); + render_quad.y = render_quad.y + (render_quad.h / 2); + render_quad.w = render_quad.w * zoomW; + render_quad.h = render_quad.h * zoomH; + render_quad.x = render_quad.x - (render_quad.w / 2); + render_quad.y = render_quad.y - (render_quad.h / 2); } // Renderiza a pantalla - SDL_RenderCopyEx(renderer_, texture_, clip, &renderQuad, angle, center, flip); + SDL_RenderTextureRotated(renderer_, texture_, clip, &render_quad, angle, center, flip); } // Establece la textura como objetivo de renderizado diff --git a/source/texture.h b/source/texture.h index 110a5f3..4dd0e40 100644 --- a/source/texture.h +++ b/source/texture.h @@ -1,10 +1,6 @@ #pragma once -#include // Para SDL_BlendMode -#include // Para SDL_PIXELFORMAT_RGBA8888, SDL_PixelF... -#include // Para SDL_Point, SDL_Rect -#include // Para SDL_Renderer, SDL_FLIP_NONE, SDL_TEX... -#include // Para Uint8, Uint32 +#include #include // Para string #include // Para vector @@ -36,7 +32,7 @@ class Texture { bool loadFromFile(const std::string& path); // Crea una textura en blanco - bool createBlank(int width, int height, SDL_PixelFormatEnum format = SDL_PIXELFORMAT_RGBA8888, SDL_TextureAccess = SDL_TEXTUREACCESS_TARGET); + auto createBlank(int width, int height, SDL_PixelFormat format = SDL_PIXELFORMAT_RGBA8888, SDL_TextureAccess access = SDL_TEXTUREACCESS_STREAMING) -> bool; // Establece el color para la modulacion void setColor(Uint8 red, Uint8 green, Uint8 blue); @@ -49,7 +45,7 @@ class Texture { void setAlpha(Uint8 alpha); // Renderiza la textura en un punto específico - void render(int x, int y, SDL_Rect* clip = nullptr, float zoomW = 1, float zoomH = 1, double angle = 0.0, SDL_Point* center = nullptr, SDL_RendererFlip flip = SDL_FLIP_NONE); + void render(int x, int y, SDL_FRect* clip = nullptr, float zoomW = 1, float zoomH = 1, double angle = 0.0, SDL_FPoint* center = nullptr, SDL_FlipMode flip = SDL_FLIP_NONE); // Establece la textura como objetivo de renderizado void setAsRenderTarget(SDL_Renderer* renderer); diff --git a/source/ui/notifier.cpp b/source/ui/notifier.cpp index 908a959..1be8eed 100644 --- a/source/ui/notifier.cpp +++ b/source/ui/notifier.cpp @@ -1,20 +1,20 @@ -#include "notifier.h" +#include "ui/notifier.h" -#include // Para SDL_GetTicks +#include #include // Para remove_if #include // Para prev #include // Para string, basic_string #include // Para vector -#include "jail_audio.h" // Para JA_PlaySound -#include "options.h" // Para Options, options, NotificationPosition -#include "resource.h" // Para Resource -#include "s_sprite.h" // Para SSprite -#include "screen.h" // Para Screen -#include "surface.h" // Para Surface -#include "text.h" // Para Text, TEXT_CENTER, TEXT_COLOR -#include "utils.h" // Para PaletteColor +#include "external/jail_audio.h" // Para JA_PlaySound +#include "options.h" // Para Options, options, NotificationPosition +#include "resource.h" // Para Resource +#include "screen.h" // Para Screen +#include "sprite/surface_sprite.h" // Para SSprite +#include "surface.h" // Para Surface +#include "text.h" // Para Text, TEXT_CENTER, TEXT_COLOR +#include "utils.h" // Para PaletteColor // [SINGLETON] Notifier* Notifier::notifier_ = nullptr; diff --git a/source/ui/notifier.h b/source/ui/notifier.h index 004014a..b46a01d 100644 --- a/source/ui/notifier.h +++ b/source/ui/notifier.h @@ -1,7 +1,6 @@ #pragma once -#include // Para SDL_Rect -#include // Para Uint32, Uint8 +#include #include // Para shared_ptr #include // Para string, basic_string diff --git a/source/utils.cpp b/source/utils.cpp index 9c39fbf..9625188 100644 --- a/source/utils.cpp +++ b/source/utils.cpp @@ -12,8 +12,8 @@ #include // Para unordered_map, operator==, _Node_const_iter... #include // Para pair -#include "jail_audio.h" // Para JA_GetMusicState, JA_Music_state, JA_PlayMusic -#include "resource.h" // Para Resource +#include "external/jail_audio.h" // Para JA_GetMusicState, JA_Music_state, JA_PlayMusic +#include "resource.h" // Para Resource // Calcula el cuadrado de la distancia entre dos puntos double distanceSquared(int x1, int y1, int x2, int y2) { diff --git a/source/utils.h b/source/utils.h index effa7d6..0948a08 100644 --- a/source/utils.h +++ b/source/utils.h @@ -1,8 +1,6 @@ #pragma once -#include // Para SDL_Rect, SDL_Point -#include // Para SDL_Renderer, SDL_Texture -#include // Para Uint8 +#include #include // Para string #include // Para vector