diff --git a/CMakeLists.txt b/CMakeLists.txt index 25f0972..7108df2 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -15,7 +15,7 @@ option(BGE_SANITIZE "Compilar con AddressSanitizer/UBSan (solo nativo)" OFF) add_library(nucleo STATIC src/Ventana.cpp src/NucleoMotor.cpp src/Dibujante.cpp src/Textura.cpp src/Jugador.cpp src/Obstaculos.cpp src/Partida.cpp src/Hud.cpp - src/Escenario.cpp src/Efectos.cpp src/Sonido.cpp) + src/Escenario.cpp src/Efectos.cpp src/Sonido.cpp src/ControlTactil.cpp) target_include_directories(nucleo PUBLIC src) if(EMSCRIPTEN) @@ -93,5 +93,9 @@ if(NOT EMSCRIPTEN) target_compile_definitions(test_efectos PRIVATE BGE_ASSETS_DIR="${CMAKE_SOURCE_DIR}/assets") add_test(NAME qa_runner_modulo_4 COMMAND test_efectos) - set_tests_properties(qa_modulos_1_2 qa_modulo_3 qa_runner_modulos_1_2 qa_runner_modulo_3 qa_runner_modulo_4 PROPERTIES ENVIRONMENT "${BGE_TEST_ENV}") + add_executable(test_tactil tests/test_tactil.cpp) + target_link_libraries(test_tactil PRIVATE nucleo) + add_test(NAME qa_runner_modulo_5 COMMAND test_tactil) + + set_tests_properties(qa_modulos_1_2 qa_modulo_3 qa_runner_modulos_1_2 qa_runner_modulo_3 qa_runner_modulo_4 qa_runner_modulo_5 PROPERTIES ENVIRONMENT "${BGE_TEST_ENV}") endif() diff --git a/README.md b/README.md index 6f62a04..7ca267c 100644 --- a/README.md +++ b/README.md @@ -26,8 +26,14 @@ velocidad aumenta con el tiempo. En la web es el `index.html` publicado. | R3.1/3.2. Obstáculos y colisión AABB | `src/Obstaculos.*`, `src/Partida.*` — generación aleatoria (con semilla), destrucción fuera de pantalla, GAME OVER | `tests/test_partida.cpp` (3.1, 3.2) | | R3.3. HUD | `src/Hud.*` — puntos, mejor puntuación, velocidad y mensajes con `Dibujante::Texto` | `tests/test_partida.cpp` (3.3) | | R4. Mundo, efectos y sonido | `src/Paleta.h` (colores del avatar), `src/Escenario.*` (parallax), `src/Efectos.*` (partículas, sacudida), `src/Sonido.*` (audio sintetizado) | `tests/test_efectos.cpp` (4.1–4.5) | +| R5. Móvil | `src/ControlTactil.*` (toques → saltar / sonido), dedos en `src/Ventana.*`, HUD tactil, `web/minimal_shell.html` responsive | `tests/test_tactil.cpp` (5.1–5.4) | | R3.4. Assets web | `CMakeLists.txt` — `--preload-file assets@/assets` empaqueta `assets/` en `index.data` | CI (3.4) | +**Móvil:** tocar la pantalla salta (y reinicia tras GAME OVER); un toque justo antes de aterrizar encadena el +siguiente salto (buffer de 0,1 s). Un botón grande «SONIDO SI/NO» sustituye a la tecla M. Los textos pasan a +«TOCA…» al detectar un móvil o el primer toque. La página usa toda la pantalla, sin zoom ni desplazamiento, con +botón de pantalla completa (Android/tablets; iPhone no lo permite en webs) y un aviso para girar el móvil. + **Sonido:** sin archivos de audio. Los efectos (salto, aterrizaje, golpe, hito cada 100 puntos, inicio) y una música en bucle de 4 s se sintetizan al arrancar con SDL2 puro (`Sintesis`/`Mezclador`/`Sonido`). Sin dispositivo de audio el juego sigue mudo. En el navegador el audio empieza tras la primera pulsación de tecla o clic. diff --git a/src/ControlTactil.cpp b/src/ControlTactil.cpp new file mode 100644 index 0000000..21f3dc1 --- /dev/null +++ b/src/ControlTactil.cpp @@ -0,0 +1,21 @@ +//------------------------------------------------------------------------------------ +// ControlTactil.cpp +//------------------------------------------------------------------------------------ +#include "ControlTactil.h" + +SalidaTactil ControlTactil::Actualizar(const std::vector& activos, const std::vector& nuevos) noexcept +{ + SalidaTactil s; + for (const SDL_Point& p : nuevos) + { + if (EnBoton(p.x, p.y)) s.alternarSonido = true; + else m_buffer = m_ticsBuffer; // toque de juego: salto "pendiente" + } + + bool apoyado = false; // dedo mantenido fuera del boton + for (const Toque& t : activos) if (!EnBoton(t.x, t.y)) { apoyado = true; break; } + + s.saltar = apoyado || m_buffer > 0; + if (m_buffer > 0) --m_buffer; + return s; +} diff --git a/src/ControlTactil.h b/src/ControlTactil.h new file mode 100644 index 0000000..1b57a4e --- /dev/null +++ b/src/ControlTactil.h @@ -0,0 +1,50 @@ +//------------------------------------------------------------------------------------ +// ControlTactil (Juego Runner - Modulo 5: control para movil) +// Encabezado C++ - ControlTactil.h +//------------------------------------------------------------------------------------ +// Traduce los dedos de la pantalla en las dos ordenes del juego, sin depender de SDL +// ni del renderizador (se prueba inyectando toques): +// - Tocar en cualquier parte -> saltar (y reiniciar tras GAME OVER). +// - Tocar el boton de sonido -> alternar sonido; ese toque NO salta. +// "Buffer de salto": un toque mantiene la orden activa unos tics (por defecto 6 = 0,1 s), +// asi tocar un instante ANTES de aterrizar tambien salta al tocar el suelo, como pide un +// juego tactil. Un dedo que se mantiene apoyado mantiene el salto (igual que mantener la +// barra espaciadora). +//------------------------------------------------------------------------------------ +#pragma once + +#include "Ventana.h" + +#include + +#include + +struct SalidaTactil +{ + bool saltar = false; + bool alternarSonido = false; // flanco: true solo en el tic del toque +}; + +class ControlTactil +{ +public: + explicit ControlTactil(const SDL_Rect& botonSonido, int ticsBuffer = 6) noexcept + : m_boton(botonSonido), m_ticsBuffer(ticsBuffer) {} + + // Un tic de logica. 'nuevos' = TomarToquesNuevos(); 'activos' = ToquesActivos(). + SalidaTactil Actualizar(const std::vector& activos, const std::vector& nuevos) noexcept; + + // Olvida el salto pendiente (p. ej. al reiniciar la partida) + void Cancelar() noexcept { m_buffer = 0; } + + bool EnBoton(int x, int y) const noexcept + { + const SDL_Point p{ x, y }; + return SDL_PointInRect(&p, &m_boton) == SDL_TRUE; + } + +private: + SDL_Rect m_boton; + int m_ticsBuffer; + int m_buffer = 0; +}; diff --git a/src/Hud.cpp b/src/Hud.cpp index 434be19..9261990 100644 --- a/src/Hud.cpp +++ b/src/Hud.cpp @@ -26,6 +26,18 @@ std::string TextoVelocidad(const Partida& p) return b; } +std::string TextoInstrucciones(bool tactil) +{ + return tactil ? "TOCA LA PANTALLA PARA SALTAR" : "ESPACIO / FLECHA ARRIBA: SALTAR"; +} +std::string TextoReinicio(bool tactil) { return tactil ? "TOCA PARA REINICIAR" : "ESPACIO: REINICIAR"; } + +SDL_Rect RectBotonSonido(int ancho, int alto) +{ + // 132x56: tras escalar el lienzo 640x480 a un movil sigue siendo comodo de pulsar + return SDL_Rect{ ancho - 142, alto - 66, 132, 56 }; +} + int TextoSombra(const Dibujante& d, int x, int y, const std::string& t, Color c, int escala) { d.Texto(x + escala, y + escala, t, Paleta::TextoSombra, escala); @@ -40,19 +52,32 @@ void Pintar(const Dibujante& d, const Partida& p, int ancho, int alto, const Opc const std::string mejor = TextoMejor(p); TextoSombra(d, ancho - 10 - Dibujante::AnchoTexto(mejor, 2), 8, mejor, Paleta::Dorado, 2); - const std::string sonido = op.sonidoActivo ? "M: SONIDO SI" : "M: SONIDO NO"; - TextoSombra(d, ancho - 8 - Dibujante::AnchoTexto(sonido, 1), alto - 14, sonido, Paleta::TextoClaro, 1); + if (op.tactil) + { + const SDL_Rect b = RectBotonSonido(ancho, alto); + d.RectanguloRelleno(b, Paleta::Contorno); + d.RectanguloRelleno(SDL_Rect{ b.x + 3, b.y + 3, b.w - 6, b.h - 6 }, Paleta::SueloOscuro); + d.Rectangulo(SDL_Rect{ b.x + 3, b.y + 3, b.w - 6, b.h - 6 }, op.sonidoActivo ? Paleta::HierbaClara : Paleta::BugSombra); + const std::string t1 = "SONIDO", t2 = op.sonidoActivo ? "SI" : "NO"; + d.Texto(b.x + (b.w - Dibujante::AnchoTexto(t1, 2)) / 2, b.y + 10, t1, Paleta::TextoClaro, 2); + d.Texto(b.x + (b.w - Dibujante::AnchoTexto(t2, 2)) / 2, b.y + 32, t2, op.sonidoActivo ? Paleta::Verde : Paleta::BugCuerpo, 2); + } + else + { + const std::string sonido = op.sonidoActivo ? "M: SONIDO SI" : "M: SONIDO NO"; + TextoSombra(d, ancho - 8 - Dibujante::AnchoTexto(sonido, 1), alto - 14, sonido, Paleta::TextoClaro, 1); + } if (p.Estado() == EstadoPartida::GameOver) { const std::string t1 = "GAME OVER"; - const std::string t2 = "ESPACIO: REINICIAR"; + const std::string t2 = TextoReinicio(op.tactil); TextoSombra(d, (ancho - Dibujante::AnchoTexto(t1, 5)) / 2, alto / 2 - 60, t1, Paleta::BugCuerpo, 5); TextoSombra(d, (ancho - Dibujante::AnchoTexto(t2, 2)) / 2, alto / 2 - 10, t2, Paleta::TextoClaro, 2); } else if (p.Puntos() < 40) // instrucciones al empezar (~1,3 s) { - const std::string t = "ESPACIO / FLECHA ARRIBA: SALTAR"; + const std::string t = TextoInstrucciones(op.tactil); TextoSombra(d, (ancho - Dibujante::AnchoTexto(t, 2)) / 2, alto / 2 - 60, t, Paleta::TextoClaro, 2); } } diff --git a/src/Hud.h b/src/Hud.h index abf3729..4e07692 100644 --- a/src/Hud.h +++ b/src/Hud.h @@ -27,8 +27,17 @@ namespace Hud { bool sonidoActivo = true; // indicador "M: SONIDO" bool resaltarPuntos = false; // la puntuacion brilla un instante al superar un hito + bool tactil = false; // movil: textos de toque y boton de sonido grande }; + // Textos segun el dispositivo de entrada + std::string TextoInstrucciones(bool tactil); // "TOCA LA PANTALLA PARA SALTAR" / "ESPACIO / FLECHA ARRIBA: SALTAR" + std::string TextoReinicio(bool tactil); // "TOCA PARA REINICIAR" / "ESPACIO: REINICIAR" + + // Boton de sonido tactil (esquina inferior derecha, sobre el suelo). Es la UNICA fuente + // de verdad: el HUD lo dibuja y ControlTactil lo usa para detectar el toque. + SDL_Rect RectBotonSonido(int ancho, int alto); + // Texto con sombra (legible sobre el degradado del cielo) int TextoSombra(const Dibujante& d, int x, int y, const std::string& t, Color c, int escala); diff --git a/src/Ventana.cpp b/src/Ventana.cpp index 7eaf0ac..cac21e3 100644 --- a/src/Ventana.cpp +++ b/src/Ventana.cpp @@ -4,6 +4,8 @@ //------------------------------------------------------------------------------------ #include "Ventana.h" +#include +#include #include //------------------------------------------------------------------------------------ @@ -11,6 +13,8 @@ //------------------------------------------------------------------------------------ Ventana::ContextoSdl::ContextoSdl() { + // Los dedos se tratan como dedos (SDL_FINGER*), sin duplicarlos como clics de raton + SDL_SetHint(SDL_HINT_TOUCH_MOUSE_EVENTS, "0"); if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_EVENTS) != 0) throw std::runtime_error(std::string("SDL_Init fallo: ") + SDL_GetError()); } @@ -88,7 +92,32 @@ EventosFrame Ventana::ProcesarEventos() } break; + case SDL_FINGERDOWN: + case SDL_FINGERMOTION: + case SDL_FINGERUP: + { + m_entradaTactil = true; + const int x = static_cast(std::lround(e.tfinger.x * m_config.ancho)); + const int y = static_cast(std::lround(e.tfinger.y * m_config.altura)); + const std::int64_t id = e.tfinger.fingerId; + auto it = std::find_if(m_toques.begin(), m_toques.end(), [id](const Toque& t) { return t.id == id; }); + if (e.type == SDL_FINGERUP) + { + if (it != m_toques.end()) m_toques.erase(it); + break; + } + if (it != m_toques.end()) { it->x = x; it->y = y; } + else if (m_toques.size() < kMaxToques) m_toques.push_back(Toque{ id, x, y }); + if (e.type == SDL_FINGERDOWN) + { + if (m_toquesNuevos.size() >= 16) m_toquesNuevos.erase(m_toquesNuevos.begin()); // acotado + m_toquesNuevos.push_back(SDL_Point{ x, y }); + } + break; + } + case SDL_KEYDOWN: + m_entradaTactil = false; if (m_config.escSale && e.key.keysym.scancode == SDL_SCANCODE_ESCAPE) resultado.salir = true; if (e.key.keysym.scancode < SDL_NUM_SCANCODES) @@ -138,8 +167,17 @@ bool Ventana::BotonRaton(std::uint8_t boton) const noexcept return (m_botonesRaton & SDL_BUTTON(boton)) != 0; } +std::vector Ventana::TomarToquesNuevos() +{ + std::vector r; + r.swap(m_toquesNuevos); + return r; +} + void Ventana::LiberarEntrada() noexcept { + m_toques.clear(); + m_toquesNuevos.clear(); m_teclas.fill(false); m_botonesRaton = 0; } diff --git a/src/Ventana.h b/src/Ventana.h index 2e7097b..08f88ae 100644 --- a/src/Ventana.h +++ b/src/Ventana.h @@ -15,6 +15,7 @@ #include #include #include +#include //------------------------------------------------------------------------------------ // Configuracion de la ventana @@ -36,6 +37,15 @@ struct EventosFrame bool salir = false; // SDL_QUIT, cierre de ventana o tecla ESC }; +//------------------------------------------------------------------------------------ +// Dedo apoyado en la pantalla (coordenadas en pixeles de la ventana) +//------------------------------------------------------------------------------------ +struct Toque +{ + std::int64_t id = 0; + int x = 0, y = 0; +}; + //------------------------------------------------------------------------------------ // Clase Ventana //------------------------------------------------------------------------------------ @@ -73,6 +83,18 @@ class Ventana int RatonX() const noexcept { return m_ratonX; } int RatonY() const noexcept { return m_ratonY; } + // Pantalla tactil. Los dedos NO generan eventos de raton (SDL_HINT_TOUCH_MOUSE_EVENTS=0). + // - ToquesActivos: dedos apoyados ahora mismo (maximo kMaxToques). + // - TomarToquesNuevos: posiciones donde se POSO un dedo desde la ultima llamada. Se + // conservan hasta que alguien los toma, asi un toque rapido (poner y quitar el dedo + // entre dos tics de logica) no se pierde nunca. + // - UltimaEntradaTactil: true si lo ultimo que uso el jugador fue un dedo (false: teclado). + static constexpr std::size_t kMaxToques = 10; + const std::vector& ToquesActivos() const noexcept { return m_toques; } + std::vector TomarToquesNuevos(); + bool UltimaEntradaTactil() const noexcept { return m_entradaTactil; } + void MarcarEntradaTactil(bool tactil) noexcept { m_entradaTactil = tactil; } // p. ej. al detectar un movil + private: // Subsistema SDL: se declara primero para destruirse el ultimo struct ContextoSdl @@ -104,5 +126,8 @@ class Ventana int m_ratonX = 0; int m_ratonY = 0; std::uint32_t m_botonesRaton = 0; + std::vector m_toques; + std::vector m_toquesNuevos; + bool m_entradaTactil = false; std::array m_teclas{}; }; diff --git a/src/runner.cpp b/src/runner.cpp index 7bc20b6..56f5d12 100644 --- a/src/runner.cpp +++ b/src/runner.cpp @@ -1,10 +1,12 @@ //------------------------------------------------------------------------------------ // runner.cpp - Juego Runner completo (nativo y Emscripten) -// ESPACIO / FLECHA ARRIBA: saltar (y reiniciar tras GAME OVER). M: sonido si/no. +// ESPACIO / FLECHA ARRIBA o TOCAR LA PANTALLA: saltar (y reiniciar tras GAME OVER). +// M o el boton tactil: sonido si/no. // Integra Textura (M1), Jugador (M2), Obstaculos/Partida/Hud (M3) y, en el Modulo 4, // Escenario (parallax), Efectos (particulas, sacudida) y Sonido (sintetizado). // La logica (Partida) solo emite EVENTOS; aqui se traducen a sonido y efectos. //------------------------------------------------------------------------------------ +#include "ControlTactil.h" #include "Efectos.h" #include "Escenario.h" #include "Hud.h" @@ -17,6 +19,10 @@ #include #include +#ifdef __EMSCRIPTEN__ +#include +#endif + // Nativo: ruta absoluta inyectada por CMake. Web: --preload-file monta la carpeta // en /assets del sistema de archivos virtual, y el directorio de trabajo es "/". #ifndef BGE_ASSETS_DIR @@ -44,6 +50,12 @@ class JuegoRunner : public Juego m_partida = std::make_unique(cfg, SDL_GetTicks()); // semilla distinta por sesion m_escenario = std::make_unique(cfg.ancho, m_ventana->Altura(), cfg.ySuelo); m_efectos = std::make_unique(cfg.ySuelo, SDL_GetTicks()); + m_tactil = std::make_unique(Hud::RectBotonSonido(cfg.ancho, m_ventana->Altura())); +#ifdef __EMSCRIPTEN__ + // Movil/tablet: se muestran desde el primer frame los textos y el boton tactiles + if (emscripten_run_script_int("(('ontouchstart' in window) || (navigator.maxTouchPoints > 0)) ? 1 : 0")) + m_ventana->MarcarEntradaTactil(true); +#endif return true; } @@ -62,7 +74,11 @@ class JuegoRunner : public Juego if (tecla_m && !m_mPrevia && m_sonido) m_sonido->AlternarSilencio(); m_mPrevia = tecla_m; - m_partida->Actualizar(dt, saltar); + // Pantalla tactil: tocar salta/reinicia; el boton de sonido alterna el audio + const SalidaTactil t = m_tactil->Actualizar(m_ventana->ToquesActivos(), m_ventana->TomarToquesNuevos()); + if (t.alternarSonido && m_sonido) m_sonido->AlternarSilencio(); + + m_partida->Actualizar(dt, saltar || t.saltar); Reaccionar(m_partida->TomarEventos()); const bool jugando = m_partida->Estado() == EstadoPartida::Jugando; @@ -93,7 +109,7 @@ class JuegoRunner : public Juego SDL_RenderSetViewport(r, nullptr); // IMPORTANTE: restaurar para el siguiente frame m_efectos->PintarDestello(d, ancho, alto); Hud::Pintar(d, *m_partida, ancho, alto, - Hud::Opciones{ m_sonido && !m_sonido->Silenciado(), m_resaltado > 0.0 }); + Hud::Opciones{ m_sonido && !m_sonido->Silenciado(), m_resaltado > 0.0, m_ventana->UltimaEntradaTactil() }); } private: @@ -111,7 +127,7 @@ class JuegoRunner : public Juego { const double suelo = m_partida->Config().ySuelo; auto sonar = [&](Efecto e) { if (m_sonido) m_sonido->Reproducir(e); }; - if (ev.reinicio) { sonar(Efecto::Inicio); if (m_sonido) m_sonido->PausarMusica(false); m_efectos->Reiniciar(); } + if (ev.reinicio) { m_tactil->Cancelar(); sonar(Efecto::Inicio); if (m_sonido) m_sonido->PausarMusica(false); m_efectos->Reiniciar(); } if (ev.salto) { sonar(Efecto::Salto); m_efectos->Polvo(PiesX(), suelo, 5); } if (ev.aterrizaje) { sonar(Efecto::Aterrizaje); m_efectos->Polvo(PiesX(), suelo, 9); } if (ev.hitos > 0) { sonar(Efecto::Hito); m_efectos->Chispas(60, 24); m_resaltado = 0.6; } @@ -132,6 +148,7 @@ class JuegoRunner : public Juego std::unique_ptr m_partida; std::unique_ptr m_escenario; std::unique_ptr m_efectos; + std::unique_ptr m_tactil; int m_ticsPolvo = 0; bool m_mPrevia = false; double m_resaltado = 0.0; diff --git a/tests/test_tactil.cpp b/tests/test_tactil.cpp new file mode 100644 index 0000000..d635e1c --- /dev/null +++ b/tests/test_tactil.cpp @@ -0,0 +1,279 @@ +//------------------------------------------------------------------------------------ +// Pruebas de QA del juego Runner - Modulo 5 (control para movil) +// Se ejecutan sin pantalla: SDL_VIDEODRIVER=dummy, SDL_RENDER_DRIVER=software. +// Test 5.1 Ventana: dedos activos, coordenadas, multitoque y toques rapidos +// Test 5.2 ControlTactil: salto, buffer, boton de sonido, dedo mantenido +// Test 5.3 HUD tactil: textos, boton visible y tamano comodo para un dedo +// Test 5.4 Partida jugable solo con toques (saltar, GAME OVER, reiniciar) +//------------------------------------------------------------------------------------ +#include "ControlTactil.h" +#include "Hud.h" +#include "Ventana.h" + +#include +#include +#include + +static int g_fallos = 0; +#define CHECK(cond, msg) \ + do { \ + if (cond) std::printf(" [ OK ] %s\n", msg); \ + else { std::printf(" [FAIL] %s (%s:%d)\n", msg, __FILE__, __LINE__); ++g_fallos; } \ + } while (0) + +namespace +{ +constexpr double kDt = 1.0 / 60.0; +constexpr int kAncho = 640, kAlto = 480; + +void Dedo(Uint32 tipo, std::int64_t id, float x, float y) // coordenadas normalizadas 0..1, como SDL +{ + SDL_Event e{}; + e.type = tipo; + e.tfinger.fingerId = id; + e.tfinger.x = x; e.tfinger.y = y; + SDL_PushEvent(&e); +} +void Tecla(Uint32 tipo, SDL_Scancode sc) +{ + SDL_Event e{}; + e.type = tipo; e.key.keysym.scancode = sc; + SDL_PushEvent(&e); +} + +// ---- Test 5.1 ------------------------------------------------------------------- +void Test_5_1() +{ + std::puts("Test 5.1: Ventana y dedos"); + Ventana v(ConfigVentana{ "tactil", kAncho, kAlto, false, true }); + CHECK(v.ToquesActivos().empty() && v.TomarToquesNuevos().empty() && !v.UltimaEntradaTactil(), "al empezar no hay toques ni modo tactil"); + + Dedo(SDL_FINGERDOWN, 1, 0.5f, 0.25f); + v.ProcesarEventos(); + CHECK(v.ToquesActivos().size() == 1 && v.ToquesActivos()[0].x == 320 && v.ToquesActivos()[0].y == 120, + "un dedo en (0,5; 0,25) se convierte a pixeles de la ventana (320, 120)"); + CHECK(v.UltimaEntradaTactil(), "tocar activa el modo tactil"); + CHECK(!v.BotonRaton(SDL_BUTTON_LEFT), "el dedo no se duplica como clic de raton"); + + Dedo(SDL_FINGERMOTION, 1, 1.0f, 1.0f); + v.ProcesarEventos(); + CHECK(v.ToquesActivos().size() == 1 && v.ToquesActivos()[0].x == 640 && v.ToquesActivos()[0].y == 480, "al arrastrar se actualiza la posicion (sin duplicar el dedo)"); + + Dedo(SDL_FINGERDOWN, 2, 0.1f, 0.1f); + v.ProcesarEventos(); + CHECK(v.ToquesActivos().size() == 2, "multitoque: dos dedos a la vez"); + Dedo(SDL_FINGERUP, 1, 0.0f, 0.0f); + v.ProcesarEventos(); + CHECK(v.ToquesActivos().size() == 1 && v.ToquesActivos()[0].id == 2, "al levantar un dedo solo desaparece ese"); + Dedo(SDL_FINGERUP, 2, 0.0f, 0.0f); + v.ProcesarEventos(); + CHECK(v.ToquesActivos().empty(), "sin dedos, sin toques activos"); + + auto nuevos = v.TomarToquesNuevos(); + CHECK(nuevos.size() == 2 && nuevos[0].x == 320 && nuevos[0].y == 120 && nuevos[1].x == 64 && nuevos[1].y == 48, + "los toques NUEVOS recuerdan donde se poso cada dedo, aunque ya se hayan levantado"); + CHECK(v.TomarToquesNuevos().empty(), "y se consumen: la segunda lectura sale vacia"); + + // Toque rapido: poner y quitar el dedo dentro del mismo frame no se pierde + Dedo(SDL_FINGERDOWN, 7, 0.3f, 0.3f); Dedo(SDL_FINGERUP, 7, 0.3f, 0.3f); + v.ProcesarEventos(); + CHECK(v.ToquesActivos().empty() && v.TomarToquesNuevos().size() == 1, "un toque que empieza y acaba entre dos tics sigue contando"); + + // Acotado: no crece sin limite + for (int i = 0; i < 100; ++i) { Dedo(SDL_FINGERDOWN, 100 + i, 0.5f, 0.5f); Dedo(SDL_FINGERUP, 100 + i, 0.5f, 0.5f); } + v.ProcesarEventos(); + CHECK(v.TomarToquesNuevos().size() <= 16, "la cola de toques nuevos esta acotada (16)"); + for (int i = 0; i < 30; ++i) Dedo(SDL_FINGERDOWN, 200 + i, 0.5f, 0.5f); + v.ProcesarEventos(); + CHECK(v.ToquesActivos().size() <= Ventana::kMaxToques, "los dedos activos estan acotados"); + + // Perder el foco suelta los dedos (evita "dedo pegado") + SDL_Event f{}; f.type = SDL_WINDOWEVENT; f.window.event = SDL_WINDOWEVENT_FOCUS_LOST; SDL_PushEvent(&f); + v.ProcesarEventos(); + CHECK(v.ToquesActivos().empty() && v.TomarToquesNuevos().empty(), "al perder el foco se sueltan todos los dedos"); + + // El teclado devuelve al modo teclado + Tecla(SDL_KEYDOWN, SDL_SCANCODE_SPACE); + v.ProcesarEventos(); + CHECK(!v.UltimaEntradaTactil(), "pulsar una tecla vuelve al modo teclado"); + v.MarcarEntradaTactil(true); + CHECK(v.UltimaEntradaTactil(), "MarcarEntradaTactil permite activar el modo desde fuera (deteccion de movil)"); +} + +// ---- Test 5.2 ------------------------------------------------------------------- +void Test_5_2() +{ + std::puts("Test 5.2: ControlTactil"); + const SDL_Rect boton = Hud::RectBotonSonido(kAncho, kAlto); + const SDL_Point fuera{ 200, 200 }, dentro{ boton.x + boton.w / 2, boton.y + boton.h / 2 }; + const std::vector sinDedos; + + { + ControlTactil c(boton); + auto s = c.Actualizar(sinDedos, {}); + CHECK(!s.saltar && !s.alternarSonido, "sin toques no pasa nada"); + s = c.Actualizar(sinDedos, { fuera }); + CHECK(s.saltar && !s.alternarSonido, "un toque en el juego salta en el mismo tic"); + int tics = 1; + while (c.Actualizar(sinDedos, {}).saltar) ++tics; + CHECK(tics == 6, "el salto pendiente (buffer) dura 6 tics = 0,1 s y luego se apaga"); + } + { + ControlTactil c(boton); + auto s = c.Actualizar(sinDedos, { dentro }); + CHECK(s.alternarSonido && !s.saltar, "tocar el boton de sonido alterna el sonido y NO salta"); + CHECK(!c.Actualizar(sinDedos, {}).alternarSonido, "el cambio de sonido es un flanco: solo en el tic del toque"); + s = c.Actualizar(sinDedos, { dentro, fuera }); + CHECK(s.alternarSonido && s.saltar, "dos dedos a la vez: uno alterna el sonido y el otro salta"); + } + { + ControlTactil c(boton); + const std::vector apoyado{ Toque{ 1, fuera.x, fuera.y } }; + bool siempre = true; + for (int i = 0; i < 120; ++i) siempre = siempre && c.Actualizar(apoyado, {}).saltar; + CHECK(siempre, "un dedo mantenido en el juego mantiene la orden de salto (como mantener la barra)"); + const std::vector enBoton{ Toque{ 1, dentro.x, dentro.y } }; + ControlTactil d(boton); + bool nunca = true; + for (int i = 0; i < 30; ++i) nunca = nunca && !d.Actualizar(enBoton, {}).saltar; + CHECK(nunca, "un dedo apoyado sobre el boton de sonido no provoca saltos"); + } + { + ControlTactil c(boton); + c.Actualizar(sinDedos, { fuera }); + c.Cancelar(); + CHECK(!c.Actualizar(sinDedos, {}).saltar, "Cancelar() borra el salto pendiente (no se salta justo tras reiniciar)"); + } +} + +// ---- Test 5.3 ------------------------------------------------------------------- +std::vector Leer(SDL_Renderer* r) +{ + std::vector px(static_cast(kAncho) * kAlto); + SDL_RenderReadPixels(r, nullptr, SDL_PIXELFORMAT_ARGB8888, px.data(), kAncho * 4); + return px; +} + +void Test_5_3() +{ + std::puts("Test 5.3: HUD tactil"); + CHECK(Hud::TextoInstrucciones(true) != Hud::TextoInstrucciones(false) && Hud::TextoInstrucciones(true).find("TOCA") == 0, + "las instrucciones cambian a 'TOCA...' en el movil"); + CHECK(Hud::TextoInstrucciones(true).find("ESPACIO") == std::string::npos && Hud::TextoReinicio(true).find("ESPACIO") == std::string::npos, + "en el movil no se menciona la barra espaciadora"); + CHECK(Hud::TextoReinicio(true) == "TOCA PARA REINICIAR", "el cartel de GAME OVER pide tocar para reiniciar"); + + // Textos soportados por la fuente bitmap (si no, saldrian huecos) + bool soportado = true; + for (char c : Hud::TextoInstrucciones(true) + Hud::TextoReinicio(true) + "SONIDO SI NO") + if (!((c >= 'A' && c <= 'Z') || c == ' ')) soportado = false; + CHECK(soportado, "todos los textos nuevos usan caracteres de la fuente del motor"); + + const SDL_Rect b = Hud::RectBotonSonido(kAncho, kAlto); + CHECK(b.x >= 0 && b.y >= 0 && b.x + b.w <= kAncho && b.y + b.h <= kAlto, "el boton esta dentro de la pantalla"); + CHECK(b.y >= 400, "y sobre el suelo (no tapa el area de juego)"); + // Tamano comodo: 44 px css es el minimo recomendado. En un movil en horizontal el lienzo 640x480 se + // muestra a ~0,56x (pantalla de 360 px de alto en css) hasta 0,75x: se exige >= 44 css px a 0,75x de escala + std::printf(" boton %dx%d px de lienzo -> %.0fx%.0f px css a escala 0,75\n", b.w, b.h, b.w * 0.75, b.h * 0.75); + CHECK(b.w * 0.75 >= 44 && b.h * 0.75 >= 40, "el boton mide al menos ~44 px css en un movil tipico (objetivo tactil comodo)"); + + Ventana v(ConfigVentana{ "hud-tactil", kAncho, kAlto, false, true }); + SDL_Renderer* r = v.Renderizador(); + Partida p; + auto render = [&](bool tactil, bool sonido) { + Dibujante d(r); d.Limpiar(Colores::Fondo); + Hud::Pintar(d, p, kAncho, kAlto, Hud::Opciones{ sonido, false, tactil }); + return Leer(r); + }; + auto contar = [&](const std::vector& px, const SDL_Rect& rc) { + int n = 0; + for (int y = rc.y; y < rc.y + rc.h; ++y) for (int x = rc.x; x < rc.x + rc.w; ++x) + n += px[static_cast(y) * kAncho + x] != 0xFF000000u + (Colores::Fondo.r << 16 | Colores::Fondo.g << 8 | Colores::Fondo.b); + return n; + }; + const auto tSi = render(true, true), tNo = render(true, false), teclado = render(false, true); + CHECK(contar(tSi, b) > b.w * b.h * 0.9, "el boton tactil se dibuja casi lleno (es una superficie solida y visible)"); + CHECK(tSi != tNo, "el boton cambia de aspecto entre SONIDO SI y SONIDO NO"); + CHECK(contar(teclado, b) < b.w * b.h * 0.2, "en modo teclado no hay boton, solo el texto 'M: SONIDO'"); + CHECK(render(true, true) == tSi, "dibujar dos veces da la misma imagen (sin parpadeo)"); + + p.Obstaculos().Agregar(Obstaculo{ double(p.ElJugador().CajaColision().x), p.Config().ySuelo - 30, 30, 30, 0.0 }); + p.Actualizar(kDt, false); + CHECK(p.Estado() == EstadoPartida::GameOver, "(preparacion) la partida esta en GAME OVER"); + CHECK(render(true, true) != render(false, true), "el cartel de GAME OVER cambia entre tactil y teclado"); +} + +// ---- Test 5.4 ------------------------------------------------------------------- +void Test_5_4() +{ + std::puts("Test 5.4: partida jugable solo con toques"); + const SDL_Rect boton = Hud::RectBotonSonido(kAncho, kAlto); + auto tic = [&](Partida& p, ControlTactil& c, const std::vector& nuevos) { + const auto s = c.Actualizar({}, nuevos); + p.Actualizar(kDt, s.saltar); + if (p.TomarEventos().reinicio) c.Cancelar(); + return s; + }; + Partida p; ControlTactil c(boton); + p.Obstaculos().Reiniciar(); + tic(p, c, {}); + CHECK(p.ElJugador().EnElSuelo(), "en el suelo al empezar"); + tic(p, c, { SDL_Point{ 100, 100 } }); + CHECK(!p.ElJugador().EnElSuelo() && p.ElJugador().Estado() == EstadoJugador::Saltando, "un toque hace saltar al personaje"); + for (int i = 0; i < 120; ++i) { p.Obstaculos().Reiniciar(); tic(p, c, {}); } + CHECK(p.ElJugador().EnElSuelo(), "el personaje aterriza"); + + // Buffer: tocar un poco ANTES de aterrizar encadena un salto al tocar el suelo + Partida q; ControlTactil cq(boton); + for (int i = 0; i < 3; ++i) { q.Obstaculos().Reiniciar(); tic(q, cq, i == 0 ? std::vector{ { 100, 100 } } : std::vector{}); } + int aterrizajes = 0, tics = 0; + bool tocadoAntes = false; + while (tics++ < 200) + { + q.Obstaculos().Reiniciar(); + const bool aPuntoDeAterrizar = q.ElJugador().Estado() == EstadoJugador::Cayendo && q.ElJugador().YPies() > q.Config().ySuelo - 12; + std::vector toque; if (aPuntoDeAterrizar && !tocadoAntes) { toque.push_back({ 100, 100 }); tocadoAntes = true; } + const auto s = cq.Actualizar({}, toque); + const bool enSueloAntes = q.ElJugador().EnElSuelo(); + q.Actualizar(kDt, s.saltar); + const auto ev = q.TomarEventos(); + aterrizajes += ev.aterrizaje; + if (tocadoAntes && !enSueloAntes && ev.aterrizaje) break; + } + bool saltoEncadenado = false; + for (int i = 0; i < 10; ++i) { q.Obstaculos().Reiniciar(); tic(q, cq, {}); if (!q.ElJugador().EnElSuelo()) saltoEncadenado = true; } + CHECK(tocadoAntes && saltoEncadenado, "un toque justo antes de aterrizar encadena otro salto (sensacion tactil fluida)"); + + // GAME OVER y reinicio solo con toques + Partida g; ControlTactil cg(boton); + for (int i = 0; i < 20; ++i) tic(g, cg, {}); + g.Obstaculos().Agregar(Obstaculo{ double(g.ElJugador().CajaColision().x), g.Config().ySuelo - 30, 30, 30, 0.0 }); + tic(g, cg, {}); + CHECK(g.Estado() == EstadoPartida::GameOver, "al chocar: GAME OVER"); + tic(g, cg, { SDL_Point{ 100, 100 } }); + CHECK(g.Estado() == EstadoPartida::GameOver, "un toque desesperado justo tras chocar no reinicia (pausa de 0,5 s)"); + for (int i = 0; i < 40; ++i) tic(g, cg, {}); + tic(g, cg, { SDL_Point{ 100, 100 } }); + CHECK(g.Estado() == EstadoPartida::Jugando && g.Puntos() == 0, "tocar pasado ese tiempo reinicia la partida"); + for (int i = 0; i < 3; ++i) { g.Obstaculos().Reiniciar(); tic(g, cg, {}); } + CHECK(g.ElJugador().EnElSuelo(), "y el toque de reinicio no provoca un salto inmediato"); +} +} // namespace + +int main() +{ + try + { + Test_5_1(); + Test_5_2(); + Test_5_3(); + Test_5_4(); + } + catch (const std::exception& e) + { + std::printf(" [FAIL] excepcion: %s\n", e.what()); + return 1; + } + std::printf(g_fallos == 0 ? "\nTODO OK\n" : "\n%d FALLO(S)\n", g_fallos); + return g_fallos == 0 ? 0 : 1; +} diff --git a/web/minimal_shell.html b/web/minimal_shell.html index 5085270..8beae6e 100644 --- a/web/minimal_shell.html +++ b/web/minimal_shell.html @@ -2,24 +2,87 @@ - + + + + + + Runner - BasicGameEngine