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
18 changes: 14 additions & 4 deletions .github/workflows/deploy.yml
Original file line number Diff line number Diff line change
Expand Up @@ -71,17 +71,17 @@ jobs:
emcmake cmake -S . -B build-web -DCMAKE_BUILD_TYPE=Release
cmake --build build-web --parallel

- name: Verificar que se generaron index.html, index.js e index.wasm
- name: Verificar que se generaron index.html, index.js, index.wasm e index.data
run: |
for f in index.html index.js index.wasm; do
for f in index.html index.js index.wasm index.data; do
test -s "build-web/$f" || { echo "::error::falta build-web/$f"; exit 1; }
done
ls -la build-web/index.*

- name: Ensamblar el sitio
run: |
mkdir site
cp build-web/index.html build-web/index.js build-web/index.wasm site/
cp build-web/index.html build-web/index.js build-web/index.wasm build-web/index.data site/
touch site/.nojekyll

- name: Prueba de integridad (servidor HTTP local)
Expand All @@ -96,7 +96,7 @@ jobs:
sleep 0.5
done

for f in index.html index.js index.wasm; do
for f in index.html index.js index.wasm index.data; do
code=$(curl -s -o "/tmp/$f" -w '%{http_code}' "http://127.0.0.1:8080/$f")
echo "$f -> HTTP $code"
test "$code" = "200"
Expand All @@ -111,6 +111,16 @@ jobs:
print('Cabecera WASM verificada')
PY

# Test 3.4: --preload-file empaqueta assets/ en index.data y lo declara en index.js.
# El .bmp debe figurar en el paquete y su contenido (cabecera "BM") estar en el .data.
grep -q 'assets/avatar_run.bmp' /tmp/index.js
python3 - <<'PY'
data = open('/tmp/index.data', 'rb').read()
assert len(data) >= 6966, f'index.data demasiado pequeno: {len(data)} bytes'
assert data.startswith(b'BM'), 'index.data no empieza por un BMP valido'
print(f'Test 3.4: index.data con avatar_run.bmp ({len(data)} bytes)')
PY

# emcc minimiza el HTML y elimina las comillas (<canvas id=canvas ...>),
# por eso se busca la etiqueta y no el atributo con comillas.
grep -qi '<canvas' /tmp/index.html
Expand Down
45 changes: 35 additions & 10 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,10 @@ endif()

option(BGE_SANITIZE "Compilar con AddressSanitizer/UBSan (solo nativo)" OFF)

# --- Biblioteca del motor (Modulos 1, 2 y 3) ------------------------------------
add_library(nucleo STATIC src/Ventana.cpp src/NucleoMotor.cpp src/Dibujante.cpp)
# --- Biblioteca del motor (Modulos 1, 2 y 3) y del Runner (texturas, jugador) ---
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)
target_include_directories(nucleo PUBLIC src)

if(EMSCRIPTEN)
Expand All @@ -33,20 +35,33 @@ else()
endif()
endif()

# --- Ejecutable de demostracion --------------------------------------------------
add_executable(juego src/main.cpp)
target_link_libraries(juego PRIVATE nucleo)
# --- Ejecutables ---------------------------------------------------------------------
# 'runner' es el juego: se compila en nativo y a WebAssembly. 'juego' es la demo del
# motor y solo se compila en nativo (en la web index.html es el Runner).
add_executable(runner src/runner.cpp)
target_link_libraries(runner PRIVATE nucleo)

if(EMSCRIPTEN)
# Salida: index.html + index.js + index.wasm (en el directorio de build)
# Salida: index.html + index.js + index.wasm + index.data (en el directorio de build)
set(BGE_SHELL "${CMAKE_SOURCE_DIR}/web/minimal_shell.html")
set_target_properties(juego PROPERTIES
set(BGE_ASSETS "${CMAKE_SOURCE_DIR}/assets")
file(GLOB_RECURSE BGE_ASSET_FILES "${BGE_ASSETS}/*")
set_target_properties(runner PROPERTIES
OUTPUT_NAME index
SUFFIX ".html"
LINK_DEPENDS "${BGE_SHELL}") # re-enlaza si cambia la plantilla
target_link_options(juego PRIVATE
LINK_DEPENDS "${BGE_SHELL};${BGE_ASSET_FILES}") # re-enlaza si cambia la plantilla o un asset
# Equivale a '--preload-file assets', pero con ruta absoluta (el enlazado no se ejecuta
# desde la raiz del repo) y '@/assets' fija el destino en el sistema de archivos virtual:
# el juego abre "assets/avatar_run.bmp" igual que en nativo. Emscripten empaqueta la
# carpeta en index.data y la monta antes de que arranque main().
target_link_options(runner PRIVATE
"SHELL:--shell-file ${BGE_SHELL}"
"SHELL:--preload-file ${BGE_ASSETS}@/assets"
$<$<CONFIG:Debug>:-sASSERTIONS=1>)
else()
target_compile_definitions(runner PRIVATE BGE_ASSETS_DIR="${CMAKE_SOURCE_DIR}/assets")
add_executable(juego src/main.cpp)
target_link_libraries(juego PRIVATE nucleo)
endif()

# --- Pruebas de QA (solo nativo) ---------------------------------------------------
Expand All @@ -62,5 +77,15 @@ if(NOT EMSCRIPTEN)
target_link_libraries(test_graficos PRIVATE nucleo)
add_test(NAME qa_modulo_3 COMMAND test_graficos)

set_tests_properties(qa_modulos_1_2 qa_modulo_3 PROPERTIES ENVIRONMENT "${BGE_TEST_ENV}")
add_executable(test_jugador tests/test_jugador.cpp)
target_link_libraries(test_jugador PRIVATE nucleo)
target_compile_definitions(test_jugador PRIVATE BGE_ASSETS_DIR="${CMAKE_SOURCE_DIR}/assets")
add_test(NAME qa_runner_modulos_1_2 COMMAND test_jugador)

add_executable(test_partida tests/test_partida.cpp)
target_link_libraries(test_partida PRIVATE nucleo)
target_compile_definitions(test_partida PRIVATE BGE_ASSETS_DIR="${CMAKE_SOURCE_DIR}/assets")
add_test(NAME qa_runner_modulo_3 COMMAND test_partida)

set_tests_properties(qa_modulos_1_2 qa_modulo_3 qa_runner_modulos_1_2 qa_runner_modulo_3 PROPERTIES ENVIRONMENT "${BGE_TEST_ENV}")
endif()
25 changes: 24 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,29 @@ Migrado desde la versión original basada en Win32.
| 3. Renderizado 2D | `src/Dibujante.*` — primitivas, texto bitmap 5x7; el motor limpia el fondo en cada frame | `tests/test_graficos.cpp` (3.1, 3.2) |
| 4. Build y CI/CD | `CMakeLists.txt`, `web/minimal_shell.html`, `.github/workflows/deploy.yml` | CI (4.1, 4.2) |

## Juego Runner

Juego "runner" horizontal construido sobre el motor: esquiva los bugs rojos saltando con
**ESPACIO / ↑** (también reinicia tras GAME OVER). La puntuación es la distancia recorrida y la
velocidad aumenta con el tiempo. En la web es el `index.html` publicado.

| Módulo | Contenido | QA |
|---|---|---|
| R1. Texturas | `src/Textura.*` — carga de BMP con SDL2 (sin SDL_image), color clave magenta / alfa → `SDL_Texture` RAII | `tests/test_jugador.cpp` (1.1, 1.2) |
| R2. Jugador | `src/Jugador.*` — estados Corriendo/Saltando/Cayendo, gravedad, suelo, animación por tics | `tests/test_jugador.cpp` (2.1, 2.2) |
| 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) |
| R3.4. Assets web | `CMakeLists.txt` — `--preload-file assets@/assets` empaqueta `assets/` en `index.data` | CI (3.4) |

`assets/avatar_run.bmp` (6 fotogramas de 16x24: 4 de carrera, salto, caída) se regenera con
`python3 tools/generar_avatar.py`. Nativo: `./build/runner`. La demo antigua del motor sigue en
`./build/juego` (solo nativo).

> En Emscripten los archivos del disco no existen: `--preload-file` los empaqueta en `index.data`
> y los monta en un sistema de archivos virtual **antes de `main()`**. Si añades assets nuevos,
> basta con ponerlos en `assets/` (se relinka solo). Al publicar hay que subir `index.data` junto
> a `index.html`, `index.js` e `index.wasm`.

## Compilar y probar en nativo

```bash
Expand Down Expand Up @@ -41,7 +64,7 @@ emcmake cmake -S . -B build-web -DCMAKE_BUILD_TYPE=Release
cmake --build build-web
```

Genera `build-web/index.html`, `index.js` e `index.wasm`. Para probarlo (los navegadores no
Genera `build-web/index.html`, `index.js`, `index.wasm` e `index.data` (los assets). Para probarlo (los navegadores no
cargan `.wasm` desde `file://`, hay que servirlo por HTTP):

```bash
Expand Down
Binary file added assets/avatar_run.bmp
Binary file not shown.
50 changes: 50 additions & 0 deletions src/Hud.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
//------------------------------------------------------------------------------------
// Hud.cpp
//------------------------------------------------------------------------------------
#include "Hud.h"

#include <cstdio>

namespace Hud
{
std::string TextoPuntos(const Partida& p)
{
char b[32];
std::snprintf(b, sizeof b, "PUNTOS: %05d", p.Puntos());
return b;
}
std::string TextoMejor(const Partida& p)
{
char b[32];
std::snprintf(b, sizeof b, "MEJOR: %05d", p.Mejor());
return b;
}
std::string TextoVelocidad(const Partida& p)
{
char b[32];
std::snprintf(b, sizeof b, "VEL: %03d", static_cast<int>(p.Velocidad()));
return b;
}

void Pintar(const Dibujante& d, const Partida& p, int ancho, int alto)
{
d.Texto(10, 8, TextoPuntos(p), Colores::Blanco, 2);
d.Texto(10, 26, TextoVelocidad(p), Colores::Verde, 1);

const std::string mejor = TextoMejor(p);
d.Texto(ancho - 10 - Dibujante::AnchoTexto(mejor, 2), 8, mejor, Colores::Amarillo, 2);

if (p.Estado() == EstadoPartida::GameOver)
{
const std::string t1 = "GAME OVER";
const std::string t2 = "ESPACIO: REINICIAR";
d.Texto((ancho - Dibujante::AnchoTexto(t1, 5)) / 2, alto / 2 - 60, t1, Colores::Rojo, 5);
d.Texto((ancho - Dibujante::AnchoTexto(t2, 2)) / 2, alto / 2 - 10, t2, Colores::Blanco, 2);
}
else if (p.Puntos() < 40) // instrucciones al empezar (~1,3 s)
{
const std::string t = "ESPACIO / FLECHA ARRIBA: SALTAR";
d.Texto((ancho - Dibujante::AnchoTexto(t, 2)) / 2, alto / 2 - 60, t, Colores::Gris, 2);
}
}
} // namespace Hud
26 changes: 26 additions & 0 deletions src/Hud.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
//------------------------------------------------------------------------------------
// Hud (Juego Runner - Modulo 3.3: puntuacion e interfaz)
// Encabezado C++ - Hud.h
//------------------------------------------------------------------------------------
// Dibuja con Dibujante::Texto (fuente bitmap del motor). Es una funcion pura del estado
// de la Partida: el motor limpia el back buffer antes de cada Pintar(), asi que cada
// frame se compone entero y no queda rastro del anterior. Los numeros se rellenan con
// ceros para que el texto no cambie de ancho al subir la puntuacion.
//------------------------------------------------------------------------------------
#pragma once

#include "Partida.h"

#include <string>

namespace Hud
{
std::string TextoPuntos(const Partida& p); // "PUNTOS: 00123"
std::string TextoMejor(const Partida& p); // "MEJOR: 00500"
std::string TextoVelocidad(const Partida& p); // "VEL: 300"

// Altura reservada para el HUD superior (nada del juego se dibuja ahi)
constexpr int kAlturaHud = 40;

void Pintar(const Dibujante& d, const Partida& p, int ancho, int alto);
}
92 changes: 92 additions & 0 deletions src/Jugador.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
//------------------------------------------------------------------------------------
// Jugador.cpp
//------------------------------------------------------------------------------------
#include "Jugador.h"

#include <cmath>

Jugador::Jugador(const ConfigJugador& config) noexcept
: m_config(config), m_animacion(config.framesCorrer, config.ticsPorFrame), m_yPies(config.ySuelo)
{
}

void Jugador::Reiniciar() noexcept
{
m_estado = EstadoJugador::Corriendo;
m_yPies = m_config.ySuelo;
m_vy = 0.0;
m_animacion.Reiniciar();
}

void Jugador::Actualizar(double dt, bool pedirSalto) noexcept
{
// Impulso inicial: solo desde el suelo
if (EnElSuelo() && pedirSalto)
{
m_vy = -m_config.velocidadSalto;
m_estado = EstadoJugador::Saltando;
}

if (EnElSuelo())
{
m_animacion.Avanzar(); // el ciclo de carrera solo corre sobre el suelo
return;
}

// Euler semi-implicito: primero la velocidad, luego la posicion
m_vy += m_config.gravedad * dt;
m_yPies += m_vy * dt;

if (m_yPies >= m_config.ySuelo) // aterrizaje: nunca se atraviesa el suelo
{
m_yPies = m_config.ySuelo;
m_vy = 0.0;
m_estado = EstadoJugador::Corriendo;
m_animacion.Reiniciar();
}
else
{
m_estado = (m_vy < 0.0) ? EstadoJugador::Saltando : EstadoJugador::Cayendo;
}
}

int Jugador::FrameActual() const noexcept
{
switch (m_estado)
{
case EstadoJugador::Saltando: return m_config.frameSalto;
case EstadoJugador::Cayendo: return m_config.frameCaida;
case EstadoJugador::Corriendo: break;
}
return m_animacion.Frame();
}

SDL_Rect Jugador::Rectangulo() const noexcept
{
const int w = m_config.anchoFrame * m_config.escala;
const int h = m_config.altoFrame * m_config.escala;
return SDL_Rect{ m_config.x, static_cast<int>(std::lround(m_yPies)) - h, w, h };
}

SDL_Rect Jugador::CajaColision() const noexcept
{
// Recorta el borde transparente del sprite (en pixeles de la hoja: 4 por cada lado,
// 1 por arriba, 2 por abajo) para que la colision sea justa; ver Test 3.2
SDL_Rect r = Rectangulo();
const int mx = 4 * m_config.escala, my = 1 * m_config.escala;
r.x += mx; r.w -= 2 * mx;
r.y += my; r.h -= my + 2 * m_config.escala; // 2 px menos por abajo (el fotograma de salto recoge las piernas)
return r;
}

void Jugador::Pintar(SDL_Renderer* renderizador, const Textura* hoja) const
{
const SDL_Rect destino = Rectangulo();
if (!hoja)
{
Dibujante(renderizador).RectanguloRelleno(destino, Colores::Azul); // respaldo visible
return;
}
const SDL_Rect origen{ FrameActual() * m_config.anchoFrame, 0, m_config.anchoFrame, m_config.altoFrame };
hoja->Dibujar(renderizador, &origen, destino);
}
Loading
Loading