Compare commits

...

3 Commits

24 changed files with 356 additions and 300 deletions

View File

@@ -11,7 +11,6 @@ set(CMAKE_CXX_STANDARD_REQUIRED True)
set(APP_SOURCES set(APP_SOURCES
# --- Archivos Principales del Sistema --- # --- Archivos Principales del Sistema ---
source/main.cpp source/main.cpp
source/game.cpp
source/director.cpp source/director.cpp
source/section.cpp source/section.cpp
source/screen.cpp source/screen.cpp
@@ -30,28 +29,29 @@ set(APP_SOURCES
source/ui/service_menu.cpp source/ui/service_menu.cpp
source/ui/menu_renderer.cpp source/ui/menu_renderer.cpp
source/ui/ui_message.cpp source/ui/ui_message.cpp
# --- Lógica y Escenas del Juego --- # --- Lógica del Juego ---
source/player.cpp
source/balloon.cpp
source/balloon_formations.cpp source/balloon_formations.cpp
source/balloon_manager.cpp source/balloon_manager.cpp
source/balloon.cpp
source/bullet.cpp source/bullet.cpp
source/item.cpp
source/explosions.cpp
# --- Escenas y Flujo ---
source/title.cpp
source/logo.cpp
source/game_logo.cpp
source/intro.cpp
source/credits.cpp
source/instructions.cpp
source/hiscore_table.cpp
source/enter_name.cpp source/enter_name.cpp
source/explosions.cpp
source/game_logo.cpp
source/item.cpp
source/manage_hiscore_table.cpp source/manage_hiscore_table.cpp
source/player.cpp
source/scoreboard.cpp source/scoreboard.cpp
# --- Escenas ---
source/sections/credits.cpp
source/sections/game.cpp
source/sections/hiscore_table.cpp
source/sections/instructions.cpp
source/sections/intro.cpp
source/sections/logo.cpp
source/sections/title.cpp
# --- Sprites y Gráficos --- # --- Sprites y Gráficos ---
source/sprite.cpp source/sprite.cpp
source/animated_sprite.cpp source/animated_sprite.cpp

View File

@@ -58,6 +58,10 @@ void DefineButtons::bindButtons()
{ {
input_->bindGameControllerButton(index_controller_, button.input, button.button); input_->bindGameControllerButton(index_controller_, button.input, button.button);
} }
// Remapea los inputs a inputs
input_->bindGameControllerButton(index_controller_, InputAction::SM_SELECT, InputAction::FIRE_LEFT);
input_->bindGameControllerButton(index_controller_, InputAction::SM_BACK, InputAction::FIRE_CENTER);
} }
// Comprueba los eventos // Comprueba los eventos

View File

@@ -1,42 +1,42 @@
// IWYU pragma: no_include <bits/chrono.h> // IWYU pragma: no_include <bits/chrono.h>
#include "director.h" #include "director.h"
#include <SDL3/SDL_audio.h> // Para SDL_AudioFormat #include <SDL3/SDL_audio.h> // Para SDL_AudioFormat
#include <SDL3/SDL_error.h> // Para SDL_GetError #include <SDL3/SDL_error.h> // Para SDL_GetError
#include <SDL3/SDL_gamepad.h> // Para SDL_GamepadButton #include <SDL3/SDL_gamepad.h> // Para SDL_GamepadButton
#include <SDL3/SDL_init.h> // Para SDL_Init, SDL_Quit, SDL_INIT_AUDIO #include <SDL3/SDL_init.h> // Para SDL_Init, SDL_Quit, SDL_INIT_AUDIO
#include <SDL3/SDL.h> // Para SDL_Log, SDL_LogCategory, SDL_LogE... #include <SDL3/SDL.h> // Para SDL_Log, SDL_LogCategory, SDL_LogE...
#include <SDL3/SDL_scancode.h> // Para SDL_Scancode #include <SDL3/SDL_scancode.h> // Para SDL_Scancode
#include <errno.h> // Para errno, EEXIST, EACCES, ENAMETOOLONG #include <errno.h> // Para errno, EEXIST, EACCES, ENAMETOOLONG
#include <stdio.h> // Para printf, perror #include <stdio.h> // Para printf, perror
#include <sys/stat.h> // Para mkdir, stat, S_IRWXU #include <sys/stat.h> // Para mkdir, stat, S_IRWXU
#include <unistd.h> // Para getuid #include <unistd.h> // Para getuid
#include <algorithm> // Para min #include <algorithm> // Para min
#include <cstdlib> // Para exit, EXIT_FAILURE, size_t, srand #include <cstdlib> // Para exit, EXIT_FAILURE, size_t, srand
#include <ctime> // Para time #include <ctime> // Para time
#include <memory> // Para make_unique, unique_ptr #include <memory> // Para make_unique, unique_ptr
#include <stdexcept> // Para runtime_error #include <stdexcept> // Para runtime_error
#include <string> // Para operator+, allocator, char_traits #include <string> // Para operator+, allocator, char_traits
#include <vector> // Para vector #include <vector> // Para vector
#include "asset.h" // Para Asset, AssetType #include "asset.h" // Para Asset, AssetType
#include "audio.h" // Para Audio #include "audio.h" // Para Audio
#include "credits.h" // Para Credits #include "input.h" // Para Input, InputAction
#include "game.h" // Para Game, GAME_MODE_DEMO_OFF, GAME_MOD... #include "lang.h" // Para Code, loadFromFile
#include "hiscore_table.h" // Para HiScoreTable #include "manage_hiscore_table.h" // Para ManageHiScoreTable
#include "input.h" // Para Input, InputAction #include "notifier.h" // Para Notifier
#include "instructions.h" // Para Instructions #include "options.h" // Para GamepadOptions, Options, options
#include "intro.h" // Para Intro #include "param.h" // Para loadParamsFromFile
#include "lang.h" // Para Code, loadFromFile #include "resource.h" // Para Resource
#include "logo.h" // Para Logo #include "screen.h" // Para Screen
#include "manage_hiscore_table.h" // Para ManageHiScoreTable #include "section.h" // Para Name, Options, name, options
#include "notifier.h" // Para Notifier #include "sections/credits.h" // Para Credits
#include "options.h" // Para GamepadOptions, Options, options #include "sections/game.h" // Para Game, GAME_MODE_DEMO_OFF, GAME_MOD...
#include "param.h" // Para loadParamsFromFile #include "sections/hiscore_table.h" // Para HiScoreTable
#include "resource.h" // Para Resource #include "sections/instructions.h" // Para Instructions
#include "screen.h" // Para Screen #include "sections/intro.h" // Para Intro
#include "section.h" // Para Name, Options, name, options #include "sections/logo.h" // Para Logo
#include "ui/service_menu.h" // Para ServiceMenu #include "sections/title.h" // Para Title
#include "title.h" // Para Title #include "ui/service_menu.h" // Para ServiceMenu
#include "utils.h" // Para Overrides, overrides #include "utils.h" // Para Overrides, overrides
#ifndef _WIN32 #ifndef _WIN32
#include <pwd.h> // Para getpwuid, passwd #include <pwd.h> // Para getpwuid, passwd
@@ -49,7 +49,7 @@ Director::Director(int argc, const char *argv[])
Section::name = Section::Name::GAME; Section::name = Section::Name::GAME;
Section::options = Section::Options::GAME_PLAY_1P; Section::options = Section::Options::GAME_PLAY_1P;
#elif DEBUG #elif DEBUG
Section::name = Section::Name::LOGO; Section::name = Section::Name::TITLE;
Section::options = Section::Options::GAME_PLAY_1P; Section::options = Section::Options::GAME_PLAY_1P;
#else // NORMAL GAME #else // NORMAL GAME
Section::name = Section::Name::LOGO; Section::name = Section::Name::LOGO;

View File

@@ -11,7 +11,7 @@
#include "param.h" // Para Param, ParamGame, param #include "param.h" // Para Param, ParamGame, param
#include "screen.h" // Para Screen #include "screen.h" // Para Screen
#include "section.h" // Para Name, name, Options, options, AttractMode #include "section.h" // Para Name, name, Options, options, AttractMode
#include "ui/service_menu.h" // Para ServiceMenu #include "ui/service_menu.h" // Para ServiceMenu
#include "utils.h" // Para boolToOnOff #include "utils.h" // Para boolToOnOff
namespace GlobalInputs namespace GlobalInputs
@@ -192,76 +192,77 @@ namespace GlobalInputs
} }
// Comprueba el boton de servicio // Comprueba el boton de servicio
void checkServiceButton() bool checkServiceButton()
{ {
// Teclado // Teclado
if (Input::get()->checkInput(InputAction::SERVICE, INPUT_DO_NOT_ALLOW_REPEAT, InputDeviceToUse::KEYBOARD)) if (Input::get()->checkInput(InputAction::SERVICE, INPUT_DO_NOT_ALLOW_REPEAT, InputDevice::KEYBOARD))
{ {
toggleServiceMenu(); toggleServiceMenu();
return; return true;
} }
// Mandos // Mandos
{ {
for (int i = 0; i < Input::get()->getNumControllers(); ++i) for (int i = 0; i < Input::get()->getNumControllers(); ++i)
{ {
if (Input::get()->checkInput(InputAction::SERVICE, INPUT_DO_NOT_ALLOW_REPEAT, InputDeviceToUse::CONTROLLER, i)) if (Input::get()->checkInput(InputAction::SERVICE, INPUT_DO_NOT_ALLOW_REPEAT, InputDevice::CONTROLLER, i))
{ {
toggleServiceMenu(); toggleServiceMenu();
return; return true;
} }
} }
} }
return false;
} }
// Comprueba las entradas del menú de servicio // Comprueba las entradas del menú de servicio
void checkServiceInputs() bool checkServiceInputs()
{ {
if (!ServiceMenu::get()->isEnabled()) if (!ServiceMenu::get()->isEnabled())
return; return false;
// Teclado // Teclado
{ {
// Arriba // Arriba
if (Input::get()->checkInput(InputAction::UP, INPUT_DO_NOT_ALLOW_REPEAT, InputDeviceToUse::KEYBOARD)) if (Input::get()->checkInput(InputAction::UP, INPUT_DO_NOT_ALLOW_REPEAT, InputDevice::KEYBOARD))
{ {
ServiceMenu::get()->setSelectorUp(); ServiceMenu::get()->setSelectorUp();
return; return true;
} }
// Abajo // Abajo
if (Input::get()->checkInput(InputAction::DOWN, INPUT_DO_NOT_ALLOW_REPEAT, InputDeviceToUse::KEYBOARD)) if (Input::get()->checkInput(InputAction::DOWN, INPUT_DO_NOT_ALLOW_REPEAT, InputDevice::KEYBOARD))
{ {
ServiceMenu::get()->setSelectorDown(); ServiceMenu::get()->setSelectorDown();
return; return true;
} }
// Derecha // Derecha
if (Input::get()->checkInput(InputAction::RIGHT, INPUT_DO_NOT_ALLOW_REPEAT, InputDeviceToUse::KEYBOARD)) if (Input::get()->checkInput(InputAction::RIGHT, INPUT_DO_NOT_ALLOW_REPEAT, InputDevice::KEYBOARD))
{ {
ServiceMenu::get()->adjustOption(true); ServiceMenu::get()->adjustOption(true);
return; return true;
} }
// Izquierda // Izquierda
if (Input::get()->checkInput(InputAction::LEFT, INPUT_DO_NOT_ALLOW_REPEAT, InputDeviceToUse::KEYBOARD)) if (Input::get()->checkInput(InputAction::LEFT, INPUT_DO_NOT_ALLOW_REPEAT, InputDevice::KEYBOARD))
{ {
ServiceMenu::get()->adjustOption(false); ServiceMenu::get()->adjustOption(false);
return; return true;
} }
// Aceptar // Aceptar
if (Input::get()->checkInput(InputAction::SM_SELECT, INPUT_DO_NOT_ALLOW_REPEAT, InputDeviceToUse::KEYBOARD)) if (Input::get()->checkInput(InputAction::SM_SELECT, INPUT_DO_NOT_ALLOW_REPEAT, InputDevice::KEYBOARD))
{ {
ServiceMenu::get()->selectOption(); ServiceMenu::get()->selectOption();
return; return true;
} }
// Atras // Atras
if (Input::get()->checkInput(InputAction::SM_BACK, INPUT_DO_NOT_ALLOW_REPEAT, InputDeviceToUse::KEYBOARD)) if (Input::get()->checkInput(InputAction::SM_BACK, INPUT_DO_NOT_ALLOW_REPEAT, InputDevice::KEYBOARD))
{ {
ServiceMenu::get()->moveBack(); ServiceMenu::get()->moveBack();
return; return true;
} }
} }
@@ -270,163 +271,169 @@ namespace GlobalInputs
for (int i = 0; i < Input::get()->getNumControllers(); ++i) for (int i = 0; i < Input::get()->getNumControllers(); ++i)
{ {
// Arriba // Arriba
if (Input::get()->checkInput(InputAction::UP, INPUT_DO_NOT_ALLOW_REPEAT, InputDeviceToUse::CONTROLLER, i)) if (Input::get()->checkInput(InputAction::UP, INPUT_DO_NOT_ALLOW_REPEAT, InputDevice::CONTROLLER, i))
{ {
ServiceMenu::get()->setSelectorUp(); ServiceMenu::get()->setSelectorUp();
return; return true;
} }
// Abajo // Abajo
if (Input::get()->checkInput(InputAction::DOWN, INPUT_DO_NOT_ALLOW_REPEAT, InputDeviceToUse::CONTROLLER, i)) if (Input::get()->checkInput(InputAction::DOWN, INPUT_DO_NOT_ALLOW_REPEAT, InputDevice::CONTROLLER, i))
{ {
ServiceMenu::get()->setSelectorDown(); ServiceMenu::get()->setSelectorDown();
return; return true;
} }
// Derecha // Derecha
if (Input::get()->checkInput(InputAction::RIGHT, INPUT_DO_NOT_ALLOW_REPEAT, InputDeviceToUse::CONTROLLER, i)) if (Input::get()->checkInput(InputAction::RIGHT, INPUT_DO_NOT_ALLOW_REPEAT, InputDevice::CONTROLLER, i))
{ {
ServiceMenu::get()->adjustOption(true); ServiceMenu::get()->adjustOption(true);
return; return true;
} }
// Izquierda // Izquierda
if (Input::get()->checkInput(InputAction::LEFT, INPUT_DO_NOT_ALLOW_REPEAT, InputDeviceToUse::CONTROLLER, i)) if (Input::get()->checkInput(InputAction::LEFT, INPUT_DO_NOT_ALLOW_REPEAT, InputDevice::CONTROLLER, i))
{ {
ServiceMenu::get()->adjustOption(false); ServiceMenu::get()->adjustOption(false);
return; return true;
} }
// Aceptar // Aceptar
if (Input::get()->checkInput(InputAction::SM_SELECT, INPUT_DO_NOT_ALLOW_REPEAT, InputDeviceToUse::CONTROLLER, i)) if (Input::get()->checkInput(InputAction::SM_SELECT, INPUT_DO_NOT_ALLOW_REPEAT, InputDevice::CONTROLLER, i))
{ {
ServiceMenu::get()->selectOption(); ServiceMenu::get()->selectOption();
return; return true;
} }
// Atras // Atras
if (Input::get()->checkInput(InputAction::SM_BACK, INPUT_DO_NOT_ALLOW_REPEAT, InputDeviceToUse::CONTROLLER, i)) if (Input::get()->checkInput(InputAction::SM_BACK, INPUT_DO_NOT_ALLOW_REPEAT, InputDevice::CONTROLLER, i))
{ {
ServiceMenu::get()->moveBack(); ServiceMenu::get()->moveBack();
return; return true;
} }
} }
} }
return false;
} }
// Comprueba las entradas fuera del menú de servicio // Comprueba las entradas fuera del menú de servicio
void checkInputs() bool checkInputs()
{ {
// Teclado // Teclado
{ {
// 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, InputDevice::KEYBOARD))
{ {
Screen::get()->toggleFullscreen(); Screen::get()->toggleFullscreen();
const std::string MODE = Options::video.fullscreen ? Lang::getText("[NOTIFICATIONS] 11") : Lang::getText("[NOTIFICATIONS] 10"); const std::string MODE = Options::video.fullscreen ? Lang::getText("[NOTIFICATIONS] 11") : Lang::getText("[NOTIFICATIONS] 10");
Notifier::get()->show({MODE}); Notifier::get()->show({MODE});
return; return true;
} }
// Comprueba el teclado para decrementar el tamaño de la ventana // Comprueba el teclado para decrementar el tamaño de la ventana
if (Input::get()->checkInput(InputAction::WINDOW_DEC_SIZE, INPUT_DO_NOT_ALLOW_REPEAT, InputDeviceToUse::KEYBOARD)) if (Input::get()->checkInput(InputAction::WINDOW_DEC_SIZE, INPUT_DO_NOT_ALLOW_REPEAT, InputDevice::KEYBOARD))
{ {
if (Screen::get()->decWindowSize()) if (Screen::get()->decWindowSize())
{ {
Notifier::get()->show({Lang::getText("[NOTIFICATIONS] 09") + " x" + std::to_string(Options::window.size)}); Notifier::get()->show({Lang::getText("[NOTIFICATIONS] 09") + " x" + std::to_string(Options::window.size)});
} }
return; return true;
} }
// Comprueba el teclado para incrementar el tamaño de la ventana // Comprueba el teclado para incrementar el tamaño de la ventana
if (Input::get()->checkInput(InputAction::WINDOW_INC_SIZE, INPUT_DO_NOT_ALLOW_REPEAT, InputDeviceToUse::KEYBOARD)) if (Input::get()->checkInput(InputAction::WINDOW_INC_SIZE, INPUT_DO_NOT_ALLOW_REPEAT, InputDevice::KEYBOARD))
{ {
if (Screen::get()->incWindowSize()) if (Screen::get()->incWindowSize())
{ {
Notifier::get()->show({Lang::getText("[NOTIFICATIONS] 09") + " x" + std::to_string(Options::window.size)}); Notifier::get()->show({Lang::getText("[NOTIFICATIONS] 09") + " x" + std::to_string(Options::window.size)});
} }
return; return true;
} }
// Salir // Salir
if (Input::get()->checkInput(InputAction::EXIT, INPUT_DO_NOT_ALLOW_REPEAT, InputDeviceToUse::KEYBOARD)) if (Input::get()->checkInput(InputAction::EXIT, INPUT_DO_NOT_ALLOW_REPEAT, InputDevice::KEYBOARD))
{ {
quit(); quit();
return; return true;
} }
// Saltar sección // Saltar sección
if (Input::get()->checkAnyButtonPressed() && !ServiceMenu::get()->isEnabled()) if (Input::get()->checkAnyButton() && !ServiceMenu::get()->isEnabled())
{ {
skipSection(); skipSection();
return; return true;
} }
// Reset // Reset
if (Input::get()->checkInput(InputAction::RESET, INPUT_DO_NOT_ALLOW_REPEAT, InputDeviceToUse::KEYBOARD)) if (Input::get()->checkInput(InputAction::RESET, INPUT_DO_NOT_ALLOW_REPEAT, InputDevice::KEYBOARD))
{ {
reset(); reset();
return; return true;
} }
// Audio // Audio
if (Input::get()->checkInput(InputAction::TOGGLE_AUDIO, INPUT_DO_NOT_ALLOW_REPEAT, InputDeviceToUse::KEYBOARD)) if (Input::get()->checkInput(InputAction::TOGGLE_AUDIO, INPUT_DO_NOT_ALLOW_REPEAT, InputDevice::KEYBOARD))
{ {
toggleAudio(); toggleAudio();
return; return true;
} }
// Autofire // Autofire
if (Input::get()->checkInput(InputAction::TOGGLE_AUTO_FIRE, INPUT_DO_NOT_ALLOW_REPEAT, InputDeviceToUse::KEYBOARD)) if (Input::get()->checkInput(InputAction::TOGGLE_AUTO_FIRE, INPUT_DO_NOT_ALLOW_REPEAT, InputDevice::KEYBOARD))
{ {
toggleFireMode(); toggleFireMode();
return; return true;
} }
// Idioma // Idioma
if (Input::get()->checkInput(InputAction::CHANGE_LANG, INPUT_DO_NOT_ALLOW_REPEAT, InputDeviceToUse::KEYBOARD)) if (Input::get()->checkInput(InputAction::CHANGE_LANG, INPUT_DO_NOT_ALLOW_REPEAT, InputDevice::KEYBOARD))
{ {
changeLang(); changeLang();
return; return true;
} }
// Shaders // Shaders
if (Input::get()->checkInput(InputAction::TOGGLE_VIDEO_SHADERS, INPUT_DO_NOT_ALLOW_REPEAT, InputDeviceToUse::KEYBOARD)) if (Input::get()->checkInput(InputAction::TOGGLE_VIDEO_SHADERS, INPUT_DO_NOT_ALLOW_REPEAT, InputDevice::KEYBOARD))
{ {
toggleShaders(); toggleShaders();
return; return true;
} }
// Integer Scale // Integer Scale
if (Input::get()->checkInput(InputAction::TOGGLE_VIDEO_INTEGER_SCALE, INPUT_DO_NOT_ALLOW_REPEAT, InputDeviceToUse::KEYBOARD)) if (Input::get()->checkInput(InputAction::TOGGLE_VIDEO_INTEGER_SCALE, INPUT_DO_NOT_ALLOW_REPEAT, InputDevice::KEYBOARD))
{ {
toggleIntegerScale(); toggleIntegerScale();
return; return true;
} }
// VSync // VSync
if (Input::get()->checkInput(InputAction::TOGGLE_VIDEO_VSYNC, INPUT_DO_NOT_ALLOW_REPEAT, InputDeviceToUse::KEYBOARD)) if (Input::get()->checkInput(InputAction::TOGGLE_VIDEO_VSYNC, INPUT_DO_NOT_ALLOW_REPEAT, InputDevice::KEYBOARD))
{ {
toggleVSync(); toggleVSync();
return; return true;
} }
#ifdef DEBUG #ifdef DEBUG
// Debug info // Debug info
if (Input::get()->checkInput(InputAction::SHOW_INFO, INPUT_DO_NOT_ALLOW_REPEAT, InputDeviceToUse::KEYBOARD)) if (Input::get()->checkInput(InputAction::SHOW_INFO, INPUT_DO_NOT_ALLOW_REPEAT, InputDevice::KEYBOARD))
{ {
Screen::get()->toggleDebugInfo(); Screen::get()->toggleDebugInfo();
return; return true;
} }
#endif #endif
} }
return false;
} }
// Comprueba los inputs que se pueden introducir en cualquier sección del juego // Comprueba los inputs que se pueden introducir en cualquier sección del juego
void check() bool check()
{ {
checkServiceButton(); if (checkServiceButton())
checkServiceInputs(); return true;
checkInputs(); if (checkServiceInputs())
return true;
if (checkInputs())
return true;
return false;
} }
} }

View File

@@ -3,5 +3,5 @@
namespace GlobalInputs namespace GlobalInputs
{ {
// Comprueba los inputs que se pueden introducir en cualquier sección del juego // Comprueba los inputs que se pueden introducir en cualquier sección del juego
void check(); bool check();
} }

View File

@@ -60,79 +60,39 @@ void Input::bindGameControllerButton(int controller_index, InputAction input_tar
} }
// Comprueba si un input esta activo // Comprueba si un input esta activo
bool Input::checkInput(InputAction input, bool repeat, InputDeviceToUse device, int controller_index) bool Input::checkInput(InputAction input, bool repeat, InputDevice device, int controller_index)
{ {
bool success_keyboard = false; bool success_keyboard = false;
bool success_controller = false; bool success_controller = false;
const int input_index = static_cast<int>(input); const int input_index = static_cast<int>(input);
if (device == InputDeviceToUse::KEYBOARD || device == InputDeviceToUse::ANY) if (device == InputDevice::KEYBOARD || device == InputDevice::ANY)
{ {
const bool *keyStates = SDL_GetKeyboardState(nullptr);
if (repeat) if (repeat)
{ { // El usuario quiere saber si está pulsada (estado mantenido)
success_keyboard = keyStates[key_bindings_[input_index].scancode] != 0; success_keyboard = key_bindings_[input_index].is_held;
} }
else else
{ { // El usuario quiere saber si ACABA de ser pulsada (evento de un solo fotograma)
if (!key_bindings_[input_index].active) success_keyboard = key_bindings_[input_index].just_pressed;
{
if (keyStates[key_bindings_[input_index].scancode] != 0)
{
key_bindings_[input_index].active = true;
success_keyboard = true;
}
else
{
success_keyboard = false;
}
}
else
{
if (keyStates[key_bindings_[input_index].scancode] == 0)
{
key_bindings_[input_index].active = false;
}
success_keyboard = false;
}
} }
} }
if (gameControllerFound() && controller_index >= 0 && controller_index < num_gamepads_) if (gameControllerFound() && controller_index >= 0 && controller_index < num_gamepads_)
{ {
if ((device == InputDeviceToUse::CONTROLLER) || (device == InputDeviceToUse::ANY)) if ((device == InputDevice::CONTROLLER) || (device == InputDevice::ANY))
{ {
success_controller = checkAxisInput(input, controller_index, repeat); success_controller = checkAxisInput(input, controller_index, repeat);
if (!success_controller) if (!success_controller)
{ {
if (repeat) if (repeat)
{ { // El usuario quiere saber si está pulsada (estado mantenido)
success_controller = SDL_GetGamepadButton(connected_controllers_.at(controller_index), controller_bindings_.at(controller_index).at(input_index).button) != 0; success_controller = controller_bindings_.at(controller_index).at(input_index).is_held;
} }
else else
{ { // El usuario quiere saber si ACABA de ser pulsada (evento de un solo fotograma)
if (!controller_bindings_.at(controller_index).at(input_index).active) success_controller = controller_bindings_.at(controller_index).at(input_index).just_pressed;
{
if (SDL_GetGamepadButton(connected_controllers_.at(controller_index), controller_bindings_.at(controller_index).at(input_index).button) != 0)
{
controller_bindings_.at(controller_index).at(input_index).active = true;
success_controller = true;
}
else
{
success_controller = false;
}
}
else
{
if (SDL_GetGamepadButton(connected_controllers_.at(controller_index), controller_bindings_.at(controller_index).at(input_index).button) == 0)
{
controller_bindings_.at(controller_index).at(input_index).active = false;
}
success_controller = false;
}
} }
} }
} }
@@ -142,54 +102,55 @@ bool Input::checkInput(InputAction input, bool repeat, InputDeviceToUse device,
} }
// Comprueba si hay almenos un input activo // Comprueba si hay almenos un input activo
bool Input::checkAnyInput(InputDeviceToUse device, int controller_index) bool Input::checkAnyInput(InputDevice device, int controller_index)
{ {
if (device == InputDeviceToUse::KEYBOARD || device == InputDeviceToUse::ANY) // Obtenemos el número total de acciones posibles para iterar sobre ellas.
{ const int num_actions = static_cast<int>(InputAction::SIZE);
const bool *mKeystates = SDL_GetKeyboardState(nullptr);
for (int i = 0; i < (int)key_bindings_.size(); ++i) // --- Comprobación del Teclado ---
if (device == InputDevice::KEYBOARD || device == InputDevice::ANY)
{
for (int i = 0; i < num_actions; ++i)
{ {
if (mKeystates[key_bindings_[i].scancode] != 0 && !key_bindings_[i].active) // Simplemente leemos el estado pre-calculado por Input::update().
// Ya no se llama a SDL_GetKeyboardState ni se modifica el estado '.active'.
if (key_bindings_.at(i).just_pressed)
{ {
key_bindings_[i].active = true; return true; // Se encontró una acción recién pulsada.
return true;
} }
} }
} }
if (gameControllerFound()) // --- Comprobación del Mando ---
// Comprobamos si hay mandos y si el índice solicitado es válido.
if (gameControllerFound() && controller_index >= 0 && controller_index < num_gamepads_)
{ {
if (device == InputDeviceToUse::CONTROLLER || device == InputDeviceToUse::ANY) if (device == InputDevice::CONTROLLER || device == InputDevice::ANY)
{ {
for (int i = 0; i < (int)controller_bindings_.size(); ++i) // Bucle CORREGIDO: Iteramos sobre todas las acciones, no sobre el número de mandos.
for (int i = 0; i < num_actions; ++i)
{ {
if (SDL_GetGamepadButton(connected_controllers_[controller_index], controller_bindings_[controller_index][i].button) != 0 && !controller_bindings_[controller_index][i].active) // Leemos el estado pre-calculado para el mando y la acción específicos.
if (controller_bindings_.at(controller_index).at(i).just_pressed)
{ {
controller_bindings_[controller_index][i].active = true; return true; // Se encontró una acción recién pulsada en el mando.
return true;
} }
} }
} }
} }
// Si llegamos hasta aquí, no se detectó ninguna nueva pulsación.
return false; return false;
} }
// Comprueba si hay algún botón pulsado. Devuelve 0 en caso de no encontrar nada o el indice del dispositivo + 1. Se hace así para poder gastar el valor devuelto como un valor "booleano" // Comprueba si hay algún botón pulsado. Devuelve 0 en caso de no encontrar nada o el indice del dispositivo + 1. Se hace así para poder gastar el valor devuelto como un valor "booleano"
int Input::checkAnyButtonPressed(bool repeat) int Input::checkAnyButton(bool repeat)
{ {
// Si está pulsado el botón de servicio, ningún botón se puede considerar pulsado
if (checkInput(InputAction::SERVICE, INPUT_ALLOW_REPEAT, InputDeviceToUse::ANY))
{
return 0;
}
// Solo comprueba los botones definidos previamente // Solo comprueba los botones definidos previamente
for (auto bi : button_inputs_) for (auto bi : button_inputs_)
{ {
// Comprueba el teclado // Comprueba el teclado
if (checkInput(bi, repeat, InputDeviceToUse::KEYBOARD)) if (checkInput(bi, repeat, InputDevice::KEYBOARD))
{ {
return 1; return 1;
} }
@@ -197,7 +158,7 @@ int Input::checkAnyButtonPressed(bool repeat)
// Comprueba los mandos // Comprueba los mandos
for (int i = 0; i < num_gamepads_; ++i) for (int i = 0; i < num_gamepads_; ++i)
{ {
if (checkInput(bi, repeat, InputDeviceToUse::CONTROLLER, i)) if (checkInput(bi, repeat, InputDevice::CONTROLLER, i))
{ {
return i + 1; return i + 1;
} }
@@ -218,7 +179,7 @@ bool Input::discoverGameControllers()
} }
// En SDL3, SDL_GetJoysticks devuelve un array de IDs, no un contador // En SDL3, SDL_GetJoysticks devuelve un array de IDs, no un contador
SDL_JoystickID* joystick_ids = SDL_GetJoysticks(&num_joysticks_); SDL_JoystickID *joystick_ids = SDL_GetJoysticks(&num_joysticks_);
num_gamepads_ = 0; num_gamepads_ = 0;
// Cuenta el número de mandos // Cuenta el número de mandos
@@ -228,7 +189,7 @@ bool Input::discoverGameControllers()
// Usar el ID del joystick, no el índice // Usar el ID del joystick, no el índice
auto joy = SDL_OpenJoystick(joystick_ids[i]); auto joy = SDL_OpenJoystick(joystick_ids[i]);
joysticks_.push_back(joy); joysticks_.push_back(joy);
// En SDL3, SDL_IsGamepad toma un SDL_JoystickID, no un índice // En SDL3, SDL_IsGamepad toma un SDL_JoystickID, no un índice
if (SDL_IsGamepad(joystick_ids[i])) if (SDL_IsGamepad(joystick_ids[i]))
{ {
@@ -261,11 +222,11 @@ bool Input::discoverGameControllers()
if (pad != nullptr) if (pad != nullptr)
{ {
connected_controllers_.push_back(pad); connected_controllers_.push_back(pad);
// Obtener el nombre usando el ID del joystick // Obtener el nombre usando el ID del joystick
const char* name_cstr = SDL_GetGamepadNameForID(joystick_ids[i]); const char *name_cstr = SDL_GetGamepadNameForID(joystick_ids[i]);
std::string name = name_cstr ? name_cstr : "Unknown Gamepad"; std::string name = name_cstr ? name_cstr : "Unknown Gamepad";
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "#%d: %s", i, name.c_str()); SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "#%d: %s", i, name.c_str());
controller_names_.push_back(name); controller_names_.push_back(name);
} }
@@ -312,14 +273,14 @@ int Input::getJoyIndex(SDL_JoystickID id) const
} }
// Muestra por consola los controles asignados // Muestra por consola los controles asignados
void Input::printBindings(InputDeviceToUse device, int controller_index) const void Input::printBindings(InputDevice device, int controller_index) const
{ {
if (device == InputDeviceToUse::ANY || device == InputDeviceToUse::KEYBOARD) if (device == InputDevice::ANY || device == InputDevice::KEYBOARD)
{ {
return; return;
} }
if (device == InputDeviceToUse::CONTROLLER) if (device == InputDevice::CONTROLLER)
{ {
if (controller_index >= num_gamepads_) if (controller_index >= num_gamepads_)
{ {
@@ -388,22 +349,21 @@ InputAction Input::to_inputs_e(const std::string &name) const
bool Input::checkAxisInput(InputAction input, int controller_index, bool repeat) bool Input::checkAxisInput(InputAction input, int controller_index, bool repeat)
{ {
// Umbral para considerar el eje como activo // Umbral para considerar el eje como activo
const Sint16 threshold = 30000;
bool axis_active_now = false; bool axis_active_now = false;
switch (input) switch (input)
{ {
case InputAction::LEFT: case InputAction::LEFT:
axis_active_now = SDL_GetGamepadAxis(connected_controllers_[controller_index], SDL_GAMEPAD_AXIS_LEFTX) < -threshold; axis_active_now = SDL_GetGamepadAxis(connected_controllers_[controller_index], SDL_GAMEPAD_AXIS_LEFTX) < -AXIS_THRESHOLD_;
break; break;
case InputAction::RIGHT: case InputAction::RIGHT:
axis_active_now = SDL_GetGamepadAxis(connected_controllers_[controller_index], SDL_GAMEPAD_AXIS_LEFTX) > threshold; axis_active_now = SDL_GetGamepadAxis(connected_controllers_[controller_index], SDL_GAMEPAD_AXIS_LEFTX) > AXIS_THRESHOLD_;
break; break;
case InputAction::UP: case InputAction::UP:
axis_active_now = SDL_GetGamepadAxis(connected_controllers_[controller_index], SDL_GAMEPAD_AXIS_LEFTY) < -threshold; axis_active_now = SDL_GetGamepadAxis(connected_controllers_[controller_index], SDL_GAMEPAD_AXIS_LEFTY) < -AXIS_THRESHOLD_;
break; break;
case InputAction::DOWN: case InputAction::DOWN:
axis_active_now = SDL_GetGamepadAxis(connected_controllers_[controller_index], SDL_GAMEPAD_AXIS_LEFTY) > threshold; axis_active_now = SDL_GetGamepadAxis(connected_controllers_[controller_index], SDL_GAMEPAD_AXIS_LEFTY) > AXIS_THRESHOLD_;
break; break;
default: default:
return false; return false;
@@ -453,15 +413,49 @@ void Input::initSDLGamePad()
} }
} }
void Input::resetInputStates() { void Input::resetInputStates()
{
// Resetear todos los KeyBindings.active a false // Resetear todos los KeyBindings.active a false
for (auto &key : key_bindings_) { for (auto &key : key_bindings_)
key.active = false; {
key.is_held = false;
key.just_pressed = false;
} }
// Resetear todos los ControllerBindings.active a false // Resetear todos los ControllerBindings.active a false
for (auto &controller_vec : controller_bindings_) { for (auto &controller_vec : controller_bindings_)
for (auto &binding : controller_vec) { {
binding.active = false; for (auto &binding : controller_vec)
{
binding.is_held = false;
binding.just_pressed = false;
}
}
}
void Input::update()
{
// --- TECLADO ---
const bool *key_states = SDL_GetKeyboardState(nullptr);
for (int i = 0; i < key_bindings_.size(); ++i)
{
bool key_is_down_now = key_states[key_bindings_[i].scancode];
// El estado .is_held del fotograma anterior nos sirve para saber si es un pulso nuevo
key_bindings_[i].just_pressed = key_is_down_now && !key_bindings_[i].is_held;
key_bindings_[i].is_held = key_is_down_now;
}
// --- MANDOS ---
for (int c = 0; c < num_gamepads_; ++c)
{
for (int i = 0; i < controller_bindings_[c].size(); ++i)
{
bool button_is_down_now = SDL_GetGamepadButton(connected_controllers_.at(c), controller_bindings_.at(c).at(i).button) != 0;
// El estado .is_held del fotograma anterior nos sirve para saber si es un pulso nuevo
controller_bindings_[c][i].just_pressed = button_is_down_now && !controller_bindings_[c][i].is_held;
controller_bindings_[c][i].is_held = button_is_down_now;
} }
} }
} }

View File

@@ -63,7 +63,7 @@ constexpr bool INPUT_ALLOW_REPEAT = true;
constexpr bool INPUT_DO_NOT_ALLOW_REPEAT = false; constexpr bool INPUT_DO_NOT_ALLOW_REPEAT = false;
// Tipos de dispositivos de entrada // Tipos de dispositivos de entrada
enum class InputDeviceToUse : int enum class InputDevice : int
{ {
KEYBOARD = 0, KEYBOARD = 0,
CONTROLLER = 1, CONTROLLER = 1,
@@ -85,9 +85,10 @@ public:
void bindGameControllerButton(int controller_index, InputAction inputTarget, InputAction inputSource); // Asigna inputs a otros inputs del mando void bindGameControllerButton(int controller_index, InputAction inputTarget, InputAction inputSource); // Asigna inputs a otros inputs del mando
// --- Métodos de consulta de entrada --- // --- Métodos de consulta de entrada ---
bool checkInput(InputAction input, bool repeat = true, InputDeviceToUse device = InputDeviceToUse::ANY, int controller_index = 0); // Comprueba si un input está activo void update(); // Comprueba fisicamente los botones y teclas que se han pulsado
bool checkAnyInput(InputDeviceToUse device = InputDeviceToUse::ANY, int controller_index = 0); // Comprueba si hay al menos un input activo bool checkInput(InputAction input, bool repeat = true, InputDevice device = InputDevice::ANY, int controller_index = 0); // Comprueba si un input está activo
int checkAnyButtonPressed(bool repeat = INPUT_DO_NOT_ALLOW_REPEAT); // Comprueba si hay algún botón pulsado bool checkAnyInput(InputDevice device = InputDevice::ANY, int controller_index = 0); // Comprueba si hay al menos un input activo
int checkAnyButton(bool repeat = INPUT_DO_NOT_ALLOW_REPEAT); // Comprueba si hay algún botón pulsado
// --- Métodos de gestión de mandos --- // --- Métodos de gestión de mandos ---
bool discoverGameControllers(); // Busca si hay mandos conectados bool discoverGameControllers(); // Busca si hay mandos conectados
@@ -97,11 +98,11 @@ public:
int getJoyIndex(SDL_JoystickID id) const; // Obtiene el índice del controlador a partir de un event.id int getJoyIndex(SDL_JoystickID id) const; // Obtiene el índice del controlador a partir de un event.id
// --- Métodos de consulta y utilidades --- // --- Métodos de consulta y utilidades ---
void printBindings(InputDeviceToUse device = InputDeviceToUse::KEYBOARD, int controller_index = 0) const; // Muestra por consola los controles asignados void printBindings(InputDevice device = InputDevice::KEYBOARD, int controller_index = 0) const; // Muestra por consola los controles asignados
SDL_GamepadButton getControllerBinding(int controller_index, InputAction input) const; // Obtiene el SDL_GamepadButton asignado a un input SDL_GamepadButton getControllerBinding(int controller_index, InputAction input) const; // Obtiene el SDL_GamepadButton asignado a un input
std::string to_string(InputAction input) const; // Convierte un InputAction a std::string std::string to_string(InputAction input) const; // Convierte un InputAction a std::string
InputAction to_inputs_e(const std::string &name) const; // Convierte un std::string a InputAction InputAction to_inputs_e(const std::string &name) const; // Convierte un std::string a InputAction
int getIndexByName(const std::string &name) const; // Obtiene el índice a partir del nombre del mando int getIndexByName(const std::string &name) const; // Obtiene el índice a partir del nombre del mando
// --- Métodos de reseteo de estado de entrada --- // --- Métodos de reseteo de estado de entrada ---
void resetInputStates(); // Pone todos los KeyBindings.active y ControllerBindings.active a false void resetInputStates(); // Pone todos los KeyBindings.active y ControllerBindings.active a false
@@ -113,23 +114,28 @@ private:
// --- Estructuras internas --- // --- Estructuras internas ---
struct KeyBindings struct KeyBindings
{ {
Uint8 scancode; // Scancode asociado Uint8 scancode; // Scancode asociado
bool active; // Indica si está activo bool is_held; // Está pulsada ahora mismo
bool just_pressed; // Se acaba de pulsar en este fotograma
KeyBindings(Uint8 sc = 0, bool act = false) KeyBindings(Uint8 scancode = 0, bool is_held = false, bool just_pressed = false)
: scancode(sc), active(act) {} : scancode(scancode), is_held(is_held), just_pressed(just_pressed) {}
}; };
struct ControllerBindings struct ControllerBindings
{ {
SDL_GamepadButton button; // GameControllerButton asociado SDL_GamepadButton button; // GameControllerButton asociado
bool active; // Indica si está activo bool is_held; // Está pulsada ahora mismo
bool just_pressed; // Se acaba de pulsar en este fotograma
bool axis_active; // Estado del eje bool axis_active; // Estado del eje
ControllerBindings(SDL_GamepadButton btn = SDL_GAMEPAD_BUTTON_INVALID, bool act = false, bool axis_act = false) ControllerBindings(SDL_GamepadButton btn = SDL_GAMEPAD_BUTTON_INVALID, bool is_held = false, bool just_pressed = false, bool axis_act = false)
: button(btn), active(act), axis_active(axis_act) {} : button(btn), is_held(is_held), just_pressed(just_pressed), axis_active(axis_act) {}
}; };
// --- Constantes ---
static constexpr Sint16 AXIS_THRESHOLD_ = 30000;
// --- Variables internas --- // --- Variables internas ---
std::vector<SDL_Gamepad *> connected_controllers_; // Vector con todos los mandos conectados std::vector<SDL_Gamepad *> connected_controllers_; // Vector con todos los mandos conectados
std::vector<SDL_Joystick *> joysticks_; // Vector con todos los joysticks conectados std::vector<SDL_Joystick *> joysticks_; // Vector con todos los joysticks conectados
@@ -142,7 +148,7 @@ private:
std::string game_controller_db_path_; // Ruta al archivo gamecontrollerdb.txt std::string game_controller_db_path_; // Ruta al archivo gamecontrollerdb.txt
// --- Métodos internos --- // --- Métodos internos ---
void initSDLGamePad(); // Inicializa SDL para la gestión de mandos void initSDLGamePad(); // Inicializa SDL para la gestión de mandos
bool checkAxisInput(InputAction input, int controller_index, bool repeat); // Comprueba el eje del mando bool checkAxisInput(InputAction input, int controller_index, bool repeat); // Comprueba el eje del mando
// --- Constructor y destructor --- // --- Constructor y destructor ---

View File

@@ -264,7 +264,7 @@ namespace Options
} }
else if (var == "controller.0.type") else if (var == "controller.0.type")
{ {
controllers.at(0).type = static_cast<InputDeviceToUse>(std::stoi(value)); controllers.at(0).type = static_cast<InputDevice>(std::stoi(value));
} }
else if (var == "controller.0.button.fire_left") else if (var == "controller.0.button.fire_left")
{ {
@@ -296,7 +296,7 @@ namespace Options
} }
else if (var == "controller.1.type") else if (var == "controller.1.type")
{ {
controllers.at(1).type = static_cast<InputDeviceToUse>(std::stoi(value)); controllers.at(1).type = static_cast<InputDevice>(std::stoi(value));
} }
else if (var == "controller.1.button.fire_left") else if (var == "controller.1.button.fire_left")
{ {
@@ -338,11 +338,11 @@ namespace Options
{ {
if (controller.player_id == player_id) if (controller.player_id == player_id)
{ {
controller.type = InputDeviceToUse::ANY; controller.type = InputDevice::ANY;
} }
else else
{ {
controller.type = InputDeviceToUse::CONTROLLER; controller.type = InputDevice::CONTROLLER;
} }
} }
} }
@@ -365,7 +365,7 @@ namespace Options
{ {
for (const auto &controller : controllers) for (const auto &controller : controllers)
{ {
if (controller.type == InputDeviceToUse::ANY) if (controller.type == InputDevice::ANY)
{ {
return controller.player_id; return controller.player_id;
} }

View File

@@ -143,7 +143,7 @@ namespace Options
{ {
int index; // Índice en el vector de mandos int index; // Índice en el vector de mandos
int player_id; // Jugador asociado al mando int player_id; // Jugador asociado al mando
InputDeviceToUse type; // Indica si se usará teclado, mando o ambos InputDevice type; // Indica si se usará teclado, mando o ambos
std::string name; // Nombre del dispositivo std::string name; // Nombre del dispositivo
bool plugged; // Indica si el mando está conectado bool plugged; // Indica si el mando está conectado
std::vector<InputAction> inputs; // Listado de acciones asignadas std::vector<InputAction> inputs; // Listado de acciones asignadas
@@ -153,7 +153,7 @@ namespace Options
GamepadOptions() GamepadOptions()
: index(INVALID_INDEX), : index(INVALID_INDEX),
player_id(INVALID_INDEX), player_id(INVALID_INDEX),
type(InputDeviceToUse::CONTROLLER), type(InputDevice::CONTROLLER),
name(), name(),
plugged(false), plugged(false),
inputs{ inputs{

View File

@@ -27,6 +27,7 @@
#include "tiled_bg.h" // Para TiledBG, TiledBGMode #include "tiled_bg.h" // Para TiledBG, TiledBGMode
#include "utils.h" // Para Color, Zone, shdw_txt_color, no_color #include "utils.h" // Para Color, Zone, shdw_txt_color, no_color
#include "ui/service_menu.h" #include "ui/service_menu.h"
#include "input.h"
// Textos // Textos
constexpr const char TEXT_COPYRIGHT[] = "@2020,2025 JailDesigner"; constexpr const char TEXT_COPYRIGHT[] = "@2020,2025 JailDesigner";
@@ -141,10 +142,12 @@ void Credits::checkEvents()
// Comprueba las entradas // Comprueba las entradas
void Credits::checkInput() void Credits::checkInput()
{ {
Input::get()->update();
if (!ServiceMenu::get()->isEnabled()) if (!ServiceMenu::get()->isEnabled())
{ {
// Comprueba si se ha pulsado cualquier botón (de los usados para jugar) // Comprueba si se ha pulsado cualquier botón (de los usados para jugar)
if (Input::get()->checkAnyButtonPressed(INPUT_ALLOW_REPEAT)) if (Input::get()->checkAnyButton(INPUT_ALLOW_REPEAT))
{ {
want_to_pass_ = true; want_to_pass_ = true;
fading_ = mini_logo_on_position_; fading_ = mini_logo_on_position_;

View File

@@ -1330,6 +1330,8 @@ int Game::getController(int player_id)
// Gestiona la entrada durante el juego // Gestiona la entrada durante el juego
void Game::checkInput() void Game::checkInput()
{ {
Input::get()->update();
// Comprueba las entradas si no está el menú de servicio activo // Comprueba las entradas si no está el menú de servicio activo
if (!ServiceMenu::get()->isEnabled()) if (!ServiceMenu::get()->isEnabled())
{ {
@@ -1353,8 +1355,7 @@ void Game::checkPauseInput()
// Comprueba los mandos // Comprueba los mandos
for (int i = 0; i < input_->getNumControllers(); ++i) for (int i = 0; i < input_->getNumControllers(); ++i)
{ {
if (input_->checkInput(InputAction::SERVICE, INPUT_ALLOW_REPEAT, InputDeviceToUse::CONTROLLER, i) && if (input_->checkInput(InputAction::PAUSE, INPUT_DO_NOT_ALLOW_REPEAT, InputDevice::CONTROLLER, i))
input_->checkInput(InputAction::PAUSE, INPUT_DO_NOT_ALLOW_REPEAT, InputDeviceToUse::CONTROLLER, i))
{ {
pause(!paused_); pause(!paused_);
return; return;
@@ -1362,7 +1363,7 @@ void Game::checkPauseInput()
} }
// Comprueba el teclado // Comprueba el teclado
if (input_->checkInput(InputAction::PAUSE, INPUT_DO_NOT_ALLOW_REPEAT, InputDeviceToUse::KEYBOARD)) if (input_->checkInput(InputAction::PAUSE, INPUT_DO_NOT_ALLOW_REPEAT, InputDevice::KEYBOARD))
{ {
pause(!paused_); pause(!paused_);
return; return;
@@ -1372,7 +1373,7 @@ void Game::checkPauseInput()
// Gestiona las entradas de los jugadores en el modo demo para saltarse la demo. // Gestiona las entradas de los jugadores en el modo demo para saltarse la demo.
void Game::DEMO_handlePassInput() void Game::DEMO_handlePassInput()
{ {
if (input_->checkAnyButtonPressed()) if (input_->checkAnyButton())
{ {
Section::name = Section::Name::TITLE; // Salir del modo demo y regresar al menú principal. Section::name = Section::Name::TITLE; // Salir del modo demo y regresar al menú principal.
Section::attract_mode = Section::AttractMode::TITLE_TO_DEMO; // El juego volverá a mostrar la demo Section::attract_mode = Section::AttractMode::TITLE_TO_DEMO; // El juego volverá a mostrar la demo

View File

@@ -25,6 +25,7 @@
#include "text.h" // Para Text, TEXT_SHADOW, TEXT_COLOR #include "text.h" // Para Text, TEXT_SHADOW, TEXT_COLOR
#include "texture.h" // Para Texture #include "texture.h" // Para Texture
#include "utils.h" // Para Color, easeOutQuint, fade_color, Zone #include "utils.h" // Para Color, easeOutQuint, fade_color, Zone
#include "input.h"
// Constructor // Constructor
HiScoreTable::HiScoreTable() HiScoreTable::HiScoreTable()
@@ -142,7 +143,11 @@ void HiScoreTable::checkEvents()
} }
// Comprueba las entradas // Comprueba las entradas
void HiScoreTable::checkInput() { GlobalInputs::check(); } void HiScoreTable::checkInput()
{
Input::get()->update();
GlobalInputs::check();
}
// Bucle para la pantalla de instrucciones // Bucle para la pantalla de instrucciones
void HiScoreTable::run() void HiScoreTable::run()

View File

@@ -20,6 +20,7 @@
#include "text.h" // Para Text, TEXT_CENTER, TEXT_COLOR, TEXT_... #include "text.h" // Para Text, TEXT_CENTER, TEXT_COLOR, TEXT_...
#include "tiled_bg.h" // Para TiledBG, TiledBGMode #include "tiled_bg.h" // Para TiledBG, TiledBGMode
#include "utils.h" // Para Color, shdw_txt_color, Zone, no_color #include "utils.h" // Para Color, shdw_txt_color, Zone, no_color
#include "input.h"
// Constructor // Constructor
Instructions::Instructions() Instructions::Instructions()
@@ -273,7 +274,11 @@ void Instructions::checkEvents()
} }
// Comprueba las entradas // Comprueba las entradas
void Instructions::checkInput() { GlobalInputs::check(); } void Instructions::checkInput()
{
Input::get()->update();
GlobalInputs::check();
}
// Bucle para la pantalla de instrucciones // Bucle para la pantalla de instrucciones
void Instructions::run() void Instructions::run()

View File

@@ -22,6 +22,7 @@
#include "tiled_bg.h" // Para TiledBG, TiledBGMode #include "tiled_bg.h" // Para TiledBG, TiledBGMode
#include "utils.h" // Para Color, Zone, easeOutQuint, BLOCK #include "utils.h" // Para Color, Zone, easeOutQuint, BLOCK
#include "writer.h" // Para Writer #include "writer.h" // Para Writer
#include "input.h"
// Constructor // Constructor
Intro::Intro() Intro::Intro()
@@ -53,7 +54,11 @@ void Intro::checkEvents()
} }
// Comprueba las entradas // Comprueba las entradas
void Intro::checkInput() { GlobalInputs::check(); } void Intro::checkInput()
{
Input::get()->update();
GlobalInputs::check();
}
// Actualiza las escenas de la intro // Actualiza las escenas de la intro
void Intro::updateScenes() void Intro::updateScenes()

View File

@@ -12,6 +12,7 @@
#include "sprite.h" // Para Sprite #include "sprite.h" // Para Sprite
#include "texture.h" // Para Texture #include "texture.h" // Para Texture
#include "utils.h" // Para Color, Zone #include "utils.h" // Para Color, Zone
#include "input.h"
// Constructor // Constructor
Logo::Logo() Logo::Logo()
@@ -74,7 +75,11 @@ void Logo::checkEvents()
} }
// Comprueba las entradas // Comprueba las entradas
void Logo::checkInput() { GlobalInputs::check(); } void Logo::checkInput()
{
Input::get()->update();
GlobalInputs::check();
}
// Gestiona el logo de JAILGAMES // Gestiona el logo de JAILGAMES
void Logo::updateJAILGAMES() void Logo::updateJAILGAMES()

View File

@@ -64,16 +64,10 @@ void Title::update()
{ {
if (SDL_GetTicks() - ticks_ > param.game.speed) if (SDL_GetTicks() - ticks_ > param.game.speed)
{ {
// Actualiza el contador de ticks_
ticks_ = SDL_GetTicks(); ticks_ = SDL_GetTicks();
// Actualiza el fade
updateFade(); updateFade();
// Actualiza el estado
updateState(); updateState();
updateStartPrompt();
// Actualiza el objeto screen
Screen::get()->update(); Screen::get()->update();
} }
} }
@@ -81,20 +75,12 @@ void Title::update()
// Dibuja el objeto en pantalla // Dibuja el objeto en pantalla
void Title::render() void Title::render()
{ {
// Prepara para empezar a dibujar en la textura de juego
Screen::get()->start(); Screen::get()->start();
// Limpia la pantalla
Screen::get()->clean(); Screen::get()->clean();
// Dibuja el mosacico de fondo
tiled_bg_->render(); tiled_bg_->render();
// Dibuja el logo con el título del juego
game_logo_->render(); game_logo_->render();
constexpr Color shadow = Color(0x14, 0x87, 0xc4);
if (state_ != TitleState::LOGO_ANIMATING) if (state_ != TitleState::LOGO_ANIMATING)
{ {
// Mini logo // Mini logo
@@ -104,34 +90,13 @@ void Title::render()
mini_logo_sprite_->render(); mini_logo_sprite_->render();
// Texto con el copyright // Texto con el copyright
text_->writeDX(TEXT_CENTER | TEXT_SHADOW, param.game.game_area.center_x, pos2, TEXT_COPYRIGHT, 1, NO_TEXT_COLOR, 1, shadow); text_->writeDX(TEXT_CENTER | TEXT_SHADOW, param.game.game_area.center_x, pos2, TEXT_COPYRIGHT, 1, NO_TEXT_COLOR, 1, TITLE_SHADOW_TEXT_COLOR);
} }
if (state_ == TitleState::LOGO_FINISHED) renderStartPrompt();
{
// 'PRESS TO PLAY'
if (counter_ % 50 > 14 && !define_buttons_->isEnabled())
{
text_->writeDX(TEXT_CENTER | TEXT_SHADOW, param.game.game_area.center_x, param.title.press_start_position, Lang::getText("[TITLE] PRESS_BUTTON_TO_PLAY"), 1, NO_TEXT_COLOR, 1, shadow);
}
}
if (state_ == TitleState::START_HAS_BEEN_PRESSED)
{
// 'PRESS TO PLAY'
if (counter_ % 10 > 4 && !define_buttons_->isEnabled())
{
text_->writeDX(TEXT_CENTER | TEXT_SHADOW, param.game.game_area.center_x, param.title.press_start_position, Lang::getText("[TITLE] PRESS_BUTTON_TO_PLAY"), 1, NO_TEXT_COLOR, 1, shadow);
}
}
// Define Buttons
define_buttons_->render(); define_buttons_->render();
// Fade
fade_->render(); fade_->render();
// Vuelca el contenido del renderizador en pantalla
Screen::get()->render(); Screen::get()->render();
} }
@@ -180,6 +145,8 @@ void Title::checkEvents()
// Comprueba las entradas // Comprueba las entradas
void Title::checkInput() void Title::checkInput()
{ {
Input::get()->update();
if (!ServiceMenu::get()->isEnabled()) if (!ServiceMenu::get()->isEnabled())
{ {
// Comprueba las entradas solo si no se estan definiendo los botones // Comprueba las entradas solo si no se estan definiendo los botones
@@ -364,4 +331,50 @@ void Title::updateState()
default: default:
break; break;
} }
}
void Title::updateStartPrompt()
{
constexpr Uint32 LOGO_BLINK_PERIOD = 833; // milisegundos
constexpr Uint32 LOGO_BLINK_ON_TIME = 583; // 833 - 250
constexpr Uint32 START_BLINK_PERIOD = 167;
constexpr Uint32 START_BLINK_ON_TIME = 83; // 167 - 83
Uint32 time_ms = SDL_GetTicks();
bool condition_met = false;
if (!define_buttons_->isEnabled())
{
switch (state_)
{
case TitleState::LOGO_FINISHED:
condition_met = (time_ms % LOGO_BLINK_PERIOD) >= (LOGO_BLINK_PERIOD - LOGO_BLINK_ON_TIME);
break;
case TitleState::START_HAS_BEEN_PRESSED:
condition_met = (time_ms % START_BLINK_PERIOD) >= (START_BLINK_PERIOD - START_BLINK_ON_TIME);
break;
default:
break;
}
}
should_render_start_prompt = condition_met;
}
void Title::renderStartPrompt()
{
if (should_render_start_prompt)
{
text_->writeDX(TEXT_CENTER | TEXT_SHADOW,
param.game.game_area.center_x,
param.title.press_start_position,
Lang::getText("[TITLE] PRESS_BUTTON_TO_PLAY"),
1,
NO_TEXT_COLOR,
1,
TITLE_SHADOW_TEXT_COLOR);
}
} }

View File

@@ -58,6 +58,7 @@ private:
Section::Options selection_ = Section::Options::TITLE_TIME_OUT; // Opción elegida en el título Section::Options selection_ = Section::Options::TITLE_TIME_OUT; // Opción elegida en el título
int num_controllers_; // Número de mandos conectados int num_controllers_; // Número de mandos conectados
TitleState state_; // Estado actual de la sección TitleState state_; // Estado actual de la sección
bool should_render_start_prompt = false; // Indica si se muestra o no el texto de PRESS START BUTTON TO PLAY
// --- Métodos internos --- // --- Métodos internos ---
void update(); // Actualiza las variables del objeto void update(); // Actualiza las variables del objeto
@@ -70,4 +71,6 @@ private:
void showControllers(); // Muestra información sobre los controles y los jugadores void showControllers(); // Muestra información sobre los controles y los jugadores
void updateFade(); // Actualiza el fade void updateFade(); // Actualiza el fade
void updateState(); // Actualiza el estado void updateState(); // Actualiza el estado
void updateStartPrompt();
void renderStartPrompt();
}; };

View File

@@ -61,38 +61,43 @@ struct Color
} }
// Método estático para crear Color desde string hexadecimal // Método estático para crear Color desde string hexadecimal
static Color fromHex(const std::string& hexStr) static Color fromHex(const std::string &hexStr)
{ {
std::string hex = hexStr; std::string hex = hexStr;
// Quitar '#' si existe // Quitar '#' si existe
if (!hex.empty() && hex[0] == '#') { if (!hex.empty() && hex[0] == '#')
{
hex = hex.substr(1); hex = hex.substr(1);
} }
// Verificar longitud válida (6 para RGB o 8 para RGBA) // Verificar longitud válida (6 para RGB o 8 para RGBA)
if (hex.length() != 6 && hex.length() != 8) { if (hex.length() != 6 && hex.length() != 8)
{
throw std::invalid_argument("String hexadecimal debe tener 6 o 8 caracteres"); throw std::invalid_argument("String hexadecimal debe tener 6 o 8 caracteres");
} }
// Verificar que todos los caracteres sean hexadecimales válidos // Verificar que todos los caracteres sean hexadecimales válidos
for (char c : hex) { for (char c : hex)
if (!std::isxdigit(c)) { {
if (!std::isxdigit(c))
{
throw std::invalid_argument("String contiene caracteres no hexadecimales"); throw std::invalid_argument("String contiene caracteres no hexadecimales");
} }
} }
// Convertir cada par de caracteres a valores RGB(A) // Convertir cada par de caracteres a valores RGB(A)
Uint8 r = static_cast<Uint8>(std::stoi(hex.substr(0, 2), nullptr, 16)); Uint8 r = static_cast<Uint8>(std::stoi(hex.substr(0, 2), nullptr, 16));
Uint8 g = static_cast<Uint8>(std::stoi(hex.substr(2, 2), nullptr, 16)); Uint8 g = static_cast<Uint8>(std::stoi(hex.substr(2, 2), nullptr, 16));
Uint8 b = static_cast<Uint8>(std::stoi(hex.substr(4, 2), nullptr, 16)); Uint8 b = static_cast<Uint8>(std::stoi(hex.substr(4, 2), nullptr, 16));
Uint8 a = 255; // Alpha por defecto Uint8 a = 255; // Alpha por defecto
// Si tiene 8 caracteres, extraer el alpha // Si tiene 8 caracteres, extraer el alpha
if (hex.length() == 8) { if (hex.length() == 8)
{
a = static_cast<Uint8>(std::stoi(hex.substr(6, 2), nullptr, 16)); a = static_cast<Uint8>(std::stoi(hex.substr(6, 2), nullptr, 16));
} }
return Color(r, g, b, a); return Color(r, g, b, a);
} }
}; };
@@ -106,14 +111,13 @@ struct HSV
// Estructura para definir el ciclo de color // Estructura para definir el ciclo de color
enum class ColorCycleStyle enum class ColorCycleStyle
{ {
SubtlePulse, // Variación leve en brillo (por defecto) SubtlePulse, // Variación leve en brillo (por defecto)
HueWave, // Variación suave en tono (sin verde) HueWave, // Variación suave en tono (sin verde)
Vibrant, // Cambios agresivos en tono y brillo Vibrant, // Cambios agresivos en tono y brillo
DarkenGlow, // Oscurece hacia el centro y regresa DarkenGlow, // Oscurece hacia el centro y regresa
LightFlash // Ilumina hacia el centro y regresa LightFlash // Ilumina hacia el centro y regresa
}; };
// Posiciones de las notificaciones // Posiciones de las notificaciones
enum class NotifyPosition enum class NotifyPosition
{ {
@@ -173,6 +177,7 @@ using ColorCycle = std::array<Color, 2 * COLOR_CYCLE_SIZE>;
// Colores // Colores
constexpr Color NO_TEXT_COLOR = Color(0XFF, 0XFF, 0XFF); constexpr Color NO_TEXT_COLOR = Color(0XFF, 0XFF, 0XFF);
constexpr Color SHADOW_TEXT_COLOR = Color(0X43, 0X43, 0X4F); constexpr Color SHADOW_TEXT_COLOR = Color(0X43, 0X43, 0X4F);
constexpr Color TITLE_SHADOW_TEXT_COLOR = Color(0x14, 0x87, 0xc4);
constexpr Color FLASH_COLOR = Color(0XFF, 0XFF, 0XFF); constexpr Color FLASH_COLOR = Color(0XFF, 0XFF, 0XFF);