Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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()
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
21 changes: 21 additions & 0 deletions src/ControlTactil.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
//------------------------------------------------------------------------------------
// ControlTactil.cpp
//------------------------------------------------------------------------------------
#include "ControlTactil.h"

SalidaTactil ControlTactil::Actualizar(const std::vector<Toque>& activos, const std::vector<SDL_Point>& 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;
}
50 changes: 50 additions & 0 deletions src/ControlTactil.h
Original file line number Diff line number Diff line change
@@ -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 <SDL.h>

#include <vector>

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<Toque>& activos, const std::vector<SDL_Point>& 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;
};
33 changes: 29 additions & 4 deletions src/Hud.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand All @@ -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);
}
}
Expand Down
9 changes: 9 additions & 0 deletions src/Hud.h
Original file line number Diff line number Diff line change
Expand Up @@ -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);

Expand Down
38 changes: 38 additions & 0 deletions src/Ventana.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,17 @@
//------------------------------------------------------------------------------------
#include "Ventana.h"

#include <algorithm>
#include <cmath>
#include <stdexcept>

//------------------------------------------------------------------------------------
// ContextoSdl
//------------------------------------------------------------------------------------
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());
}
Expand Down Expand Up @@ -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<int>(std::lround(e.tfinger.x * m_config.ancho));
const int y = static_cast<int>(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)
Expand Down Expand Up @@ -138,8 +167,17 @@ bool Ventana::BotonRaton(std::uint8_t boton) const noexcept
return (m_botonesRaton & SDL_BUTTON(boton)) != 0;
}

std::vector<SDL_Point> Ventana::TomarToquesNuevos()
{
std::vector<SDL_Point> r;
r.swap(m_toquesNuevos);
return r;
}

void Ventana::LiberarEntrada() noexcept
{
m_toques.clear();
m_toquesNuevos.clear();
m_teclas.fill(false);
m_botonesRaton = 0;
}
25 changes: 25 additions & 0 deletions src/Ventana.h
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
#include <cstdint>
#include <memory>
#include <string>
#include <vector>

//------------------------------------------------------------------------------------
// Configuracion de la ventana
Expand All @@ -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
//------------------------------------------------------------------------------------
Expand Down Expand Up @@ -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<Toque>& ToquesActivos() const noexcept { return m_toques; }
std::vector<SDL_Point> 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
Expand Down Expand Up @@ -104,5 +126,8 @@ class Ventana
int m_ratonX = 0;
int m_ratonY = 0;
std::uint32_t m_botonesRaton = 0;
std::vector<Toque> m_toques;
std::vector<SDL_Point> m_toquesNuevos;
bool m_entradaTactil = false;
std::array<bool, SDL_NUM_SCANCODES> m_teclas{};
};
25 changes: 21 additions & 4 deletions src/runner.cpp
Original file line number Diff line number Diff line change
@@ -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"
Expand All @@ -17,6 +19,10 @@
#include <iostream>
#include <memory>

#ifdef __EMSCRIPTEN__
#include <emscripten.h>
#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
Expand Down Expand Up @@ -44,6 +50,12 @@ class JuegoRunner : public Juego
m_partida = std::make_unique<Partida>(cfg, SDL_GetTicks()); // semilla distinta por sesion
m_escenario = std::make_unique<Escenario>(cfg.ancho, m_ventana->Altura(), cfg.ySuelo);
m_efectos = std::make_unique<Efectos>(cfg.ySuelo, SDL_GetTicks());
m_tactil = std::make_unique<ControlTactil>(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;
}

Expand All @@ -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;
Expand Down Expand Up @@ -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:
Expand All @@ -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; }
Expand All @@ -132,6 +148,7 @@ class JuegoRunner : public Juego
std::unique_ptr<Partida> m_partida;
std::unique_ptr<Escenario> m_escenario;
std::unique_ptr<Efectos> m_efectos;
std::unique_ptr<ControlTactil> m_tactil;
int m_ticsPolvo = 0;
bool m_mPrevia = false;
double m_resaltado = 0.0;
Expand Down
Loading
Loading