corregits mes includes

llevats els errors en texture
This commit is contained in:
2025-10-15 09:14:30 +02:00
parent 78c5333144
commit 7c102e42cc
63 changed files with 1122 additions and 1621 deletions

View File

@@ -1,14 +1,13 @@
#include "cheevos.h"
#include <SDL3/SDL_error.h> // Para SDL_GetError
#include <SDL3/SDL_rwops.h> // Para SDL_RWFromFile, SDL_RWclose, SDL_RWwrite
#include <stddef.h> // Para NULL
#include <SDL3/SDL.h>
#include <stddef.h> // Para NULL
#include <fstream> // Para basic_ostream, operator<<, basic_ofstream
#include <iostream> // 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;

View File

@@ -1,6 +1,6 @@
#pragma once
#include <SDL3/SDL_rect.h> // Para SDL_Point
#include <SDL3/SDL.h>
#include <string> // Para string
#include <vector> // Para vector

View File

@@ -1,44 +1,34 @@
#include "director.h"
#include <SDL3/SDL.h> // Para SDL_Init, SDL_Quit, SDL_INIT_EV...
#include <SDL3/SDL_audio.h> // Para AUDIO_S16
#include <SDL3/SDL_blendmode.h> // Para SDL_BLENDMODE_BLEND
#include <SDL3/SDL_error.h> // Para SDL_GetError
#include <SDL3/SDL_events.h> // Para SDL_DISABLE
#include <SDL3/SDL_gamecontroller.h> // Para SDL_CONTROLLER_BUTTON_B, SDL_CO...
#include <SDL3/SDL_hints.h> // Para SDL_SetHint, SDL_HINT_RENDER_DR...
#include <SDL3/SDL_mouse.h> // Para SDL_ShowCursor
#include <SDL3/SDL_scancode.h> // Para SDL_SCANCODE_A, SDL_SCANCODE_ES...
#include <SDL3/SDL_stdinc.h> // Para Uint32
#include <SDL3/SDL_timer.h> // Para SDL_GetTicks
#include <errno.h> // Para errno, EEXIST, EACCES, ENAMETOO...
#include <stdio.h> // Para printf, perror
#include <sys/stat.h> // Para mkdir, stat, S_IRWXU
#include <unistd.h> // Para getuid
#include <SDL3/SDL.h>
#include <errno.h> // Para errno, EEXIST, EACCES, ENAMETOO...
#include <stdio.h> // Para printf, perror
#include <sys/stat.h> // Para mkdir, stat, S_IRWXU
#include <unistd.h> // Para getuid
#include <cstdlib> // Para exit, EXIT_FAILURE, srand
#include <iostream> // Para basic_ostream, operator<<, cout
#include <memory> // Para make_unique, unique_ptr
#include <string> // 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 <pwd.h>

View File

@@ -1,7 +1,6 @@
#pragma once
#include <SDL3/SDL_render.h> // Para SDL_Renderer
#include <SDL3/SDL_video.h> // Para SDL_Window
#include <SDL3/SDL.h>
#include <string> // Para string

View File

@@ -1,11 +1,11 @@
#include "enemy.h"
#include <SDL3/SDL_render.h> // Para SDL_RendererFlip, SDL_FLIP_NONE, SDL_...
#include <stdlib.h> // Para rand
#include <SDL3/SDL.h>
#include <stdlib.h> // 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)

View File

@@ -1,7 +1,6 @@
#pragma once
#include <SDL3/SDL_rect.h> // Para SDL_Rect
#include <SDL3/SDL_stdinc.h> // Para Uint8
#include <SDL3/SDL.h>
#include <memory> // Para shared_ptr
#include <string> // Para string

View File

@@ -1,7 +1,6 @@
#include "jail_audio.h"
#include "external/jail_audio.h"
#include <SDL3/SDL_rwops.h> // Para SDL_RWFromMem
#include <SDL3/SDL_timer.h> // Para SDL_GetTicks
#include <SDL3/SDL.h>
#include <stdint.h> // Para uint8_t, uint32_t
#include <stdio.h> // Para NULL, fseek, fclose, fopen, fread, ftell
#include <stdlib.h> // Para free, malloc

View File

@@ -1,7 +1,6 @@
#pragma once
#include <SDL3/SDL_audio.h> // Para SDL_AudioFormat
#include <SDL3/SDL_stdinc.h> // Para Uint32, Uint8
#include <SDL3/SDL.h>
struct JA_Music_t; // lines 5-5
struct JA_Sound_t; // lines 6-6

View File

@@ -1,7 +1,6 @@
#include "jail_shader.h"
#include "external/jail_shader.h"
#include <SDL3/SDL_rect.h> // Para SDL_Point
#include <SDL3/SDL_stdinc.h> // Para SDL_bool
#include <SDL3/SDL.h>
#include <cstring> // Para strncmp
#include <iostream> // Para basic_ostream, operator<<, endl, cout

View File

@@ -1,7 +1,6 @@
#pragma once
#include <SDL3/SDL_render.h> // Para SDL_Texture
#include <SDL3/SDL_video.h> // Para SDL_Window
#include <SDL3/SDL.h>
#include <string>

View File

@@ -1,6 +1,6 @@
#pragma once
#include <SDL3/SDL_events.h>
#include <SDL3/SDL.h>
namespace globalEvents {
// Comprueba los eventos que se pueden producir en cualquier sección del juego

View File

@@ -1,16 +1,15 @@
#include "global_inputs.h"
#include <SDL3/SDL_render.h> // Para SDL_RenderSetIntegerScale
#include <SDL3/SDL_stdinc.h> // Para SDL_FALSE, SDL_TRUE
#include <SDL3/SDL.h>
#include <string> // Para allocator, operator+, char_traits, string
#include <vector> // 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() {

View File

@@ -1,9 +1,6 @@
#include "input.h"
#include <SDL3/SDL.h> // Para SDL_INIT_GAMECONTROLLER, SDL_InitSubS...
#include <SDL3/SDL_error.h> // Para SDL_GetError
#include <SDL3/SDL_events.h> // Para SDL_ENABLE
#include <SDL3/SDL_keyboard.h> // Para SDL_GetKeyboardState
#include <SDL3/SDL.h>
#include <algorithm> // Para find
#include <iostream> // Para basic_ostream, operator<<, cout, endl

View File

@@ -1,8 +1,6 @@
#pragma once
#include <SDL3/SDL_gamecontroller.h> // Para SDL_GameControllerButton, SDL_G...
#include <SDL3/SDL_scancode.h> // Para SDL_Scancode
#include <SDL3/SDL_stdinc.h> // Para Uint8
#include <SDL3/SDL.h>
#include <string> // Para string, basic_string
#include <vector> // Para vector

View File

@@ -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<SSprite>(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();

View File

@@ -1,7 +1,6 @@
#pragma once
#include <SDL3/SDL_rect.h> // Para SDL_Rect, SDL_Point
#include <SDL3/SDL_stdinc.h> // Para Uint8
#include <SDL3/SDL.h>
#include <memory> // Para shared_ptr
#include <string> // Para string

View File

@@ -1,6 +1,6 @@
#pragma once
#include <SDL3/SDL_rect.h> // Para SDL_Point
#include <SDL3/SDL.h>
#include <string> // Para string, basic_string
#include <vector> // Para vector

View File

@@ -1,7 +1,5 @@
#include "mouse.h"
#include <SDL3/SDL_mouse.h> // Para SDL_ShowCursor
#include <SDL3/SDL_timer.h> // Para SDL_GetTicks
namespace Mouse {
Uint32 cursor_hide_time = 3000; // Tiempo en milisegundos para ocultar el cursor

View File

@@ -1,7 +1,6 @@
#pragma once
#include <SDL3/SDL_events.h> // Para SDL_Event
#include <SDL3/SDL_stdinc.h> // Para Uint32
#include <SDL3/SDL.h>
namespace Mouse {
extern Uint32 cursor_hide_time; // Tiempo en milisegundos para ocultar el cursor

View File

@@ -1,6 +1,6 @@
#include "options.h"
#include <SDL3/SDL_video.h> // Para SDL_WINDOW_FULLSCREEN_DESKTOP
#include <SDL3/SDL.h>
#include <algorithm> // Para find_if
#include <cctype> // Para isspace

View File

@@ -1,6 +1,6 @@
#pragma once
#include <SDL3/SDL_stdinc.h> // Para Uint32
#include <SDL3/SDL.h>
#include <algorithm>
#include <string> // Para string, basic_string

View File

@@ -1,20 +1,21 @@
// IWYU pragma: no_include <bits/std_abs.h>
#include "player.h"
#include <algorithm> // Para max, min
#include <cmath> // 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 <algorithm> // Para max, min
#include <cmath> // 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<int>(x_), static_cast<int>(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<int>(x_), static_cast<int>(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<Uint8>(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<int>(x_ + vx_);
proj.y = static_cast<int>(y_);
proj.h = HEIGHT_;
proj.w = static_cast<int>(std::ceil(std::fabs(vx_))); // Para evitar que tenga un ancho de 0 pixels
proj.w = static_cast<int>(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<int>(x_), static_cast<int>(y_) + HEIGHT_ - 2, static_cast<int>(y_) + HEIGHT_ - 1}; // Comprueba solo los dos pixels de abajo
if (state_ != PlayerState::JUMPING) {
const LineVertical LEFT_SIDE = {static_cast<int>(x_), static_cast<int>(y_) + HEIGHT_ - 2, static_cast<int>(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<int>(x_) + WIDTH_;
proj.y = static_cast<int>(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<int>(x_) + WIDTH_ - 1, static_cast<int>(y_) + HEIGHT_ - 2, static_cast<int>(y_) + HEIGHT_ - 1}; // Comprueba solo los dos pixels de abajo
if (state_ != PlayerState::JUMPING) {
const LineVertical RIGHT_SIDE = {static_cast<int>(x_) + WIDTH_ - 1, static_cast<int>(y_) + HEIGHT_ - 2, static_cast<int>(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<int>(x_);
proj.y = static_cast<int>(y_ + vy_);
proj.h = static_cast<int>(std::ceil(std::fabs(vy_))); // Para evitar que tenga una altura de 0 pixels
proj.h = static_cast<int>(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<int>(x_);
proj.y = static_cast<int>(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<Uint8>(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<Uint8>(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<Uint8>(PaletteColor::CYAN);
}
else if (options.cheats.infinite_lives == Cheat::CheatState::ENABLED)
{
} else if (options.cheats.infinite_lives == Cheat::CheatState::ENABLED) {
color_ = static_cast<Uint8>(PaletteColor::YELLOW);
}
else
{
} else {
color_ = static_cast<Uint8>(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<int>(x_), static_cast<int>(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<Uint8>(PaletteColor::BRIGHT_MAGENTA));
surface->putPixel(under_feet_[1].x, under_feet_[1].y,static_cast<Uint8>(PaletteColor::BRIGHT_MAGENTA));
surface->putPixel(under_feet_[0].x, under_feet_[0].y, static_cast<Uint8>(PaletteColor::BRIGHT_MAGENTA));
surface->putPixel(under_feet_[1].x, under_feet_[1].y, static_cast<Uint8>(PaletteColor::BRIGHT_MAGENTA));
// Pinta rectangulo del jugador
SDL_Rect rect = getRect();
surface->drawRectBorder(&rect, static_cast<Uint8>(PaletteColor::BRIGHT_CYAN));
// Pinta el rectangulo de movimiento
if (vx_ != 0.0f)
{
if (vx_ != 0.0f) {
surface->fillRect(&debug_rect_x_, static_cast<Uint8>(PaletteColor::BRIGHT_RED));
}
if (vy_ != 0.0f)
{
if (vy_ != 0.0f) {
surface->fillRect(&debug_rect_y_, static_cast<Uint8>(PaletteColor::BRIGHT_RED));
}
@@ -757,4 +652,4 @@ void Player::renderDebugInfo()
surface->putPixel(debug_point_.x, debug_point_.y, rand() % 16);
}
}
#endif // DEBUG
#endif // DEBUG

View File

@@ -1,8 +1,6 @@
#pragma once
#include <SDL3/SDL_rect.h> // Para SDL_Rect, SDL_Point
#include <SDL3/SDL_render.h> // Para SDL_RendererFlip, SDL_FLIP_NONE
#include <SDL3/SDL_stdinc.h> // Para Uint8
#include <SDL3/SDL.h>
#include <memory> // Para shared_ptr, __shared_ptr_access
#include <string> // 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,

View File

@@ -1,24 +1,21 @@
#include "resource.h"
#include <SDL3/SDL_events.h> // Para SDL_PollEvent, SDL_Event, SDL_KEYDOWN
#include <SDL3/SDL_keycode.h> // Para SDLK_ESCAPE
#include <SDL3/SDL_rect.h> // Para SDL_Rect
#include <SDL3/SDL_stdinc.h> // Para Uint8
#include <stdlib.h> // Para exit, size_t
#include <SDL3/SDL.h>
#include <stdlib.h> // Para exit, size_t
#include <algorithm> // Para find_if
#include <iostream> // Para basic_ostream, operator<<, endl, cout
#include <stdexcept> // 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;

View File

@@ -1,258 +1,257 @@
#pragma once
#include <memory> // Para shared_ptr
#include <string> // Para string
#include <vector> // 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 <memory> // Para shared_ptr
#include <string> // Para string
#include <vector> // 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> surface; // Objeto con la surface
struct ResourceSurface {
std::string name; // Nombre de la surface
std::shared_ptr<Surface> surface; // Objeto con la surface
// Constructor
ResourceSurface(const std::string &name, std::shared_ptr<Surface> surface)
: name(name), surface(surface) {}
// Constructor
ResourceSurface(const std::string& name, std::shared_ptr<Surface> 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<TextFile> text_file; // Objeto con los descriptores de la fuente de texto
struct ResourceTextFile {
std::string name; // Nombre del fichero
std::shared_ptr<TextFile> text_file; // Objeto con los descriptores de la fuente de texto
// Constructor
ResourceTextFile(const std::string &name, std::shared_ptr<TextFile> text_file)
: name(name), text_file(text_file) {}
// Constructor
ResourceTextFile(const std::string& name, std::shared_ptr<TextFile> 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> text; // Objeto
struct ResourceText {
std::string name; // Nombre del objeto
std::shared_ptr<Text> text; // Objeto
// Constructor
ResourceText(const std::string &name, std::shared_ptr<Text> text)
: name(name), text(text) {}
// Constructor
ResourceText(const std::string& name, std::shared_ptr<Text> 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<int> tileMap; // Vector con los indices del mapa de tiles
struct ResourceTileMap {
std::string name; // Nombre del mapa de tiles
std::vector<int> tileMap; // Vector con los indices del mapa de tiles
// Constructor
ResourceTileMap(const std::string &name, const std::vector<int> &tileMap)
: name(name), tileMap(tileMap) {}
// Constructor
ResourceTileMap(const std::string& name, const std::vector<int>& 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<RoomData> room; // Habitación
struct ResourceRoom {
std::string name; // Nombre de la habitación
std::shared_ptr<RoomData> room; // Habitación
// Constructor
ResourceRoom(const std::string &name, std::shared_ptr<RoomData> room)
: name(name), room(room) {}
// Constructor
ResourceRoom(const std::string& name, std::shared_ptr<RoomData> 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<float>(loaded) / static_cast<float>(total);
}
// Obtiene el porcentaje de recursos cargados
float getPercentage() {
return static_cast<float>(loaded) / static_cast<float>(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<ResourceSound> sounds_; // Vector con los sonidos
std::vector<ResourceMusic> musics_; // Vector con las musicas
std::vector<ResourceSurface> surfaces_; // Vector con las surfaces
std::vector<ResourcePalette> palettes_; // Vector con las paletas
std::vector<ResourceTextFile> text_files_; // Vector con los ficheros de texto
std::vector<ResourceText> texts_; // Vector con los objetos de texto
std::vector<ResourceAnimation> animations_; // Vector con las animaciones
std::vector<ResourceTileMap> tile_maps_; // Vector con los mapas de tiles
std::vector<ResourceRoom> rooms_; // Vector con las habitaciones
std::vector<ResourceSound> sounds_; // Vector con los sonidos
std::vector<ResourceMusic> musics_; // Vector con las musicas
std::vector<ResourceSurface> surfaces_; // Vector con las surfaces
std::vector<ResourcePalette> palettes_; // Vector con las paletas
std::vector<ResourceTextFile> text_files_; // Vector con los ficheros de texto
std::vector<ResourceText> texts_; // Vector con los objetos de texto
std::vector<ResourceAnimation> animations_; // Vector con las animaciones
std::vector<ResourceTileMap> tile_maps_; // Vector con los mapas de tiles
std::vector<ResourceRoom> 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<Surface> getSurface(const std::string &name);
// Obtiene la surface a partir de un nombre
std::shared_ptr<Surface> 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<TextFile> getTextFile(const std::string &name);
// Obtiene el fichero de texto a partir de un nombre
std::shared_ptr<TextFile> getTextFile(const std::string& name);
// Obtiene el objeto de texto a partir de un nombre
std::shared_ptr<Text> getText(const std::string &name);
// Obtiene el objeto de texto a partir de un nombre
std::shared_ptr<Text> 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<int> &getTileMap(const std::string &name);
// Obtiene el mapa de tiles a partir de un nombre
std::vector<int>& getTileMap(const std::string& name);
// Obtiene la habitación a partir de un nombre
std::shared_ptr<RoomData> getRoom(const std::string &name);
// Obtiene la habitación a partir de un nombre
std::shared_ptr<RoomData> getRoom(const std::string& name);
// Obtiene todas las habitaciones
std::vector<ResourceRoom> &getRooms();
// Obtiene todas las habitaciones
std::vector<ResourceRoom>& getRooms();
// Recarga todos los recursos
void reload();
// Recarga todos los recursos
void reload();
};

File diff suppressed because it is too large Load Diff

View File

@@ -1,7 +1,7 @@
#pragma once
#include <SDL3/SDL_rect.h> // Para SDL_Rect, SDL_Point
#include <SDL3/SDL_stdinc.h> // Para Uint8
#include <SDL3/SDL.h>
#include <memory> // Para shared_ptr
#include <string> // Para string

View File

@@ -1,16 +1,15 @@
#include "scoreboard.h"
#include <SDL3/SDL_rect.h> // Para SDL_Rect
#include <SDL3/SDL_timer.h> // Para SDL_GetTicks
#include <SDL3/SDL.h>
#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<ScoreboardData> data)

View File

@@ -1,7 +1,6 @@
#pragma once
#include <SDL3/SDL_rect.h> // Para SDL_Rect
#include <SDL3/SDL_stdinc.h> // Para Uint32, Uint8
#include <SDL3/SDL.h>
#include <memory> // Para shared_ptr
#include <string> // Para string, basic_string

View File

@@ -1,11 +1,7 @@
#include "screen.h"
#include <SDL3/SDL_error.h> // Para SDL_GetError
#include <SDL3/SDL_events.h> // Para SDL_DISABLE, SDL_ENABLE
#include <SDL3/SDL_mouse.h> // Para SDL_ShowCursor
#include <SDL3/SDL_pixels.h> // Para SDL_PIXELFORMAT_ARGB8888, SDL_PIXELFORM...
#include <SDL3/SDL_timer.h> // Para SDL_GetTicks
#include <ctype.h> // Para toupper
#include <SDL3/SDL.h>
#include <ctype.h> // Para toupper
#include <algorithm> // Para max, min, transform
#include <fstream> // Para basic_ostream, operator<<, endl, basic_...
@@ -13,14 +9,14 @@
#include <iterator> // Para istreambuf_iterator, operator==
#include <string> // 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() {

View File

@@ -1,11 +1,7 @@
#pragma once
#include <SDL3/SDL_blendmode.h> // Para SDL_BlendMode
#include <SDL3/SDL_rect.h> // Para SDL_Rect
#include <SDL3/SDL_render.h> // Para SDL_Renderer, SDL_Texture
#include <SDL3/SDL_stdinc.h> // Para Uint8, Uint32
#include <SDL3/SDL_video.h> // Para SDL_Window
#include <stddef.h> // Para size_t
#include <SDL3/SDL.h>
#include <stddef.h> // Para size_t
#include <memory> // Para shared_ptr, __shared_ptr_access
#include <string> // Para string

View File

@@ -1,21 +1,19 @@
#include "credits.h"
#include <SDL3/SDL_events.h> // Para SDL_PollEvent, SDL_Event
#include <SDL3/SDL_rect.h> // Para SDL_Rect
#include <SDL3/SDL_timer.h> // Para SDL_GetTicks
#include <SDL3/SDL.h>
#include <algorithm> // 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()

View File

@@ -1,6 +1,6 @@
#pragma once
#include <SDL3/SDL_stdinc.h> // Para Uint32, Uint8
#include <SDL3/SDL.h>
#include <memory> // Para shared_ptr
#include <string> // Para string

View File

@@ -1,22 +1,20 @@
#include "ending.h"
#include <SDL3/SDL_events.h> // Para SDL_PollEvent, SDL_Event
#include <SDL3/SDL_rect.h> // Para SDL_Rect
#include <SDL3/SDL_timer.h> // Para SDL_GetTicks
#include <SDL3/SDL.h>
#include <algorithm> // 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()

View File

@@ -1,6 +1,6 @@
#pragma once
#include <SDL3/SDL_stdinc.h> // Para Uint32
#include <SDL3/SDL.h>
#include <memory> // Para shared_ptr
#include <string> // Para string

View File

@@ -1,23 +1,21 @@
#include "ending2.h"
#include <SDL3/SDL_events.h> // Para SDL_PollEvent, SDL_Event
#include <SDL3/SDL_rect.h> // Para SDL_Rect
#include <SDL3/SDL_timer.h> // Para SDL_GetTicks
#include <SDL3/SDL.h>
#include <algorithm> // 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()

View File

@@ -1,6 +1,6 @@
#pragma once
#include <SDL3/SDL_stdinc.h> // Para Uint32, Uint8
#include <SDL3/SDL.h>
#include <memory> // Para shared_ptr
#include <string> // Para string

View File

@@ -1,31 +1,29 @@
#include "game.h"
#include <SDL3/SDL_render.h> // Para SDL_FLIP_HORIZONTAL
#include <SDL3/SDL_scancode.h> // Para SDL_SCANCODE_7, SDL_SCANCODE_A, SDL_S...
#include <SDL3/SDL_timer.h> // Para SDL_GetTicks
#include <SDL3/SDL.h>
#include <vector> // 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)

View File

@@ -1,8 +1,6 @@
#pragma once
#include <SDL3/SDL_events.h> // Para SDL_Event
#include <SDL3/SDL_rect.h> // Para SDL_Rect
#include <SDL3/SDL_stdinc.h> // Para Uint32
#include <SDL3/SDL.h>
#include <initializer_list> // Para initializer_list
#include <memory> // Para shared_ptr

View File

@@ -1,21 +1,20 @@
#include "game_over.h"
#include <SDL3/SDL_events.h> // Para SDL_PollEvent, SDL_Event
#include <SDL3/SDL_timer.h> // Para SDL_GetTicks
#include <SDL3/SDL.h>
#include <algorithm> // Para min, max
#include <string> // 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()

View File

@@ -1,6 +1,6 @@
#pragma once
#include <SDL3/SDL_stdinc.h> // Para Uint8, Uint32
#include <SDL3/SDL.h>
#include <memory> // Para shared_ptr
#include <vector> // Para vector

View File

@@ -1,19 +1,18 @@
#include "loading_screen.h"
#include <SDL3/SDL_events.h> // Para SDL_PollEvent, SDL_Event
#include <SDL3/SDL_timer.h> // Para SDL_GetTicks
#include <stdlib.h> // Para rand
#include <SDL3/SDL.h>
#include <stdlib.h> // 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()

View File

@@ -1,7 +1,6 @@
#pragma once
#include <SDL3/SDL_rect.h> // Para SDL_Rect
#include <SDL3/SDL_stdinc.h> // Para Uint32
#include <SDL3/SDL.h>
#include <memory> // Para shared_ptr
class SSprite; // lines 7-7

View File

@@ -1,17 +1,16 @@
#include "logo.h"
#include <SDL3/SDL_events.h> // Para SDL_PollEvent, SDL_Event
#include <SDL3/SDL_timer.h> // Para SDL_GetTicks
#include <SDL3/SDL.h>
#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()

View File

@@ -1,6 +1,6 @@
#pragma once
#include <SDL3/SDL_stdinc.h> // Para Uint8, Uint32
#include <SDL3/SDL.h>
#include <memory> // Para shared_ptr
#include <vector> // Para vector

View File

@@ -1,23 +1,21 @@
#include "title.h"
#include <SDL3/SDL_events.h> // Para SDL_PollEvent, SDL_Event, SDL_KEYDOWN
#include <SDL3/SDL_scancode.h> // Para SDL_SCANCODE_1, SDL_SCANCODE_2
#include <SDL3/SDL_timer.h> // Para SDL_GetTicks
#include <SDL3/SDL.h>
#include <algorithm> // 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()

View File

@@ -1,7 +1,6 @@
#pragma once
#include <SDL3/SDL_rect.h> // Para SDL_Rect
#include <SDL3/SDL_stdinc.h> // Para Uint32
#include <SDL3/SDL.h>
#include <memory> // Para shared_ptr
#include <string> // Para string

View File

@@ -1,269 +1,236 @@
#include "s_animated_sprite.h"
#include <stddef.h> // Para size_t
#include <fstream> // Para basic_ostream, basic_istream, operator<<, basic...
#include <iostream> // Para cout, cerr
#include <sstream> // Para basic_stringstream
#include <stdexcept> // Para runtime_error
#include "surface.h" // Para Surface
#include "utils.h" // Para printWithDots
#include "sprite/surface_animated_sprite.h"
#include <stddef.h> // Para size_t
#include <fstream> // Para basic_ostream, basic_istream, operator<<, basic...
#include <iostream> // Para cout, cerr
#include <sstream> // Para basic_stringstream
#include <stdexcept> // 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<std::string> buffer;
std::string line;
while (std::getline(file, line))
{
if (!line.empty())
buffer.push_back(line);
}
std::vector<std::string> 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> 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> 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> surface, const Animations &animations)
: SMovingSprite(surface)
{
if (!animations.empty())
{
setAnimations(animations);
}
SAnimatedSprite::SAnimatedSprite(std::shared_ptr<Surface> 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<int>(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<int>(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<int>(animations_[current_animation_].frames.size()))
{
num = 0;
}
void SAnimatedSprite::setCurrentAnimationFrame(int num) {
// Descarta valores fuera de rango
if (num < 0 || num >= static_cast<int>(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]);
}

View File

@@ -1,13 +1,13 @@
#pragma once
#include <SDL3/SDL_rect.h> // Para SDL_Rect
#include <SDL3/SDL.h>
#include <memory> // Para shared_ptr
#include <string> // Para string
#include <vector> // 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

View File

@@ -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> 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> 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> 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<int>(x_);
pos_.y = static_cast<int>(y_);
pos_.x = static_cast<int>(x_);
pos_.y = static_cast<int>(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<float>(rect.x);
y_ = static_cast<float>(rect.y);
void SMovingSprite::setPos(SDL_Rect rect) {
x_ = static_cast<float>(rect.x);
y_ = static_cast<float>(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<int>(x_);
pos_.y = static_cast<int>(y_);
pos_.x = static_cast<int>(x_);
pos_.y = static_cast<int>(y_);
}
// Establece el valor de la variable
void SMovingSprite::setPosX(float value)
{
x_ = value;
pos_.x = static_cast<int>(x_);
void SMovingSprite::setPosX(float value) {
x_ = value;
pos_.x = static_cast<int>(x_);
}
// Establece el valor de la variable
void SMovingSprite::setPosY(float value)
{
y_ = value;
pos_.y = static_cast<int>(y_);
void SMovingSprite::setPosY(float value) {
y_ = value;
pos_.y = static_cast<int>(y_);
}

View File

@@ -1,13 +1,11 @@
#pragma once
#include <SDL3/SDL_rect.h> // Para SDL_Rect
#include <SDL3/SDL_render.h> // Para SDL_RendererFlip, SDL_FLIP_HORIZONTAL
#include <SDL3/SDL_stdinc.h> // Para Uint8
#include <SDL3/SDL.h>
#include <memory> // 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 {

View File

@@ -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> 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> 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_(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};
}

View File

@@ -1,7 +1,6 @@
#pragma once
#include <SDL3/SDL_rect.h> // Para SDL_Rect, SDL_Point
#include <SDL3/SDL_stdinc.h> // Para Uint8
#include <SDL3/SDL.h>
#include <memory> // Para shared_ptr
class Surface; // lines 5-5

View File

@@ -1,8 +1,6 @@
// IWYU pragma: no_include <bits/std_abs.h>
#include "surface.h"
#include <SDL3/SDL_error.h> // Para SDL_GetError
#include <SDL3/SDL_timer.h> // Para SDL_GetTicks
#include <SDL3/SDL.h>
#include <algorithm> // Para min, max, copy_n, fill
#include <cmath> // Para abs

View File

@@ -1,8 +1,6 @@
#pragma once
#include <SDL3/SDL_rect.h> // Para SDL_Rect
#include <SDL3/SDL_render.h> // Para SDL_FLIP_NONE, SDL_RendererFlip, SDL_Re...
#include <SDL3/SDL_stdinc.h> // Para Uint8, Uint16, Uint32
#include <SDL3/SDL.h>
#include <array> // Para array
#include <memory> // Para default_delete, shared_ptr, __shared_pt...

View File

@@ -1,16 +1,16 @@
#include "text.h"
#include <SDL3/SDL_rect.h> // Para SDL_Rect
#include <stddef.h> // Para size_t
#include <SDL3/SDL.h>
#include <stddef.h> // Para size_t
#include <fstream> // Para basic_ifstream, basic_istream, basic_ostream
#include <iostream> // Para cerr
#include <stdexcept> // 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<TextFile> loadTextFile(const std::string& file_path) {

View File

@@ -1,12 +1,12 @@
#pragma once
#include <SDL3/SDL_stdinc.h> // Para Uint8
#include <SDL3/SDL.h>
#include <memory> // Para shared_ptr, unique_ptr
#include <string> // 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;

View File

@@ -1,8 +1,7 @@
#include "texture.h"
#include <SDL3/SDL.h>
#include <SDL3/SDL_error.h> // Para SDL_GetError
#include <SDL3/SDL_surface.h> // Para SDL_CreateRGBSurfaceWithFormatFrom
#include <iostream> // Para basic_ostream, operator<<, endl, cout
#include <stdexcept> // 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<void*>(data), width, height, depth, pitch, pixel_format);
if (loadedSurface == nullptr) {
auto *loaded_surface = SDL_CreateSurfaceFrom(width, height, pixel_format, static_cast<void *>(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

View File

@@ -1,10 +1,6 @@
#pragma once
#include <SDL3/SDL_blendmode.h> // Para SDL_BlendMode
#include <SDL3/SDL_pixels.h> // Para SDL_PIXELFORMAT_RGBA8888, SDL_PixelF...
#include <SDL3/SDL_rect.h> // Para SDL_Point, SDL_Rect
#include <SDL3/SDL_render.h> // Para SDL_Renderer, SDL_FLIP_NONE, SDL_TEX...
#include <SDL3/SDL_stdinc.h> // Para Uint8, Uint32
#include <SDL3/SDL.h>
#include <string> // Para string
#include <vector> // 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);

View File

@@ -1,20 +1,20 @@
#include "notifier.h"
#include "ui/notifier.h"
#include <SDL3/SDL_timer.h> // Para SDL_GetTicks
#include <SDL3/SDL.h>
#include <algorithm> // Para remove_if
#include <iterator> // Para prev
#include <string> // Para string, basic_string
#include <vector> // 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;

View File

@@ -1,7 +1,6 @@
#pragma once
#include <SDL3/SDL_rect.h> // Para SDL_Rect
#include <SDL3/SDL_stdinc.h> // Para Uint32, Uint8
#include <SDL3/SDL.h>
#include <memory> // Para shared_ptr
#include <string> // Para string, basic_string

View File

@@ -12,8 +12,8 @@
#include <unordered_map> // Para unordered_map, operator==, _Node_const_iter...
#include <utility> // 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) {

View File

@@ -1,8 +1,6 @@
#pragma once
#include <SDL3/SDL_rect.h> // Para SDL_Rect, SDL_Point
#include <SDL3/SDL_render.h> // Para SDL_Renderer, SDL_Texture
#include <SDL3/SDL_stdinc.h> // Para Uint8
#include <SDL3/SDL.h>
#include <string> // Para string
#include <vector> // Para vector