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
10 changes: 8 additions & 2 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@ option(BGE_SANITIZE "Compilar con AddressSanitizer/UBSan (solo nativo)" OFF)
# --- 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)
src/Textura.cpp src/Jugador.cpp src/Obstaculos.cpp src/Partida.cpp src/Hud.cpp
src/Escenario.cpp src/Efectos.cpp src/Sonido.cpp)
target_include_directories(nucleo PUBLIC src)

if(EMSCRIPTEN)
Expand Down Expand Up @@ -87,5 +88,10 @@ if(NOT EMSCRIPTEN)
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}")
add_executable(test_efectos tests/test_efectos.cpp)
target_link_libraries(test_efectos PRIVATE nucleo)
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}")
endif()
8 changes: 7 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ Migrado desde la versión original basada en Win32.
## 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
**ESPACIO / ↑** (también reinicia tras GAME OVER); **M** activa o silencia el sonido. 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 |
Expand All @@ -25,8 +25,14 @@ velocidad aumenta con el tiempo. En la web es el `index.html` publicado.
| 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) |
| 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) |
| R3.4. Assets web | `CMakeLists.txt` — `--preload-file assets@/assets` empaqueta `assets/` en `index.data` | CI (3.4) |

**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.
**Estilo:** todos los colores salen del avatar (`Paleta.h`); el Test 4.1 comprueba que siguen cerca de los del sprite.

`assets/avatar_run.bmp` (6 fotogramas de 64x90: 4 de trote, salto, caída) se genera desde `tools/avatar_fuente.webp` con
`python3 tools/generar_avatar.py` (requiere Pillow y numpy). Nativo: `./build/runner`. La demo antigua del motor sigue en
`./build/juego` (solo nativo).
Expand Down
139 changes: 139 additions & 0 deletions src/Efectos.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
//------------------------------------------------------------------------------------
// Efectos.cpp
//------------------------------------------------------------------------------------
#include "Efectos.h"

#include "Paleta.h"

#include <algorithm>
#include <cmath>

namespace
{
constexpr double kPi = 3.14159265358979323846;
}

Efectos::Efectos(double ySuelo, std::uint32_t semilla) : m_ySuelo(ySuelo), m_rng(semilla), m_semilla(semilla) {}

void Efectos::Reiniciar() noexcept
{
m_cuenta = 0;
m_rng.seed(m_semilla);
m_sacudidaRestante = m_destelloRestante = 0;
m_desplazamiento = SDL_Point{ 0, 0 };
}

void Efectos::Emitir(const Particula& p) noexcept
{
if (m_cuenta < kMaxParticulas) m_particulas[m_cuenta++] = p; // lleno: se descarta
}

void Efectos::Polvo(double x, double y, int cantidad)
{
for (int i = 0; i < cantidad; ++i)
{
Particula p;
p.x = x + Azar(-6, 6); p.y = y - Azar(0, 3);
p.vx = Azar(-110, -30); p.vy = Azar(-70, -15); p.g = 60;
p.vidaMax = p.vida = Azar(0.28, 0.5);
p.color = Paleta::Polvo; p.lado = static_cast<int>(Azar(4, 7));
Emitir(p);
}
}

void Efectos::Explosion(double x, double y)
{
const Color colores[] = { Paleta::Violeta, Paleta::Verde, Paleta::Dorado, Paleta::BugCuerpo, Paleta::Piel, Colores::Blanco };
for (int i = 0; i < 44; ++i)
{
const double ang = Azar(0, 2 * kPi), vel = Azar(120, 420);
Particula p;
p.x = x; p.y = y;
p.vx = std::cos(ang) * vel; p.vy = std::sin(ang) * vel - 120; p.g = 900;
p.vidaMax = p.vida = Azar(0.6, 1.1);
p.color = colores[i % 6]; p.lado = static_cast<int>(Azar(5, 9)); p.rebota = true;
Emitir(p);
}
}

void Efectos::Chispas(double x, double y)
{
for (int i = 0; i < 14; ++i)
{
Particula p;
p.x = x + Azar(-20, 20); p.y = y;
p.vx = Azar(-90, 90); p.vy = Azar(-220, -80); p.g = 260;
p.vidaMax = p.vida = Azar(0.45, 0.8);
p.color = (i % 2) ? Paleta::Dorado : Colores::Blanco; p.lado = static_cast<int>(Azar(3, 5));
Emitir(p);
}
}

void Efectos::Sacudir(double amplitudPx, double duracion)
{
m_sacudidaAmp = amplitudPx; m_sacudidaRestante = m_sacudidaTotal = std::max(duracion, 1e-6);
}

void Efectos::Destello(double duracion)
{
m_destelloRestante = m_destelloTotal = std::max(duracion, 1e-6);
}

double Efectos::IntensidadDestello() const noexcept
{
return m_destelloRestante > 0 ? m_destelloRestante / m_destelloTotal : 0.0;
}

void Efectos::Actualizar(double dt)
{
// Particulas: integracion, rebote en el suelo y compactado de las muertas
std::size_t vivas = 0;
for (std::size_t i = 0; i < m_cuenta; ++i)
{
Particula p = m_particulas[i];
p.vida -= dt;
if (p.vida <= 0) continue;
p.vy += p.g * dt;
p.x += p.vx * dt;
p.y += p.vy * dt;
if (p.y > m_ySuelo) { p.y = m_ySuelo; p.vy = p.rebota ? -p.vy * 0.4 : 0; p.vx *= 0.6; }
m_particulas[vivas++] = p;
}
m_cuenta = vivas;

// Sacudida: la amplitud decae linealmente hasta 0
if (m_sacudidaRestante > 0)
{
m_sacudidaRestante = std::max(0.0, m_sacudidaRestante - dt);
const double a = m_sacudidaAmp * m_sacudidaRestante / m_sacudidaTotal;
const int r = static_cast<int>(std::lround(a));
m_desplazamiento = r > 0 ? SDL_Point{ std::uniform_int_distribution<int>(-r, r)(m_rng),
std::uniform_int_distribution<int>(-r, r)(m_rng) }
: SDL_Point{ 0, 0 };
}
else m_desplazamiento = SDL_Point{ 0, 0 };

if (m_destelloRestante > 0) m_destelloRestante = std::max(0.0, m_destelloRestante - dt);
}

void Efectos::Pintar(const Dibujante& d) const
{
for (std::size_t i = 0; i < m_cuenta; ++i)
{
const Particula& p = m_particulas[i];
const double f = p.vida / p.vidaMax; // 1 -> 0: se encoge al morir
const int lado = std::max(1, static_cast<int>(std::lround(p.lado * (0.4 + 0.6 * f))));
d.RectanguloRelleno(SDL_Rect{ static_cast<int>(p.x) - lado / 2, static_cast<int>(p.y) - lado / 2, lado, lado }, p.color);
}
}

void Efectos::PintarDestello(const Dibujante& d, int ancho, int alto) const
{
const double k = IntensidadDestello();
if (k <= 0) return;
const int g = std::max(2, static_cast<int>(std::lround(14 * k))); // marco naranja que se cierra
d.RectanguloRelleno(SDL_Rect{ 0, 0, ancho, g }, Paleta::BugCuerpo);
d.RectanguloRelleno(SDL_Rect{ 0, alto - g, ancho, g }, Paleta::BugCuerpo);
d.RectanguloRelleno(SDL_Rect{ 0, 0, g, alto }, Paleta::BugCuerpo);
d.RectanguloRelleno(SDL_Rect{ ancho - g, 0, g, alto }, Paleta::BugCuerpo);
}
67 changes: 67 additions & 0 deletions src/Efectos.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
//------------------------------------------------------------------------------------
// Efectos (Juego Runner - Modulo 4: efectos visuales)
// Encabezado C++ - Efectos.h
//------------------------------------------------------------------------------------
// Particulas (polvo, explosion, chispas), sacudida de pantalla y borde de impacto.
// - Capacidad fija (kMaxParticulas): nunca asigna memoria durante el juego y, si se
// llena, ignora las nuevas en vez de crecer.
// - Determinista (generador con semilla) y avanza con los tics de logica.
//------------------------------------------------------------------------------------
#pragma once

#include "Dibujante.h"

#include <SDL.h>

#include <array>
#include <cstddef>
#include <cstdint>
#include <random>

class Efectos
{
public:
static constexpr std::size_t kMaxParticulas = 256;

explicit Efectos(double ySuelo, std::uint32_t semilla = 1);

void Actualizar(double dt);
void Reiniciar() noexcept;

void Polvo(double x, double y, int cantidad); // al correr, saltar y aterrizar
void Explosion(double x, double y); // al chocar
void Chispas(double x, double y); // al superar un hito
void Sacudir(double amplitudPx, double duracion);
void Destello(double duracion);

// Desplazamiento (px) a aplicar al mundo este frame; (0,0) en reposo
SDL_Point Sacudida() const noexcept { return m_desplazamiento; }
double IntensidadDestello() const noexcept; // 1 -> 0
std::size_t Activas() const noexcept { return m_cuenta; }

void Pintar(const Dibujante& d) const; // particulas
void PintarDestello(const Dibujante& d, int ancho, int alto) const; // borde de impacto

private:
struct Particula
{
double x = 0, y = 0, vx = 0, vy = 0, g = 0;
double vida = 0, vidaMax = 1;
Color color{};
int lado = 4;
bool rebota = false;
};

void Emitir(const Particula& p) noexcept;
double Azar(double a, double b) { return std::uniform_real_distribution<double>(a, b)(m_rng); }

double m_ySuelo;
std::mt19937 m_rng;
std::uint32_t m_semilla;
std::array<Particula, kMaxParticulas> m_particulas{};
std::size_t m_cuenta = 0;

double m_sacudidaAmp = 0, m_sacudidaRestante = 0, m_sacudidaTotal = 1;
double m_destelloRestante = 0, m_destelloTotal = 1;
SDL_Point m_desplazamiento{ 0, 0 };
};
131 changes: 131 additions & 0 deletions src/Escenario.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
//------------------------------------------------------------------------------------
// Escenario.cpp
//------------------------------------------------------------------------------------
#include "Escenario.h"

#include "Paleta.h"

#include <algorithm>
#include <cmath>
#include <random>

namespace
{
Color Mezcla(Color a, Color b, double t)
{
auto m = [t](int x, int y) { return static_cast<std::uint8_t>(std::lround(x + (y - x) * t)); };
return Color{ m(a.r, b.r), m(a.g, b.g), m(a.b, b.b), 255 };
}

// Perfil periodico: paseo aleatorio al que se resta la deriva para que el final enlace con el principio
std::vector<int> Perfil(std::mt19937& rng, int columnas, int minimo, int maximo, int paso)
{
std::vector<double> h(static_cast<std::size_t>(columnas));
double v = (minimo + maximo) / 2.0;
for (auto& x : h)
{
v = std::clamp(v + std::uniform_int_distribution<int>(-1, 1)(rng) * paso, double(minimo), double(maximo));
x = v;
}
const double deriva = h.back() - h.front();
std::vector<int> r(h.size());
for (std::size_t i = 0; i < h.size(); ++i)
r[i] = std::clamp(static_cast<int>(std::lround(h[i] - deriva * i / h.size())), minimo, maximo);
return r;
}
} // namespace

Escenario::Escenario(int ancho, int alto, double ySuelo, std::uint32_t semilla)
: m_ancho(ancho), m_alto(alto), m_ySuelo(ySuelo)
{
std::mt19937 rng(semilla);
for (int i = 0; i < 46; ++i)
m_estrellas.push_back({ std::uniform_int_distribution<int>(0, ancho - 1)(rng),
std::uniform_int_distribution<int>(44, std::max(45, int(ySuelo) - 150))(rng),
std::uniform_int_distribution<int>(0, 3)(rng) });
m_colinasLejos = Perfil(rng, 2 * ancho / kAnchoColumna, 50, 140, 12);
m_colinasCerca = Perfil(rng, 2 * ancho / kAnchoColumna, 24, 80, 8);
for (int i = 0; i < 18; ++i)
m_motas.push_back({ std::uniform_int_distribution<int>(0, kPeriodoSuelo - 1)(rng),
std::uniform_int_distribution<int>(18, std::max(19, alto - int(ySuelo) - 8))(rng),
std::uniform_int_distribution<int>(6, 18)(rng) });
}

void Escenario::Actualizar(double dt, double velocidad) noexcept
{
++m_tics;
m_suelo = std::fmod(m_suelo + velocidad * dt, kPeriodoSuelo);
m_cerca = std::fmod(m_cerca + velocidad * 0.30 * dt, 2.0 * m_ancho);
m_lejos = std::fmod(m_lejos + velocidad * 0.10 * dt, 2.0 * m_ancho);
}

void Escenario::PintarCielo(const Dibujante& d) const
{
const int banda = 8, fin = static_cast<int>(m_ySuelo);
for (int y = 0; y < fin; y += banda)
{
// Se acerca al horizonte en pasos discretos (look de paleta limitada)
const double t = std::floor(double(y) / fin * 10.0) / 10.0;
d.RectanguloRelleno(SDL_Rect{ 0, y, m_ancho, std::min(banda, fin - y) }, Mezcla(Paleta::CieloArriba, Paleta::CieloHorizonte, t * t));
}
for (const Estrella& e : m_estrellas)
{
const bool brillo = ((m_tics / 40 + static_cast<std::uint64_t>(e.fase)) % 4) != 0; // parpadeo lento
d.RectanguloRelleno(SDL_Rect{ e.x, e.y, brillo ? 2 : 1, brillo ? 2 : 1 }, Paleta::Estrella);
}
// Luna de bloques de 4 px, con crateres
const int cx = m_ancho - 150, cy = 92, r = 7;
for (int j = -r; j <= r; ++j)
{
const int mitad = static_cast<int>(std::floor(std::sqrt(double(r * r - j * j) + 0.5)));
d.RectanguloRelleno(SDL_Rect{ cx - mitad * 4, cy + j * 4, (2 * mitad + 1) * 4, 4 }, Paleta::Luna);
}
d.RectanguloRelleno(SDL_Rect{ cx - 12, cy - 8, 8, 8 }, Paleta::LunaCrater);
d.RectanguloRelleno(SDL_Rect{ cx + 8, cy + 8, 12, 8 }, Paleta::LunaCrater);
d.RectanguloRelleno(SDL_Rect{ cx - 4, cy + 16, 4, 4 }, Paleta::LunaCrater);
}

void Escenario::PintarColinas(const Dibujante& d, const std::vector<int>& alturas, double desplazamiento, Color c) const
{
const int n = static_cast<int>(alturas.size());
const int offset = static_cast<int>(desplazamiento);
const int primera = offset / kAnchoColumna;
const int resto = offset % kAnchoColumna;
for (int x = -resto, i = primera; x < m_ancho; x += kAnchoColumna, ++i)
{
const int h = alturas[static_cast<std::size_t>(i % n)];
d.RectanguloRelleno(SDL_Rect{ x, static_cast<int>(m_ySuelo) - h, kAnchoColumna, h }, c);
}
}

void Escenario::PintarSuelo(const Dibujante& d) const
{
const int y0 = static_cast<int>(m_ySuelo);
const int offset = static_cast<int>(m_suelo);
d.RectanguloRelleno(SDL_Rect{ 0, y0, m_ancho, m_alto - y0 }, Paleta::Suelo);

// Detalles del suelo (periodo 640 px, se dibujan dos copias para cubrir el borde)
for (const Mota& m : m_motas)
for (int copia = -1; copia <= 1; ++copia)
{
const int x = m.x - offset + copia * kPeriodoSuelo;
if (x + m.w > 0 && x < m_ancho)
d.RectanguloRelleno(SDL_Rect{ x, y0 + m.y, m.w, 4 }, Paleta::SueloOscuro);
}

// Hierba: contorno oscuro, cuerpo verde y pelillos que avanzan con el suelo
d.RectanguloRelleno(SDL_Rect{ 0, y0, m_ancho, 10 }, Paleta::Hierba);
d.RectanguloRelleno(SDL_Rect{ 0, y0, m_ancho, 3 }, Paleta::HierbaClara);
d.RectanguloRelleno(SDL_Rect{ 0, y0 + 10, m_ancho, 3 }, Paleta::Contorno);
const int paso = 32;
for (int x = -(offset % paso); x < m_ancho; x += paso)
d.RectanguloRelleno(SDL_Rect{ x + 8, y0 + 3, 4, 6 }, Paleta::SombraSuelo);
}

void Escenario::Pintar(const Dibujante& d) const
{
PintarCielo(d);
PintarColinas(d, m_colinasLejos, m_lejos, Paleta::ColinaLejana);
PintarColinas(d, m_colinasCerca, m_cerca, Paleta::ColinaCercana);
PintarSuelo(d);
}
Loading
Loading