migrant a SDL3

This commit is contained in:
2025-03-27 08:14:37 +01:00
parent a9c869baf6
commit d2286905dc
83 changed files with 570 additions and 541 deletions

View File

@@ -6,12 +6,6 @@ project(coffee_crisis_arcade_edition VERSION 2.00)
# Establece las políticas # Establece las políticas
cmake_policy(SET CMP0072 NEW) cmake_policy(SET CMP0072 NEW)
# Configuración de compilador para MinGW en Windows, si es necesario
if(WIN32 AND NOT CMAKE_CXX_COMPILER_ID MATCHES "MSVC")
set(CMAKE_CXX_COMPILER "g++")
set(CMAKE_C_COMPILER "gcc")
endif()
# Establecer estándar de C++ # Establecer estándar de C++
set(CMAKE_CXX_STANDARD 20) set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED True) set(CMAKE_CXX_STANDARD_REQUIRED True)
@@ -31,49 +25,43 @@ if(NOT SOURCES)
message(FATAL_ERROR "No se encontraron archivos fuente en ${DIR_SOURCES}. Verifica que el directorio existe y contiene archivos .cpp.") message(FATAL_ERROR "No se encontraron archivos fuente en ${DIR_SOURCES}. Verifica que el directorio existe y contiene archivos .cpp.")
endif() endif()
# Configuración de SDL3 # Configuración de SDL3 (usando el método recomendado)
find_package(SDL3 REQUIRED) find_package(SDL3 REQUIRED CONFIG REQUIRED COMPONENTS SDL3)
if(SDL3_FOUND)
message(STATUS "SDL3 encontrado: ${SDL3_INCLUDE_DIRS}") message(STATUS "SDL3 encontrado: ${SDL3_INCLUDE_DIRS}")
# Incluye los directorios si es necesario (SDL3::SDL3 ya incluye la información necesaria)
include_directories(${SDL3_INCLUDE_DIRS}) include_directories(${SDL3_INCLUDE_DIRS})
link_directories(${SDL3_LIBDIR})
else()
message(FATAL_ERROR "SDL3 no encontrado")
endif()
# Incluye rutas de SDL3 obtenidas con pkg-config
include_directories(/usr/local/include /usr/local/include/SDL3)
link_directories(/usr/local/lib)
# Definir las bibliotecas comunes
set(LIBS SDL2)
# Configuración común de salida de ejecutables en el directorio raíz
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_SOURCE_DIR})
# Añadir ejecutable principal # Añadir ejecutable principal
add_executable(${PROJECT_NAME} ${SOURCES}) add_executable(${PROJECT_NAME} ${SOURCES})
# Enlazar la librería SDL3
target_link_libraries(${PROJECT_NAME} PRIVATE SDL3::SDL3)
# Configuración común de salida de ejecutables en el directorio raíz
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_SOURCE_DIR})
# Añadir definiciones de compilación dependiendo del tipo de build # Añadir definiciones de compilación dependiendo del tipo de build
target_compile_definitions(${PROJECT_NAME} PRIVATE $<$<CONFIG:DEBUG>:DEBUG VERBOSE>) target_compile_definitions(${PROJECT_NAME} PRIVATE $<$<CONFIG:DEBUG>:DEBUG VERBOSE>)
# Enlazar bibliotecas
target_link_libraries(${PROJECT_NAME} ${LIBS})
# Configuración específica para cada plataforma # Configuración específica para cada plataforma
if(WIN32) if(WIN32)
target_compile_definitions(${PROJECT_NAME} PRIVATE WINDOWS_BUILD) target_compile_definitions(${PROJECT_NAME} PRIVATE WINDOWS_BUILD)
target_link_libraries(${PROJECT_NAME} mingw32 opengl32 gdi32 winmm imm32 ole32 version) target_link_libraries(${PROJECT_NAME} PRIVATE mingw32 opengl32)
elseif(APPLE) elseif(APPLE)
set(LIBS ${LIBS} "-framework OpenGL")
target_compile_definitions(${PROJECT_NAME} PRIVATE MACOS_BUILD) target_compile_definitions(${PROJECT_NAME} PRIVATE MACOS_BUILD)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-deprecated") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-deprecated")
# Configurar compilación para Apple Silicon
set(CMAKE_OSX_ARCHITECTURES "arm64") set(CMAKE_OSX_ARCHITECTURES "arm64")
elseif(UNIX AND NOT APPLE) elseif(UNIX AND NOT APPLE)
set(LIBS ${LIBS} GL)
target_compile_definitions(${PROJECT_NAME} PRIVATE LINUX_BUILD) target_compile_definitions(${PROJECT_NAME} PRIVATE LINUX_BUILD)
target_link_libraries(${PROJECT_NAME} ${LIBS}) # Por ejemplo, si necesitas enlazar OpenGL:
find_package(OpenGL REQUIRED)
if(OPENGL_FOUND)
message(STATUS "OpenGL encontrado: ${OPENGL_LIBRARIES}")
target_link_libraries(${PROJECT_NAME} PRIVATE ${OPENGL_LIBRARIES})
else()
message(FATAL_ERROR "OpenGL no encontrado")
endif()
endif() endif()
# Añadir OpenGL a las bibliotecas enlazadas # Añadir OpenGL a las bibliotecas enlazadas

View File

@@ -156,8 +156,8 @@ void AnimatedSprite::resetAnimation()
// Carga la animación desde un vector de cadenas // Carga la animación desde un vector de cadenas
void AnimatedSprite::loadFromAnimationsFileBuffer(const AnimationsFileBuffer &source) void AnimatedSprite::loadFromAnimationsFileBuffer(const AnimationsFileBuffer &source)
{ {
int frame_width = 1; float frame_width = 1;
int frame_height = 1; float frame_height = 1;
int frames_per_row = 1; int frames_per_row = 1;
int max_tiles = 1; int max_tiles = 1;

View File

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

View File

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

View File

@@ -57,11 +57,11 @@ Background::Background()
const float TOP_CLOUDS_Y = base_ - 165; const float TOP_CLOUDS_Y = base_ - 165;
const float BOTTOM_CLOUDS_Y = base_ - 101; const float BOTTOM_CLOUDS_Y = base_ - 101;
top_clouds_sprite_a_ = std::make_unique<MovingSprite>(top_clouds_texture_, (SDL_FRect){0, TOP_CLOUDS_Y, rect_.w, top_clouds_texture_->getHeight()}); top_clouds_sprite_a_ = std::make_unique<MovingSprite>(top_clouds_texture_, (SDL_FRect){0, TOP_CLOUDS_Y, rect_.w, static_cast<float>(top_clouds_texture_->getHeight())});
top_clouds_sprite_b_ = std::make_unique<MovingSprite>(top_clouds_texture_, (SDL_FRect){rect_.w, TOP_CLOUDS_Y, rect_.w, top_clouds_texture_->getHeight()}); top_clouds_sprite_b_ = std::make_unique<MovingSprite>(top_clouds_texture_, (SDL_FRect){rect_.w, TOP_CLOUDS_Y, rect_.w, static_cast<float>(top_clouds_texture_->getHeight())});
bottom_clouds_sprite_a_ = std::make_unique<MovingSprite>(bottom_clouds_texture_, (SDL_FRect){0, BOTTOM_CLOUDS_Y, rect_.w, bottom_clouds_texture_->getHeight()}); bottom_clouds_sprite_a_ = std::make_unique<MovingSprite>(bottom_clouds_texture_, (SDL_FRect){0, BOTTOM_CLOUDS_Y, rect_.w, static_cast<float>(bottom_clouds_texture_->getHeight())});
bottom_clouds_sprite_b_ = std::make_unique<MovingSprite>(bottom_clouds_texture_, (SDL_FRect){rect_.w, BOTTOM_CLOUDS_Y, rect_.w, bottom_clouds_texture_->getHeight()}); bottom_clouds_sprite_b_ = std::make_unique<MovingSprite>(bottom_clouds_texture_, (SDL_FRect){rect_.w, BOTTOM_CLOUDS_Y, rect_.w, static_cast<float>(bottom_clouds_texture_->getHeight())});
buildings_sprite_ = std::make_unique<Sprite>(buildings_texture_); buildings_sprite_ = std::make_unique<Sprite>(buildings_texture_);
gradient_sprite_ = std::make_unique<Sprite>(gradients_texture_, 0, 0, rect_.w, rect_.h); gradient_sprite_ = std::make_unique<Sprite>(gradients_texture_, 0, 0, rect_.w, rect_.h);
@@ -337,21 +337,21 @@ void Background::updateClouds()
// Precalcula el vector con el recorrido del sol // Precalcula el vector con el recorrido del sol
void Background::createSunPath() void Background::createSunPath()
{ {
constexpr int CENTER_X = 170; constexpr float CENTER_X = 170;
const int center_y = base_ - 80; const float center_y = base_ - 80;
constexpr int RADIUS = 120; constexpr float RADIUS = 120;
// Generar puntos de la curva desde 90 a 180 grados // Generar puntos de la curva desde 90 a 180 grados
for (double theta = M_PI / 2; theta <= M_PI; theta += 0.01) for (double theta = M_PI / 2; theta <= M_PI; theta += 0.01)
{ {
int x = CENTER_X + static_cast<int>(RADIUS * cos(theta)); float x = CENTER_X + (RADIUS * cos(theta));
int y = center_y - static_cast<int>(RADIUS * sin(theta)); float y = center_y - (RADIUS * sin(theta));
sun_path_.push_back({x, y}); sun_path_.push_back({x, y});
} }
// Agregar puntos en línea recta después de la curva // Agregar puntos en línea recta después de la curva
constexpr int EXTRA_PIXELS = 40; constexpr int EXTRA_PIXELS = 40;
SDL_Point last_point = sun_path_.back(); SDL_FPoint last_point = sun_path_.back();
for (int i = 1; i <= EXTRA_PIXELS; ++i) for (int i = 1; i <= EXTRA_PIXELS; ++i)
{ {
sun_path_.push_back({last_point.x, last_point.y + i}); sun_path_.push_back({last_point.x, last_point.y + i});
@@ -361,15 +361,15 @@ void Background::createSunPath()
// Precalcula el vector con el recorrido de la luna // Precalcula el vector con el recorrido de la luna
void Background::createMoonPath() void Background::createMoonPath()
{ {
constexpr int CENTER_X = 100; constexpr float CENTER_X = 100;
const int center_y = base_ - 50; const float center_y = base_ - 50;
constexpr int RADIUS = 140; constexpr float RADIUS = 140;
// Generar puntos de la curva desde 0 a 90 grados // Generar puntos de la curva desde 0 a 90 grados
for (double theta = 0; theta <= M_PI / 2; theta += 0.01) for (double theta = 0; theta <= M_PI / 2; theta += 0.01)
{ {
int x = CENTER_X + static_cast<int>(RADIUS * cos(theta)); float x = CENTER_X + (RADIUS * cos(theta));
int y = center_y - static_cast<int>(RADIUS * sin(theta)); float y = center_y - (RADIUS * sin(theta));
moon_path_.push_back({x, y}); moon_path_.push_back({x, y});
} }
} }

View File

@@ -1,6 +1,7 @@
#pragma once #pragma once
#include <SDL3/SDL.h>
#include <SDL3/SDL_rect.h> // Para SDL_FRect, SDL_Point #include <SDL3/SDL_rect.h> // Para SDL_FRect, SDL_FPoint
#include <SDL3/SDL_render.h> // Para SDL_Texture, SDL_Renderer #include <SDL3/SDL_render.h> // Para SDL_Texture, SDL_Renderer
#include <stddef.h> // Para size_t #include <stddef.h> // Para size_t
#include <memory> // Para unique_ptr, shared_ptr #include <memory> // Para unique_ptr, shared_ptr
@@ -86,8 +87,8 @@ private:
Color attenuate_color_; // Color para atenuar el fondo Color attenuate_color_; // Color para atenuar el fondo
int alpha_color_text_; // Alpha para atenuar el fondo int alpha_color_text_; // Alpha para atenuar el fondo
int alpha_color_text_temp_; // Valor temporal para hacer la transición de alpha int alpha_color_text_temp_; // Valor temporal para hacer la transición de alpha
std::vector<SDL_Point> sun_path_; // Vector con el recorrido del sol std::vector<SDL_FPoint> sun_path_; // Vector con el recorrido del sol
std::vector<SDL_Point> moon_path_; // Vector con el recorrido de la luna std::vector<SDL_FPoint> moon_path_; // Vector con el recorrido de la luna
size_t sun_index_ = 0; // Posición del vector del recorrido del sol size_t sun_index_ = 0; // Posición del vector del recorrido del sol
size_t moon_index_ = 0; // Posición del vector del recorrido de la luna size_t moon_index_ = 0; // Posición del vector del recorrido de la luna

View File

@@ -117,7 +117,7 @@ void Balloon::render()
// Renderiza la estrella // Renderiza la estrella
if (!invulnerable_) if (!invulnerable_)
{ {
SDL_Point p = {24, 24}; SDL_FPoint p = {24.0f, 24.0f};
sprite_->setRotatingCenter(p); sprite_->setRotatingCenter(p);
sprite_->render(); sprite_->render();
} }

View File

@@ -1,4 +1,5 @@
#pragma once #pragma once
#include <SDL3/SDL.h>
#include <SDL3/SDL_rect.h> // Para SDL_FRect #include <SDL3/SDL_rect.h> // Para SDL_FRect
#include <SDL3/SDL_stdinc.h> // Para Uint8, Uint16, Uint32 #include <SDL3/SDL_stdinc.h> // Para Uint8, Uint16, Uint32
@@ -90,8 +91,8 @@ private:
// Variables // Variables
float x_; // Posición en el eje X float x_; // Posición en el eje X
float y_; // Posición en el eje Y float y_; // Posición en el eje Y
Uint8 w_; // Ancho float w_; // Ancho
Uint8 h_; // Alto float h_; // Alto
float vx_; // Velocidad en el eje X. Cantidad de pixeles a desplazarse float vx_; // Velocidad en el eje X. Cantidad de pixeles a desplazarse
float vy_; // Velocidad en el eje Y. Cantidad de pixeles a desplazarse float vy_; // Velocidad en el eje Y. Cantidad de pixeles a desplazarse
float gravity_; // Aceleración en el eje Y. Modifica la velocidad float gravity_; // Aceleración en el eje Y. Modifica la velocidad

View File

@@ -1,4 +1,5 @@
#pragma once #pragma once
#include <SDL3/SDL.h>
#include "balloon.h" // Para BALLOON_VELX_NEGATIVE, BALLOON_VELX_POSITIVE #include "balloon.h" // Para BALLOON_VELX_NEGATIVE, BALLOON_VELX_POSITIVE
#include <vector> #include <vector>

View File

@@ -216,19 +216,19 @@ void BalloonManager::createPowerBall()
{ {
if (can_deploy_balloons_) if (can_deploy_balloons_)
{ {
constexpr int values = 6; constexpr int VALUES = 6;
constexpr int pos_y = -BALLOON_SIZE[4]; constexpr float POS_Y = -BALLOON_SIZE[4];
constexpr int creation_time = 0; constexpr int CREATION_TIME = 0;
const auto left = param.game.play_area.rect.x; const float LEFT = param.game.play_area.rect.x;
const auto center = param.game.play_area.center_x - (BALLOON_SIZE[4] / 2); const float CENTER = param.game.play_area.center_x - (BALLOON_SIZE[4] / 2);
const auto right = param.game.play_area.rect.w - BALLOON_SIZE[4]; const float RIGHT = param.game.play_area.rect.w - BALLOON_SIZE[4];
const auto luck = rand() % values; const int LUCK = rand() % VALUES;
const int x[values] = {left, left, center, center, right, right}; const float POS_X[VALUES] = {LEFT, LEFT, CENTER, CENTER, RIGHT, RIGHT};
const float vx[values] = {BALLOON_VELX_POSITIVE, BALLOON_VELX_POSITIVE, BALLOON_VELX_POSITIVE, BALLOON_VELX_NEGATIVE, BALLOON_VELX_NEGATIVE, BALLOON_VELX_NEGATIVE}; const float VEL_X[VALUES] = {BALLOON_VELX_POSITIVE, BALLOON_VELX_POSITIVE, BALLOON_VELX_POSITIVE, BALLOON_VELX_NEGATIVE, BALLOON_VELX_NEGATIVE, BALLOON_VELX_NEGATIVE};
balloons_.emplace_back(std::make_unique<Balloon>(x[luck], pos_y, BalloonType::POWERBALL, BalloonSize::SIZE4, vx[luck], balloon_speed_, creation_time, play_area_, balloon_textures_[4], balloon_animations_[4])); balloons_.emplace_back(std::make_unique<Balloon>(POS_X[LUCK], POS_Y, BalloonType::POWERBALL, BalloonSize::SIZE4, VEL_X[LUCK], balloon_speed_, CREATION_TIME, play_area_, balloon_textures_[4], balloon_animations_[4]));
balloons_.back()->setInvulnerable(true); balloons_.back()->setInvulnerable(true);
power_ball_enabled_ = true; power_ball_enabled_ = true;

View File

@@ -1,4 +1,5 @@
#pragma once #pragma once
#include <SDL3/SDL.h>
#include <SDL3/SDL_rect.h> // Para SDL_FRect #include <SDL3/SDL_rect.h> // Para SDL_FRect
#include <memory> // Para shared_ptr, unique_ptr #include <memory> // Para shared_ptr, unique_ptr

View File

@@ -6,7 +6,7 @@
class Texture; // lines 5-5 class Texture; // lines 5-5
// Constructor // Constructor
Bullet::Bullet(int x, int y, BulletType bullet_type, bool powered_up, int owner, std::shared_ptr<Texture> texture) Bullet::Bullet(float x, float y, BulletType bullet_type, bool powered_up, int owner, std::shared_ptr<Texture> texture)
: sprite_(std::make_unique<Sprite>(texture, SDL_FRect{x, y, BULLET_WIDTH_, BULLET_HEIGHT_})), : sprite_(std::make_unique<Sprite>(texture, SDL_FRect{x, y, BULLET_WIDTH_, BULLET_HEIGHT_})),
pos_x_(x), pos_x_(x),
pos_y_(y), pos_y_(y),

View File

@@ -1,4 +1,5 @@
#pragma once #pragma once
#include <SDL3/SDL.h>
#include <SDL3/SDL_stdinc.h> // Para Uint8 #include <SDL3/SDL_stdinc.h> // Para Uint8
#include <memory> // Para shared_ptr, unique_ptr #include <memory> // Para shared_ptr, unique_ptr
@@ -27,17 +28,17 @@ class Bullet
{ {
private: private:
// Constantes // Constantes
static constexpr int BULLET_WIDTH_ = 12; static constexpr float BULLET_WIDTH_ = 12.0f;
static constexpr int BULLET_HEIGHT_ = 12; static constexpr float BULLET_HEIGHT_ = 12.0f;
static constexpr int BULLET_VEL_Y_ = -3; static constexpr float BULLET_VEL_Y_ = -3.0f;
static constexpr int BULLET_VEL_X_LEFT_ = -2; static constexpr float BULLET_VEL_X_LEFT_ = -2.0f;
static constexpr int BULLET_VEL_X_RIGHT_ = 2; static constexpr float BULLET_VEL_X_RIGHT_ = 2.0f;
std::unique_ptr<Sprite> sprite_; // Sprite con los gráficos y métodos de pintado std::unique_ptr<Sprite> sprite_; // Sprite con los gráficos y métodos de pintado
int pos_x_; // Posición en el eje X float pos_x_; // Posición en el eje X
int pos_y_; // Posición en el eje Y float pos_y_; // Posición en el eje Y
int vel_x_; // Velocidad en el eje X float vel_x_; // Velocidad en el eje X
BulletType bullet_type_; // Tipo de objeto BulletType bullet_type_; // Tipo de objeto
int owner_; // Identificador del dueño del objeto int owner_; // Identificador del dueño del objeto
@@ -48,7 +49,7 @@ private:
public: public:
// Constructor // Constructor
Bullet(int x, int y, BulletType bullet_type, bool powered_up, int owner, std::shared_ptr<Texture> texture); Bullet(float x, float y, BulletType bullet_type, bool powered_up, int owner, std::shared_ptr<Texture> texture);
// Destructor // Destructor
~Bullet() = default; ~Bullet() = default;

View File

@@ -408,11 +408,11 @@ void Credits::updateBlackRects()
if (counter_ % 4 == 0) if (counter_ % 4 == 0)
{ {
// Incrementa la altura del rectangulo superior // Incrementa la altura del rectangulo superior
top_black_rect_.h = std::min(static_cast<int>(top_black_rect_.h) + 1, param.game.game_area.center_y - 1); top_black_rect_.h = std::min(top_black_rect_.h + 1, param.game.game_area.center_y - 1);
// Incrementa la altura y modifica la posición del rectangulo inferior // Incrementa la altura y modifica la posición del rectangulo inferior
++bottom_black_rect_.h; ++bottom_black_rect_.h;
bottom_black_rect_.y = std::max(static_cast<int>(bottom_black_rect_.y) - 1, param.game.game_area.center_y + 1); bottom_black_rect_.y = std::max(bottom_black_rect_.y - 1, param.game.game_area.center_y + 1);
--current_step; --current_step;
setVolume(static_cast<int>(initial_volume_ * current_step / steps_)); setVolume(static_cast<int>(initial_volume_ * current_step / steps_));
@@ -426,11 +426,11 @@ void Credits::updateBlackRects()
constexpr int SPEED = 2; constexpr int SPEED = 2;
// Si los rectangulos izquierdo y derecho no han llegado al centro // Si los rectangulos izquierdo y derecho no han llegado al centro
// Incrementa la anchura del rectangulo situado a la izquierda // Incrementa la anchura del rectangulo situado a la izquierda
left_black_rect_.w = std::min(static_cast<int>(left_black_rect_.w) + SPEED, param.game.game_area.center_x); left_black_rect_.w = std::min(left_black_rect_.w + SPEED, param.game.game_area.center_x);
// Incrementa la anchura y modifica la posición del rectangulo situado a la derecha // Incrementa la anchura y modifica la posición del rectangulo situado a la derecha
right_black_rect_.w += SPEED; right_black_rect_.w += SPEED;
right_black_rect_.x = std::max(static_cast<int>(right_black_rect_.x) - SPEED, param.game.game_area.center_x); right_black_rect_.x = std::max(right_black_rect_.x - SPEED, param.game.game_area.center_x);
--current_step; --current_step;
setVolume(static_cast<int>(initial_volume_ * current_step / steps_)); setVolume(static_cast<int>(initial_volume_ * current_step / steps_));

View File

@@ -1,4 +1,5 @@
#pragma once #pragma once
#include <SDL3/SDL.h>
#include <SDL3/SDL_rect.h> // Para SDL_FRect #include <SDL3/SDL_rect.h> // Para SDL_FRect
#include <SDL3/SDL_render.h> // Para SDL_Texture #include <SDL3/SDL_render.h> // Para SDL_Texture
@@ -28,11 +29,11 @@ private:
std::vector<std::shared_ptr<Player>> players_; // Vector con los jugadores std::vector<std::shared_ptr<Player>> players_; // Vector con los jugadores
// Variables // Variables
Uint32 ticks_ = 0; // Contador de ticks para ajustar la velocidad del programa Uint64 ticks_ = 0; // Contador de ticks para ajustar la velocidad del programa
Uint32 counter_ = 0; // Contador para la lógica de la clase Uint32 counter_ = 0; // Contador para la lógica de la clase
Uint32 counter_pre_fade_ = 0; // Contador para activar el fundido final Uint32 counter_pre_fade_ = 0; // Contador para activar el fundido final
Uint32 counter_prevent_endless_ = 0; // Contador para evitar que el juego se quede para siempre en los creditos Uint32 counter_prevent_endless_ = 0; // Contador para evitar que el juego se quede para siempre en los creditos
int black_bars_size_ = (param.game.game_area.rect.h - PLAY_AREA_HEIGHT) / 2; // Tamaño de las barras negras float black_bars_size_ = (param.game.game_area.rect.h - PLAY_AREA_HEIGHT) / 2; // Tamaño de las barras negras
int mini_logo_final_pos_ = 0; // Ubicación donde se detiene el minilogo int mini_logo_final_pos_ = 0; // Ubicación donde se detiene el minilogo
bool fading_ = false; // Indica si se está realizando el fade final bool fading_ = false; // Indica si se está realizando el fade final
bool want_to_pass_ = false; // Indica si el jugador quiere saltarse los titulos de crédito bool want_to_pass_ = false; // Indica si el jugador quiere saltarse los titulos de crédito

View File

@@ -1,4 +1,5 @@
#pragma once #pragma once
#include <SDL3/SDL.h>
#include <SDL3/SDL_events.h> // Para SDL_ControllerButtonEvent #include <SDL3/SDL_events.h> // Para SDL_ControllerButtonEvent
#include <SDL3/SDL.h> // Para SDL_GamepadButton #include <SDL3/SDL.h> // Para SDL_GamepadButton

View File

@@ -327,7 +327,7 @@ bool Director::initSDL()
else else
{ {
// Crea un renderizador para la ventana. El vsync se activa en funcion de las opciones // Crea un renderizador para la ventana. El vsync se activa en funcion de las opciones
Uint32 flags = 0; //Uint32 flags = 0;
if (options.video.v_sync) if (options.video.v_sync)
{ {
// flags = SDL_RENDERER_PRESENTVSYNC; // flags = SDL_RENDERER_PRESENTVSYNC;
@@ -347,7 +347,7 @@ bool Director::initSDL()
{ {
SDL_SetRenderDrawColor(renderer_, 0x00, 0x00, 0x00, 0xFF); SDL_SetRenderDrawColor(renderer_, 0x00, 0x00, 0x00, 0xFF);
SDL_SetRenderLogicalPresentation(renderer_, param.game.width, param.game.height, SDL_LOGICAL_PRESENTATION_INTEGER_SCALE); SDL_SetRenderLogicalPresentation(renderer_, param.game.width, param.game.height, SDL_LOGICAL_PRESENTATION_INTEGER_SCALE);
SDL_SetWindowFullscreen(window_, static_cast<Uint32>(options.video.mode)); SDL_SetWindowFullscreen(window_, static_cast<Uint32>(options.video.fullscreen));
SDL_SetRenderDrawBlendMode(renderer_, SDL_BLENDMODE_BLEND); SDL_SetRenderDrawBlendMode(renderer_, SDL_BLENDMODE_BLEND);
} }
} }
@@ -799,9 +799,9 @@ std::string Director::getLangFile(lang::Code code)
#ifdef ARCADE #ifdef ARCADE
// Apaga el sistema // Apaga el sistema
void Director::shutdownSystem(bool shouldShutdown) void Director::shutdownSystem(bool should_shutdown)
{ {
if (shouldShutdown) if (should_shutdown)
{ {
#ifdef _WIN32 #ifdef _WIN32
// Apaga el sistema en Windows // Apaga el sistema en Windows

View File

@@ -1,4 +1,5 @@
#pragma once #pragma once
#include <SDL3/SDL.h>
#include <SDL3/SDL_render.h> // Para SDL_Renderer #include <SDL3/SDL_render.h> // Para SDL_Renderer
#include <SDL3/SDL_video.h> // Para SDL_Window #include <SDL3/SDL_video.h> // Para SDL_Window
@@ -74,7 +75,7 @@ private:
std::string getLangFile(lang::Code code); std::string getLangFile(lang::Code code);
#ifdef ARCADE #ifdef ARCADE
// Apaga el sistema // Apaga el sistema
void shutdownSystem(bool shouldShutdown); void shutdownSystem(bool should_shutdown);
#endif #endif
// Inicializa todo // Inicializa todo

View File

@@ -1,4 +1,5 @@
#pragma once #pragma once
#include <SDL3/SDL.h>
#include <string> #include <string>
#include <array> #include <array>

View File

@@ -1,4 +1,5 @@
#pragma once #pragma once
#include <SDL3/SDL.h>
#include <memory> // Para unique_ptr, shared_ptr #include <memory> // Para unique_ptr, shared_ptr
#include <string> // Para string #include <string> // Para string

View File

@@ -1,4 +1,5 @@
#pragma once #pragma once
#include <SDL3/SDL.h>
#include <SDL3/SDL_rect.h> // Para SDL_FRect #include <SDL3/SDL_rect.h> // Para SDL_FRect
#include <SDL3/SDL_render.h> // Para SDL_Renderer, SDL_Texture #include <SDL3/SDL_render.h> // Para SDL_Renderer, SDL_Texture

View File

@@ -314,7 +314,7 @@ void Game::updateGameStateGameOver()
if (game_over_counter_ == GAME_OVER_COUNTER_) if (game_over_counter_ == GAME_OVER_COUNTER_)
{ {
createMessage({paths_.at(2), paths_.at(3)}, Resource::get()->getTexture("game_text_game_over")); createMessage({paths_.at(2), paths_.at(3)}, Resource::get()->getTexture("game_text_game_over"));
JA_FadeOutMusic(1000); /*JA_FadeOutMusic(1000);*/
balloon_manager_->setSounds(true); balloon_manager_->setSounds(true);
} }

View File

@@ -1,4 +1,5 @@
#pragma once #pragma once
#include <SDL3/SDL.h>
#include <SDL3/SDL_render.h> // Para SDL_Renderer, SDL_Texture #include <SDL3/SDL_render.h> // Para SDL_Renderer, SDL_Texture
#include <SDL3/SDL_stdinc.h> // Para Uint32, Uint8 #include <SDL3/SDL_stdinc.h> // Para Uint32, Uint8
@@ -159,7 +160,7 @@ private:
Demo demo_; // Variable con todas las variables relacionadas con el modo demo Demo demo_; // Variable con todas las variables relacionadas con el modo demo
GameDifficulty difficulty_ = options.game.difficulty; // Dificultad del juego GameDifficulty difficulty_ = options.game.difficulty; // Dificultad del juego
Helper helper_; // Variable para gestionar las ayudas Helper helper_; // Variable para gestionar las ayudas
Uint32 ticks_ = 0; // Contador de ticks para ajustar la velocidad del programa Uint64 ticks_ = 0; // Contador de ticks para ajustar la velocidad del programa
bool coffee_machine_enabled_ = false; // Indica si hay una máquina de café en el terreno de juego bool coffee_machine_enabled_ = false; // Indica si hay una máquina de café en el terreno de juego
bool hi_score_achieved_ = false; // Indica si se ha superado la puntuación máxima bool hi_score_achieved_ = false; // Indica si se ha superado la puntuación máxima
bool paused_ = false; // Indica si el juego está pausado (no se deberia de poder utilizar en el modo arcade) bool paused_ = false; // Indica si el juego está pausado (no se deberia de poder utilizar en el modo arcade)

View File

@@ -247,8 +247,8 @@ bool GameLogo::hasFinished() const
// Calcula el desplazamiento vertical inicial // Calcula el desplazamiento vertical inicial
int GameLogo::getInitialVerticalDesp() int GameLogo::getInitialVerticalDesp()
{ {
auto desp_up = y_; const float OFFSET_UP = y_;
auto desp_down = param.game.height - y_; const float OFFSET_DOWN = param.game.height - y_;
return std::max(desp_up, desp_down); return std::max(OFFSET_UP, OFFSET_DOWN);
} }

View File

@@ -1,4 +1,5 @@
#pragma once #pragma once
#include <SDL3/SDL.h>
#include <memory> // Para unique_ptr, shared_ptr #include <memory> // Para unique_ptr, shared_ptr
#include "animated_sprite.h" // Para AnimatedSprite #include "animated_sprite.h" // Para AnimatedSprite
@@ -61,8 +62,8 @@ private:
std::unique_ptr<Sprite> arcade_edition_sprite_; // Sprite con los graficos de "Arcade Edition" std::unique_ptr<Sprite> arcade_edition_sprite_; // Sprite con los graficos de "Arcade Edition"
// Variables // Variables
int x_; // Posición donde dibujar el logo float x_; // Posición donde dibujar el logo
int y_; // Posición donde dibujar el logo float y_; // Posición donde dibujar el logo
float zoom_ = 1.0f; // Zoom aplicado al texto "ARCADE EDITION" float zoom_ = 1.0f; // Zoom aplicado al texto "ARCADE EDITION"
int post_finished_counter_ = 1; // Contador final una vez terminada las animaciones de los logos int post_finished_counter_ = 1; // Contador final una vez terminada las animaciones de los logos

View File

@@ -1,4 +1,5 @@
#pragma once #pragma once
#include <SDL3/SDL.h>
#include <SDL3/SDL_events.h> #include <SDL3/SDL_events.h>

View File

@@ -10,7 +10,7 @@
#include "notifier.h" // Para Notifier #include "notifier.h" // Para Notifier
#include "on_screen_help.h" // Para OnScreenHelp #include "on_screen_help.h" // Para OnScreenHelp
#include "options.h" // Para Options, options, OptionsGame, OptionsV... #include "options.h" // Para Options, options, OptionsGame, OptionsV...
#include "screen.h" // Para Screen, ScreenVideoMode #include "screen.h" // Para Screen
#include "section.h" // Para Name, name, Options, options, AttractMode #include "section.h" // Para Name, name, Options, options, AttractMode
#include "utils.h" // Para boolToOnOff #include "utils.h" // Para boolToOnOff
@@ -79,7 +79,7 @@ namespace globalInputs
{ {
options.video.integer_scale = !options.video.integer_scale; options.video.integer_scale = !options.video.integer_scale;
SDL_SetRenderLogicalPresentation(Screen::get()->getRenderer(), param.game.width, param.game.height, options.video.integer_scale ? SDL_LOGICAL_PRESENTATION_INTEGER_SCALE : SDL_LOGICAL_PRESENTATION_LETTERBOX); SDL_SetRenderLogicalPresentation(Screen::get()->getRenderer(), param.game.width, param.game.height, options.video.integer_scale ? SDL_LOGICAL_PRESENTATION_INTEGER_SCALE : SDL_LOGICAL_PRESENTATION_LETTERBOX);
Screen::get()->setVideoMode(); Screen::get()->setFullscreenMode();
Notifier::get()->show({lang::getText(134) + " " + boolToOnOff(options.video.integer_scale)}); Notifier::get()->show({lang::getText(134) + " " + boolToOnOff(options.video.integer_scale)});
} }
@@ -180,9 +180,9 @@ namespace globalInputs
// Comprueba el teclado para cambiar entre pantalla completa y ventana // Comprueba el teclado para cambiar entre pantalla completa y ventana
if (Input::get()->checkInput(InputAction::WINDOW_FULLSCREEN, INPUT_DO_NOT_ALLOW_REPEAT, InputDeviceToUse::KEYBOARD)) if (Input::get()->checkInput(InputAction::WINDOW_FULLSCREEN, INPUT_DO_NOT_ALLOW_REPEAT, InputDeviceToUse::KEYBOARD))
{ {
Screen::get()->toggleVideoMode(); Screen::get()->toggleFullscreen();
const std::string mode = options.video.mode == ScreenVideoMode::WINDOW ? lang::getText(132) : lang::getText(133); const std::string MODE = options.video.fullscreen ? lang::getText(133) : lang::getText(132);
Notifier::get()->show({mode}); Notifier::get()->show({MODE});
return; return;
} }

View File

@@ -1,3 +1,6 @@
#pragma once
#include <SDL3/SDL.h>
namespace globalInputs namespace globalInputs
{ {
extern int service_pressed_counter; extern int service_pressed_counter;

View File

@@ -123,7 +123,7 @@ void HiScoreTable::render()
background_->render(); background_->render();
// Establece la ventana del backbuffer // Establece la ventana del backbuffer
view_area_.y = std::max(0, param.game.height - counter_ + 100); view_area_.y = std::max(0.0f, param.game.height - counter_ + 100);
// Copia el backbuffer al renderizador // Copia el backbuffer al renderizador
SDL_RenderTexture(renderer_, backbuffer_, nullptr, &view_area_); SDL_RenderTexture(renderer_, backbuffer_, nullptr, &view_area_);

View File

@@ -1,4 +1,5 @@
#pragma once #pragma once
#include <SDL3/SDL.h>
#include <SDL3/SDL_rect.h> // Para SDL_FRect #include <SDL3/SDL_rect.h> // Para SDL_FRect
#include <SDL3/SDL_render.h> // Para SDL_Renderer, SDL_Texture #include <SDL3/SDL_render.h> // Para SDL_Renderer, SDL_Texture
@@ -43,7 +44,7 @@ private:
// Variables // Variables
Uint16 counter_ = 0; // Contador Uint16 counter_ = 0; // Contador
Uint32 ticks_; // Contador de ticks para ajustar la velocidad del programa Uint64 ticks_; // Contador de ticks para ajustar la velocidad del programa
SDL_FRect view_area_; // Parte de la textura que se muestra en pantalla SDL_FRect view_area_; // Parte de la textura que se muestra en pantalla
FadeMode fade_mode_; // Modo de fade a utilizar FadeMode fade_mode_; // Modo de fade a utilizar
Color background_fade_color_; // Color de atenuación del fondo Color background_fade_color_; // Color de atenuación del fondo

View File

@@ -296,7 +296,7 @@ std::string Input::getControllerName(int controller_index) const { return num_ga
int Input::getNumControllers() const { return num_gamepads_; } int Input::getNumControllers() const { return num_gamepads_; }
// Obtiene el indice del controlador a partir de un event.id // Obtiene el indice del controlador a partir de un event.id
int Input::getJoyIndex(int id) const int Input::getJoyIndex(SDL_JoystickID id) const
{ {
for (int i = 0; i < num_joysticks_; ++i) for (int i = 0; i < num_joysticks_; ++i)
{ {

View File

@@ -148,7 +148,7 @@ public:
std::string getControllerName(int controller_index) const; std::string getControllerName(int controller_index) const;
// Obtiene el indice del controlador a partir de un event.id // Obtiene el indice del controlador a partir de un event.id
int getJoyIndex(int id) const; int getJoyIndex(SDL_JoystickID id) const;
// Muestra por consola los controles asignados // Muestra por consola los controles asignados
void printBindings(InputDeviceToUse device = InputDeviceToUse::KEYBOARD, int controller_index = 0) const; void printBindings(InputDeviceToUse device = InputDeviceToUse::KEYBOARD, int controller_index = 0) const;

View File

@@ -78,7 +78,7 @@ void Instructions::iniSprites()
for (int i = 0; i < (int)item_textures_.size(); ++i) for (int i = 0; i < (int)item_textures_.size(); ++i)
{ {
auto sprite = std::make_unique<Sprite>(item_textures_[i], 0, 0, param.game.item_size, param.game.item_size); auto sprite = std::make_unique<Sprite>(item_textures_[i], 0, 0, param.game.item_size, param.game.item_size);
sprite->setPosition((SDL_Point){sprite_pos_.x, sprite_pos_.y + ((param.game.item_size + item_space_) * i)}); sprite->setPosition((SDL_FPoint){sprite_pos_.x, sprite_pos_.y + ((param.game.item_size + item_space_) * i)});
sprites_.push_back(std::move(sprite)); sprites_.push_back(std::move(sprite));
} }
} }
@@ -302,44 +302,44 @@ std::vector<Line> Instructions::initializeLines(int height)
// Método para mover las líneas con suavizado // Método para mover las líneas con suavizado
bool Instructions::moveLines(std::vector<Line> &lines, int width, float duration, Uint32 startDelay) bool Instructions::moveLines(std::vector<Line> &lines, int width, float duration, Uint32 startDelay)
{ {
Uint32 currentTime = SDL_GetTicks(); Uint32 current_time = SDL_GetTicks();
bool allLinesOffScreen = true; bool all_lines_off_screen = true;
for (auto &line : lines) for (auto &line : lines)
{ {
// Establecer startTime en el primer cuadro de animación // Establecer startTime en el primer cuadro de animación
if (line.startTime == 0) if (line.startTime == 0)
{ {
line.startTime = currentTime + line.y * startDelay; line.startTime = current_time + line.y * startDelay;
} }
float elapsedTime = (currentTime - line.startTime) / 1000.0f; // Convertir a segundos float elapsed_time = (current_time - line.startTime) / 1000.0f; // Convertir a segundos
if (elapsedTime < 0) if (elapsed_time < 0)
{ {
allLinesOffScreen = false; // Si aún no se debe mover esta línea, no están todas fuera de pantalla all_lines_off_screen = false; // Si aún no se debe mover esta línea, no están todas fuera de pantalla
continue; continue;
} }
if (elapsedTime >= duration) if (elapsed_time >= duration)
{ {
continue; // Si la línea ha salido de los límites, no la muevas más continue; // Si la línea ha salido de los límites, no la muevas más
} }
float t = elapsedTime / duration; float t = elapsed_time / duration;
float smoothFactor = easeInOutQuint(t); float smooth_factor = easeInOutQuint(t);
line.x = line.direction * smoothFactor * width; line.x = line.direction * smooth_factor * width;
allLinesOffScreen = false; // Si alguna línea aún se está moviendo, no están todas fuera de pantalla all_lines_off_screen = false; // Si alguna línea aún se está moviendo, no están todas fuera de pantalla
} }
return allLinesOffScreen; return all_lines_off_screen;
} }
// Método para renderizar las líneas // Método para renderizar las líneas
void Instructions::renderLines(SDL_Renderer *renderer, SDL_Texture *texture, const std::vector<Line> &lines) void Instructions::renderLines(SDL_Renderer *renderer, SDL_Texture *texture, const std::vector<Line> &lines)
{ {
for (const auto &line : lines) for (const auto &LINE : lines)
{ {
SDL_FRect srcRect = {0, line.y, 320, 1}; SDL_FRect srcRect = {0, static_cast<float>(LINE.y), 320, 1};
SDL_FRect dstRect = {static_cast<int>(line.x), line.y, 320, 1}; SDL_FRect dstRect = {static_cast<float>(LINE.x), static_cast<float>(LINE.y), 320, 1};
SDL_RenderTexture(renderer, texture, &srcRect, &dstRect); SDL_RenderTexture(renderer, texture, &srcRect, &dstRect);
} }
} }
@@ -357,7 +357,7 @@ void Instructions::updateMusic()
void Instructions::updateBackbuffer() void Instructions::updateBackbuffer()
{ {
// Establece la ventana del backbuffer // Establece la ventana del backbuffer
view_.y = std::max(0, param.game.height - counter_ + 100); view_.y = std::max(0.0f, param.game.height - counter_ + 100);
// Verifica si view_.y == 0 y gestiona el temporizador // Verifica si view_.y == 0 y gestiona el temporizador
if (view_.y == 0) if (view_.y == 0)

View File

@@ -1,6 +1,7 @@
#pragma once #pragma once
#include <SDL3/SDL.h>
#include <SDL3/SDL_rect.h> // Para SDL_Point, SDL_FRect #include <SDL3/SDL_rect.h> // Para SDL_FPoint, SDL_FRect
#include <SDL3/SDL_render.h> // Para SDL_Texture, SDL_Renderer #include <SDL3/SDL_render.h> // Para SDL_Texture, SDL_Renderer
#include <SDL3/SDL_stdinc.h> // Para Uint32 #include <SDL3/SDL_stdinc.h> // Para Uint32
#include <memory> // Para unique_ptr, shared_ptr #include <memory> // Para unique_ptr, shared_ptr
@@ -54,10 +55,10 @@ private:
// Variables // Variables
int counter_ = 0; // Contador para manejar el progreso en la pantalla de instrucciones int counter_ = 0; // Contador para manejar el progreso en la pantalla de instrucciones
Uint32 ticks_ = 0; // Contador de ticks para ajustar la velocidad del programa Uint64 ticks_ = 0; // Contador de ticks para ajustar la velocidad del programa
SDL_FRect view_; // Vista del backbuffer que se va a mostrar por pantalla SDL_FRect view_; // Vista del backbuffer que se va a mostrar por pantalla
SDL_Point sprite_pos_ = {0, 0}; // Posición del primer sprite en la lista SDL_FPoint sprite_pos_ = {0, 0}; // Posición del primer sprite en la lista
int item_space_ = 2; // Espacio entre los items en pantalla float item_space_ = 2.0; // Espacio entre los items en pantalla
std::vector<Line> lines_; // Vector que contiene las líneas animadas en la pantalla std::vector<Line> lines_; // Vector que contiene las líneas animadas en la pantalla
bool all_lines_off_screen_ = false; // Indica si todas las líneas han salido de la pantalla bool all_lines_off_screen_ = false; // Indica si todas las líneas han salido de la pantalla
Uint32 start_delay_time_ = 0; // Tiempo de inicio del retraso para mover las líneas Uint32 start_delay_time_ = 0; // Tiempo de inicio del retraso para mover las líneas

View File

@@ -308,10 +308,10 @@ void Intro::initSprites()
// Constantes // Constantes
auto texture = Resource::get()->getTexture(TEXTURE_LIST.front()); auto texture = Resource::get()->getTexture(TEXTURE_LIST.front());
const int SPRITE_WIDTH = texture->getWidth(); const float SPRITE_WIDTH = texture->getWidth();
const int SPRITE_HEIGHT = texture->getHeight(); const float SPRITE_HEIGHT = texture->getHeight();
const int X_DEST = param.game.game_area.center_x - SPRITE_WIDTH / 2; const float X_DEST = param.game.game_area.center_x - SPRITE_WIDTH / 2;
const int Y_DEST = param.game.game_area.first_quarter_y - (SPRITE_HEIGHT / 4); const float Y_DEST = param.game.game_area.first_quarter_y - (SPRITE_HEIGHT / 4);
// Inicializa los sprites con las imagenes // Inicializa los sprites con las imagenes
constexpr int TOTAL_SPRITES = 6; constexpr int TOTAL_SPRITES = 6;
@@ -333,11 +333,11 @@ void Intro::initSprites()
sprites_.at(5)->addPath(X_DEST, -SPRITE_WIDTH, PathType::HORIZONTAL, Y_DEST, 80, easeInElastic, 0); sprites_.at(5)->addPath(X_DEST, -SPRITE_WIDTH, PathType::HORIZONTAL, Y_DEST, 80, easeInElastic, 0);
// Constantes // Constantes
const int BORDER = 4; const float BORDER = 4;
const int SHADOW_SPRITE_WIDTH = SPRITE_WIDTH + BORDER; const float SHADOW_SPRITE_WIDTH = SPRITE_WIDTH + BORDER;
const int SHADOW_SPRITE_HEIGHT = SPRITE_HEIGHT + BORDER; const float SHADOW_SPRITE_HEIGHT = SPRITE_HEIGHT + BORDER;
const int S_X_DEST = X_DEST - BORDER / 2; const float S_X_DEST = X_DEST - BORDER / 2;
const int S_Y_DEST = Y_DEST - BORDER / 2; const float S_Y_DEST = Y_DEST - BORDER / 2;
// Crea las texturas para las imágenes traseras // Crea las texturas para las imágenes traseras
std::vector<std::shared_ptr<Texture>> shadow_textures; std::vector<std::shared_ptr<Texture>> shadow_textures;

View File

@@ -1,4 +1,5 @@
#pragma once #pragma once
#include <SDL3/SDL.h>
#include <SDL3/SDL_stdinc.h> // Para Uint32, Uint8 #include <SDL3/SDL_stdinc.h> // Para Uint32, Uint8
#include <memory> // Para unique_ptr #include <memory> // Para unique_ptr
@@ -35,7 +36,7 @@ private:
std::unique_ptr<TiledBG> tiled_bg_; std::unique_ptr<TiledBG> tiled_bg_;
// Variables // Variables
Uint32 ticks_ = 0; // Contador de ticks para ajustar la velocidad del programa Uint64 ticks_ = 0; // Contador de ticks para ajustar la velocidad del programa
int scene_ = 0; // Indica que escena está activa int scene_ = 0; // Indica que escena está activa
IntroState state_ = IntroState::SCENES; // Estado IntroState state_ = IntroState::SCENES; // Estado
IntroPostState post_state_ = IntroPostState::STOP_BG; // Estado IntroPostState post_state_ = IntroPostState::STOP_BG; // Estado

View File

@@ -1,4 +1,5 @@
#pragma once #pragma once
#include <SDL3/SDL.h>
#include <SDL3/SDL_rect.h> // Para SDL_FRect #include <SDL3/SDL_rect.h> // Para SDL_FRect
#include <SDL3/SDL_stdinc.h> // Para Uint16 #include <SDL3/SDL_stdinc.h> // Para Uint16

View File

@@ -89,7 +89,7 @@ Uint32 JA_UpdateCallback(void *userdata, SDL_TimerID timerID, Uint32 interval)
{ {
if (current_music->times != 0) if (current_music->times != 0)
{ {
if (SDL_GetAudioStreamAvailable(current_music->stream) < (current_music->length / 2)) if (SDL_GetAudioStreamAvailable(current_music->stream) < static_cast<int>(current_music->length / 2))
SDL_PutAudioStreamData(current_music->stream, current_music->buffer, current_music->length); SDL_PutAudioStreamData(current_music->stream, current_music->buffer, current_music->length);
if (current_music->times > 0) if (current_music->times > 0)
current_music->times--; current_music->times--;
@@ -108,7 +108,7 @@ Uint32 JA_UpdateCallback(void *userdata, SDL_TimerID timerID, Uint32 interval)
{ {
if (channels[i].times != 0) if (channels[i].times != 0)
{ {
if (SDL_GetAudioStreamAvailable(channels[i].stream) < (channels[i].sound->length / 2)) if (SDL_GetAudioStreamAvailable(channels[i].stream) < static_cast<int>(channels[i].sound->length / 2))
SDL_PutAudioStreamData(channels[i].stream, channels[i].sound->buffer, channels[i].sound->length); SDL_PutAudioStreamData(channels[i].stream, channels[i].sound->buffer, channels[i].sound->length);
if (channels[i].times > 0) if (channels[i].times > 0)
channels[i].times--; channels[i].times--;

View File

@@ -1,5 +1,5 @@
#include "jail_shader.h" #include "jail_shader.h"
#include <SDL3/SDL_rect.h> // Para SDL_Point #include <SDL3/SDL_rect.h> // Para SDL_FPoint
#include <SDL3/SDL_stdinc.h> // Para SDL_bool #include <SDL3/SDL_stdinc.h> // Para SDL_bool
#include <cstring> // Para strncmp #include <cstring> // Para strncmp
#include <iostream> // Para basic_ostream, operator<<, endl, cout #include <iostream> // Para basic_ostream, operator<<, endl, cout
@@ -25,7 +25,7 @@ namespace shader
GLuint programId = 0; GLuint programId = 0;
SDL_Texture *backBuffer = nullptr; SDL_Texture *backBuffer = nullptr;
SDL_Point win_size = {320 * 4, 256 * 4}; SDL_Point win_size = {320 * 4, 256 * 4};
SDL_Point tex_size = {320, 256}; SDL_FPoint tex_size = {320, 256};
bool usingOpenGL = false; bool usingOpenGL = false;
#ifndef __APPLE__ #ifndef __APPLE__
@@ -157,12 +157,13 @@ namespace shader
shader::backBuffer = texturaBackBuffer; shader::backBuffer = texturaBackBuffer;
SDL_GetWindowSize(ventana, &win_size.x, &win_size.y); SDL_GetWindowSize(ventana, &win_size.x, &win_size.y);
int acceso; //int acceso;
SDL_QueryTexture(texturaBackBuffer, nullptr, &acceso, &tex_size.x, &tex_size.y); SDL_GetTextureSize(texturaBackBuffer, &tex_size.x, &tex_size.y);
if (acceso != SDL_TEXTUREACCESS_TARGET) // SDL_QueryTexture(texturaBackBuffer, nullptr, &acceso, &tex_size.x, &tex_size.y);
/*if (acceso != SDL_TEXTUREACCESS_TARGET)
{ {
throw std::runtime_error("ERROR FATAL: La textura debe tener definido SDL_TEXTUREACCESS_TARGET."); throw std::runtime_error("ERROR FATAL: La textura debe tener definido SDL_TEXTUREACCESS_TARGET.");
} }*/
const auto RENDER_NAME = SDL_GetRendererName(renderer); const auto RENDER_NAME = SDL_GetRendererName(renderer);

View File

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

View File

@@ -23,9 +23,9 @@ namespace lang
while (std::getline(rfile, line)) while (std::getline(rfile, line))
{ {
// Almacena solo las lineas que no empiezan por # o no esten vacias // Almacena solo las lineas que no empiezan por # o no esten vacias
const bool test1 = line.substr(0, 1) != "#"; const bool TEST1 = line.substr(0, 1) != "#";
const bool test2 = !line.empty(); const bool TEST2 = !line.empty();
if (test1 && test2) if (TEST1 && TEST2)
{ {
texts.push_back(line); texts.push_back(line);
} }

View File

@@ -1,4 +1,5 @@
#pragma once #pragma once
#include <SDL3/SDL.h>
#include <string> // Para string #include <string> // Para string

View File

@@ -24,7 +24,11 @@ Logo::Logo()
section::name = section::Name::LOGO; section::name = section::Name::LOGO;
dest_.x = param.game.game_area.center_x - jail_texture_->getWidth() / 2; dest_.x = param.game.game_area.center_x - jail_texture_->getWidth() / 2;
dest_.y = param.game.game_area.center_y - jail_texture_->getHeight() / 2; dest_.y = param.game.game_area.center_y - jail_texture_->getHeight() / 2;
since_sprite_->setPosition({(param.game.width - since_texture_->getWidth()) / 2, 83 + jail_texture_->getHeight() + 5, since_texture_->getWidth(), since_texture_->getHeight()}); since_sprite_->setPosition(SDL_FRect{
static_cast<float>((param.game.width - since_texture_->getWidth()) / 2),
static_cast<float>(83 + jail_texture_->getHeight() + 5),
static_cast<float>(since_texture_->getWidth()),
static_cast<float>(since_texture_->getHeight())});
since_sprite_->setY(dest_.y + jail_texture_->getHeight() + 5); since_sprite_->setY(dest_.y + jail_texture_->getHeight() + 5);
since_sprite_->setSpriteClip(0, 0, since_texture_->getWidth(), since_texture_->getHeight()); since_sprite_->setSpriteClip(0, 0, since_texture_->getWidth(), since_texture_->getHeight());
since_texture_->setColor(0x00, 0x00, 0x00); since_texture_->setColor(0x00, 0x00, 0x00);
@@ -181,7 +185,7 @@ void Logo::render()
void Logo::run() void Logo::run()
{ {
// Detiene la música // Detiene la música
JA_FadeOutMusic(300); /*JA_FadeOutMusic(300);*/
while (section::name == section::Name::LOGO) while (section::name == section::Name::LOGO)
{ {

View File

@@ -1,6 +1,7 @@
#pragma once #pragma once
#include <SDL3/SDL.h>
#include <SDL3/SDL_rect.h> // Para SDL_Point #include <SDL3/SDL_rect.h> // Para SDL_FPoint
#include <SDL3/SDL_stdinc.h> // Para Uint32 #include <SDL3/SDL_stdinc.h> // Para Uint32
#include <memory> // Para shared_ptr, unique_ptr #include <memory> // Para shared_ptr, unique_ptr
#include <vector> // Para vector #include <vector> // Para vector
@@ -36,8 +37,8 @@ private:
// Variables // Variables
std::vector<Color> color_; // Vector con los colores para el fade std::vector<Color> color_; // Vector con los colores para el fade
int counter_ = 0; // Contador int counter_ = 0; // Contador
Uint32 ticks_ = 0; // Contador de ticks para ajustar la velocidad del programa Uint64 ticks_ = 0; // Contador de ticks para ajustar la velocidad del programa
SDL_Point dest_; // Posición X donde dibujar el logo SDL_FPoint dest_; // Posición X donde dibujar el logo
// Actualiza las variables // Actualiza las variables
void update(); void update();

View File

@@ -1,6 +1,6 @@
#include "manage_hiscore_table.h" #include "manage_hiscore_table.h"
#include <SDL3/SDL_error.h> // Para SDL_GetError #include <SDL3/SDL_error.h> // Para SDL_GetError
#include <SDL3/SDL_rwops.h> // Para SDL_RWread, SDL_RWwrite, SDL_RWFromFile #include <SDL3/SDL.h> // Para SDL_RWread, SDL_WriteIO, SDL_RWFromFile
#include <algorithm> // Para find_if, sort #include <algorithm> // Para find_if, sort
#include <iostream> // Para basic_ostream, operator<<, cout, endl #include <iostream> // Para basic_ostream, operator<<, cout, endl
#include <iterator> // Para distance #include <iterator> // Para distance
@@ -70,9 +70,9 @@ void ManageHiScoreTable::sort()
struct struct
{ {
bool operator()(const HiScoreEntry &a, const HiScoreEntry &b) const { return a.score > b.score; } bool operator()(const HiScoreEntry &a, const HiScoreEntry &b) const { return a.score > b.score; }
} scoreDescendingComparator; } score_descending_comparator;
std::sort(table_.begin(), table_.end(), scoreDescendingComparator); std::sort(table_.begin(), table_.end(), score_descending_comparator);
} }
// Carga la tabla desde un fichero // Carga la tabla desde un fichero
@@ -80,44 +80,44 @@ bool ManageHiScoreTable::loadFromFile(const std::string &file_path)
{ {
clear(); clear();
auto success = true; auto success = true;
auto file = SDL_RWFromFile(file_path.c_str(), "rb"); auto file = SDL_IOFromFile(file_path.c_str(), "rb");
if (file) if (file)
{ {
table_.clear(); // Limpia la tabla actual table_.clear(); // Limpia la tabla actual
// Lee el número de entradas en la tabla // Lee el número de entradas en la tabla
int tableSize = 0; int table_size = 0;
SDL_RWread(file, &tableSize, sizeof(int), 1); SDL_ReadIO(file, &table_size, sizeof(int));
// Lee los datos de cada entrada // Lee los datos de cada entrada
for (int i = 0; i < tableSize; ++i) for (int i = 0; i < table_size; ++i)
{ {
HiScoreEntry entry; HiScoreEntry entry;
// Lee la puntuación // Lee la puntuación
SDL_RWread(file, &entry.score, sizeof(int), 1); SDL_ReadIO(file, &entry.score, sizeof(int));
// Lee el tamaño del nombre y luego el nombre // Lee el tamaño del nombre y luego el nombre
int nameSize = 0; int name_size = 0;
SDL_RWread(file, &nameSize, sizeof(int), 1); SDL_ReadIO(file, &name_size, sizeof(int));
std::vector<char> nameBuffer(nameSize + 1); std::vector<char> name_buffer(name_size + 1);
SDL_RWread(file, nameBuffer.data(), nameSize, 1); SDL_ReadIO(file, name_buffer.data(), name_size);
nameBuffer[nameSize] = '\0'; // Asegurar el fin de la cadena name_buffer[name_size] = '\0'; // Asegurar el fin de la cadena
entry.name = std::string(nameBuffer.data()); entry.name = std::string(name_buffer.data());
// Lee el valor de one_credit_complete // Lee el valor de one_credit_complete
int occValue = 0; int occ_value = 0;
SDL_RWread(file, &occValue, sizeof(int), 1); SDL_ReadIO(file, &occ_value, sizeof(int));
entry.one_credit_complete = (occValue != 0); entry.one_credit_complete = (occ_value != 0);
// Añade la entrada a la tabla // Añade la entrada a la tabla
table_.push_back(entry); table_.push_back(entry);
} }
std::cout << "Reading file: " << getFileName(file_path) << std::endl; std::cout << "Reading file: " << getFileName(file_path) << std::endl;
SDL_RWclose(file); SDL_CloseIO(file);
} }
else else
{ {
@@ -131,34 +131,34 @@ bool ManageHiScoreTable::loadFromFile(const std::string &file_path)
bool ManageHiScoreTable::saveToFile(const std::string &file_path) bool ManageHiScoreTable::saveToFile(const std::string &file_path)
{ {
auto success = true; auto success = true;
auto file = SDL_RWFromFile(file_path.c_str(), "w+b"); auto file = SDL_IOFromFile(file_path.c_str(), "w+b");
if (file) if (file)
{ {
// Guarda el número de entradas en la tabla // Guarda el número de entradas en la tabla
int tableSize = static_cast<int>(table_.size()); int table_size = static_cast<int>(table_.size());
SDL_RWwrite(file, &tableSize, sizeof(int), 1); SDL_WriteIO(file, &table_size, sizeof(int));
// Guarda los datos de cada entrada // Guarda los datos de cada entrada
for (int i = 0; i < tableSize; ++i) for (int i = 0; i < table_size; ++i)
{ {
const HiScoreEntry &entry = table_.at(i); const HiScoreEntry &entry = table_.at(i);
// Guarda la puntuación // Guarda la puntuación
SDL_RWwrite(file, &entry.score, sizeof(int), 1); SDL_WriteIO(file, &entry.score, sizeof(int));
// Guarda el tamaño del nombre y luego el nombre // Guarda el tamaño del nombre y luego el nombre
int nameSize = static_cast<int>(entry.name.size()); int name_size = static_cast<int>(entry.name.size());
SDL_RWwrite(file, &nameSize, sizeof(int), 1); SDL_WriteIO(file, &name_size, sizeof(int));
SDL_RWwrite(file, entry.name.c_str(), nameSize, 1); SDL_WriteIO(file, entry.name.c_str(), name_size);
// Guarda el valor de one_credit_complete como un entero (0 o 1) // Guarda el valor de one_credit_complete como un entero (0 o 1)
int occValue = entry.one_credit_complete ? 1 : 0; int occ_value = entry.one_credit_complete ? 1 : 0;
SDL_RWwrite(file, &occValue, sizeof(int), 1); SDL_WriteIO(file, &occ_value, sizeof(int));
} }
std::cout << "Writing file: " << getFileName(file_path) << std::endl; std::cout << "Writing file: " << getFileName(file_path) << std::endl;
SDL_RWclose(file); SDL_CloseIO(file);
} }
else else
{ {

View File

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

View File

@@ -10,14 +10,12 @@ namespace Mouse
void handleEvent(const SDL_Event &event) void handleEvent(const SDL_Event &event)
{ {
if (event.type == SDL_MOUSEMOTION) if (event.type == SDL_EVENT_MOUSE_MOTION)
{ {
last_mouse_move_time = SDL_GetTicks(); last_mouse_move_time = SDL_GetTicks();
if (!cursor_visible) if (!cursor_visible)
{ {
#ifndef ARCADE SDL_ShowCursor();
SDL_ShowCursor(SDL_ENABLE);
#endif
cursor_visible = true; cursor_visible = true;
} }
} }
@@ -28,7 +26,7 @@ namespace Mouse
Uint32 current_time = SDL_GetTicks(); Uint32 current_time = SDL_GetTicks();
if (cursor_visible && (current_time - last_mouse_move_time > cursor_hide_time)) if (cursor_visible && (current_time - last_mouse_move_time > cursor_hide_time))
{ {
SDL_ShowCursor(SDL_DISABLE); SDL_HideCursor();
cursor_visible = false; cursor_visible = false;
} }
} }

View File

@@ -1,4 +1,5 @@
#pragma once #pragma once
#include <SDL3/SDL.h>
#include <SDL3/SDL_events.h> // Para SDL_Event #include <SDL3/SDL_events.h> // Para SDL_Event
#include <SDL3/SDL_stdinc.h> // Para Uint32 #include <SDL3/SDL_stdinc.h> // Para Uint32

View File

@@ -2,7 +2,7 @@
#include "texture.h" // Para Texture #include "texture.h" // Para Texture
// Constructor // Constructor
MovingSprite::MovingSprite(std::shared_ptr<Texture> texture, SDL_FRect pos, Rotate rotate, float zoom_w, float zoom_h, SDL_RendererFlip flip) MovingSprite::MovingSprite(std::shared_ptr<Texture> texture, SDL_FRect pos, Rotate rotate, float zoom_w, float zoom_h, SDL_FlipMode flip)
: Sprite(texture, pos), : Sprite(texture, pos),
x_(pos.x), x_(pos.x),
y_(pos.y), y_(pos.y),

View File

@@ -1,7 +1,8 @@
#pragma once #pragma once
#include <SDL3/SDL.h>
#include <SDL3/SDL_rect.h> // Para SDL_FRect, SDL_Point #include <SDL3/SDL_rect.h> // Para SDL_FRect, SDL_FPoint
#include <SDL3/SDL_render.h> // Para SDL_RendererFlip #include <SDL3/SDL_render.h> // Para SDL_FlipMode
#include <memory> // Para shared_ptr #include <memory> // Para shared_ptr
#include <algorithm> #include <algorithm>
#include "sprite.h" // Para Sprite #include "sprite.h" // Para Sprite
@@ -18,14 +19,14 @@ public:
int speed; // Velocidad de giro int speed; // Velocidad de giro
double angle; // Angulo para dibujarlo double angle; // Angulo para dibujarlo
float amount; // Cantidad de grados a girar en cada iteración float amount; // Cantidad de grados a girar en cada iteración
SDL_Point center; // Centro de rotación SDL_FPoint center; // Centro de rotación
Rotate() : enabled(false), counter(0), speed(1), angle(0.0), amount(0.0f), center({0, 0}) {} Rotate() : enabled(false), counter(0), speed(1), angle(0.0), amount(0.0f), center({0.0f, 0.0f}) {}
}; };
protected: protected:
float x_; // Posición en el eje X float x_ = 0.0f; // Posición en el eje X
float y_; // Posición en el eje Y float y_ = 0.0f; // Posición en el eje Y
float vx_ = 0.0f; // Velocidad en el eje X. Cantidad de pixeles a desplazarse float vx_ = 0.0f; // Velocidad en el eje X. Cantidad de pixeles a desplazarse
float vy_ = 0.0f; // Velocidad en el eje Y. Cantidad de pixeles a desplazarse float vy_ = 0.0f; // Velocidad en el eje Y. Cantidad de pixeles a desplazarse
@@ -36,7 +37,7 @@ protected:
Rotate rotate_; // Variables usada para controlar la rotación del sprite Rotate rotate_; // Variables usada para controlar la rotación del sprite
float zoom_w_; // Zoom aplicado a la anchura float zoom_w_; // Zoom aplicado a la anchura
float zoom_h_; // Zoom aplicado a la altura float zoom_h_; // Zoom aplicado a la altura
SDL_RendererFlip flip_; // Indica como se voltea el sprite SDL_FlipMode flip_; // Indica como se voltea el sprite
// Incrementa el valor del ángulo // Incrementa el valor del ángulo
void updateAngle() { rotate_.angle += rotate_.amount; } void updateAngle() { rotate_.angle += rotate_.amount; }
@@ -49,7 +50,7 @@ protected:
public: public:
// Constructor // Constructor
MovingSprite(std::shared_ptr<Texture> texture, SDL_FRect pos, MovingSprite::Rotate rotate, float zoom_w, float zoom_h, SDL_RendererFlip flip); MovingSprite(std::shared_ptr<Texture> texture, SDL_FRect pos, MovingSprite::Rotate rotate, float zoom_w, float zoom_h, SDL_FlipMode flip);
MovingSprite(std::shared_ptr<Texture> texture, SDL_FRect pos); MovingSprite(std::shared_ptr<Texture> texture, SDL_FRect pos);
explicit MovingSprite(std::shared_ptr<Texture> texture); explicit MovingSprite(std::shared_ptr<Texture> texture);
@@ -88,7 +89,7 @@ public:
// Establece el valor de la variable // Establece el valor de la variable
void setAngle(double value) { rotate_.angle = value; } void setAngle(double value) { rotate_.angle = value; }
void setRotatingCenter(SDL_Point point) { rotate_.center = point; } void setRotatingCenter(SDL_FPoint point) { rotate_.center = point; }
// Activa o desactiva el efecto de rotación // Activa o desactiva el efecto de rotación
void setRotate(bool enable); void setRotate(bool enable);
@@ -101,13 +102,13 @@ public:
void switchRotate() { rotate_.amount *= -1; } void switchRotate() { rotate_.amount *= -1; }
// Establece el valor de la variable // Establece el valor de la variable
void setFlip(SDL_RendererFlip flip) { flip_ = flip; } void setFlip(SDL_FlipMode flip) { flip_ = flip; }
// Gira el sprite horizontalmente // Gira el sprite horizontalmente
void flip() { flip_ = (flip_ == SDL_FLIP_HORIZONTAL) ? SDL_FLIP_NONE : SDL_FLIP_HORIZONTAL; } void flip() { flip_ = (flip_ == SDL_FLIP_HORIZONTAL) ? SDL_FLIP_NONE : SDL_FLIP_HORIZONTAL; }
// Obtiene el valor de la variable // Obtiene el valor de la variable
SDL_RendererFlip getFlip() { return flip_; } SDL_FlipMode getFlip() { return flip_; }
// Establece la posición y_ el tamaño del objeto // Establece la posición y_ el tamaño del objeto
void setPos(SDL_FRect rect); void setPos(SDL_FRect rect);

View File

@@ -181,60 +181,60 @@ void Notifier::show(std::vector<std::string> texts, int icon, const std::string
} }
// Inicializa variables // Inicializa variables
constexpr int icon_size = 16; constexpr int ICON_SIZE = 16;
constexpr int padding_out = 1; constexpr int PADDING_OUT = 1;
const auto padding_in_h = text_->getCharacterSize(); const float PADDING_IN_H = text_->getCharacterSize();
const auto padding_in_v = text_->getCharacterSize() / 2; const float PADDING_IN_V = text_->getCharacterSize() / 2;
const int icon_space = icon >= 0 ? icon_size + padding_in_h : 0; const int ICON_SPACE = icon >= 0 ? ICON_SIZE + PADDING_IN_H : 0;
const int width = text_->lenght(longest) + (padding_in_h * 2) + icon_space; const float WIDTH = text_->lenght(longest) + (PADDING_IN_H * 2) + ICON_SPACE;
const int height = (text_->getCharacterSize() * texts.size()) + (padding_in_v * 2); const float HEIGHT = (text_->getCharacterSize() * texts.size()) + (PADDING_IN_V * 2);
const auto shape = NotificationShape::SQUARED; const auto SHAPE = NotificationShape::SQUARED;
// Posición horizontal // Posición horizontal
auto desp_h = 0; float desp_h = 0;
if (param.notification.pos_h == NotifyPosition::LEFT) switch (param.notification.pos_h)
{ {
desp_h = padding_out; case NotifyPosition::LEFT:
} desp_h = PADDING_OUT;
else if (param.notification.pos_h == NotifyPosition::MIDDLE) break;
{
desp_h = ((param.game.width / 2) - (width / 2)); case NotifyPosition::MIDDLE:
} desp_h = ((param.game.width / 2) - (WIDTH / 2));
else break;
{
desp_h = param.game.width - width - padding_out; case NotifyPosition::RIGHT:
desp_h = param.game.width - WIDTH - PADDING_OUT;
break;
default:
desp_h = 0;
break;
} }
// Posición vertical // Posición vertical
const int desp_v = (param.notification.pos_v == NotifyPosition::TOP) ? padding_out : (param.game.height - height - padding_out); const int DESP_V = (param.notification.pos_v == NotifyPosition::TOP) ? PADDING_OUT : (param.game.height - HEIGHT - PADDING_OUT);
// Offset // Offset
const auto travel_dist = height + padding_out; const auto TRAVEL_DIST = HEIGHT + PADDING_OUT;
auto offset = 0; auto OFFSET = notifications_.empty()
if (param.notification.pos_v == NotifyPosition::TOP) ? DESP_V
{ : notifications_.back().y + (param.notification.pos_v == NotifyPosition::TOP ? TRAVEL_DIST : -TRAVEL_DIST);
offset = !notifications_.empty() ? notifications_.back().y + travel_dist : desp_v;
}
else
{
offset = !notifications_.empty() ? notifications_.back().y - travel_dist : desp_v;
}
// Crea la notificacion // Crea la notificacion
Notification n; Notification n;
// Inicializa variables // Inicializa variables
n.code = code; n.code = code;
n.y = offset; n.y = OFFSET;
n.travel_dist = travel_dist; n.travel_dist = TRAVEL_DIST;
n.texts = texts; n.texts = texts;
n.shape = shape; n.shape = SHAPE;
auto y_pos = offset + (param.notification.pos_v == NotifyPosition::TOP ? -travel_dist : travel_dist); const float POS_Y = OFFSET + (param.notification.pos_v == NotifyPosition::TOP ? -TRAVEL_DIST : TRAVEL_DIST);
n.rect = {desp_h, y_pos, width, height}; n.rect = {desp_h, POS_Y, WIDTH, HEIGHT};
// Crea la textura // Crea la textura
n.texture = std::make_shared<Texture>(renderer_); n.texture = std::make_shared<Texture>(renderer_);
n.texture->createBlank(width, height, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET); n.texture->createBlank(WIDTH, HEIGHT, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET);
n.texture->setBlendMode(SDL_BLENDMODE_BLEND); n.texture->setBlendMode(SDL_BLENDMODE_BLEND);
// Prepara para dibujar en la textura // Prepara para dibujar en la textura
@@ -243,22 +243,22 @@ void Notifier::show(std::vector<std::string> texts, int icon, const std::string
// Dibuja el fondo de la notificación // Dibuja el fondo de la notificación
SDL_SetRenderDrawColor(renderer_, bg_color_.r, bg_color_.g, bg_color_.b, 255); SDL_SetRenderDrawColor(renderer_, bg_color_.r, bg_color_.g, bg_color_.b, 255);
SDL_FRect rect; SDL_FRect rect;
if (shape == NotificationShape::ROUNDED) if (SHAPE == NotificationShape::ROUNDED)
{ {
rect = {4, 0, width - (4 * 2), height}; rect = {4, 0, WIDTH - (4 * 2), HEIGHT};
SDL_RenderFillRect(renderer_, &rect); SDL_RenderFillRect(renderer_, &rect);
rect = {4 / 2, 1, width - 4, height - 2}; rect = {4 / 2, 1, WIDTH - 4, HEIGHT - 2};
SDL_RenderFillRect(renderer_, &rect); SDL_RenderFillRect(renderer_, &rect);
rect = {1, 4 / 2, width - 2, height - 4}; rect = {1, 4 / 2, WIDTH - 2, HEIGHT - 4};
SDL_RenderFillRect(renderer_, &rect); SDL_RenderFillRect(renderer_, &rect);
rect = {0, 4, width, height - (4 * 2)}; rect = {0, 4, WIDTH, HEIGHT - (4 * 2)};
SDL_RenderFillRect(renderer_, &rect); SDL_RenderFillRect(renderer_, &rect);
} }
else if (shape == NotificationShape::SQUARED) else if (SHAPE == NotificationShape::SQUARED)
{ {
SDL_RenderClear(renderer_); SDL_RenderClear(renderer_);
} }
@@ -266,9 +266,13 @@ void Notifier::show(std::vector<std::string> texts, int icon, const std::string
// Dibuja el icono de la notificación // Dibuja el icono de la notificación
if (has_icons_ && icon >= 0 && texts.size() >= 2) if (has_icons_ && icon >= 0 && texts.size() >= 2)
{ {
auto sp = std::make_unique<Sprite>(icon_texture_, (SDL_FRect){0, 0, icon_size, icon_size}); auto sp = std::make_unique<Sprite>(icon_texture_, (SDL_FRect){0, 0, ICON_SIZE, ICON_SIZE});
sp->setPosition({padding_in_h, padding_in_v, icon_size, icon_size}); sp->setPosition({PADDING_IN_H, PADDING_IN_V, ICON_SIZE, ICON_SIZE});
sp->setSpriteClip({icon_size * (icon % 10), icon_size * (icon / 10), icon_size, icon_size}); sp->setSpriteClip(SDL_FRect{
static_cast<float>(ICON_SIZE * (icon % 10)),
static_cast<float>(ICON_SIZE * (icon / 10)),
ICON_SIZE,
ICON_SIZE});
sp->render(); sp->render();
} }
@@ -277,7 +281,7 @@ void Notifier::show(std::vector<std::string> texts, int icon, const std::string
int iterator = 0; int iterator = 0;
for (const auto &text : texts) for (const auto &text : texts)
{ {
text_->writeColored(padding_in_h + icon_space, padding_in_v + iterator * (text_->getCharacterSize() + 1), text, color); text_->writeColored(PADDING_IN_H + ICON_SPACE, PADDING_IN_V + iterator * (text_->getCharacterSize() + 1), text, color);
++iterator; ++iterator;
} }

View File

@@ -1,4 +1,5 @@
#pragma once #pragma once
#include <SDL3/SDL.h>
#include <SDL3/SDL_rect.h> // Para SDL_FRect #include <SDL3/SDL_rect.h> // Para SDL_FRect
#include <SDL3/SDL_render.h> // Para SDL_Renderer #include <SDL3/SDL_render.h> // Para SDL_Renderer

View File

@@ -15,8 +15,8 @@ OnScreenHelp *OnScreenHelp::onScreenHelp = nullptr;
// Constantes evaluables en tiempo de compilación // Constantes evaluables en tiempo de compilación
constexpr int ICONSIZE = 16; constexpr int ICONSIZE = 16;
constexpr SDL_Point PADDING = {8, 8}; constexpr SDL_FPoint PADDING = {8, 8};
constexpr SDL_Point DESP = {ICONSIZE + 4, 5}; constexpr SDL_FPoint DESP = {ICONSIZE + 4, 5};
constexpr SDL_FRect CONTROLLER_UP = {16, 0, ICONSIZE, ICONSIZE}; constexpr SDL_FRect CONTROLLER_UP = {16, 0, ICONSIZE, ICONSIZE};
constexpr SDL_FRect CONTROLLER_DOWN = {48, 0, ICONSIZE, ICONSIZE}; constexpr SDL_FRect CONTROLLER_DOWN = {48, 0, ICONSIZE, ICONSIZE};

View File

@@ -1,4 +1,5 @@
#pragma once #pragma once
#include <SDL3/SDL.h>
#include <SDL3/SDL_rect.h> // Para SDL_FRect #include <SDL3/SDL_rect.h> // Para SDL_FRect
#include <SDL3/SDL_render.h> // Para SDL_Texture #include <SDL3/SDL_render.h> // Para SDL_Texture

View File

@@ -1,5 +1,5 @@
#include "options.h" #include "options.h"
#include <SDL3/SDL_gamecontroller.h> // Para SDL_GameControllerButton #include <SDL3/SDL.h> // Para SDL_GamepadButton
#include <algorithm> // Para clamp #include <algorithm> // Para clamp
#include <fstream> // Para basic_ostream, operator<<, basi... #include <fstream> // Para basic_ostream, operator<<, basi...
#include <iostream> // Para cout #include <iostream> // Para cout
@@ -7,7 +7,7 @@
#include <vector> // Para vector #include <vector> // Para vector
#include "input.h" // Para InputDeviceToUse #include "input.h" // Para InputDeviceToUse
#include "lang.h" // Para Code #include "lang.h" // Para Code
#include "screen.h" // Para ScreenVideoMode, ScreenFilter #include "screen.h" // Para ScreenFilter
#include "utils.h" // Para boolToString, stringToBool, get... #include "utils.h" // Para boolToString, stringToBool, get...
// Variables // Variables
@@ -21,10 +21,10 @@ void initOptions()
{ {
// Opciones de video // Opciones de video
#ifdef ANBERNIC #ifdef ANBERNIC
options.video.mode = ScreenVideoMode::WINDOW; options.video.mode = false;
options.video.window.size = 3; options.video.window.size = 3;
#else #else
options.video.mode = ScreenVideoMode::WINDOW; options.video.fullscreen = false;
options.video.window.zoom = 2; options.video.window.zoom = 2;
#endif #endif
options.video.filter = ScreenFilter::NEAREST; options.video.filter = ScreenFilter::NEAREST;
@@ -98,13 +98,6 @@ bool loadOptionsFile(std::string file_path)
} }
// Normaliza los valores // Normaliza los valores
const bool a = options.video.mode == ScreenVideoMode::WINDOW;
const bool b = options.video.mode == ScreenVideoMode::FULLSCREEN;
if (!(a || b))
{
options.video.mode = ScreenVideoMode::WINDOW;
}
options.video.window.zoom = std::clamp(options.video.window.zoom, 1, 4); options.video.window.zoom = std::clamp(options.video.window.zoom, 1, 4);
if (options.game.language != lang::Code::en_UK && if (options.game.language != lang::Code::en_UK &&
@@ -132,11 +125,10 @@ bool saveOptionsFile(std::string file_path)
// Opciones de video // Opciones de video
file << "## VIDEO\n"; file << "## VIDEO\n";
file << "## video.mode [" << static_cast<int>(ScreenVideoMode::WINDOW) << ": window, " << static_cast<int>(ScreenVideoMode::FULLSCREEN) << ": fullscreen]\n";
file << "## video.filter [" << static_cast<int>(ScreenFilter::NEAREST) << ": nearest, " << static_cast<int>(ScreenFilter::LINEAL) << ": lineal]\n"; file << "## video.filter [" << static_cast<int>(ScreenFilter::NEAREST) << ": nearest, " << static_cast<int>(ScreenFilter::LINEAL) << ": lineal]\n";
file << "\n"; file << "\n";
file << "video.mode=" << static_cast<int>(options.video.mode) << "\n"; file << "video.fullscreen=" << boolToString(options.video.fullscreen) << "\n";
file << "video.window.size=" << options.video.window.zoom << "\n"; file << "video.window.size=" << options.video.window.zoom << "\n";
file << "video.filter=" << static_cast<int>(options.video.filter) << "\n"; file << "video.filter=" << static_cast<int>(options.video.filter) << "\n";
file << "video.v_sync=" << boolToString(options.video.v_sync) << "\n"; file << "video.v_sync=" << boolToString(options.video.v_sync) << "\n";
@@ -200,7 +192,7 @@ bool setOptions(const std::string &var, const std::string &value)
// Opciones de video // Opciones de video
if (var == "video.mode") if (var == "video.mode")
{ {
options.video.mode = static_cast<ScreenVideoMode>(std::stoi(value)); options.video.fullscreen = stringToBool(value);
} }
else if (var == "video.window.size") else if (var == "video.window.size")
{ {
@@ -282,23 +274,23 @@ bool setOptions(const std::string &var, const std::string &value)
} }
else if (var == "controller.0.button.fire_left") else if (var == "controller.0.button.fire_left")
{ {
options.controllers.at(0).buttons.at(0) = static_cast<SDL_GameControllerButton>(std::stoi(value)); options.controllers.at(0).buttons.at(0) = static_cast<SDL_GamepadButton>(std::stoi(value));
} }
else if (var == "controller.0.button.fire_center") else if (var == "controller.0.button.fire_center")
{ {
options.controllers.at(0).buttons.at(1) = static_cast<SDL_GameControllerButton>(std::stoi(value)); options.controllers.at(0).buttons.at(1) = static_cast<SDL_GamepadButton>(std::stoi(value));
} }
else if (var == "controller.0.button.fire_right") else if (var == "controller.0.button.fire_right")
{ {
options.controllers.at(0).buttons.at(2) = static_cast<SDL_GameControllerButton>(std::stoi(value)); options.controllers.at(0).buttons.at(2) = static_cast<SDL_GamepadButton>(std::stoi(value));
} }
else if (var == "controller.0.button.start") else if (var == "controller.0.button.start")
{ {
options.controllers.at(0).buttons.at(3) = static_cast<SDL_GameControllerButton>(std::stoi(value)); options.controllers.at(0).buttons.at(3) = static_cast<SDL_GamepadButton>(std::stoi(value));
} }
else if (var == "controller.0.button.service") else if (var == "controller.0.button.service")
{ {
options.controllers.at(0).buttons.at(4) = static_cast<SDL_GameControllerButton>(std::stoi(value)); options.controllers.at(0).buttons.at(4) = static_cast<SDL_GamepadButton>(std::stoi(value));
} }
else if (var == "controller.1.name") else if (var == "controller.1.name")
{ {
@@ -314,23 +306,23 @@ bool setOptions(const std::string &var, const std::string &value)
} }
else if (var == "controller.1.button.fire_left") else if (var == "controller.1.button.fire_left")
{ {
options.controllers.at(1).buttons.at(0) = static_cast<SDL_GameControllerButton>(std::stoi(value)); options.controllers.at(1).buttons.at(0) = static_cast<SDL_GamepadButton>(std::stoi(value));
} }
else if (var == "controller.1.button.fire_center") else if (var == "controller.1.button.fire_center")
{ {
options.controllers.at(1).buttons.at(1) = static_cast<SDL_GameControllerButton>(std::stoi(value)); options.controllers.at(1).buttons.at(1) = static_cast<SDL_GamepadButton>(std::stoi(value));
} }
else if (var == "controller.1.button.fire_right") else if (var == "controller.1.button.fire_right")
{ {
options.controllers.at(1).buttons.at(2) = static_cast<SDL_GameControllerButton>(std::stoi(value)); options.controllers.at(1).buttons.at(2) = static_cast<SDL_GamepadButton>(std::stoi(value));
} }
else if (var == "controller.1.button.start") else if (var == "controller.1.button.start")
{ {
options.controllers.at(1).buttons.at(3) = static_cast<SDL_GameControllerButton>(std::stoi(value)); options.controllers.at(1).buttons.at(3) = static_cast<SDL_GamepadButton>(std::stoi(value));
} }
else if (var == "controller.1.button.service") else if (var == "controller.1.button.service")
{ {
options.controllers.at(1).buttons.at(4) = static_cast<SDL_GameControllerButton>(std::stoi(value)); options.controllers.at(1).buttons.at(4) = static_cast<SDL_GamepadButton>(std::stoi(value));
} }
// Lineas vacias o que empiezan por comentario // Lineas vacias o que empiezan por comentario

View File

@@ -7,7 +7,6 @@
#include "input.h" // Para InputAction, InputDeviceToUse #include "input.h" // Para InputAction, InputDeviceToUse
#include "manage_hiscore_table.h" // Para HiScoreEntry #include "manage_hiscore_table.h" // Para HiScoreEntry
enum class ScreenFilter : int; // lines 8-8 enum class ScreenFilter : int; // lines 8-8
enum class ScreenVideoMode : Uint32; // lines 9-9
namespace lang namespace lang
{ {
enum class Code : int; enum class Code : int;
@@ -22,48 +21,48 @@ enum class GameDifficulty
}; };
// Estructura para las opciones de la ventana // Estructura para las opciones de la ventana
struct OptionsWindow struct WindowOptions
{ {
int zoom = 1; // Contiene el valor por el que se multiplica el tamaño de la ventana int zoom = 1; // Contiene el valor por el que se multiplica el tamaño de la ventana
int max_zoom = 1; // Tamaño máximo para que el tamaño de la ventana no sea mayor que el tamaño de la pantalla int max_zoom = 1; // Tamaño máximo para que el tamaño de la ventana no sea mayor que el tamaño de la pantalla
}; };
// Estructura con opciones para el video // Estructura con opciones para el video
struct OptionsVideo struct VideoOptions
{ {
OptionsWindow window; // Opciones para la ventana del programa WindowOptions window; // Opciones para la ventana del programa
ScreenVideoMode mode; // Contiene el valor del modo de pantalla completa
ScreenFilter filter; // Filtro usado para el escalado de la imagen ScreenFilter filter; // Filtro usado para el escalado de la imagen
bool fullscreen; // Contiene el valor del modo de pantalla completa
bool v_sync; // Indica si se quiere usar vsync o no bool v_sync; // Indica si se quiere usar vsync o no
bool integer_scale; // Indica si se va a usar el escalado entero bool integer_scale; // Indica si se va a usar el escalado entero
bool shaders; // Indica si se van a usar shaders para los filtros de video bool shaders; // Indica si se van a usar shaders para los filtros de video
}; };
// Estructura para las opciones de musica // Estructura para las opciones de musica
struct OptionsMusic struct MusicOptions
{ {
bool enabled; // Indica si la musica suena o no bool enabled; // Indica si la musica suena o no
int volume; // Volumen al que suena la música int volume; // Volumen al que suena la música
}; };
// Estructura para las opciones de sonido // Estructura para las opciones de sonido
struct OptionsSound struct SoundOptions
{ {
bool enabled; // Indica si los sonidos suenan o no bool enabled; // Indica si los sonidos suenan o no
int volume; // Volumen al que suenan los sonidos int volume; // Volumen al que suenan los sonidos
}; };
// Estructura para las opciones de audio // Estructura para las opciones de audio
struct OptionsAudio struct AudioOptions
{ {
OptionsMusic music; // Opciones para la música MusicOptions music; // Opciones para la música
OptionsSound sound; // Opciones para los efectos de sonido SoundOptions sound; // Opciones para los efectos de sonido
bool enabled; // Indica si el audio está activo o no bool enabled; // Indica si el audio está activo o no
int volume; // Volumen al que suenan el audio int volume; // Volumen al que suenan el audio
}; };
// Estructura para las opciones del juego // Estructura para las opciones del juego
struct OptionsGame struct GameOptions
{ {
GameDifficulty difficulty; // Dificultad del juego GameDifficulty difficulty; // Dificultad del juego
lang::Code language; // Idioma usado en el juego lang::Code language; // Idioma usado en el juego
@@ -80,7 +79,7 @@ struct OptionsGame
}; };
// Estructura para los controles del juego // Estructura para los controles del juego
struct OptionsController struct GamepadOptions
{ {
int index; // Indice en el vector de mandos int index; // Indice en el vector de mandos
int player_id; // Jugador asociado al mando int player_id; // Jugador asociado al mando
@@ -88,27 +87,28 @@ struct OptionsController
std::string name; // Nombre del dispositivo std::string name; // Nombre del dispositivo
bool plugged; // Indica si el mando se encuentra conectado bool plugged; // Indica si el mando se encuentra conectado
std::vector<InputAction> inputs; // Listado de inputs std::vector<InputAction> inputs; // Listado de inputs
std::vector<SDL_GameControllerButton> buttons; // Listado de botones asignados a cada input std::vector<SDL_GamepadButton> buttons; // Listado de botones asignados a cada input
// Constructor por defecto // Constructor por defecto
OptionsController() GamepadOptions()
: index(-1), player_id(-1), type(InputDeviceToUse::CONTROLLER), name(""), plugged(false), : index(-1), player_id(-1), type(InputDeviceToUse::CONTROLLER), name(""), plugged(false),
inputs{InputAction::FIRE_LEFT, InputAction::FIRE_CENTER, InputAction::FIRE_RIGHT, InputAction::START, InputAction::SERVICE}, inputs{InputAction::FIRE_LEFT, InputAction::FIRE_CENTER, InputAction::FIRE_RIGHT, InputAction::START, InputAction::SERVICE},
buttons{SDL_CONTROLLER_BUTTON_X, SDL_CONTROLLER_BUTTON_Y, SDL_CONTROLLER_BUTTON_B, SDL_CONTROLLER_BUTTON_START, SDL_CONTROLLER_BUTTON_BACK} {} buttons{SDL_GAMEPAD_BUTTON_WEST, SDL_GAMEPAD_BUTTON_NORTH, SDL_GAMEPAD_BUTTON_EAST, SDL_GAMEPAD_BUTTON_START, SDL_GAMEPAD_BUTTON_BACK} {}
}; };
// Estructura con todas las opciones de configuración del programa // Estructura con todas las opciones de configuración del programa
struct Options struct Options
{ {
OptionsGame game; // Opciones para el propio juego GameOptions game; // Opciones para el propio juego
OptionsVideo video; // Opciones relativas a la clase screen VideoOptions video; // Opciones relativas a la clase screen
OptionsAudio audio; // Opciones para el audio AudioOptions audio; // Opciones para el audio
std::vector<OptionsController> controllers; // Opciones con las asignaciones del mando para cada jugador std::vector<GamepadOptions> controllers; // Opciones con las asignaciones del mando para cada jugador
}; };
// Variables // Variables
extern Options options; extern Options options;
// Inicializa las opciones del programa
void initOptions(); void initOptions();
// Carga el fichero de configuración // Carga el fichero de configuración

View File

@@ -360,7 +360,7 @@ void precalculateZones()
param.game.play_area.third_quarter_y = param.game.play_area.rect.h / 4 * 3; param.game.play_area.third_quarter_y = param.game.play_area.rect.h / 4 * 3;
// gameArea // gameArea
param.game.game_area.rect = {0, 0, param.game.width, param.game.height}; param.game.game_area.rect = {0, 0, static_cast<float>(param.game.width), static_cast<float>(param.game.height)};
param.game.game_area.center_x = param.game.game_area.rect.w / 2; param.game.game_area.center_x = param.game.game_area.rect.w / 2;
param.game.game_area.first_quarter_x = param.game.game_area.rect.w / 4; param.game.game_area.first_quarter_x = param.game.game_area.rect.w / 4;
param.game.game_area.third_quarter_x = param.game.game_area.rect.w / 4 * 3; param.game.game_area.third_quarter_x = param.game.game_area.rect.w / 4 * 3;

View File

@@ -1,4 +1,5 @@
#pragma once #pragma once
#include <SDL3/SDL.h>
#include <SDL3/SDL_rect.h> // Para SDL_FRect #include <SDL3/SDL_rect.h> // Para SDL_FRect
#include <SDL3/SDL_stdinc.h> // Para Uint32 #include <SDL3/SDL_stdinc.h> // Para Uint32
@@ -9,11 +10,11 @@
// param.game // param.game
struct ParamGame struct ParamGame
{ {
int width; // Ancho de la resolucion nativa del juego float width; // Ancho de la resolucion nativa del juego
int height; // Alto de la resolucion nativa del juego float height; // Alto de la resolucion nativa del juego
int item_size; // Tamaño de los items del juego float item_size; // Tamaño de los items del juego
int coffee_machine_w; // Ancho de la máquina de café float coffee_machine_w; // Ancho de la máquina de café
int coffee_machine_h; // Alto de la máquina de café float coffee_machine_h; // Alto de la máquina de café
Zone play_area; // Rectangulo con la posición de la zona de juego Zone play_area; // Rectangulo con la posición de la zona de juego
Zone game_area; // Rectangulo con las dimensiones del juego Zone game_area; // Rectangulo con las dimensiones del juego
int enter_name_seconds; // Duración en segundos para introducir el nombre al finalizar la partida int enter_name_seconds; // Duración en segundos para introducir el nombre al finalizar la partida
@@ -23,12 +24,12 @@ struct ParamGame
// param.fade // param.fade
struct ParamFade struct ParamFade
{ {
int num_squares_width; // Cantidad total de cuadraditos en horizontal para el FadeType::RANDOM_SQUARE float num_squares_width; // Cantidad total de cuadraditos en horizontal para el FadeType::RANDOM_SQUARE
int num_squares_height; // Cantidad total de cuadraditos en vertical para el FadeType::RANDOM_SQUARE float num_squares_height; // Cantidad total de cuadraditos en vertical para el FadeType::RANDOM_SQUARE
int random_squares_delay; // Duración entre cada pintado de cuadrados int random_squares_delay; // Duración entre cada pintado de cuadrados
int random_squares_mult; // Cantidad de cuadrados que se pintaran cada vez int random_squares_mult; // Cantidad de cuadrados que se pintaran cada vez
int post_duration; // Duración final del fade int post_duration; // Duración final del fade
int venetian_size; // Altura de los rectangulos para FadeType::VENETIAN float venetian_size; // Altura de los rectangulos para FadeType::VENETIAN
}; };
// param.title // param.title

View File

@@ -5,9 +5,9 @@
#include <utility> // Para move #include <utility> // Para move
// Devuelve un vector con los puntos que conforman la ruta // Devuelve un vector con los puntos que conforman la ruta
std::vector<SDL_Point> createPath(int start, int end, PathType type, int fixed_pos, int steps, const std::function<double(double)> &easingFunction) std::vector<SDL_FPoint> createPath(float start, float end, PathType type, float fixed_pos, int steps, const std::function<double(double)> &easingFunction)
{ {
std::vector<SDL_Point> v; std::vector<SDL_FPoint> v;
v.reserve(steps); v.reserve(steps);
for (int i = 0; i < steps; ++i) for (int i = 0; i < steps; ++i)
@@ -23,10 +23,10 @@ std::vector<SDL_Point> createPath(int start, int end, PathType type, int fixed_p
switch (type) switch (type)
{ {
case PathType::HORIZONTAL: case PathType::HORIZONTAL:
v.emplace_back(SDL_Point{static_cast<int>(value), fixed_pos}); v.emplace_back(SDL_FPoint{static_cast<float>(value), fixed_pos});
break; break;
case PathType::VERTICAL: case PathType::VERTICAL:
v.emplace_back(SDL_Point{fixed_pos, static_cast<int>(value)}); v.emplace_back(SDL_FPoint{fixed_pos, static_cast<float>(value)});
break; break;
default: default:
break; break;
@@ -93,7 +93,7 @@ void PathSprite::addPath(int start, int end, PathType type, int fixed_pos, int s
} }
// Añade un recorrido // Añade un recorrido
void PathSprite::addPath(std::vector<SDL_Point> spots, int waiting_counter) void PathSprite::addPath(std::vector<SDL_FPoint> spots, int waiting_counter)
{ {
paths_.emplace_back(std::move(spots), waiting_counter); paths_.emplace_back(std::move(spots), waiting_counter);
} }

View File

@@ -1,6 +1,7 @@
#pragma once #pragma once
#include <SDL3/SDL.h>
#include <SDL3/SDL_rect.h> // Para SDL_Point #include <SDL3/SDL_rect.h> // Para SDL_FPoint
#include <functional> // Para function #include <functional> // Para function
#include <memory> // Para shared_ptr #include <memory> // Para shared_ptr
#include <vector> // Para vector #include <vector> // Para vector
@@ -23,19 +24,19 @@ enum class PathCentered
// Estructuras // Estructuras
struct Path struct Path
{ {
std::vector<SDL_Point> spots; // Puntos por los que se desplazará el sprite std::vector<SDL_FPoint> spots; // Puntos por los que se desplazará el sprite
int waiting_counter; // Tiempo de espera una vez en el destino int waiting_counter; // Tiempo de espera una vez en el destino
bool on_destination = false; // Indica si ha llegado al destino bool on_destination = false; // Indica si ha llegado al destino
bool finished = false; // Indica si ha terminado de esperarse bool finished = false; // Indica si ha terminado de esperarse
int counter = 0; // Contador interno int counter = 0; // Contador interno
// Constructor // Constructor
Path(const std::vector<SDL_Point> &spots_init, int waiting_counter_init) Path(const std::vector<SDL_FPoint> &spots_init, int waiting_counter_init)
: spots(spots_init), waiting_counter(waiting_counter_init) {} : spots(spots_init), waiting_counter(waiting_counter_init) {}
}; };
// Devuelve un vector con los puntos que conforman la ruta // Devuelve un vector con los puntos que conforman la ruta
std::vector<SDL_Point> createPath(int start, int end, PathType type, int fixed_pos, int steps, const std::function<double(double)> &easingFunction); std::vector<SDL_FPoint> createPath(float start, float end, PathType type, float fixed_pos, int steps, const std::function<double(double)> &easingFunction);
// Clase PathSprite // Clase PathSprite
class PathSprite : public Sprite class PathSprite : public Sprite
@@ -69,7 +70,7 @@ public:
// Añade un recorrido // Añade un recorrido
void addPath(Path path, bool centered = false); void addPath(Path path, bool centered = false);
void addPath(std::vector<SDL_Point> spots, int waiting_counter = 0); void addPath(std::vector<SDL_FPoint> spots, int waiting_counter = 0);
void addPath(int start, int end, PathType type, int fixed_pos, int steps, const std::function<double(double)> &easingFunction, int waiting_counter = 0); void addPath(int start, int end, PathType type, int fixed_pos, int steps, const std::function<double(double)> &easingFunction, int waiting_counter = 0);
// Habilita el objeto // Habilita el objeto

View File

@@ -350,34 +350,34 @@ void Player::setAnimation()
case PlayerState::CREDITS: case PlayerState::CREDITS:
{ {
// Crea cadenas de texto para componer el nombre de la animación // Crea cadenas de texto para componer el nombre de la animación
const std::string a_walking = walking_state_ == PlayerState::WALKING_STOP ? "stand" : "walk"; const std::string WALKING_ANIMATION = walking_state_ == PlayerState::WALKING_STOP ? "stand" : "walk";
const std::string a_firing = firing_state_ == PlayerState::FIRING_UP ? "centershoot" : "sideshoot"; const std::string FIRING_ANIMATION = firing_state_ == PlayerState::FIRING_UP ? "centershoot" : "sideshoot";
const std::string a_cooling = firing_state_ == PlayerState::COOLING_UP ? "centershoot" : "sideshoot"; const std::string COOLING_ANIMATION = firing_state_ == PlayerState::COOLING_UP ? "centershoot" : "sideshoot";
const SDL_RendererFlip flip_walk = walking_state_ == PlayerState::WALKING_RIGHT ? SDL_FLIP_HORIZONTAL : SDL_FLIP_NONE; const SDL_FlipMode FLIP_WALK = walking_state_ == PlayerState::WALKING_RIGHT ? SDL_FLIP_HORIZONTAL : SDL_FLIP_NONE;
const SDL_RendererFlip flip_fire = firing_state_ == PlayerState::FIRING_RIGHT ? SDL_FLIP_HORIZONTAL : SDL_FLIP_NONE; const SDL_FlipMode FLIP_FIRE = firing_state_ == PlayerState::FIRING_RIGHT ? SDL_FLIP_HORIZONTAL : SDL_FLIP_NONE;
const SDL_RendererFlip flip_cooling = firing_state_ == PlayerState::COOLING_RIGHT ? SDL_FLIP_HORIZONTAL : SDL_FLIP_NONE; const SDL_FlipMode FLIP_COOLING = firing_state_ == PlayerState::COOLING_RIGHT ? SDL_FLIP_HORIZONTAL : SDL_FLIP_NONE;
// Establece la animación a partir de las cadenas // Establece la animación a partir de las cadenas
if (firing_state_ == PlayerState::FIRING_NONE) if (firing_state_ == PlayerState::FIRING_NONE)
{ {
// No esta disparando // No esta disparando
player_sprite_->setCurrentAnimation(a_walking); player_sprite_->setCurrentAnimation(WALKING_ANIMATION);
player_sprite_->setFlip(flip_walk); player_sprite_->setFlip(FLIP_WALK);
} }
else if (isCooling()) else if (isCooling())
{ {
// Acaba de disparar // Acaba de disparar
player_sprite_->setCurrentAnimation(a_walking + "-" + a_cooling + "-cooldown"); player_sprite_->setCurrentAnimation(WALKING_ANIMATION + "-" + COOLING_ANIMATION + "-cooldown");
player_sprite_->setFlip(flip_cooling); player_sprite_->setFlip(FLIP_COOLING);
} }
else else
{ {
// Está disparando // Está disparando
player_sprite_->setCurrentAnimation(a_walking + "-" + a_firing); player_sprite_->setCurrentAnimation(WALKING_ANIMATION + "-" + FIRING_ANIMATION);
// Si dispara de lado, invierte el sprite segun hacia donde dispara // Si dispara de lado, invierte el sprite segun hacia donde dispara
// Si dispara recto, invierte el sprite segun hacia donde camina // Si dispara recto, invierte el sprite segun hacia donde camina
player_sprite_->setFlip(a_firing == "centershoot" ? flip_walk : flip_fire); player_sprite_->setFlip(FIRING_ANIMATION == "centershoot" ? FLIP_WALK : FLIP_FIRE);
} }
break; break;
} }

View File

@@ -1,4 +1,5 @@
#pragma once #pragma once
#include <SDL3/SDL.h>
#include <SDL3/SDL_rect.h> // Para SDL_FRect #include <SDL3/SDL_rect.h> // Para SDL_FRect
#include <SDL3/SDL_stdinc.h> // Para Uint32 #include <SDL3/SDL_stdinc.h> // Para Uint32

View File

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

View File

@@ -57,7 +57,11 @@ Scoreboard::Scoreboard()
// Recalcula las anclas de los elementos // Recalcula las anclas de los elementos
recalculateAnchors(); recalculateAnchors();
power_meter_sprite_->setPosition({slot4_2_.x - 20, slot4_2_.y, 40, 7}); power_meter_sprite_->setPosition(SDL_FRect{
static_cast<float>(slot4_2_.x - 20),
static_cast<float>(slot4_2_.y),
40,
7});
// Crea la textura de fondo // Crea la textura de fondo
background_ = nullptr; background_ = nullptr;
@@ -259,7 +263,7 @@ void Scoreboard::fillPanelTextures()
// ENTER NAME // ENTER NAME
{ {
text_scoreboard_->writeCentered(slot4_3_.x, slot4_3_.y, lang::getText(106)); text_scoreboard_->writeCentered(slot4_3_.x, slot4_3_.y, lang::getText(106));
SDL_FRect rect = {enter_name_pos_.x, enter_name_pos_.y, 5, 7}; SDL_FRect rect = {enter_name_pos_.x, enter_name_pos_.y, 5.0f, 7.0f};
// Recorre todos los slots de letras del nombre // Recorre todos los slots de letras del nombre
for (size_t j = 0; j < MAX_NAME_LENGHT; ++j) for (size_t j = 0; j < MAX_NAME_LENGHT; ++j)
@@ -273,7 +277,7 @@ void Scoreboard::fillPanelTextures()
if (j >= selector_pos_[i]) if (j >= selector_pos_[i])
{ {
SDL_SetRenderDrawColor(renderer_, color.r, color.g, color.b, 255); SDL_SetRenderDrawColor(renderer_, color.r, color.g, color.b, 255);
SDL_RenderDrawLine(renderer_, rect.x, rect.y + rect.h, rect.x + rect.w, rect.y + rect.h); SDL_RenderLine(renderer_, rect.x, rect.y + rect.h, rect.x + rect.w, rect.y + rect.h);
} }
// Dibuja la letra // Dibuja la letra
@@ -364,28 +368,28 @@ void Scoreboard::recalculateAnchors()
} }
// Constantes para definir las zonas del panel_: 4 filas y 1 columna // Constantes para definir las zonas del panel_: 4 filas y 1 columna
const int row_size = rect_.h / 4; const int ROW_SIZE = rect_.h / 4;
const int text_height = 7; const int TEXT_HEIGHT = 7;
// Filas // Filas
const int row1 = (row_size * 0) + (text_height / 2); const float ROW1 = (ROW_SIZE * 0) + (TEXT_HEIGHT / 2);
const int row2 = (row_size * 1) + (text_height / 2) - 1; const float ROW2 = (ROW_SIZE * 1) + (TEXT_HEIGHT / 2) - 1;
const int row3 = (row_size * 2) + (text_height / 2) - 2; const float ROW3 = (ROW_SIZE * 2) + (TEXT_HEIGHT / 2) - 2;
const int row4 = (row_size * 3) + (text_height / 2) - 3; const float ROW4 = (ROW_SIZE * 3) + (TEXT_HEIGHT / 2) - 3;
// Columna // Columna
const int col = panel_width / 2; const float COL = panel_width / 2;
// Slots de 4 // Slots de 4
slot4_1_ = {col, row1}; slot4_1_ = {COL, ROW1};
slot4_2_ = {col, row2}; slot4_2_ = {COL, ROW2};
slot4_3_ = {col, row3}; slot4_3_ = {COL, ROW3};
slot4_4_ = {col, row4}; slot4_4_ = {COL, ROW4};
// Primer cuadrado para poner el nombre de record // Primer cuadrado para poner el nombre de record
const int enter_name_lenght = text_scoreboard_->lenght(std::string(MAX_NAME_LENGHT, 'A')); const int enter_name_lenght = text_scoreboard_->lenght(std::string(MAX_NAME_LENGHT, 'A'));
enter_name_pos_.x = col - (enter_name_lenght / 2); enter_name_pos_.x = COL - (enter_name_lenght / 2);
enter_name_pos_.y = row4; enter_name_pos_.y = ROW4;
// Recoloca los sprites // Recoloca los sprites
if (power_meter_sprite_) if (power_meter_sprite_)
@@ -436,7 +440,7 @@ void Scoreboard::renderSeparator()
{ {
// Dibuja la linea que separa el marcador de la zona de juego // Dibuja la linea que separa el marcador de la zona de juego
SDL_SetRenderDrawColor(renderer_, separator_color.r, separator_color.g, separator_color.b, 255); SDL_SetRenderDrawColor(renderer_, separator_color.r, separator_color.g, separator_color.b, 255);
SDL_RenderDrawLine(renderer_, 0, 0, rect_.w, 0); SDL_RenderLine(renderer_, 0, 0, rect_.w, 0);
} }
// Inicializa el vector de colores para el nombre // Inicializa el vector de colores para el nombre

View File

@@ -1,6 +1,7 @@
#pragma once #pragma once
#include <SDL3/SDL.h>
#include <SDL3/SDL_rect.h> // Para SDL_Point, SDL_FRect #include <SDL3/SDL_rect.h> // Para SDL_FPoint, SDL_FRect
#include <SDL3/SDL_render.h> // Para SDL_Texture, SDL_Renderer #include <SDL3/SDL_render.h> // Para SDL_Texture, SDL_Renderer
#include <SDL3/SDL_stdinc.h> // Para Uint32 #include <SDL3/SDL_stdinc.h> // Para Uint32
#include <SDL3/SDL_timer.h> // Para SDL_GetTicks #include <SDL3/SDL_timer.h> // Para SDL_GetTicks
@@ -72,14 +73,14 @@ private:
std::string hi_score_name_ = std::string(); // Nombre del jugador con la máxima puntuación std::string hi_score_name_ = std::string(); // Nombre del jugador con la máxima puntuación
Color color_ = Color(); // Color del marcador Color color_ = Color(); // Color del marcador
SDL_FRect rect_ = {0, 0, 320, 40}; // Posición y dimensiones del marcador SDL_FRect rect_ = {0, 0, 320, 40}; // Posición y dimensiones del marcador
Uint32 ticks_ = SDL_GetTicks(); // Variable donde almacenar el valor de SDL_GetTiks() Uint64 ticks_ = SDL_GetTicks(); // Variable donde almacenar el valor de SDL_GetTiks()
int time_counter_ = 0; // Contador de segundos int time_counter_ = 0; // Contador de segundos
int loop_counter_ = 0; // Contador de bucle int loop_counter_ = 0; // Contador de bucle
std::vector<Color> name_colors_; // Colores para destacar el nombre una vez introducido std::vector<Color> name_colors_; // Colores para destacar el nombre una vez introducido
// Puntos predefinidos para colocar elementos en los paneles // Puntos predefinidos para colocar elementos en los paneles
SDL_Point slot4_1_, slot4_2_, slot4_3_, slot4_4_; SDL_FPoint slot4_1_, slot4_2_, slot4_3_, slot4_4_;
SDL_Point enter_name_pos_; SDL_FPoint enter_name_pos_;
// Recalcula las anclas de los elementos // Recalcula las anclas de los elementos
void recalculateAnchors(); void recalculateAnchors();

View File

@@ -6,7 +6,6 @@
#include <iterator> // Para istreambuf_iterator, operator== #include <iterator> // Para istreambuf_iterator, operator==
#include <string> // Para allocator, char_traits, operator+, to_s... #include <string> // Para allocator, char_traits, operator+, to_s...
#include "asset.h" // Para Asset #include "asset.h" // Para Asset
#include "dbgtxt.h" // Para dbg_print
#include "global_inputs.h" // Para service_pressed_counter #include "global_inputs.h" // Para service_pressed_counter
#include "jail_shader.h" // Para init, render #include "jail_shader.h" // Para init, render
#include "mouse.h" // Para updateCursorVisibility #include "mouse.h" // Para updateCursorVisibility
@@ -90,26 +89,22 @@ void Screen::renderScreen()
} }
// Establece el modo de video // Establece el modo de video
void Screen::setVideoMode(ScreenVideoMode mode) void Screen::setFullscreenMode(bool mode)
{ {
// Actualiza las opciones // Actualiza las opciones
options.video.mode = mode; options.video.fullscreen = mode;
// Configura el modo de pantalla // Configura el modo de pantalla
Uint32 flags = SDL_GetWindowFlags(window_); SDL_SetWindowFullscreen(window_, options.video.fullscreen);
if (flags != static_cast<Uint32>(options.video.mode))
{
SDL_SetWindowFullscreen(window_, static_cast<bool>(options.video.mode));
}
initShaders(); initShaders();
} }
// Camibia entre pantalla completa y ventana // Camibia entre pantalla completa y ventana
void Screen::toggleVideoMode() void Screen::toggleFullscreen()
{ {
options.video.mode = options.video.mode == ScreenVideoMode::WINDOW ? ScreenVideoMode::FULLSCREEN : ScreenVideoMode::WINDOW; options.video.fullscreen = !options.video.fullscreen;
setVideoMode(); setFullscreenMode();
} }
// Cambia el tamaño de la ventana // Cambia el tamaño de la ventana
@@ -122,7 +117,7 @@ void Screen::setWindowZoom(int zoom)
// Reduce el tamaño de la ventana // Reduce el tamaño de la ventana
bool Screen::decWindowZoom() bool Screen::decWindowZoom()
{ {
if (options.video.mode == ScreenVideoMode::WINDOW) if (!options.video.fullscreen)
{ {
const int PREVIOUS_ZOOM = options.video.window.zoom; const int PREVIOUS_ZOOM = options.video.window.zoom;
--options.video.window.zoom; --options.video.window.zoom;
@@ -141,7 +136,7 @@ bool Screen::decWindowZoom()
// Aumenta el tamaño de la ventana // Aumenta el tamaño de la ventana
bool Screen::incWindowZoom() bool Screen::incWindowZoom()
{ {
if (options.video.mode == ScreenVideoMode::WINDOW) if (!options.video.fullscreen)
{ {
const int PREVIOUS_ZOOM = options.video.window.zoom; const int PREVIOUS_ZOOM = options.video.window.zoom;
++options.video.window.zoom; ++options.video.window.zoom;
@@ -245,7 +240,7 @@ void Screen::adjustWindowSize()
options.video.window.max_zoom = getMaxZoom(); options.video.window.max_zoom = getMaxZoom();
// Establece el nuevo tamaño // Establece el nuevo tamaño
if (options.video.mode == ScreenVideoMode::WINDOW) if (!options.video.fullscreen)
{ {
const int WIDTH = param.game.width * options.video.window.zoom; const int WIDTH = param.game.width * options.video.window.zoom;
const int HEIGHT = param.game.height * options.video.window.zoom; const int HEIGHT = param.game.height * options.video.window.zoom;
@@ -259,7 +254,7 @@ void Screen::adjustWindowSize()
const int NEW_POS_X = old_pos_x + (old_width - WIDTH) / 2; const int NEW_POS_X = old_pos_x + (old_width - WIDTH) / 2;
const int NEW_POS_Y = old_pos_y + (old_height - HEIGHT) / 2; const int NEW_POS_Y = old_pos_y + (old_height - HEIGHT) / 2;
SDL_FRect viewport = {0, 0, WIDTH, HEIGHT}; SDL_Rect viewport = {0, 0, WIDTH, HEIGHT};
SDL_SetRenderViewport(renderer_, &viewport); SDL_SetRenderViewport(renderer_, &viewport);
SDL_SetWindowPosition(window_, std::max(NEW_POS_X, WINDOWS_DECORATIONS_), std::max(NEW_POS_Y, 0)); SDL_SetWindowPosition(window_, std::max(NEW_POS_X, WINDOWS_DECORATIONS_), std::max(NEW_POS_Y, 0));

View File

@@ -1,7 +1,8 @@
#pragma once #pragma once
#include <SDL3/SDL.h>
#include <SDL3/SDL_blendmode.h> // Para SDL_BlendMode #include <SDL3/SDL_blendmode.h> // Para SDL_BlendMode
#include <SDL3/SDL_rect.h> // Para SDL_FRect, SDL_Point #include <SDL3/SDL_rect.h> // Para SDL_FRect, SDL_FPoint
#include <SDL3/SDL_render.h> // Para SDL_Renderer, SDL_Texture #include <SDL3/SDL_render.h> // Para SDL_Renderer, SDL_Texture
#include <SDL3/SDL_stdinc.h> // Para Uint32 #include <SDL3/SDL_stdinc.h> // Para Uint32
#include <SDL3/SDL_video.h> // Para SDL_Window #include <SDL3/SDL_video.h> // Para SDL_Window
@@ -16,12 +17,6 @@ enum class ScreenFilter : int
LINEAL = 1, LINEAL = 1,
}; };
enum class ScreenVideoMode : bool
{
WINDOW = false,
FULLSCREEN = true,
};
class Screen class Screen
{ {
private: private:
@@ -239,10 +234,10 @@ public:
void render(); void render();
// Establece el modo de video // Establece el modo de video
void setVideoMode(ScreenVideoMode mode = options.video.mode); void setFullscreenMode(bool mode = options.video.fullscreen);
// Cambia entre pantalla completa y ventana // Cambia entre pantalla completa y ventana
void toggleVideoMode(); void toggleFullscreen();
// Cambia el tamaño de la ventana // Cambia el tamaño de la ventana
void setWindowZoom(int size); void setWindowZoom(int size);

View File

@@ -1,4 +1,5 @@
#pragma once #pragma once
#include <SDL3/SDL.h>
namespace section namespace section
{ {

View File

@@ -1,4 +1,5 @@
#pragma once #pragma once
#include <SDL3/SDL.h>
#include <memory> // Para shared_ptr #include <memory> // Para shared_ptr
#include "animated_sprite.h" // Para SpriteAnimated #include "animated_sprite.h" // Para SpriteAnimated

View File

@@ -2,7 +2,7 @@
#include "texture.h" // Para Texture #include "texture.h" // Para Texture
// Constructor // Constructor
Sprite::Sprite(std::shared_ptr<Texture> texture, int x, int y, int w, int h) Sprite::Sprite(std::shared_ptr<Texture> texture, float x, float y, float w, float h)
: texture_(texture), : texture_(texture),
pos_((SDL_FRect){x, y, w, h}), pos_((SDL_FRect){x, y, w, h}),
sprite_clip_((SDL_FRect){0, 0, pos_.w, pos_.h}) {} sprite_clip_((SDL_FRect){0, 0, pos_.w, pos_.h}) {}
@@ -14,7 +14,7 @@ Sprite::Sprite(std::shared_ptr<Texture> texture, SDL_FRect rect)
Sprite::Sprite(std::shared_ptr<Texture> texture) Sprite::Sprite(std::shared_ptr<Texture> texture)
: texture_(texture), : texture_(texture),
pos_({0, 0, texture_->getWidth(), texture_->getHeight()}), pos_(SDL_FRect{0, 0, static_cast<float>(texture_->getWidth()), static_cast<float>(texture_->getHeight())}),
sprite_clip_(pos_) {} sprite_clip_(pos_) {}
// Muestra el sprite por pantalla // Muestra el sprite por pantalla
@@ -24,14 +24,14 @@ void Sprite::render()
} }
// Establece la posición del objeto // Establece la posición del objeto
void Sprite::setPosition(int x, int y) void Sprite::setPosition(float x, float y)
{ {
pos_.x = x; pos_.x = x;
pos_.y = y; pos_.y = y;
} }
// Establece la posición del objeto // Establece la posición del objeto
void Sprite::setPosition(SDL_Point p) void Sprite::setPosition(SDL_FPoint p)
{ {
pos_.x = p.x; pos_.x = p.x;
pos_.y = p.y; pos_.y = p.y;

View File

@@ -1,6 +1,7 @@
#pragma once #pragma once
#include <SDL3/SDL.h>
#include <SDL3/SDL_rect.h> // Para SDL_FRect, SDL_Point #include <SDL3/SDL_rect.h> // Para SDL_FRect, SDL_FPoint
#include <memory> // Para shared_ptr #include <memory> // Para shared_ptr
class Texture; class Texture;
@@ -16,7 +17,7 @@ protected:
public: public:
// Constructor // Constructor
Sprite(std::shared_ptr<Texture>, int x, int y, int w, int h); Sprite(std::shared_ptr<Texture>, float x, float y, float w, float h);
Sprite(std::shared_ptr<Texture>, SDL_FRect rect); Sprite(std::shared_ptr<Texture>, SDL_FRect rect);
explicit Sprite(std::shared_ptr<Texture>); explicit Sprite(std::shared_ptr<Texture>);
@@ -30,39 +31,39 @@ public:
virtual void clear(); virtual void clear();
// Obtiene la posición y el tamaño // Obtiene la posición y el tamaño
int getX() const { return pos_.x; } float getX() const { return pos_.x; }
int getY() const { return pos_.y; } float getY() const { return pos_.y; }
int getWidth() const { return pos_.w; } float getWidth() const { return pos_.w; }
int getHeight() const { return pos_.h; } float getHeight() const { return pos_.h; }
// Devuelve el rectangulo donde está el sprite // Devuelve el rectangulo donde está el sprite
SDL_FRect getPosition() const { return pos_; } SDL_FRect getPosition() const { return pos_; }
SDL_FRect &getRect() { return pos_; } SDL_FRect &getRect() { return pos_; }
// Establece la posición y el tamaño // Establece la posición y el tamaño
void setX(int x) { pos_.x = x; } void setX(float x) { pos_.x = x; }
void setY(int y) { pos_.y = y; } void setY(float y) { pos_.y = y; }
void setWidth(int w) { pos_.w = w; } void setWidth(float w) { pos_.w = w; }
void setHeight(int h) { pos_.h = h; } void setHeight(float h) { pos_.h = h; }
// Establece la posición del objeto // Establece la posición del objeto
void setPosition(int x, int y); void setPosition(float x, float y);
void setPosition(SDL_Point p); void setPosition(SDL_FPoint p);
void setPosition(SDL_FRect r) { pos_ = r; } void setPosition(SDL_FRect r) { pos_ = r; }
// Establece el nivel de zoom // Establece el nivel de zoom
void setZoom(float zoom) { zoom_ = zoom; } void setZoom(float zoom) { zoom_ = zoom; }
// Aumenta o disminuye la posición // Aumenta o disminuye la posición
void incX(int value) { pos_.x += value; } void incX(float value) { pos_.x += value; }
void incY(int value) { pos_.y += value; } void incY(float value) { pos_.y += value; }
// Obtiene el rectangulo que se dibuja de la textura // Obtiene el rectangulo que se dibuja de la textura
SDL_FRect getSpriteClip() const { return sprite_clip_; } SDL_FRect getSpriteClip() const { return sprite_clip_; }
// Establece el rectangulo que se dibuja de la textura // Establece el rectangulo que se dibuja de la textura
void setSpriteClip(SDL_FRect rect) { sprite_clip_ = rect; } void setSpriteClip(SDL_FRect rect) { sprite_clip_ = rect; }
void setSpriteClip(int x, int y, int w, int h) { sprite_clip_ = (SDL_FRect){x, y, w, h}; } void setSpriteClip(float x, float y, float w, float h) { sprite_clip_ = (SDL_FRect){x, y, w, h}; }
// Obtiene un puntero a la textura // Obtiene un puntero a la textura
std::shared_ptr<Texture> getTexture() const { return texture_; } std::shared_ptr<Texture> getTexture() const { return texture_; }

View File

@@ -1,4 +1,5 @@
#pragma once #pragma once
#include <SDL3/SDL.h>
#include <vector> #include <vector>

View File

@@ -1,4 +1,5 @@
#pragma once #pragma once
#include <SDL3/SDL.h>
#include <SDL3/SDL_rect.h> // Para SDL_FRect #include <SDL3/SDL_rect.h> // Para SDL_FRect
#include <SDL3/SDL_stdinc.h> // Para Uint32 #include <SDL3/SDL_stdinc.h> // Para Uint32

View File

@@ -96,7 +96,7 @@ Text::Text(std::shared_ptr<Texture> texture, const std::string &text_file)
} }
// Crea los objetos // Crea los objetos
sprite_ = std::make_unique<Sprite>(texture, (SDL_FRect){0, 0, box_width_, box_height_}); sprite_ = std::make_unique<Sprite>(texture, (SDL_FRect){0, 0, static_cast<float>(box_width_), static_cast<float>(box_height_)});
// Inicializa variables // Inicializa variables
fixed_width_ = false; fixed_width_ = false;
@@ -116,7 +116,7 @@ Text::Text(std::shared_ptr<Texture> texture, std::shared_ptr<TextFile> text_file
} }
// Crea los objetos // Crea los objetos
sprite_ = std::make_unique<Sprite>(texture, (SDL_FRect){0, 0, box_width_, box_height_}); sprite_ = std::make_unique<Sprite>(texture, (SDL_FRect){0, 0, static_cast<float>(box_width_), static_cast<float>(box_height_)});
// Inicializa variables // Inicializa variables
fixed_width_ = false; fixed_width_ = false;
@@ -148,7 +148,7 @@ void Text::write2X(int x, int y, const std::string &text, int kerning)
for (size_t i = 0; i < text.length(); ++i) for (size_t i = 0; i < text.length(); ++i)
{ {
auto index = static_cast<size_t>(text[i]); auto index = static_cast<size_t>(text[i]);
SDL_FRect rect = {offset_[index].x, offset_[index].y, box_width_, box_height_}; SDL_FRect rect = {static_cast<float>(offset_[index].x), static_cast<float>(offset_[index].y), static_cast<float>(box_width_), static_cast<float>(box_height_)};
sprite_->getTexture()->render(x + shift, y, &rect, 2.0f, 2.0f); sprite_->getTexture()->render(x + shift, y, &rect, 2.0f, 2.0f);
shift += (offset_[index].w + kerning) * 2; shift += (offset_[index].w + kerning) * 2;
} }

View File

@@ -1,4 +1,5 @@
#pragma once #pragma once
#include <SDL3/SDL.h>
#include <SDL3/SDL_stdinc.h> // Para Uint8 #include <SDL3/SDL_stdinc.h> // Para Uint8
#include <memory> // Para unique_ptr, shared_ptr #include <memory> // Para unique_ptr, shared_ptr

View File

@@ -75,11 +75,10 @@ bool Texture::loadFromFile(const std::string &file_path)
printWithDots("Image : ", getFileName(file_path), "[ LOADED ]"); printWithDots("Image : ", getFileName(file_path), "[ LOADED ]");
} }
int depth, pitch; int pitch;
Uint32 pixel_format; SDL_PixelFormat pixel_format;
// STBI_rgb_alpha (RGBA) // STBI_rgb_alpha (RGBA)
depth = 32;
pitch = 4 * width; pitch = 4 * width;
pixel_format = SDL_PIXELFORMAT_RGBA32; pixel_format = SDL_PIXELFORMAT_RGBA32;
@@ -87,41 +86,42 @@ bool Texture::loadFromFile(const std::string &file_path)
unloadTexture(); unloadTexture();
// La textura final // La textura final
SDL_Texture *newTexture = nullptr; SDL_Texture *new_texture = nullptr;
// Carga la imagen desde una ruta específica // Carga la imagen desde una ruta específica
auto loadedSurface = SDL_CreateRGBSurfaceWithFormatFrom(static_cast<void *>(data), width, height, depth, pitch, pixel_format); /*auto loaded_surface = 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; std::cout << "Unable to load image " << file_path << std::endl;
} }
else else
{ {
// Crea la textura desde los pixels de la surface // Crea la textura desde los pixels de la surface
newTexture = SDL_CreateTextureFromSurface(renderer_, loadedSurface); new_texture = SDL_CreateTextureFromSurface(renderer_, loaded_surface);
if (newTexture == nullptr) if (new_texture == nullptr)
{ {
std::cout << "Unable to create texture from " << file_path << "! SDL Error: " << SDL_GetError() << std::endl; std::cout << "Unable to create texture from " << file_path << "! SDL Error: " << SDL_GetError() << std::endl;
} }
else else
{ {
// Obtiene las dimensiones de la imagen // Obtiene las dimensiones de la imagen
width_ = loadedSurface->w; width_ = loaded_surface->w;
height_ = loadedSurface->h; height_ = loaded_surface->h;
} }
// Elimina la textura cargada // Elimina la textura cargada
SDL_FreeSurface(loadedSurface); SDL_DestroySurface(loaded_surface);
} }
// Return success // Return success
stbi_image_free(data); stbi_image_free(data);
texture_ = newTexture; texture_ = new_texture;
return texture_ != nullptr; return texture_ != nullptr;
} }
// Crea una textura en blanco // Crea una textura en blanco
bool Texture::createBlank(int width, int height, SDL_PixelFormatEnum format, SDL_TextureAccess access) bool Texture::createBlank(int width, int height, SDL_PixelFormat format, SDL_TextureAccess access)
{ {
// Crea una textura sin inicializar // Crea una textura sin inicializar
texture_ = SDL_CreateTexture(renderer_, format, access, width, height); texture_ = SDL_CreateTexture(renderer_, format, access, width, height);
@@ -174,10 +174,10 @@ void Texture::setAlpha(Uint8 alpha)
} }
// Renderiza la textura en un punto específico // Renderiza la textura en un punto específico
void Texture::render(int x, int y, SDL_FRect *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 // Establece el destino de renderizado en la pantalla
SDL_FRect renderQuad = {x, y, width_, height_}; SDL_FRect renderQuad = {static_cast<float>(x), static_cast<float>(y), static_cast<float>(width_), static_cast<float>(height_)};
// Obtiene las dimesiones del clip de renderizado // Obtiene las dimesiones del clip de renderizado
if (clip != nullptr) if (clip != nullptr)
@@ -198,7 +198,7 @@ void Texture::render(int x, int y, SDL_FRect *clip, float zoomW, float zoomH, do
} }
// Renderiza a pantalla // Renderiza a pantalla
SDL_RenderCopyEx(renderer_, texture_, clip, &renderQuad, angle, center, flip); SDL_RenderTextureRotated(renderer_, texture_, clip, &renderQuad, angle, center, flip);
} }
// Establece la textura como objetivo de renderizado // Establece la textura como objetivo de renderizado

View File

@@ -1,8 +1,9 @@
#pragma once #pragma once
#include <SDL3/SDL.h>
#include <SDL3/SDL_blendmode.h> // Para SDL_BlendMode #include <SDL3/SDL_blendmode.h> // Para SDL_BlendMode
#include <SDL3/SDL_pixels.h> // Para SDL_PIXELFORMAT_RGBA8888, SDL_PixelF... #include <SDL3/SDL_pixels.h> // Para SDL_PIXELFORMAT_RGBA8888, SDL_PixelF...
#include <SDL3/SDL_rect.h> // Para SDL_Point, SDL_FRect #include <SDL3/SDL_rect.h> // Para SDL_FPoint, SDL_FRect
#include <SDL3/SDL_render.h> // Para SDL_Renderer, SDL_FLIP_NONE, SDL_TEX... #include <SDL3/SDL_render.h> // Para SDL_Renderer, SDL_FLIP_NONE, SDL_TEX...
#include <SDL3/SDL_stdinc.h> // Para Uint8, Uint16, Uint32 #include <SDL3/SDL_stdinc.h> // Para Uint8, Uint16, Uint32
#include <memory> // Para shared_ptr #include <memory> // Para shared_ptr
@@ -62,7 +63,7 @@ public:
bool loadFromFile(const std::string &path); bool loadFromFile(const std::string &path);
// Crea una textura en blanco // Crea una textura en blanco
bool createBlank(int width, int height, SDL_PixelFormatEnum format = SDL_PIXELFORMAT_RGBA8888, SDL_TextureAccess = SDL_TEXTUREACCESS_STREAMING); bool createBlank(int width, int height, SDL_PixelFormat format = SDL_PIXELFORMAT_RGBA8888, SDL_TextureAccess = SDL_TEXTUREACCESS_STREAMING);
// Establece el color para la modulacion // Establece el color para la modulacion
void setColor(Uint8 red, Uint8 green, Uint8 blue); void setColor(Uint8 red, Uint8 green, Uint8 blue);
@@ -75,7 +76,7 @@ public:
void setAlpha(Uint8 alpha); void setAlpha(Uint8 alpha);
// Renderiza la textura en un punto específico // Renderiza la textura en un punto específico
void render(int x, int y, SDL_FRect *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 // Establece la textura como objetivo de renderizado
void setAsRenderTarget(SDL_Renderer *renderer); void setAsRenderTarget(SDL_Renderer *renderer);

View File

@@ -1,4 +1,5 @@
#pragma once #pragma once
#include <SDL3/SDL.h>
#include <SDL3/SDL_rect.h> // Para SDL_FRect #include <SDL3/SDL_rect.h> // Para SDL_FRect
#include <SDL3/SDL_render.h> // Para SDL_Renderer, SDL_Texture #include <SDL3/SDL_render.h> // Para SDL_Renderer, SDL_Texture

View File

@@ -143,11 +143,11 @@ void Title::checkEvents()
SDL_Event event; SDL_Event event;
while (SDL_PollEvent(&event)) while (SDL_PollEvent(&event))
{ {
if (event.type == SDL_KEYDOWN && event.key.repeat == 0) if (event.type == SDL_EVENT_KEY_DOWN && event.key.repeat == 0)
{ {
bool should_reset = false; bool should_reset = false;
switch (event.key.keysym.sym) switch (event.key.key)
{ {
case SDLK_1: // Redefine los botones del mando #0 case SDLK_1: // Redefine los botones del mando #0
should_reset = define_buttons_->enable(0); should_reset = define_buttons_->enable(0);
@@ -204,7 +204,7 @@ void Title::checkInput()
if ((state_ == TitleState::LOGO_FINISHED || ALLOW_TITLE_ANIMATION_SKIP) && !fade_->isEnabled()) if ((state_ == TitleState::LOGO_FINISHED || ALLOW_TITLE_ANIMATION_SKIP) && !fade_->isEnabled())
{ {
JA_PlaySound(Resource::get()->getSound("game_start.wav")); JA_PlaySound(Resource::get()->getSound("game_start.wav"));
JA_FadeOutMusic(1500); /*JA_FadeOutMusic(1500);*/
switch (controller.player_id) switch (controller.player_id)
{ {
case 1: case 1:

View File

@@ -1,4 +1,5 @@
#pragma once #pragma once
#include <SDL3/SDL.h>
#include <SDL3/SDL_stdinc.h> // Para Uint32 #include <SDL3/SDL_stdinc.h> // Para Uint32
#include <memory> // Para unique_ptr, shared_ptr #include <memory> // Para unique_ptr, shared_ptr
@@ -54,7 +55,7 @@ private:
// Variable // Variable
int counter_ = 0; // Temporizador para la pantalla de titulo int counter_ = 0; // Temporizador para la pantalla de titulo
Uint32 ticks_ = 0; // Contador de ticks para ajustar la velocidad del programa Uint64 ticks_ = 0; // Contador de ticks para ajustar la velocidad del programa
section::Name next_section_; // Indica cual es la siguiente sección a cargar cuando termine el contador del titulo section::Name next_section_; // Indica cual es la siguiente sección a cargar cuando termine el contador del titulo
section::Options selection_ = section::Options::TITLE_TIME_OUT; // Opción elegida en el titulo section::Options selection_ = section::Options::TITLE_TIME_OUT; // Opción elegida en el titulo
int num_controllers_; // Número de mandos conectados int num_controllers_; // Número de mandos conectados

View File

@@ -1,5 +1,6 @@
#define _USE_MATH_DEFINES
#include "utils.h" #include "utils.h"
#include <SDL3/SDL_rwops.h> // Para SDL_RWFromFile, SDL_RWclose, SDL_RWread #include <SDL3/SDL.h> // Para SDL_IOFromFile, SDL_CloseIO, SDL_RIO
#include <stddef.h> // Para size_t #include <stddef.h> // Para size_t
#include <algorithm> // Para min, clamp, find_if_not, find, transform #include <algorithm> // Para min, clamp, find_if_not, find, transform
#include <cctype> // Para tolower, isspace #include <cctype> // Para tolower, isspace
@@ -72,11 +73,11 @@ bool checkCollision(const Circle &a, const Circle &b)
bool checkCollision(const Circle &a, const SDL_FRect &b) bool checkCollision(const Circle &a, const SDL_FRect &b)
{ {
// Encuentra el punto más cercano en el rectángulo // Encuentra el punto más cercano en el rectángulo
int cX = std::clamp(a.x, b.x, b.x + b.w); float cX = std::clamp(static_cast<float>(a.x), b.x, b.x + b.w);
int cY = std::clamp(a.y, b.y, b.y + b.h); float cY = std::clamp(static_cast<float>(a.y), b.y, b.y + b.h);
// Si el punto más cercano está dentro del círculo // Si el punto más cercano está dentro del círculo
return distanceSquared(a.x, a.y, cX, cY) < a.r * a.r; return distanceSquared(static_cast<float>(a.x), static_cast<float>(a.y), cX, cY) < static_cast<float>(a.r) * a.r;
} }
// Detector de colisiones entre dos rectangulos // Detector de colisiones entre dos rectangulos
@@ -98,7 +99,7 @@ bool checkCollision(const SDL_FRect &a, const SDL_FRect &b)
} }
// Detector de colisiones entre un punto y un rectangulo // Detector de colisiones entre un punto y un rectangulo
bool checkCollision(const SDL_Point &p, const SDL_FRect &r) bool checkCollision(const SDL_FPoint &p, const SDL_FRect &r)
{ {
if (p.x < r.x || p.x > r.x + r.w) if (p.x < r.x || p.x > r.x + r.w)
return false; return false;
@@ -149,14 +150,14 @@ void DrawCircle(SDL_Renderer *renderer, int32_t centerX, int32_t centerY, int32_
while (x >= y) while (x >= y)
{ {
// Each of the following renders an octant of the circle // Each of the following renders an octant of the circle
SDL_RenderDrawPoint(renderer, centerX + x, centerY - y); SDL_RenderPoint(renderer, centerX + x, centerY - y);
SDL_RenderDrawPoint(renderer, centerX + x, centerY + y); SDL_RenderPoint(renderer, centerX + x, centerY + y);
SDL_RenderDrawPoint(renderer, centerX - x, centerY - y); SDL_RenderPoint(renderer, centerX - x, centerY - y);
SDL_RenderDrawPoint(renderer, centerX - x, centerY + y); SDL_RenderPoint(renderer, centerX - x, centerY + y);
SDL_RenderDrawPoint(renderer, centerX + y, centerY - x); SDL_RenderPoint(renderer, centerX + y, centerY - x);
SDL_RenderDrawPoint(renderer, centerX + y, centerY + x); SDL_RenderPoint(renderer, centerX + y, centerY + x);
SDL_RenderDrawPoint(renderer, centerX - y, centerY - x); SDL_RenderPoint(renderer, centerX - y, centerY - x);
SDL_RenderDrawPoint(renderer, centerX - y, centerY + x); SDL_RenderPoint(renderer, centerX - y, centerY + x);
if (error <= 0) if (error <= 0)
{ {
@@ -317,7 +318,7 @@ DemoData loadDemoDataFromFile(const std::string &file_path)
DemoData dd; DemoData dd;
// Indicador de éxito en la carga // Indicador de éxito en la carga
auto file = SDL_RWFromFile(file_path.c_str(), "r+b"); auto file = SDL_IOFromFile(file_path.c_str(), "r+b");
if (!file) if (!file)
{ {
std::cerr << "Error: Fichero no encontrado " << file_path << std::endl; std::cerr << "Error: Fichero no encontrado " << file_path << std::endl;
@@ -331,12 +332,12 @@ DemoData loadDemoDataFromFile(const std::string &file_path)
for (int i = 0; i < TOTAL_DEMO_DATA; ++i) for (int i = 0; i < TOTAL_DEMO_DATA; ++i)
{ {
DemoKeys dk = DemoKeys(); DemoKeys dk = DemoKeys();
SDL_RWread(file, &dk, sizeof(DemoKeys), 1); SDL_ReadIO(file, &dk, sizeof(DemoKeys));
dd.push_back(dk); dd.push_back(dk);
} }
// Cierra el fichero // Cierra el fichero
SDL_RWclose(file); SDL_CloseIO(file);
} }
return dd; return dd;
@@ -347,7 +348,7 @@ DemoData loadDemoDataFromFile(const std::string &file_path)
bool saveDemoFile(const std::string &file_path, const DemoData &dd) bool saveDemoFile(const std::string &file_path, const DemoData &dd)
{ {
auto success = true; auto success = true;
auto file = SDL_RWFromFile(file_path.c_str(), "w+b"); auto file = SDL_IOFromFile(file_path.c_str(), "w+b");
if (file) if (file)
{ {
@@ -366,7 +367,7 @@ bool saveDemoFile(const std::string &file_path, const DemoData &dd)
std::cout << "Writing file " << getFileName(file_path).c_str() << std::endl; std::cout << "Writing file " << getFileName(file_path).c_str() << std::endl;
} }
// Cierra el fichero // Cierra el fichero
SDL_RWclose(file); SDL_CloseIO(file);
} }
else else
{ {

View File

@@ -1,6 +1,7 @@
#pragma once #pragma once
#include <SDL3/SDL.h>
#include <SDL3/SDL_rect.h> // Para SDL_FRect, SDL_Point #include <SDL3/SDL_rect.h> // Para SDL_FRect, SDL_FPoint
#include <SDL3/SDL_render.h> // Para SDL_Renderer #include <SDL3/SDL_render.h> // Para SDL_Renderer
#include <SDL3/SDL_stdinc.h> // Para Uint8 #include <SDL3/SDL_stdinc.h> // Para Uint8
#include <stdint.h> // Para int32_t #include <stdint.h> // Para int32_t
@@ -117,12 +118,12 @@ struct Demo
struct Zone struct Zone
{ {
SDL_FRect rect; // Rectangulo que define la zona SDL_FRect rect; // Rectangulo que define la zona
int center_x; // Anclaje al 50% del eje X float center_x; // Anclaje al 50% del eje X
int first_quarter_x; // Anclaje al 25% del eje X float first_quarter_x; // Anclaje al 25% del eje X
int third_quarter_x; // Anclaje al 75% del eje X float third_quarter_x; // Anclaje al 75% del eje X
int center_y; // Anclaje al 50% del eje Y float center_y; // Anclaje al 50% del eje Y
int first_quarter_y; // Anclaje al 25% del eje Y float first_quarter_y; // Anclaje al 25% del eje Y
int third_quarter_y; // Anclaje al 75% del eje X float third_quarter_y; // Anclaje al 75% del eje X
}; };
// Obtiene un color del vector de colores imitando al Coche Fantástico // Obtiene un color del vector de colores imitando al Coche Fantástico
@@ -141,7 +142,7 @@ bool checkCollision(const Circle &a, const SDL_FRect &b);
bool checkCollision(const SDL_FRect &a, const SDL_FRect &b); bool checkCollision(const SDL_FRect &a, const SDL_FRect &b);
// Detector de colisiones entre un punto y un rectangulo // Detector de colisiones entre un punto y un rectangulo
bool checkCollision(const SDL_Point &p, const SDL_FRect &r); bool checkCollision(const SDL_FPoint &p, const SDL_FRect &r);
// Convierte una cadena en un valor booleano // Convierte una cadena en un valor booleano
bool stringToBool(const std::string &str); bool stringToBool(const std::string &str);

View File

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