diff --git a/CMakeLists.txt b/CMakeLists.txt index 6309e75..25f0972 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -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) @@ -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() diff --git a/README.md b/README.md index 4ad4742..6f62a04 100644 --- a/README.md +++ b/README.md @@ -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 | @@ -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). diff --git a/src/Efectos.cpp b/src/Efectos.cpp new file mode 100644 index 0000000..9392ae0 --- /dev/null +++ b/src/Efectos.cpp @@ -0,0 +1,139 @@ +//------------------------------------------------------------------------------------ +// Efectos.cpp +//------------------------------------------------------------------------------------ +#include "Efectos.h" + +#include "Paleta.h" + +#include +#include + +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(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(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(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(std::lround(a)); + m_desplazamiento = r > 0 ? SDL_Point{ std::uniform_int_distribution(-r, r)(m_rng), + std::uniform_int_distribution(-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(std::lround(p.lado * (0.4 + 0.6 * f)))); + d.RectanguloRelleno(SDL_Rect{ static_cast(p.x) - lado / 2, static_cast(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(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); +} diff --git a/src/Efectos.h b/src/Efectos.h new file mode 100644 index 0000000..b767c83 --- /dev/null +++ b/src/Efectos.h @@ -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 + +#include +#include +#include +#include + +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(a, b)(m_rng); } + + double m_ySuelo; + std::mt19937 m_rng; + std::uint32_t m_semilla; + std::array 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 }; +}; diff --git a/src/Escenario.cpp b/src/Escenario.cpp new file mode 100644 index 0000000..4b12175 --- /dev/null +++ b/src/Escenario.cpp @@ -0,0 +1,131 @@ +//------------------------------------------------------------------------------------ +// Escenario.cpp +//------------------------------------------------------------------------------------ +#include "Escenario.h" + +#include "Paleta.h" + +#include +#include +#include + +namespace +{ +Color Mezcla(Color a, Color b, double t) +{ + auto m = [t](int x, int y) { return static_cast(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 Perfil(std::mt19937& rng, int columnas, int minimo, int maximo, int paso) +{ + std::vector h(static_cast(columnas)); + double v = (minimo + maximo) / 2.0; + for (auto& x : h) + { + v = std::clamp(v + std::uniform_int_distribution(-1, 1)(rng) * paso, double(minimo), double(maximo)); + x = v; + } + const double deriva = h.back() - h.front(); + std::vector r(h.size()); + for (std::size_t i = 0; i < h.size(); ++i) + r[i] = std::clamp(static_cast(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(0, ancho - 1)(rng), + std::uniform_int_distribution(44, std::max(45, int(ySuelo) - 150))(rng), + std::uniform_int_distribution(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(0, kPeriodoSuelo - 1)(rng), + std::uniform_int_distribution(18, std::max(19, alto - int(ySuelo) - 8))(rng), + std::uniform_int_distribution(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(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(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(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& alturas, double desplazamiento, Color c) const +{ + const int n = static_cast(alturas.size()); + const int offset = static_cast(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(i % n)]; + d.RectanguloRelleno(SDL_Rect{ x, static_cast(m_ySuelo) - h, kAnchoColumna, h }, c); + } +} + +void Escenario::PintarSuelo(const Dibujante& d) const +{ + const int y0 = static_cast(m_ySuelo); + const int offset = static_cast(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); +} diff --git a/src/Escenario.h b/src/Escenario.h new file mode 100644 index 0000000..f18fb10 --- /dev/null +++ b/src/Escenario.h @@ -0,0 +1,49 @@ +//------------------------------------------------------------------------------------ +// Escenario (Juego Runner - Modulo 4: fondo con parallax) +// Encabezado C++ - Escenario.h +//------------------------------------------------------------------------------------ +// Cielo en degradado por bandas, estrellas, luna, dos capas de colinas "escalonadas" +// (pixel art) que se desplazan a distinta velocidad, y suelo con hierba. Todo se dibuja +// con rectangulos del Dibujante, sin texturas. Es determinista (semilla) y avanza con +// los tics de logica, no con el reloj, asi que se congela solo cuando el juego se para. +//------------------------------------------------------------------------------------ +#pragma once + +#include "Dibujante.h" + +#include +#include + +class Escenario +{ +public: + Escenario(int ancho, int alto, double ySuelo, std::uint32_t semilla = 7); + + // 'velocidad' en px/s del suelo (0 = escenario congelado) + void Actualizar(double dt, double velocidad) noexcept; + void Pintar(const Dibujante& d) const; + + double DesplazamientoSuelo() const noexcept { return m_suelo; } + double DesplazamientoCerca() const noexcept { return m_cerca; } + double DesplazamientoLejos() const noexcept { return m_lejos; } + +private: + struct Estrella { int x, y, fase; }; + struct Mota { int x, y, w; }; + + void PintarCielo(const Dibujante& d) const; + void PintarColinas(const Dibujante& d, const std::vector& alturas, double desplazamiento, Color c) const; + void PintarSuelo(const Dibujante& d) const; + + int m_ancho, m_alto; + double m_ySuelo; + std::vector m_estrellas; + std::vector m_colinasLejos, m_colinasCerca; // altura por columna, periodicas + std::vector m_motas; // detalles del suelo + double m_suelo = 0, m_cerca = 0, m_lejos = 0; + std::uint64_t m_tics = 0; + +public: + static constexpr int kAnchoColumna = 16; + static constexpr int kPeriodoSuelo = 640; +}; diff --git a/src/Hud.cpp b/src/Hud.cpp index e668915..434be19 100644 --- a/src/Hud.cpp +++ b/src/Hud.cpp @@ -26,25 +26,34 @@ std::string TextoVelocidad(const Partida& p) return b; } -void Pintar(const Dibujante& d, const Partida& p, int ancho, int alto) +int TextoSombra(const Dibujante& d, int x, int y, const std::string& t, Color c, int escala) { - d.Texto(10, 8, TextoPuntos(p), Colores::Blanco, 2); - d.Texto(10, 26, TextoVelocidad(p), Colores::Verde, 1); + d.Texto(x + escala, y + escala, t, Paleta::TextoSombra, escala); + return d.Texto(x, y, t, c, escala); +} + +void Pintar(const Dibujante& d, const Partida& p, int ancho, int alto, const Opciones& op) +{ + TextoSombra(d, 10, 8, TextoPuntos(p), op.resaltarPuntos ? Paleta::Dorado : Paleta::TextoClaro, 2); + TextoSombra(d, 10, 26, TextoVelocidad(p), Paleta::Verde, 1); const std::string mejor = TextoMejor(p); - d.Texto(ancho - 10 - Dibujante::AnchoTexto(mejor, 2), 8, mejor, Colores::Amarillo, 2); + 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 (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); + 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"; - d.Texto((ancho - Dibujante::AnchoTexto(t, 2)) / 2, alto / 2 - 60, t, Colores::Gris, 2); + TextoSombra(d, (ancho - Dibujante::AnchoTexto(t, 2)) / 2, alto / 2 - 60, t, Paleta::TextoClaro, 2); } } } // namespace Hud diff --git a/src/Hud.h b/src/Hud.h index 5c9c44d..abf3729 100644 --- a/src/Hud.h +++ b/src/Hud.h @@ -10,6 +10,7 @@ #pragma once #include "Partida.h" +#include "Paleta.h" #include @@ -22,5 +23,14 @@ namespace Hud // 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); + struct Opciones + { + bool sonidoActivo = true; // indicador "M: SONIDO" + bool resaltarPuntos = false; // la puntuacion brilla un instante al superar un hito + }; + + // 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); + + void Pintar(const Dibujante& d, const Partida& p, int ancho, int alto, const Opciones& op = {}); } diff --git a/src/Obstaculos.cpp b/src/Obstaculos.cpp index 657ff06..32705cd 100644 --- a/src/Obstaculos.cpp +++ b/src/Obstaculos.cpp @@ -3,6 +3,8 @@ //------------------------------------------------------------------------------------ #include "Obstaculos.h" +#include "Paleta.h" + #include #include @@ -69,14 +71,28 @@ bool GestorObstaculos::ColisionaCon(const SDL_Rect& caja) const noexcept void GestorObstaculos::Pintar(const Dibujante& d) const { + // "Bug" en el mismo estilo que el avatar: contorno oscuro, dos tonos y ojos grandes. + // Todo se dibuja DENTRO de la caja de colision (lo que se ve es lo que choca). for (const Obstaculo& o : m_activos) { const SDL_Rect c = o.Caja(); - d.RectanguloRelleno(c, Colores::Rojo); - d.Rectangulo(c, Color{ 120, 20, 20, 255 }); - // Dos "ojos" de bug para que no sea un bloque liso - const int ojo = std::max(3, c.w / 8); - d.RectanguloRelleno(SDL_Rect{ c.x + c.w / 4, c.y + c.h / 4, ojo, ojo }, Colores::Blanco); - d.RectanguloRelleno(SDL_Rect{ c.x + c.w - c.w / 4 - ojo, c.y + c.h / 4, ojo, ojo }, Colores::Blanco); + d.RectanguloRelleno(c, Paleta::Contorno); + const SDL_Rect in{ c.x + 2, c.y + 2, c.w - 4, c.h - 4 }; + d.RectanguloRelleno(in, Paleta::BugCuerpo); + d.RectanguloRelleno(SDL_Rect{ in.x, in.y, in.w, 4 }, Paleta::BugLuz); // brillo superior + d.RectanguloRelleno(SDL_Rect{ in.x, in.y + in.h - 5, in.w, 5 }, Paleta::BugSombra); // sombra inferior + + const int ojo = std::max(6, c.w / 5); + const int ey = c.y + std::max(6, c.h / 4); + const int ex1 = c.x + c.w / 5, ex2 = c.x + c.w - c.w / 5 - ojo; + for (int ex : { ex1, ex2 }) + { + d.RectanguloRelleno(SDL_Rect{ ex, ey, ojo, ojo }, Colores::Blanco); + d.RectanguloRelleno(SDL_Rect{ ex, ey + 1, ojo / 2, ojo - 2 }, Paleta::Contorno); // pupila: mira al jugador (izquierda) + } + // Boca con dientes + const int bw = c.w / 2, bx = c.x + (c.w - bw) / 2, by = c.y + c.h - std::max(12, c.h / 4); + d.RectanguloRelleno(SDL_Rect{ bx, by, bw, 5 }, Paleta::Contorno); + for (int t = bx + 2; t + 3 <= bx + bw - 1; t += 6) d.RectanguloRelleno(SDL_Rect{ t, by, 3, 2 }, Colores::Blanco); } } diff --git a/src/Paleta.h b/src/Paleta.h new file mode 100644 index 0000000..20d7090 --- /dev/null +++ b/src/Paleta.h @@ -0,0 +1,48 @@ +//------------------------------------------------------------------------------------ +// Paleta (Juego Runner - Modulo 4: identidad visual) +// Encabezado C++ - Paleta.h +//------------------------------------------------------------------------------------ +// Todos los colores del mundo salen de los del avatar (muestreados de la hoja de sprites; +// el Test 4.x comprueba que siguen estando cerca de ellos): violeta de la gorra y la +// camiseta, verde del mono, marron de los zapatos y tono de piel. El mundo usa versiones +// oscuras/desaturadas de esos tonos para que el personaje destaque, y los peligros usan +// el naranja calido (vecino del marron y el dorado) para contrastar con el violeta/verde. +//------------------------------------------------------------------------------------ +#pragma once + +#include "Dibujante.h" + +namespace Paleta +{ + // --- Colores del avatar (referencia) --- + inline constexpr Color Violeta { 164, 0, 255, 255 }; + inline constexpr Color Verde { 20, 253, 2, 255 }; + inline constexpr Color Marron { 126, 60, 27, 255 }; + inline constexpr Color Piel { 238, 168, 123, 255 }; + inline constexpr Color Dorado { 236, 190, 48, 255 }; + inline constexpr Color Contorno{ 17, 9, 6, 255 }; // el negro calido de su contorno + + // --- Mundo --- + inline constexpr Color CieloArriba { 14, 6, 38, 255 }; // violeta casi negro + inline constexpr Color CieloHorizonte{ 78, 22, 112, 255 }; // violeta calido de atardecer + inline constexpr Color Estrella { 236, 222, 255, 255 }; + inline constexpr Color Luna { 255, 226, 190, 255 }; // piel muy clara + inline constexpr Color LunaCrater { 232, 196, 168, 255 }; + inline constexpr Color ColinaLejana { 52, 18, 92, 255 }; + inline constexpr Color ColinaCercana { 34, 12, 66, 255 }; + inline constexpr Color Suelo { 64, 30, 60, 255 }; // marron + violeta + inline constexpr Color SueloOscuro { 44, 18, 46, 255 }; + inline constexpr Color Hierba { 36, 176, 22, 255 }; // verde del mono, apagado + inline constexpr Color HierbaClara { 96, 230, 40, 255 }; + inline constexpr Color SombraSuelo { 20, 96, 14, 255 }; + + // --- Peligro: los "bugs" --- + inline constexpr Color BugCuerpo { 252, 120, 24, 255 }; + inline constexpr Color BugLuz { 255, 186, 80, 255 }; + inline constexpr Color BugSombra { 176, 66, 18, 255 }; + + // --- Interfaz y efectos --- + inline constexpr Color TextoClaro { 236, 222, 255, 255 }; + inline constexpr Color TextoSombra{ 14, 6, 38, 255 }; + inline constexpr Color Polvo { 186, 152, 204, 255 }; +} diff --git a/src/Partida.cpp b/src/Partida.cpp index cf4a51e..a7a9590 100644 --- a/src/Partida.cpp +++ b/src/Partida.cpp @@ -36,6 +36,8 @@ void Partida::Reiniciar() m_velocidad = m_config.velocidadInicial; m_distancia = 0.0; m_ticsGameOver = 0; + m_hitoPrevio = 0; + m_eventos.reinicio = true; } void Partida::Actualizar(double dt, bool saltar) @@ -50,14 +52,20 @@ void Partida::Actualizar(double dt, bool saltar) return; // mundo congelado } + const bool enSueloAntes = m_jugador.EnElSuelo(); m_jugador.Actualizar(dt, saltar); + if (enSueloAntes && !m_jugador.EnElSuelo()) m_eventos.salto = true; + if (!enSueloAntes && m_jugador.EnElSuelo()) m_eventos.aterrizaje = true; m_obstaculos.Actualizar(dt, m_velocidad); m_distancia += m_velocidad * dt; m_velocidad = std::min(m_config.velocidadMaxima, m_velocidad + m_config.aceleracion * dt); + if (const int hito = Puntos() / 100; hito > m_hitoPrevio) { m_eventos.hitos += hito - m_hitoPrevio; m_hitoPrevio = hito; } + if (m_obstaculos.ColisionaCon(m_jugador.CajaColision())) { m_estado = EstadoPartida::GameOver; + m_eventos.choque = true; m_mejor = std::max(m_mejor, Puntos()); m_ticsGameOver = 0; } diff --git a/src/Partida.h b/src/Partida.h index 6bfdd21..1f26312 100644 --- a/src/Partida.h +++ b/src/Partida.h @@ -28,6 +28,17 @@ struct ConfigPartida int ticsBloqueoGameOver = 30; // 0,5 s a 60 Hz }; +// Sucesos de la partida desde la ultima llamada a TomarEventos(). El juego los traduce a +// sonido y efectos visuales; la logica no sabe nada de audio ni de graficos. +struct EventosPartida +{ + bool salto = false; // el jugador despega + bool aterrizaje = false; // el jugador toca el suelo + bool choque = false; // paso a GameOver + bool reinicio = false; // nueva partida + int hitos = 0; // veces que se cruzo un multiplo de 100 puntos +}; + class Partida { public: @@ -37,6 +48,9 @@ class Partida void Actualizar(double dt, bool saltar); void Reiniciar(); + // Devuelve y borra los sucesos acumulados (puede haber varios tics por frame) + EventosPartida TomarEventos() noexcept { const EventosPartida e = m_eventos; m_eventos = {}; return e; } + EstadoPartida Estado() const noexcept { return m_estado; } int Puntos() const noexcept { return static_cast(m_distancia / m_config.pixelesPorPunto); } int Mejor() const noexcept { return m_mejor; } @@ -58,4 +72,6 @@ class Partida int m_mejor = 0; int m_ticsGameOver = 0; bool m_saltarPrevio = false; + int m_hitoPrevio = 0; + EventosPartida m_eventos; }; diff --git a/src/Sonido.cpp b/src/Sonido.cpp new file mode 100644 index 0000000..9c56446 --- /dev/null +++ b/src/Sonido.cpp @@ -0,0 +1,276 @@ +//------------------------------------------------------------------------------------ +// Sonido.cpp +//------------------------------------------------------------------------------------ +#include "Sonido.h" + +#include +#include + +namespace +{ +constexpr double kPi = 3.14159265358979323846; +constexpr double kFs = Sintesis::kFrecuencia; + +enum class Onda { Cuadrada, Triangular, Sierra }; + +// Buffer de trabajo en coma flotante con osciladores simples +class Lienzo +{ +public: + explicit Lienzo(double segundos) : m_b(static_cast(segundos * kFs), 0.f) {} + + // Tono con barrido de frecuencia f0 -> f1 y caida exponencial (constante 'decay' en s) + void Tono(double t0, double dur, double f0, double f1, Onda onda, double vol, double decay, double duty = 0.5) + { + const std::size_t i0 = static_cast(t0 * kFs), n = static_cast(dur * kFs); + double fase = 0; + for (std::size_t i = 0; i < n && i0 + i < m_b.size(); ++i) + { + const double t = double(i) / n; + fase += (f0 + (f1 - f0) * t) / kFs; + fase -= std::floor(fase); + double v = 0; + switch (onda) + { + case Onda::Cuadrada: // media cero para cualquier ciclo de trabajo (sin componente continua) + v = (fase < duty ? 2.0 * (1.0 - duty) : -2.0 * duty) / std::max(2.0 * (1.0 - duty), 2.0 * duty); + break; + case Onda::Triangular: v = 4.0 * std::fabs(fase - 0.5) - 1.0; break; + case Onda::Sierra: v = 2.0 * fase - 1.0; break; + } + const double liberacion = std::min(1.0, double(n - i) / (0.004 * kFs)); // 4 ms finales a 0 + m_b[i0 + i] += static_cast(v * vol * liberacion * std::exp(-double(i) / kFs / decay)); + } + } + + // Ruido blanco filtrado (paso bajo de un polo: 'suave' en (0,1], menor = mas grave) + void Ruido(double t0, double dur, double vol, double decay, double suave, std::uint32_t semilla = 12345u) + { + const std::size_t i0 = static_cast(t0 * kFs), n = static_cast(dur * kFs); + std::uint32_t x = semilla; + double y = 0; + for (std::size_t i = 0; i < n && i0 + i < m_b.size(); ++i) + { + x ^= x << 13; x ^= x >> 17; x ^= x << 5; // xorshift32 + const double r = (double(x) / 4294967295.0) * 2.0 - 1.0; + y += suave * (r - y); + m_b[i0 + i] += static_cast(y * vol * std::exp(-double(i) / kFs / decay)); + } + } + + // A 16 bits: fundidos de 3 ms (sin clics) y pico normalizado a 'pico' (0..1) + std::vector Terminar(double pico, bool fundidoFinal = true) + { + float max = 1e-9f; + for (float v : m_b) max = std::max(max, std::fabs(v)); + const double k = pico / max; + const std::size_t f = static_cast(0.003 * kFs); + std::vector r(m_b.size()); + for (std::size_t i = 0; i < m_b.size(); ++i) + { + double g = 1.0; + if (i < f) g = double(i) / f; + if (fundidoFinal && m_b.size() - 1 - i < f) g = std::min(g, double(m_b.size() - 1 - i) / f); + r[i] = static_cast(std::lround(m_b[i] * k * g * 32767.0)); + } + return r; + } + +private: + std::vector m_b; +}; +} // namespace + +namespace Sintesis +{ +std::vector Generar(Efecto e) +{ + switch (e) + { + case Efecto::Salto: + { + Lienzo l(0.24); + l.Tono(0, 0.22, 260, 640, Onda::Cuadrada, 1.0, 0.12); // "boing" ascendente + return l.Terminar(0.55); + } + case Efecto::Aterrizaje: + { + Lienzo l(0.12); + l.Tono(0, 0.10, 150, 55, Onda::Triangular, 1.0, 0.04); // golpe sordo + l.Ruido(0, 0.07, 0.5, 0.03, 0.25); + return l.Terminar(0.6); + } + case Efecto::Golpe: + { + Lienzo l(0.7); + l.Ruido(0, 0.5, 1.0, 0.16, 0.18, 777u); // crujido + l.Tono(0, 0.65, 330, 50, Onda::Sierra, 0.7, 0.22); // caida de tono + return l.Terminar(0.8); + } + case Efecto::Hito: + { + Lienzo l(0.34); + l.Tono(0.00, 0.10, 880, 880, Onda::Cuadrada, 1.0, 0.07, 0.25); // "ding-ding" + l.Tono(0.09, 0.24, 1320, 1320, Onda::Cuadrada, 1.0, 0.10, 0.25); + return l.Terminar(0.5); + } + case Efecto::Inicio: + { + Lienzo l(0.34); + const double notas[] = { 440.0, 554.4, 659.3 }; // La mayor ascendente + for (int i = 0; i < 3; ++i) l.Tono(0.08 * i, 0.12, notas[i], notas[i], Onda::Triangular, 1.0, 0.09); + return l.Terminar(0.6); + } + } + return {}; +} + +std::vector Musica() +{ + // 16 corcheas a 120 ppm = 4 s. La Menor pentatonica: bajo triangular + arpegio cuadrado + constexpr double paso = 0.25; + const double bajo[16] = { 110, 110, 164.8, 110, 130.8, 130.8, 196, 130.8, 146.8, 146.8, 220, 146.8, 98, 98, 146.8, 196 }; + const double arpa[16] = { 440, 523.3, 659.3, 523.3, 523.3, 659.3, 784, 659.3, 587.3, 740, 880, 740, 392, 494, 587.3, 784 }; + Lienzo l(16 * paso); + for (int i = 0; i < 16; ++i) + { + l.Tono(i * paso, paso * 0.9, bajo[i], bajo[i], Onda::Triangular, 0.9, 0.35); + if (i % 2 == 0 || i % 4 == 3) l.Tono(i * paso, paso * 0.8, arpa[i], arpa[i], Onda::Cuadrada, 0.22, 0.12, 0.125); + if (i % 4 == 2) l.Ruido(i * paso, 0.05, 0.25, 0.02, 0.6, 99u + i); // charles + } + return l.Terminar(0.9, false); // sin fundido al final: el bucle enlaza (empieza y acaba en ~0) +} +} // namespace Sintesis + +// -------------------------------------------------------------------------------- Mezclador +Mezclador::Mezclador() = default; + +void Mezclador::Registrar(Efecto e, std::vector muestras) +{ + m_efectos[static_cast(e)] = std::move(muestras); +} + +void Mezclador::EstablecerMusica(std::vector muestras) +{ + m_musica = std::move(muestras); + m_posMusica = 0; +} + +void Mezclador::Silenciar(bool silencio) noexcept +{ + m_silencio = silencio; + if (silencio) for (Voz& v : m_voces) v = Voz{}; // corta lo que estuviera sonando +} + +void Mezclador::Reproducir(Efecto e) +{ + const auto& m = m_efectos[static_cast(e)]; + if (m_silencio || m.empty()) return; + Voz* destino = nullptr; + for (Voz& v : m_voces) if (!v.muestras) { destino = &v; break; } + if (!destino) // todas ocupadas: se roba la mas avanzada + destino = &*std::max_element(m_voces.begin(), m_voces.end(), [](const Voz& a, const Voz& b) { return a.pos < b.pos; }); + *destino = Voz{ &m, 0 }; +} + +int Mezclador::VocesActivas() const noexcept +{ + return static_cast(std::count_if(m_voces.begin(), m_voces.end(), [](const Voz& v) { return v.muestras != nullptr; })); +} + +void Mezclador::Mezclar(std::int16_t* salida, int n) noexcept +{ + for (int i = 0; i < n; ++i) salida[i] = 0; + if (m_silencio) return; + + if (!m_musicaPausada && !m_musica.empty()) + for (int i = 0; i < n; ++i) + { + salida[i] = static_cast(std::lround(m_musica[m_posMusica] * GananciaMusica)); + if (++m_posMusica >= m_musica.size()) m_posMusica = 0; // bucle + } + + for (Voz& v : m_voces) + { + if (!v.muestras) continue; + for (int i = 0; i < n && v.pos < v.muestras->size(); ++i, ++v.pos) + { + const long suma = salida[i] + std::lround((*v.muestras)[v.pos] * GananciaEfectos); + salida[i] = static_cast(std::clamp(suma, -32768, 32767)); + } + if (v.pos >= v.muestras->size()) v = Voz{}; + } +} + +// -------------------------------------------------------------------------------- Sonido +std::unique_ptr Sonido::Abrir() +{ + if (SDL_InitSubSystem(SDL_INIT_AUDIO) != 0) return nullptr; + + std::unique_ptr s(new Sonido()); + for (int i = 0; i < kNumEfectos; ++i) s->m_mezclador.Registrar(static_cast(i), Sintesis::Generar(static_cast(i))); + s->m_mezclador.EstablecerMusica(Sintesis::Musica()); + + SDL_AudioSpec pedido{}; + pedido.freq = Sintesis::kFrecuencia; + pedido.format = AUDIO_S16SYS; + pedido.channels = 1; + pedido.samples = 1024; + pedido.callback = &Sonido::Callback; + pedido.userdata = s.get(); + SDL_AudioSpec obtenido{}; + // allowed_changes = 0: SDL convierte por su cuenta al formato real del dispositivo + s->m_dispositivo = SDL_OpenAudioDevice(nullptr, 0, &pedido, &obtenido, 0); + if (s->m_dispositivo == 0) + { + SDL_QuitSubSystem(SDL_INIT_AUDIO); + return nullptr; + } + SDL_PauseAudioDevice(s->m_dispositivo, 0); + return s; +} + +Sonido::~Sonido() +{ + if (m_dispositivo != 0) + { + SDL_CloseAudioDevice(m_dispositivo); // espera a que termine el callback en curso + SDL_QuitSubSystem(SDL_INIT_AUDIO); + } +} + +void Sonido::Callback(void* datos, Uint8* flujo, int longitud) +{ + static_cast(datos)->m_mezclador.Mezclar(reinterpret_cast(flujo), longitud / 2); +} + +void Sonido::Reproducir(Efecto e) +{ + SDL_LockAudioDevice(m_dispositivo); + m_mezclador.Reproducir(e); + SDL_UnlockAudioDevice(m_dispositivo); +} + +void Sonido::PausarMusica(bool pausa) +{ + SDL_LockAudioDevice(m_dispositivo); + m_mezclador.PausarMusica(pausa); + SDL_UnlockAudioDevice(m_dispositivo); +} + +bool Sonido::AlternarSilencio() +{ + SDL_LockAudioDevice(m_dispositivo); + m_mezclador.Silenciar(!m_mezclador.Silenciado()); + const bool r = m_mezclador.Silenciado(); + SDL_UnlockAudioDevice(m_dispositivo); + return r; +} + +bool Sonido::Silenciado() const +{ + SDL_LockAudioDevice(m_dispositivo); + const bool r = m_mezclador.Silenciado(); + SDL_UnlockAudioDevice(m_dispositivo); + return r; +} diff --git a/src/Sonido.h b/src/Sonido.h new file mode 100644 index 0000000..517944c --- /dev/null +++ b/src/Sonido.h @@ -0,0 +1,89 @@ +//------------------------------------------------------------------------------------ +// Sonido (Juego Runner - Modulo 4: audio) +// Encabezado C++ - Sonido.h +//------------------------------------------------------------------------------------ +// Audio con SDL2 puro, sin SDL_mixer ni archivos: los efectos y la musica se SINTETIZAN +// al arrancar (ondas cuadrada/triangular/sierra y ruido, a 22,05 kHz mono 16 bits). +// Sintesis funciones puras que generan las muestras (se prueban sin dispositivo) +// Mezclador suma voces y bucle de musica en un buffer; sin SDL, determinista +// Sonido abre el dispositivo SDL y alimenta el mezclador desde el hilo de audio +// Si no hay dispositivo de audio, Sonido::Abrir() devuelve nullptr y el juego sigue mudo. +//------------------------------------------------------------------------------------ +#pragma once + +#include + +#include +#include +#include +#include +#include + +enum class Efecto { Salto, Aterrizaje, Golpe, Hito, Inicio }; +inline constexpr int kNumEfectos = 5; + +namespace Sintesis +{ + inline constexpr int kFrecuencia = 22050; // Hz + + std::vector Generar(Efecto e); // un efecto (deterministas: mismas muestras siempre) + std::vector Musica(); // bucle sin cortes de 4 s +} + +class Mezclador +{ +public: + static constexpr int kVoces = 8; + + Mezclador(); + + // Registra las muestras de cada efecto (antes de reproducir) y la musica en bucle + void Registrar(Efecto e, std::vector muestras); + void EstablecerMusica(std::vector muestras); + + // Inicia un efecto. Sin voz libre sustituye a la mas avanzada. En silencio no hace nada. + void Reproducir(Efecto e); + void PausarMusica(bool pausa) noexcept { m_musicaPausada = pausa; } + void Silenciar(bool silencio) noexcept; + bool Silenciado() const noexcept { return m_silencio; } + + // Rellena 'n' muestras de salida (suma con saturacion, nunca desborda) + void Mezclar(std::int16_t* salida, int n) noexcept; + + int VocesActivas() const noexcept; + + double GananciaEfectos = 0.7; + double GananciaMusica = 0.28; + +private: + struct Voz { const std::vector* muestras = nullptr; std::size_t pos = 0; }; + + std::array, kNumEfectos> m_efectos; + std::vector m_musica; + std::array m_voces{}; + std::size_t m_posMusica = 0; + bool m_musicaPausada = false; + bool m_silencio = false; +}; + +class Sonido +{ +public: + // nullptr si no se puede abrir un dispositivo de audio (sin tarjeta, navegador sin permiso...) + static std::unique_ptr Abrir(); + ~Sonido(); + Sonido(const Sonido&) = delete; + Sonido& operator=(const Sonido&) = delete; + + void Reproducir(Efecto e); + void PausarMusica(bool pausa); + bool AlternarSilencio(); // devuelve true si queda en silencio + bool Silenciado() const; + +private: + Sonido() = default; + static void Callback(void* datos, Uint8* flujo, int longitud); + + SDL_AudioDeviceID m_dispositivo = 0; + Mezclador m_mezclador; +}; diff --git a/src/runner.cpp b/src/runner.cpp index 391cdd0..7bc20b6 100644 --- a/src/runner.cpp +++ b/src/runner.cpp @@ -1,13 +1,18 @@ //------------------------------------------------------------------------------------ // runner.cpp - Juego Runner completo (nativo y Emscripten) -// ESPACIO / FLECHA ARRIBA: saltar (y reiniciar tras GAME OVER). Esquiva los bugs rojos. -// Integra Textura (M1), Jugador (M2), GestorObstaculos/Partida/Hud (M3) en los hooks -// del motor: Actualizar(dt) a 60 Hz fijos y Pintar(SDL_Renderer*). +// ESPACIO / FLECHA ARRIBA: saltar (y reiniciar tras GAME OVER). M: 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 "Efectos.h" +#include "Escenario.h" #include "Hud.h" #include "NucleoMotor.h" +#include "Paleta.h" +#include "Sonido.h" -#include +#include #include #include #include @@ -30,44 +35,106 @@ class JuegoRunner : public Juego if (!m_hoja) // no abortamos: Jugador::Pintar usa un rectangulo de respaldo std::cerr << "Aviso: " << Textura::UltimoError() << std::endl; + m_sonido = Sonido::Abrir(); // nullptr = sin audio: el juego sigue mudo + if (!m_sonido) std::cerr << "Aviso: sin dispositivo de audio, el juego sonara mudo" << std::endl; + ConfigPartida cfg; cfg.ancho = m_ventana->Ancho(); cfg.ySuelo = m_ventana->Altura() - 80.0; - m_partida = std::make_unique(cfg, SDL_GetTicks()); // semilla distinta por sesion + 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()); return true; } + void Finalizar() override + { + m_sonido.reset(); // cerrar el audio antes de que el motor cierre SDL + m_hoja.reset(); + } + void Actualizar(double dt) override { const Ventana& v = *m_ventana; const bool saltar = v.TeclaPulsada(SDL_SCANCODE_SPACE) || v.TeclaPulsada(SDL_SCANCODE_UP) || v.TeclaPulsada(SDL_SCANCODE_W); + const bool tecla_m = v.TeclaPulsada(SDL_SCANCODE_M); + if (tecla_m && !m_mPrevia && m_sonido) m_sonido->AlternarSilencio(); + m_mPrevia = tecla_m; + m_partida->Actualizar(dt, saltar); - if (m_partida->Estado() == EstadoPartida::Jugando) - m_scroll = std::fmod(m_scroll + m_partida->Velocidad() * dt, 64.0); + Reaccionar(m_partida->TomarEventos()); + + const bool jugando = m_partida->Estado() == EstadoPartida::Jugando; + if (jugando && m_partida->ElJugador().EnElSuelo() && ++m_ticsPolvo % 7 == 0) + m_efectos->Polvo(PiesX() - 14, m_partida->Config().ySuelo, 1); // polvo al correr + m_escenario->Actualizar(dt, jugando ? m_partida->Velocidad() : 0.0); + m_efectos->Actualizar(dt); + m_resaltado = m_resaltado > dt ? m_resaltado - dt : 0.0; } void Pintar(SDL_Renderer* r) override { const Dibujante d(r); // el motor ya limpio el fondo const int ancho = m_ventana->Ancho(), alto = m_ventana->Altura(); - const int suelo = static_cast(m_partida->Config().ySuelo); + const double suelo = m_partida->Config().ySuelo; - d.RectanguloRelleno(SDL_Rect{ 0, suelo, ancho, alto - suelo }, Color{ 40, 48, 76, 255 }); - d.Linea(0, suelo, ancho, suelo, Colores::Gris); - for (int x = -static_cast(m_scroll); x < ancho; x += 64) - d.Linea(x, suelo + 20, x + 24, suelo + 20, Colores::Gris); + // El mundo se desplaza con la sacudida; la interfaz no + const SDL_Point s = m_efectos->Sacudida(); + const SDL_Rect vista{ s.x, s.y, ancho, alto }; + SDL_RenderSetViewport(r, &vista); + m_escenario->Pintar(d); + PintarSombra(d, suelo); m_partida->Obstaculos().Pintar(d); m_partida->ElJugador().Pintar(r, m_hoja.get()); - Hud::Pintar(d, *m_partida, ancho, alto); + m_efectos->Pintar(d); + + 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 }); } private: - Ventana* m_ventana = nullptr; - std::unique_ptr m_hoja; - std::unique_ptr m_partida; - double m_scroll = 0.0; + double PiesX() const { const SDL_Rect r = m_partida->ElJugador().Rectangulo(); return r.x + r.w / 2.0; } + + // Sombra en el suelo: se estrecha al subir el jugador + void PintarSombra(const Dibujante& d, double suelo) const + { + const double altura = suelo - m_partida->ElJugador().YPies(); + const int w = std::max(16, static_cast(46 - altura * 0.18)); + d.RectanguloRelleno(SDL_Rect{ static_cast(PiesX()) - w / 2, static_cast(suelo) + 1, w, 5 }, Paleta::SombraSuelo); + } + + void Reaccionar(const EventosPartida& ev) + { + 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.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; } + if (ev.choque) + { + sonar(Efecto::Golpe); + if (m_sonido) m_sonido->PausarMusica(true); + const SDL_Rect c = m_partida->ElJugador().CajaColision(); + m_efectos->Explosion(c.x + c.w / 2.0, c.y + c.h / 2.0); + m_efectos->Sacudir(9, 0.45); + m_efectos->Destello(0.3); + } + } + + Ventana* m_ventana = nullptr; + std::unique_ptr m_hoja; + std::unique_ptr m_sonido; + std::unique_ptr m_partida; + std::unique_ptr m_escenario; + std::unique_ptr m_efectos; + int m_ticsPolvo = 0; + bool m_mPrevia = false; + double m_resaltado = 0.0; }; } // namespace @@ -83,6 +150,7 @@ int main(int, char**) true #endif }; + config.colorFondo = Paleta::CieloArriba; // Duracion estatica: en Emscripten el bucle sigue vivo cuando main() retorna. static JuegoRunner juego; static NucleoMotor motor(config, juego); diff --git a/tests/test_efectos.cpp b/tests/test_efectos.cpp new file mode 100644 index 0000000..58ccf8f --- /dev/null +++ b/tests/test_efectos.cpp @@ -0,0 +1,409 @@ +//------------------------------------------------------------------------------------ +// Pruebas de QA del juego Runner - Modulo 4 (identidad visual, efectos y sonido) +// Se ejecutan sin pantalla ni altavoces: SDL_VIDEODRIVER=dummy, SDL_AUDIODRIVER=dummy. +// Test 4.1 Paleta armonica con el avatar y legible (contraste) +// Test 4.2 Escenario: parallax, ciclo sin saltos y cobertura total de pantalla +// Test 4.3 Efectos: particulas acotadas, sacudida que se apaga, determinismo +// Test 4.4 Eventos de la partida (la logica avisa; el juego reacciona) +// Test 4.5 Sintesis de audio, mezclador y dispositivo (con y sin audio) +//------------------------------------------------------------------------------------ +#include "Efectos.h" +#include "Escenario.h" +#include "Hud.h" +#include "Paleta.h" +#include "Sonido.h" +#include "Ventana.h" + +#include +#include +#include +#include +#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) + +#ifndef BGE_ASSETS_DIR +#define BGE_ASSETS_DIR "assets" +#endif + +namespace +{ +constexpr double kDt = 1.0 / 60.0; +constexpr int kAncho = 640, kAlto = 480; +constexpr double kSuelo = 400.0; +constexpr std::uint32_t Pack(Color c) { return 0xFF000000u | (c.r << 16) | (c.g << 8) | c.b; } + +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; +} + +double Lin(int c) { const double s = c / 255.0; return s <= 0.03928 ? s / 12.92 : std::pow((s + 0.055) / 1.055, 2.4); } +double Luz(Color c) { return 0.2126 * Lin(c.r) + 0.7152 * Lin(c.g) + 0.0722 * Lin(c.b); } +double Contraste(Color a, Color b) +{ + const double la = Luz(a), lb = Luz(b); + return (std::max(la, lb) + 0.05) / (std::min(la, lb) + 0.05); +} +double Dist(Color a, Color b) { return std::sqrt(double((a.r - b.r) * (a.r - b.r) + (a.g - b.g) * (a.g - b.g) + (a.b - b.b) * (a.b - b.b))); } + +// ---- Test 4.1 ------------------------------------------------------------------- +void Test_4_1() +{ + std::puts("Test 4.1: paleta"); + std::vector sprite; + if (SDL_Surface* bmp = SDL_LoadBMP(BGE_ASSETS_DIR "/avatar_run.bmp")) + { + SDL_Surface* s = SDL_ConvertSurfaceFormat(bmp, SDL_PIXELFORMAT_ARGB8888, 0); + SDL_FreeSurface(bmp); + std::set unicos; + for (int i = 0; i < s->w * s->h; ++i) unicos.insert(static_cast(s->pixels)[i] & 0xFFFFFFu); + for (auto p : unicos) if (p != 0xFF00FFu) sprite.push_back(Color{ std::uint8_t(p >> 16), std::uint8_t(p >> 8), std::uint8_t(p), 255 }); + SDL_FreeSurface(s); + } + CHECK(!sprite.empty(), "se pudo leer la hoja de sprites del avatar"); + + auto cercano = [&](Color c) { double m = 1e9; for (Color s : sprite) m = std::min(m, Dist(c, s)); return m; }; + struct { const char* n; Color c; } acentos[] = { { "violeta", Paleta::Violeta }, { "verde", Paleta::Verde }, + { "marron", Paleta::Marron }, { "piel", Paleta::Piel } }; + for (auto& a : acentos) + { + char m[96]; std::snprintf(m, sizeof m, "el %s de la paleta existe en el sprite del avatar (distancia %.0f <= 25)", a.n, cercano(a.c)); + CHECK(cercano(a.c) <= 25.0, m); + } + std::printf(" (dorado: distancia al sprite %.0f; es el tono de los botones, no se exige)\n", cercano(Paleta::Dorado)); + + // El mundo es mas oscuro que el personaje: el avatar siempre destaca + const Color fondos[] = { Paleta::CieloArriba, Paleta::CieloHorizonte, Paleta::ColinaLejana, Paleta::ColinaCercana, Paleta::Suelo }; + bool masOscuro = true; + for (Color f : fondos) if (Luz(f) >= Luz(Paleta::Violeta)) masOscuro = false; + CHECK(masOscuro, "todos los colores del fondo son mas oscuros que el violeta del avatar"); + CHECK(Contraste(Paleta::Violeta, Paleta::CieloHorizonte) >= 1.8 && Contraste(Paleta::Verde, Paleta::Suelo) >= 3.0, + "violeta y verde del avatar contrastan con el cielo y el suelo"); + + // Peligro y texto legibles + CHECK(Contraste(Paleta::BugCuerpo, Paleta::CieloHorizonte) >= 3.0, "los bugs naranjas destacan sobre el cielo"); + CHECK(Contraste(Paleta::Contorno, Paleta::Hierba) >= 4.0 && Contraste(Paleta::Contorno, Paleta::BugCuerpo) >= 4.0, + "sobre la hierba (luminosidad parecida) el contorno oscuro del bug lo separa con claridad"); + CHECK(std::fabs(Dist(Paleta::BugCuerpo, Paleta::Verde) - Dist(Paleta::BugCuerpo, Paleta::Violeta)) < 400 && + Dist(Paleta::BugCuerpo, Paleta::Verde) > 250 && Dist(Paleta::BugCuerpo, Paleta::Violeta) > 150, + "el naranja es un tono claramente distinto del violeta y del verde del avatar (no se confunde con el)"); + CHECK(Contraste(Paleta::TextoClaro, Paleta::CieloHorizonte) >= 4.5 && Contraste(Paleta::TextoClaro, Paleta::CieloArriba) >= 7.0, + "el texto del HUD cumple contraste AA sobre todo el degradado del cielo"); + CHECK(Contraste(Paleta::Dorado, Paleta::CieloArriba) >= 7.0 && Contraste(Paleta::Verde, Paleta::CieloArriba) >= 7.0, + "las cifras doradas y verdes del HUD tambien se leen bien"); +} + +// ---- Test 4.2 ------------------------------------------------------------------- +void Test_4_2(SDL_Renderer* r) +{ + std::puts("Test 4.2: escenario"); + const Dibujante d(r); + const Color centinela{ 255, 0, 255, 255 }; + + Escenario e(kAncho, kAlto, kSuelo); + d.Limpiar(centinela); + e.Pintar(d); + const auto px = Leer(r); + CHECK(std::count(px.begin(), px.end(), Pack(centinela)) == 0, "el escenario cubre toda la pantalla (sin huecos)"); + CHECK(px[static_cast(kSuelo + 5) * kAncho + 100] == Pack(Paleta::Hierba) || + px[static_cast(kSuelo + 5) * kAncho + 100] == Pack(Paleta::SombraSuelo), "bajo los pies hay hierba"); + CHECK(px[static_cast(5) * kAncho + 3] == Pack(Paleta::CieloArriba), "arriba del todo el cielo es el violeta oscuro"); + + // Parallax: capas lejanas mas lentas + Escenario p(kAncho, kAlto, kSuelo); + for (int i = 0; i < 60; ++i) p.Actualizar(kDt, 300.0); + std::printf(" tras 1 s a 300 px/s: suelo %.1f, colinas cercanas %.1f, lejanas %.1f\n", + p.DesplazamientoSuelo(), p.DesplazamientoCerca(), p.DesplazamientoLejos()); + CHECK(std::fabs(p.DesplazamientoSuelo() - 300.0) < 1.0 && std::fabs(p.DesplazamientoCerca() - 90.0) < 1.0 && + std::fabs(p.DesplazamientoLejos() - 30.0) < 1.0, "suelo 100%, colinas cercanas 30%, lejanas 10% de la velocidad"); + + // Congelado cuando velocidad = 0 (GAME OVER) + const double s0 = p.DesplazamientoSuelo(); + for (int i = 0; i < 30; ++i) p.Actualizar(kDt, 0.0); + CHECK(p.DesplazamientoSuelo() == s0, "con velocidad 0 el escenario se congela"); + + // Sin saltos al dar la vuelta al ciclo: antes y despues del cambio casi todos los pixeles coinciden + Escenario s(kAncho, kAlto, kSuelo); + s.Actualizar(1.0, 1279.0 / 0.30); // colinas cercanas justo antes de completar el periodo + d.Limpiar(centinela); s.Pintar(d); const auto antes = Leer(r); + s.Actualizar(1.0, 1.0 / 0.30); // cruzan el periodo (+1 px) + d.Limpiar(centinela); s.Pintar(d); const auto despues = Leer(r); + std::size_t difieren = 0; + for (std::size_t i = 0; i < antes.size(); ++i) difieren += (antes[i] != despues[i]); + const double pct = 100.0 * difieren / antes.size(); + std::printf(" pixeles distintos al cruzar el periodo: %.2f%%\n", pct); + CHECK(pct < 4.0, "el ciclo de las colinas enlaza sin saltos visibles"); + + // Determinismo + Escenario a(kAncho, kAlto, kSuelo, 5), b(kAncho, kAlto, kSuelo, 5); + d.Limpiar(centinela); a.Pintar(d); const auto pa = Leer(r); + d.Limpiar(centinela); b.Pintar(d); const auto pb = Leer(r); + CHECK(pa == pb, "misma semilla -> mismo escenario"); +} + +// ---- Test 4.3 ------------------------------------------------------------------- +void Test_4_3(SDL_Renderer* r) +{ + std::puts("Test 4.3: efectos"); + const Dibujante d(r); + const Color centinela{ 255, 0, 255, 255 }; + + Efectos e(kSuelo, 3); + for (int i = 0; i < 20; ++i) e.Explosion(300, 350); + CHECK(e.Activas() <= Efectos::kMaxParticulas && e.Activas() == Efectos::kMaxParticulas, + "capacidad fija: 20 explosiones seguidas llenan el pool sin desbordarlo"); + + // Las particulas no atraviesan el suelo (mientras viven) + bool bajoSuelo = false; + for (int i = 0; i < 90; ++i) + { + e.Actualizar(kDt); + d.Limpiar(centinela); e.Pintar(d); + const auto px = Leer(r); + for (int y = static_cast(kSuelo) + 6; y < kAlto && !bajoSuelo; ++y) + for (int x = 0; x < kAncho; ++x) if (px[static_cast(y) * kAncho + x] != Pack(centinela)) { bajoSuelo = true; break; } + } + CHECK(!bajoSuelo, "ninguna particula se dibuja por debajo del suelo"); + for (int i = 0; i < 120; ++i) e.Actualizar(kDt); + CHECK(e.Activas() == 0, "todas las particulas mueren y se liberan (a los ~3 s no queda ninguna)"); + + Efectos p(kSuelo, 3); + p.Polvo(100, kSuelo, 5); + CHECK(p.Activas() == 5, "Polvo(n) emite n particulas"); + p.Chispas(60, 24); + CHECK(p.Activas() == 5 + 14, "Chispas emite 14 particulas"); + + // Sacudida + Efectos s(kSuelo, 9); + CHECK(s.Sacudida().x == 0 && s.Sacudida().y == 0, "en reposo no hay desplazamiento"); + s.Sacudir(9, 0.45); + int maxPrimera = 0, maxUltima = 0; + bool acotada = true; + for (int i = 0; i < 27; ++i) // 0,45 s = 27 tics + { + s.Actualizar(kDt); + const int m = std::max(std::abs(s.Sacudida().x), std::abs(s.Sacudida().y)); + if (m > 9) acotada = false; + if (i < 9) maxPrimera = std::max(maxPrimera, m); + if (i >= 18) maxUltima = std::max(maxUltima, m); + } + s.Actualizar(kDt); s.Actualizar(kDt); + CHECK(acotada, "el desplazamiento nunca supera la amplitud"); + CHECK(maxPrimera >= 4 && maxUltima < maxPrimera, "la sacudida es fuerte al principio y decae"); + CHECK(s.Sacudida().x == 0 && s.Sacudida().y == 0, "al terminar la duracion la pantalla queda quieta"); + + // Destello + Efectos f(kSuelo); + f.Destello(0.3); + CHECK(f.IntensidadDestello() == 1.0, "el destello empieza a intensidad 1"); + for (int i = 0; i < 6; ++i) f.Actualizar(kDt); + const double mitad = f.IntensidadDestello(); + for (int i = 0; i < 20; ++i) f.Actualizar(kDt); + CHECK(mitad > 0.3 && mitad < 0.8 && f.IntensidadDestello() == 0.0, "el destello se apaga linealmente"); + d.Limpiar(centinela); f.PintarDestello(d, kAncho, kAlto); + const auto apagado = Leer(r); + CHECK(std::count(apagado.begin(), apagado.end(), Pack(centinela)) == kAncho * kAlto, "apagado, no dibuja nada"); + + // Determinismo + Efectos a(kSuelo, 11), b(kSuelo, 11); + for (Efectos* x : { &a, &b }) { x->Explosion(200, 300); for (int i = 0; i < 20; ++i) x->Actualizar(kDt); } + d.Limpiar(centinela); a.Pintar(d); const auto pa = Leer(r); + d.Limpiar(centinela); b.Pintar(d); const auto pb = Leer(r); + CHECK(pa == pb && pa != std::vector(pa.size(), Pack(centinela)), "misma semilla -> mismas particulas (y se ven)"); +} + +// ---- Test 4.4 ------------------------------------------------------------------- +void Test_4_4() +{ + std::puts("Test 4.4: eventos de la partida"); + auto vacio = [](const EventosPartida& e) { return !e.salto && !e.aterrizaje && !e.choque && !e.reinicio && e.hitos == 0; }; + + { + Partida p; + p.Obstaculos().Reiniciar(); + CHECK(vacio(p.TomarEventos()), "una partida recien creada no tiene eventos"); + int saltos = 0, aterrizajes = 0, otros = 0; + for (int t = 0; t < 120; ++t) + { + p.Obstaculos().Reiniciar(); // pista vacia: solo se prueba el salto + p.Actualizar(kDt, t == 5); + const auto e = p.TomarEventos(); + saltos += e.salto; aterrizajes += e.aterrizaje; otros += e.choque + e.reinicio + e.hitos; + } + CHECK(saltos == 1 && aterrizajes == 1 && otros == 0, "un salto emite exactamente un 'salto' y un 'aterrizaje'"); + p.Actualizar(kDt, false); + CHECK(vacio(p.TomarEventos()), "TomarEventos() borra los eventos pendientes"); + } + { + Partida p; + for (int i = 0; i < 20; ++i) p.Actualizar(kDt, false); // varios tics antes de recoger: se acumulan + const SDL_Rect c = p.ElJugador().CajaColision(); + Obstaculo o; o.x = c.x; o.y = p.Config().ySuelo - 30; o.ancho = 30; o.alto = 30; o.vx = 0; + p.Obstaculos().Agregar(o); + p.Actualizar(kDt, false); + auto e = p.TomarEventos(); + CHECK(e.choque && !e.reinicio && p.Estado() == EstadoPartida::GameOver, "el choque emite 'choque' una vez"); + for (int i = 0; i < 100; ++i) p.Actualizar(kDt, false); + CHECK(vacio(p.TomarEventos()), "en GameOver no hay mas eventos (el mundo esta congelado)"); + p.Actualizar(kDt, true); + e = p.TomarEventos(); + CHECK(e.reinicio && p.Estado() == EstadoPartida::Jugando, "reiniciar emite 'reinicio'"); + } + { + Partida p; + int hitos = 0; bool maxUno = true; + for (int t = 0; t < 600; ++t) + { + p.Obstaculos().Reiniciar(); + p.Actualizar(kDt, false); + const auto e = p.TomarEventos(); + hitos += e.hitos; if (e.hitos > 1) maxUno = false; + } + std::printf(" 10 s corriendo: %d puntos, %d hitos\n", p.Puntos(), hitos); + CHECK(hitos == p.Puntos() / 100 && hitos >= 2 && maxUno, "se emite un 'hito' por cada 100 puntos, sin repetir ni saltarse ninguno"); + } +} + +// ---- Test 4.5 ------------------------------------------------------------------- +double DuracionS(const std::vector& m) { return double(m.size()) / Sintesis::kFrecuencia; } +int Pico(const std::vector& m) { int p = 0; for (auto v : m) p = std::max(p, std::abs(int(v))); return p; } +double Rms(const std::vector& m) { double s = 0; for (auto v : m) s += double(v) * v; return std::sqrt(s / m.size()); } + +void Test_4_5_Sintesis() +{ + std::puts("Test 4.5: sintesis, mezclador y dispositivo"); + struct { Efecto e; const char* n; double min, max; } casos[] = { + { Efecto::Salto, "salto", 0.15, 0.4 }, { Efecto::Aterrizaje, "aterrizaje", 0.05, 0.25 }, + { Efecto::Golpe, "golpe", 0.4, 1.0 }, { Efecto::Hito, "hito", 0.2, 0.6 }, { Efecto::Inicio, "inicio", 0.2, 0.6 } }; + std::vector> todos; + for (auto& c : casos) + { + const auto m = Sintesis::Generar(c.e); + todos.push_back(m); + char msg[128]; + std::snprintf(msg, sizeof msg, "%s: %.2f s, pico %d, rms %.0f", c.n, DuracionS(m), Pico(m), Rms(m)); + std::printf(" %s\n", msg); + const double media = std::accumulate(m.begin(), m.end(), 0.0, [](double a, std::int16_t v) { return a + v; }) / m.size(); + CHECK(DuracionS(m) >= c.min && DuracionS(m) <= c.max, "duracion razonable"); + CHECK(Pico(m) >= 0.3 * 32767 && Pico(m) <= 0.9 * 32767, "volumen audible y sin saturar (pico entre 30% y 90%)"); + CHECK(Rms(m) > 500 && std::fabs(media) < 0.05 * Pico(m), "no es silencio ni tiene componente continua"); + CHECK(std::abs(m.front()) <= 300 && std::abs(m.back()) <= 300, "empieza y termina en silencio (sin clics)"); + CHECK(m == Sintesis::Generar(c.e), "determinista: dos generaciones dan las mismas muestras"); + } + bool distintos = true; + for (std::size_t i = 0; i < todos.size(); ++i) for (std::size_t j = i + 1; j < todos.size(); ++j) if (todos[i] == todos[j]) distintos = false; + CHECK(distintos, "los cinco efectos suenan distinto"); + + const auto mus = Sintesis::Musica(); + std::printf(" musica: %.2f s, pico %d, rms %.0f\n", DuracionS(mus), Pico(mus), Rms(mus)); + CHECK(std::fabs(DuracionS(mus) - 4.0) < 0.01, "la musica dura 4 s (16 corcheas a 120 ppm)"); + CHECK(Pico(mus) <= 0.9 * 32767 && Rms(mus) > 500, "musica audible y sin saturar"); + CHECK(std::abs(mus.front()) <= 300 && std::abs(mus.back()) <= 300 && std::abs(mus.front() - mus.back()) <= 600, + "el bucle enlaza: final e inicio estan en silencio (sin chasquido al repetir)"); +} + +void Test_4_5_Mezclador() +{ + { + Mezclador m; + const auto salto = Sintesis::Generar(Efecto::Salto); + m.Registrar(Efecto::Salto, salto); + m.Reproducir(Efecto::Salto); + CHECK(m.VocesActivas() == 1, "Reproducir ocupa una voz"); + std::vector sal; + std::int16_t bloque[100]; + for (std::size_t i = 0; i < salto.size() + 500; i += 100) { m.Mezclar(bloque, 100); sal.insert(sal.end(), bloque, bloque + 100); } + bool igual = true; + for (std::size_t i = 0; i < salto.size(); ++i) if (sal[i] != static_cast(std::lround(salto[i] * 0.7))) igual = false; + bool silencioDespues = true; + for (std::size_t i = salto.size(); i < sal.size(); ++i) if (sal[i] != 0) silencioDespues = false; + CHECK(igual && silencioDespues, "la salida es la muestra x ganancia, y despues silencio (mezclando en bloques de 100)"); + CHECK(m.VocesActivas() == 0, "la voz se libera al terminar"); + } + { + Mezclador m; + m.EstablecerMusica({ 1000, 2000, 3000 }); + std::int16_t s[7]; + m.Mezclar(s, 7); + CHECK(s[0] == 280 && s[1] == 560 && s[2] == 840 && s[3] == 280 && s[6] == 280, "la musica se repite en bucle sin cortes"); + m.PausarMusica(true); m.Mezclar(s, 7); + CHECK(std::all_of(s, s + 7, [](std::int16_t v) { return v == 0; }), "pausada, la musica no suena"); + m.PausarMusica(false); + m.Registrar(Efecto::Hito, std::vector(5000, 1000)); + m.Reproducir(Efecto::Hito); + m.Silenciar(true); + m.Mezclar(s, 7); + CHECK(std::all_of(s, s + 7, [](std::int16_t v) { return v == 0; }) && m.VocesActivas() == 0, "silenciado: todo a cero y se cortan las voces"); + m.Reproducir(Efecto::Hito); + CHECK(m.VocesActivas() == 0, "en silencio no se inician voces nuevas"); + m.Silenciar(false); m.Reproducir(Efecto::Hito); + CHECK(m.VocesActivas() == 1, "al reactivar el sonido vuelve a funcionar"); + } + { + Mezclador m; + m.GananciaEfectos = 1.0; + m.Registrar(Efecto::Golpe, std::vector(50, 30000)); + m.Registrar(Efecto::Hito, std::vector(50, -30000)); + m.Reproducir(Efecto::Golpe); m.Reproducir(Efecto::Golpe); + std::int16_t s[10]; m.Mezclar(s, 10); + CHECK(std::all_of(s, s + 10, [](std::int16_t v) { return v == 32767; }), "la suma satura en 32767 (no da la vuelta a negativo)"); + std::int16_t resto[40]; m.Mezclar(resto, 40); // agota las voces anteriores + m.Reproducir(Efecto::Hito); m.Reproducir(Efecto::Hito); m.Mezclar(s, 10); + CHECK(std::all_of(s, s + 10, [](std::int16_t v) { return v == -32768; }), "y satura en -32768 por abajo"); + for (int i = 0; i < 30; ++i) m.Reproducir(Efecto::Golpe); + CHECK(m.VocesActivas() == Mezclador::kVoces, "con todas las voces ocupadas se sustituye la mas antigua (sin desbordar)"); + } +} + +void Test_4_5_Dispositivo() +{ + // Sin audio disponible: Abrir() devuelve nullptr y el juego puede seguir mudo + SDL_setenv("SDL_AUDIODRIVER", "controlador_inexistente", 1); + CHECK(Sonido::Abrir() == nullptr, "sin dispositivo de audio, Abrir() devuelve nullptr (sin excepcion ni cierre)"); + SDL_setenv("SDL_AUDIODRIVER", "dummy", 1); + + auto s = Sonido::Abrir(); + CHECK(s != nullptr, "con dispositivo, Abrir() devuelve el sonido"); + if (!s) return; + for (int i = 0; i < kNumEfectos; ++i) s->Reproducir(static_cast(i)); // en paralelo con el hilo de audio + SDL_Delay(120); + for (int i = 0; i < 200; ++i) { s->Reproducir(Efecto::Salto); s->PausarMusica(i % 2 == 0); } + CHECK(!s->Silenciado() && s->AlternarSilencio() && s->Silenciado() && !s->AlternarSilencio(), "M alterna entre silencio y sonido"); + s.reset(); + CHECK(Sonido::Abrir() != nullptr, "se puede cerrar y volver a abrir el audio"); +} +} // namespace + +int main() +{ + try + { + Test_4_1(); + { + Ventana v(ConfigVentana{ "efectos", kAncho, kAlto, false, true }); + Test_4_2(v.Renderizador()); + Test_4_3(v.Renderizador()); + } + Test_4_4(); + Test_4_5_Sintesis(); + Test_4_5_Mezclador(); + Test_4_5_Dispositivo(); + } + 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 c6f6e9a..5085270 100644 --- a/web/minimal_shell.html +++ b/web/minimal_shell.html @@ -10,24 +10,24 @@ html, body { height: 100%; margin: 0; } body { display: flex; flex-direction: column; align-items: center; justify-content: center; - gap: 14px; padding: 16px; background: #0d1020; color: #c9d1e8; + gap: 14px; padding: 16px; background: #0e0620; color: #d9c8f0; font: 14px/1.4 system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; } h1 { margin: 0; font-size: 18px; font-weight: 600; letter-spacing: .04em; color: #fff; } #marco { position: relative; width: min(100%, 640px); aspect-ratio: 4 / 3; - background: #141a33; border: 1px solid #2a3358; border-radius: 8px; overflow: hidden; + background: #1b0b3a; border: 1px solid #4a2a7a; border-radius: 8px; overflow: hidden; box-shadow: 0 10px 40px rgba(0, 0, 0, .5); } canvas#canvas { display: block; width: 100%; height: 100%; outline: none; background: #000; } #estado { position: absolute; inset: 0; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 12px; padding: 24px; - text-align: center; background: #141a33; transition: opacity .25s; + text-align: center; background: #1b0b3a; transition: opacity .25s; } #estado.oculto { opacity: 0; pointer-events: none; } - #barra { width: 60%; height: 6px; background: #232b4d; border-radius: 3px; overflow: hidden; } - #barra > i { display: block; height: 100%; width: 0; background: #f0b428; transition: width .15s; } + #barra { width: 60%; height: 6px; background: #3a1f66; border-radius: 3px; overflow: hidden; } + #barra > i { display: block; height: 100%; width: 0; background: #ecbe30; transition: width .15s; } #error { display: none; position: absolute; inset: 0; align-items: center; justify-content: center; flex-direction: column; gap: 8px; padding: 24px; text-align: center; @@ -35,7 +35,7 @@ } #error.visible { display: flex; } #error code { display: block; max-width: 100%; overflow-wrap: anywhere; font-size: 12px; color: #ffb3b8; } - small { color: #7d89b3; } + small { color: #9a86c4; } noscript { color: #ffb3b8; }