From 97335c9d216250e79652909d7b164be86eb4b673 Mon Sep 17 00:00:00 2001 From: Diego De la Viuda Llorente Date: Thu, 29 Oct 2026 18:01:19 +0100 Subject: [PATCH] Personajes seleccionables --- README.md | 47 +- assets/characters/band/README.md | 15 + assets/characters/band/bassist.svg | 790 +++++ assets/characters/band/drummer.svg | 736 ++++ assets/characters/band/guitarist.svg | 663 ++++ assets/characters/band/singer.svg | 689 ++++ docs/architecture.md | 23 +- docs/characters.md | 99 + docs/design_vision.md | 50 +- docs/level_01.md | 2 +- docs/level_design.md | 8 +- docs/pixel_combat.md | 18 +- docs/project_status.md | 31 +- docs/start_menu.md | 28 +- docs/tuning.md | 24 +- effects/combat_fx.gd | 105 +- game/player_progress.gd | 3 +- game/run_session.gd | 31 + mortal_maze_rare_items_breakables.patch | 2990 ----------------- player/camera_2d.gd | 15 +- player/character_data.gd | 21 +- .../characters/animations/bassist_frames.tres | 266 ++ .../characters/animations/drummer_frames.tres | 266 ++ .../animations/guitarist_frames.tres | 266 ++ .../characters/animations/singer_frames.tres | 266 ++ player/characters/bassist.tres | 12 +- player/characters/drummer.tres | 12 +- player/characters/guitarist.tres | 12 +- player/characters/singer.tres | 12 +- player/player.gd | 43 +- player/player.tscn | 4 +- project.godot | 1 + tests/test_band_resources.py | 190 ++ tests/test_menu_resources.py | 7 +- tests/test_menu_runtime.gd | 32 +- tools/generate_band_art.py | 386 +++ ui/menu/character_card.gd | 25 + ui/menu/character_card.tscn | 47 + ui/menu/character_select.gd | 27 + ui/menu/character_select.tscn | 54 + ui/menu/main_menu.gd | 65 +- ui/menu/main_menu.tscn | 7 +- 42 files changed, 5282 insertions(+), 3106 deletions(-) create mode 100644 assets/characters/band/README.md create mode 100644 assets/characters/band/bassist.svg create mode 100644 assets/characters/band/drummer.svg create mode 100644 assets/characters/band/guitarist.svg create mode 100644 assets/characters/band/singer.svg create mode 100644 docs/characters.md create mode 100644 game/run_session.gd delete mode 100644 mortal_maze_rare_items_breakables.patch create mode 100644 player/characters/animations/bassist_frames.tres create mode 100644 player/characters/animations/drummer_frames.tres create mode 100644 player/characters/animations/guitarist_frames.tres create mode 100644 player/characters/animations/singer_frames.tres create mode 100644 tests/test_band_resources.py create mode 100644 tools/generate_band_art.py create mode 100644 ui/menu/character_card.gd create mode 100644 ui/menu/character_card.tscn create mode 100644 ui/menu/character_select.gd create mode 100644 ui/menu/character_select.tscn diff --git a/README.md b/README.md index 4aeb3dd..0409829 100644 --- a/README.md +++ b/README.md @@ -4,12 +4,13 @@ Plataformas y accion 2D sobre una banda de thrash metal, en Godot. Un solo `Player` utiliza cuatro recursos `CharacterData`; los escenarios se montan con piezas reutilizables desde el editor. -**Estado: prototipo con intro, menu, coleccion permanente y construccion visual de niveles.** +**Estado: prototipo con intro, menu, cuatro personajes elegibles, coleccion permanente y construccion visual de niveles.** Hay movimiento, combate, enemigos, objetos y HUD. Todavia no hay campana, guardado de campana, pausa, audio, bosses ni pantallas completas de victoria/derrota. Si existe guardado local de objetos raros confirmados al terminar un nivel. -La seleccion de personaje queda **aplazada por decision de diseno**: no bloquea -el trabajo de escenarios y menus; se utiliza el personaje ya asignado. +Al elegir un nivel aparece una **cuadricula 2x2**: Diego, Ivan, Fer y Hector. +Se escoge antes de cargar; morir conserva la eleccion. Sus ataques tienen la misma +logica, dano, alcance y tiempos: solo cambian aspecto y efectos visuales. [Tareas y decisiones](docs/design_vision.md) ยท [Estado y validacion](docs/project_status.md). @@ -23,18 +24,19 @@ Python no es necesario para editar ni para jugar. ```text Cargando... (intro de 10 s, saltable) -> INICIO -> JUGAR -> ELEGIR NIVEL - -> escenario elegido + -> ELEGIR PERSONAJE -> escenario elegido ``` El boton SALTAR INTRO funciona desde el primer arranque. Los diez segundos son una presentacion provisional, no una barra de progreso inventada. El menu se -carga en paralelo; cada nivel se carga al elegirlo, con su indicador de carga +carga en paralelo; cada nivel se carga tras elegir al personaje, con su indicador de carga real. El menu admite tacto, clics y navegacion de foco por teclado. | Escena | Uso | |---|---| | `game/main.tscn` | Entrada del proyecto e intro provisional | -| `ui/menu/main_menu.tscn` | Inicio y submenu de niveles | +| `ui/menu/main_menu.tscn` | Inicio y submenus de niveles/coleccion | +| `ui/menu/character_select.tscn` | Cuadricula tactil 2x2, antes de cargar un nivel | | `levels/level_00.tscn` | Beta: antigua calle Level02, 29 enemigos y 14 objetos | | `levels/level_01.tscn` | Nuevo recorrido vertical, 12 enemigos, 14 objetos y rincones opcionales | | `levels/templates/level_template.tscn` | Plantilla para crear escenarios | @@ -51,7 +53,7 @@ mano. Todos esos niveles estan accesibles: no hay desbloqueos todavia. **F6** sigue ejecutando la escena abierta sin pasar por la intro. En escenarios con `LevelRoot`, el boton **MENU**, Escape o Atras de Android devuelve al inicio sin repetir la intro. No pausa ni confirma raros: abandonar descarta su estado temporal. -Morir conserva la recarga del nivel actual. La meta colocable confirma los raros +Morir conserva la recarga del nivel actual y el personaje elegido. La meta colocable confirma los raros y vuelve al menu; la meta de la beta tambien confirma y reinicia tras nueve segundos. | Teclado | Accion | @@ -87,6 +89,24 @@ carteles, texto, fondo urbano, cinco variantes enemigas y 17 objetos recogibles. La decoracion puede estar delante o detras sin bloquear. HUD y controles no estorban al editar el mapa; se muestran al abrir sus propias escenas o al jugar. +## La banda y sus ataques + +| Personaje | Ground Pound (solo presentacion) | Especial (solo presentacion) | +|---|---|---| +| Diego, guitarrista | Golpea el suelo con la guitarra; rayos electricos | Solo de guitarra original | +| Ivan, bateria | Conserva la caida, trazos de baquetas e impacto anteriores | Platos en todas direcciones | +| Fer, bajista | Cae sentado; grietas en el suelo | Bajo y sacudida grave por cada pulso | +| Hector, cantante | Aterriza con el puno; cupula amarilla transparente | Microfono, grito y ondas | + +**El radio del Ground Pound aumenta de 54 a 108 para los cuatro.** El circulo, +formula, dano (7-12), tiempos y objetivos son compartidos. Los platos no son +proyectiles daninos; ondas, grietas y rayos no agregan impactos. Todos mantienen +50 de vida, velocidad 390, salto -600 y punetazo de 5, antes de mejoras. +El punetazo conserva la misma pose y tiempos, adaptando solo pelo/ropa. + +Ivan tiene pelo liso negro y munequeras; Fer pelo negro largo/rizado, manga corta +y pantalon corto; Hector es rubio y lleva pantalon corto. [Guia de personajes](docs/characters.md). + ## Objetos y especial Las mejoras de **dano general y dano aereo duran hasta recibir un golpe valido**, @@ -127,6 +147,7 @@ Colision y profundidad siguen siendo independientes; romper no recarga el especi | Tareas y decisiones | [Guia maestra](docs/design_vision.md) | | Evidencias y limites de validacion | [Estado](docs/project_status.md) | | Intro, menus y alta de niveles | [Inicio y menu](docs/start_menu.md) | +| Personajes, selector y efectos visuales | [La banda](docs/characters.md) | | Colocar piezas, objetos y salidas | [Niveles](docs/level_design.md) | | Velocidad, salto, duraciones y HUD | [Ajustes](docs/tuning.md) | | Responsabilidades y funciones | [Arquitectura](docs/architecture.md) | @@ -138,7 +159,9 @@ Los valores particulares de personaje viven en `player/characters/*.tres`; las reglas comunes, en las propiedades de `player/player.tscn`. La intro se ajusta en `game/main.tscn`; el aspecto del menu, en `ui/menu/`. No hay un segundo sistema de configuracion de combate en un singleton. `PlayerProgress` solo conserva -la coleccion y su catalogo; los efectos viven en `rare_items/data/*.tres`. Codigo nuevo en ingles; comentarios en espanol. +la coleccion y su catalogo; los efectos viven en `rare_items/data/*.tres`. +`RunSession` conserva solo la eleccion de personaje/nivel en memoria, no escribe +el guardado ni duplica ajustes de combate. Codigo en ingles; comentarios en espanol. **Diferencia pendiente:** el radio general del especial sigue en `100000`, pero Level00/Level01 lo sobrescriben a `290`. La plantilla hereda el general. El filtro @@ -155,7 +178,7 @@ El segundo comando importa el proyecto y ejecuta las once suites `*_runtime.gd`. En Windows, indica la ruta del ejecutable de consola entre comillas. El runner y las pruebas estaticas solo requieren la biblioteca estandar de Python. -**73 pruebas estaticas superadas en esta entrega.** La comprobacion jugable +**87 pruebas estaticas superadas en esta entrega.** La comprobacion jugable y visual corresponde a las pruebas locales del autor. Las once suites usan perfiles de prueba aislados y estan preparadas; tampoco se ha exportado una APK ni probado el tacto real. Los contratos de texto/geometria @@ -167,9 +190,9 @@ jugar. El workflow exporta, pero todavia no ejecuta el runner de pruebas. ## Continuar y aplicar cambios -La seleccion de personaje, su momento y las restricciones por nivel se decidiran -mas adelante. Se puede continuar con escenarios, audio, pausa y validacion sin -cerrar ahora esa decision. El menu actual es de pruebas, no una campana final. +La seleccion se hace antes de cada entrada a un nivel desde el menu; no hay +personajes bloqueados ni obligatorios por escenario. Quedan audio, pausa, +resultado y continuidad. El menu actual es de pruebas, no una campana final. Las entregas se aplican como **parches Git** sobre la base indicada: diff --git a/assets/characters/band/README.md b/assets/characters/band/README.md new file mode 100644 index 0000000..091f0b1 --- /dev/null +++ b/assets/characters/band/README.md @@ -0,0 +1,15 @@ +# Atlas de la banda + +Cuatro SVG autocontenidos, de 512 x 320, con celdas de 64 x 64. Derivan del arte +pixelado ya presente en `../ankarde/player_pixel.svg`. No incorporan imagenes +externas, fuentes ni dependencias durante la partida. + +Los SpriteFrames estan en `player/characters/animations/`. Diego conserva las +celdas previas salvo ground_pound; los otros integrantes adaptan pelo/ropa y +las poses de ataques propias. Todos mantienen tiempos y cajas fisicas comunes. + +Para editar manualmente, modifica SVG/SpriteFrames y conserva sus regiones. +La utilidad `tools/generate_band_art.py` regenera ambos (requiere Pillow), +sobrescribiendo el arte de esta carpeta. No es parte del arranque del juego. + +Documentacion de comportamiento: `docs/characters.md`. diff --git a/assets/characters/band/bassist.svg b/assets/characters/band/bassist.svg new file mode 100644 index 0000000..2a2a652 --- /dev/null +++ b/assets/characters/band/bassist.svg @@ -0,0 +1,790 @@ + +bassist: band member animations + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/assets/characters/band/drummer.svg b/assets/characters/band/drummer.svg new file mode 100644 index 0000000..2cc9889 --- /dev/null +++ b/assets/characters/band/drummer.svg @@ -0,0 +1,736 @@ + +drummer: band member animations + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/assets/characters/band/guitarist.svg b/assets/characters/band/guitarist.svg new file mode 100644 index 0000000..ff66f91 --- /dev/null +++ b/assets/characters/band/guitarist.svg @@ -0,0 +1,663 @@ + +guitarist: band member animations + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/assets/characters/band/singer.svg b/assets/characters/band/singer.svg new file mode 100644 index 0000000..fe2e2ce --- /dev/null +++ b/assets/characters/band/singer.svg @@ -0,0 +1,689 @@ + +singer: band member animations + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/docs/architecture.md b/docs/architecture.md index 57cfeda..30d02a8 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -7,8 +7,9 @@ las tareas y [la revision del proyecto](project_status.md), sus evidencias. `project.godot` inicia `game/main.tscn` con `boot.gd`: intro de 10 s saltable y carga asincrona del menu. `ui/menu/main_menu.gd` descubre escenas de la raiz de levels -y carga solo la elegida. `PlayerProgress` es el unico autoload: catalogo y -coleccion local confirmada, sin responsabilidades de seleccion ni campana. +y muestra el selector de personajes antes de cargar solo la elegida. +`PlayerProgress` mantiene catalogo y coleccion confirmada. `RunSession` mantiene +ruta/personaje en memoria para recargar sin perder la eleccion, sin tocar el perfil. `LevelRoot` aplica camara/caidas y agrega una instancia de LevelNavigation solo al jugar. Esta ofrece MENU/Escape/Atras; la salida Area2D reutilizable tambien @@ -18,7 +19,8 @@ Ambas van directamente al menu, no a la intro. Player._die aun recarga el mapa, la meta de beta Level00 aun reinicia tras 9 s y la nueva salida de Level01 confirma raros y vuelve al inicio. No existe un coordinador de victoria/derrota ni campana. Resolver las recargas competidoras cuando se implemente ese flujo. -La seleccion de personaje se aplaza; se usa el recurso asignado al Player. +La seleccion se realiza antes de cada entrada desde el menu. F6 utiliza el +recurso asignado al Player; por defecto, Diego. No hay restricciones por mapa. F6 sigue siendo independiente del menu. La plantilla permite nuevos niveles sin script propio, y una salida se puede colocar arrastrando su escena. Mas detalle @@ -41,6 +43,11 @@ abrirse y ejecutarse directamente sin un generador ni un plugin de edicion. | Archivo / carpeta | Responsabilidad | |---|---| | `game/player_progress.gd/.tscn` | Catalogo, unicidad, atributos y archivo local de raros confirmados | +| `game/run_session.gd` | Ruta y personaje elegidos en memoria; sin disco ni estadisticas | +| `ui/menu/character_select.gd/.tscn` | Cuatro tarjetas 2x2 y senales de elegir/volver | +| `ui/menu/character_card.gd/.tscn` | Boton con retrato obtenido del mismo SpriteFrames del personaje | +| `player/characters/animations/` | Un SpriteFrames por integrante, con tiempos compartidos | +| `assets/characters/band/` | Cuatro atlas SVG de 40 celdas, sin fuentes ni imagenes externas | | `rare_items/` | Datos, recogida pendiente y variantes visuales de objetos raros | | `ui/menu/rare_inventory.gd` | Coleccion en el menu, sin equipamiento ni efectos propios | | `game/boot.gd` | Espera provisional, salto y carga del menu | @@ -79,7 +86,8 @@ superficies, varios adornos, texto sobre adornos y varios niveles con limites de camara. El terreno no conoce al jugador. SceneryProp admite el contrato `take_damage` para romperse; RarePickup comunica su hallazgo al LevelRoot propietario. -Solo el perfil confirmado necesita vivir entre escenas. No se han creado +El perfil confirmado y la eleccion temporal necesitan vivir entre escenas, +pero estan separados: `RunSession` no tiene acceso al archivo de progreso. No se han creado fabricas de niveles, un sistema universal de eventos ni un plugin propio para sustituir el flujo de escenas de Godot. El catalogo es una escena normal que puedes editar. @@ -89,6 +97,13 @@ tengan que intercambiar todo su estado. Esta entrega modifica las reglas de mejoras en Player, sin cambiar el movimiento ni la IA. Una extraccion futura deberia responder a una segunda reutilizacion real o a una responsabilidad con estado propio. +Los cuatro integrantes usan las mismas funciones daninas y cajas fisicas. +CharacterData solo selecciona animaciones, efecto de aterrizaje y presentacion +del especial. El radio compartido de Ground Pound es 108. No hay clase Player por +personaje, proyectiles de platos ni dano asociado a dibujos. +`_pound_landing_timer` elige una pose visual, no bloquea entradas ni altera cooldown. +La vibracion grave de Fer se sincroniza con los pulsos comunes, sin otro reloj de dano. + ## Navegar por Player La primera parte de `player.gd` contiene los ajustes exportados y sus ayudas. diff --git a/docs/characters.md b/docs/characters.md new file mode 100644 index 0000000..248e2cf --- /dev/null +++ b/docs/characters.md @@ -0,0 +1,99 @@ +# La banda: seleccion, aspecto y combate compartido + +## Regla principal + +Los cuatro integrantes son elecciones visuales. Usan **un solo Player**, una +forma fisica y las mismas funciones de combate. A igualdad de carga, altura, +distancia, nivel y mejoras, el dano, alcance, tiempos y objetivos son iguales. +Ni los platos son proyectiles daninos ni las ondas/grietas/rayos producen golpes +por contacto. Los efectos solo dibujan y desaparecen. + +Ground Pound tiene **radio 108 para todos**, el doble de los 54 anteriores. Se +mantiene el circulo y su centro, la caida, formula por altura, limites 7-12 y +reglas de mejoras. No se suman impactos por dibujar mas rayos o platos. +El especial conserva carga 100, +10 por baja, minimo 25, 2.4 s y cuatro pulsos. +La Pua Perdida aplica su +20% igual a los cuatro; no cambia el formato de guardado. + +Los cuatro recursos mantienen vida 50, velocidad 390, salto -600 y punetazo 5. +No se ha reajustado el movimiento, el dano enemigo ni el alcance especial de +cada nivel. El radio especial de 00/01 sigue en 290; la plantilla conserva su +valor heredado, una diferencia entre mapas, no entre personajes. + +## Aspecto y efectos + +| Nombre / recurso | Apariencia | Ground Pound | Especial | +|---|---|---|---| +| Diego / `guitarist` | Aspecto original | Baja la guitarra contra el suelo; rayos azules | Solo de guitarra original | +| Ivan / `drummer` | Pelo liso negro y munequeras | Caida/impacto anteriores y trazos tipo baqueta | Baquetas y platos giratorios en todas direcciones | +| Fer / `bassist` | Pelo negro largo/rizado, manga corta, pantalon corto | Caida sentado y grietas | Bajo; cada pulso coincide con una nota y vibracion grave | +| Hector / `singer` | Rubio y pantalon corto thrasher | Aterrizaje con puno y cupula amarilla semitransparente | Microfono, grito y frentes de onda | + +El punetazo conserva la misma pose, fotogramas, velocidades y duraciones: solo +se adaptan el pelo/ropa de cada integrante. Las celdas originales de Diego son +identicas salvo `ground_pound`; se anade `pound_land` para el golpe al aterrizar. +`land` sigue siendo el aterrizaje normal. No se bloquea el movimiento por esa +pose adicional. No hay sonido nuevo: el grito, los instrumentos y sus ondas son +animaciones/efectos visuales hasta que se integre audio. + +## Flujo de eleccion + +```text +Inicio -> Jugar -> Nivel -> Diego / Ivan / Fer / Hector (2x2) -> Carga -> Juego + | | + +-- Volver -> Niveles +-- Morir: mismo personaje +``` + +Toda la tarjeta es pulsable con tacto o clic. Hay scroll cuando no caben las dos +filas, foco de teclado y boton para volver. Elegir nivel aun no lo carga. +Elegir personaje inicia la carga y bloquea dobles pulsaciones. Un error vuelve +al selector sin dejar una sesion a medias. + +`RunSession` guarda solo ruta/recurso en memoria. Player resuelve la eleccion +antes de vida, animaciones, hitboxes y senales iniciales del HUD. Recargar por +muerte, caida o reinicio de la beta la conserva. El menu la limpia: cada entrada +muestra de nuevo la banda. No se persiste al cerrar, no se registra en los raros +y no hay restricciones ni personajes desbloqueables. + +Con F6 no hace falta pasar por el menu: se usa `Character Data` de Player en +esa escena. La escena base usa Diego; para revisar otro, cambia ese recurso en +el Inspector. `RunSession` solo aplica la eleccion si coincide la ruta de nivel +entre los ancestros, no a cualquier jugador de otra escena. + +## Donde editar + +| Necesidad | Archivo / propiedad | +|---|---| +| Nombre, rol, atlas, efecto y sacudida | `player/characters/*.tres` | +| Animaciones de cada integrante | `player/characters/animations/*_frames.tres` | +| Dibujos, sin dependencias externas | `assets/characters/band/*.svg` | +| Posiciones/nombres de tarjetas | `ui/menu/character_select.tscn` | +| Aspecto de una tarjeta | `ui/menu/character_card.tscn` | +| Alcance compartido del golpe de caida | Player > Ground Pound > `Ground Pound Radius` | +| Efectos temporales | `effects/combat_fx.gd` | +| Vibracion / superposicion | `player/camera_2d.gd` | +| Reducir o desactivar feedback | Camera2D > `Feedback Strength` (0 = apagado) | + +`ground_pound_effect` y `special_effect` eligen presentacion, no estrategias de +combate. `special_shake_*` solo ajusta la camara: Fer usa frecuencia mas lenta +y 3 px de amplitud maxima, sincronizados con los cuatro pulsos ya existentes. +El cuerpo fisico y los ataques no se mueven para dibujar esos efectos. + +Los SVG y `.tres` se incluyen listos. Python no es necesario para importar ni +jugar. `tools/generate_band_art.py` permite regenerarlos a partir del atlas +original; requiere Pillow solo como utilidad de arte. Sobrescribe los cuatro +atlas/recursos: no lo ejecutes sobre arte retocado a mano sin guardar sus cambios. + +## Revision manual del autor + +1. Abre cada nivel desde el menu con los cuatro integrantes. Comprueba nombre, + aspecto, retorno, doble pulsacion, muerte/reinicio y F6 con otro recurso. +2. Compara los ataques contra el mismo enemigo a la misma altura/distancia, + con la misma carga y mejoras. Ground Pound alcanza igual en todos; la pose + no debe cambiar colisiones, dano, knockback ni cooldown. +3. Revisa guitarra/baquetas/puno/caida sentado y los cuatro especiales. El dibujo + no debe causar impactos extra; romper un barril no concede carga. +4. Prueba la Pua Perdida confirmada y Feedback Strength a 0. El bono se mantiene + igual entre personajes y la vibracion de Fer se desactiva sin alterar dano. + +Las pruebas estaticas validan recursos, celdas, tiempos y reglas en el codigo; +no sustituyen jugar y revisar la presentacion en dispositivo. diff --git a/docs/design_vision.md b/docs/design_vision.md index e63d0da..f5f9bda 100644 --- a/docs/design_vision.md +++ b/docs/design_vision.md @@ -1,6 +1,6 @@ # Guia maestra: vision, decisiones y tareas -Actualizacion: **29 de octubre de 2026**, entrega de coleccion permanente y objetos rompibles. Este es el unico backlog activo. `[x]` significa presente +Actualizacion: **29 de octubre de 2026**, entrega de cuatro personajes y seleccion antes de cada nivel. Este es el unico backlog activo. `[x]` significa presente en la implementacion revisada, **no probado jugando**. `[ ]` queda pendiente. La evidencia de ejecucion se registra aparte en [Estado](project_status.md). @@ -17,11 +17,13 @@ checkpoints internos: reinicia el nivel. No hay experiencia ni arbol de habilida confirmadas solo al completar el nivel. Esto sustituye la restriccion inicial de no tener mejoras permanentes. No se guardan vida actual, carga ni buffs temporales. -**Decision expresamente aplazada: seleccion de personaje.** No se elige ahora -entre seleccion al arrancar, antes de cada nivel, tras morir o personaje impuesto -por escenario. No implementar restricciones ni un flujo de seleccion por inercia. -El proyecto sigue usando el recurso asignado al Player; esta decision no bloquea -escenarios, presentacion, audio, pruebas ni menus. +**Decision confirmada: seleccionar despues del nivel y antes de cargarlo.** +Cuatro tarjetas 2x2: Diego, Ivan, Fer y Hector. No se vuelve a elegir al morir; +regresar al menu permite otra eleccion. No hay personajes obligatorios ni +bloqueados. F6 conserva el recurso del Inspector. +**Misma logica de ataques para los cuatro:** dano, alcance, forma fisica, tiempos +y reglas de mejoras iguales; solo cambian animaciones y efectos. Ground Pound +tiene radio comun 108 (antes 54). El punetazo tambien comparte animacion. Flujo implementado ahora: @@ -29,7 +31,7 @@ Flujo implementado ahora: Intro 10 s, saltable -> Inicio -> Jugar -> lista de escenas en levels/ ^ | | v - +----- MENU / salida -- escenario + +----- MENU / salida -- personaje 2x2 -> escenario | +-- muerte: recarga ``` @@ -85,7 +87,11 @@ verificar el parche y separar implementacion de validacion efectiva. - [x] Descubrimiento no recursivo de escenas de la raiz `levels/`. - [x] MENU / Escape / Atras para abandonar escenarios sin repetir la intro. - [x] Meta arrastrable que confirma raros y vuelve al menu, sin sistema de campana. -- [x] Submenu OBJETOS RAROS con estado/efecto, sin equipamiento ni seleccion de personaje. +- [x] Submenu OBJETOS RAROS con estado/efecto, sin equipamiento. +- [x] Selector de banda 2x2 antes de cargar, con retratos/nombres y retorno a niveles. +- [x] Cuatro apariencias y efectos; Diego conserva las demas animaciones originales. +- [x] Ground Pound comun de radio 108, sin ventajas de dano/alcance por integrante. +- [x] Eleccion temporal independiente del guardado raro; muerte/caida la conservan. ### Escenarios y herramientas @@ -93,7 +99,7 @@ verificar el parche y separar implementacion de validacion efectiva. - [x] Level01: nuevo mapa vertical con 12 enemigos, 14 objetos y desvios opcionales. - [x] Laboratorio antiguo, su script y `lab_control.tres` retirados; tests desacoplados. - [x] Sala de combate y catalogo fuera del selector, dentro de subcarpetas. -- [x] 73 pruebas estaticas ejecutadas y once suites de motor preparadas, con perfil aislado. +- [x] 87 pruebas estaticas ejecutadas y once suites de motor preparadas, con perfil aislado. - [x] Preset Android arm64, script de exportacion y workflow Gitea conservados. - [x] README, guias y backlog actualizados con esta entrega. @@ -126,7 +132,7 @@ MENU abandona; no se ha implementado pausa por llamarlo menu. | Preparacion/movimiento/sensacion | Implementados, pendiente validacion en motor/dispositivo | | Combate basico/aereo/enemigo | Implementados con cinco perfiles de una IA | | Especial | Implementado, carga parcial y economia revisada | -| Personajes | Datos existentes, seleccion y diferenciacion aplazadas | +| Personajes | Cuatro apariencias/efectos y selector antes de nivel; logica de ataques compartida | | Nivel completo | Beta horizontal y nuevo vertical; no campana publicada | | Power-ups | 17 objetos, incluidos dano hasta golpe y temporales mas largos | | Inicio/seleccion de nivel | Implementado como selector libre de pruebas | @@ -146,6 +152,9 @@ MENU abandona; no se ha implementado pausa por llamarlo menu. - [ ] Probar dano igual/peor/mejor, golpe con escudo, invulnerabilidad y expiracion de temporales. - [ ] Verificar raros: recoger/morir/abandonar/ganar/reabrir, premio automatico y duplicados. - [ ] Verificar barriles: premio normal/raro/vacio, colision opcional y ataques sin recarga. +- [ ] Elegir cada integrante en 00/01, morir, volver al menu y probar F6. +- [ ] Comparar impactos/carga/rango con los mismos enemigos y mejoras para los cuatro. +- [ ] Revisar que los platos/rayos/ondas no apliquen dano por contacto visual. - [ ] Probar en Android, registrar dispositivo/orientacion/resultado, botones simultaneos y salida. Cierre: logs del runner y pruebas manuales con entorno, no solo contratos de texto. @@ -160,7 +169,7 @@ Listas: [menu](start_menu.md), [00](level_00.md), [01](level_01.md), [HUD](thras Cierre: escenarios comparables sin excepciones ocultas ni saltos que dependan de un buff obligatorio. -## NEXT - completar experiencia sin forzar seleccion de personaje +## NEXT - completar experiencia ### UX-01 - pausa y ajustes @@ -193,7 +202,7 @@ La salida actual es un avance parcial, no se marca esta tarea completa. - [x] Entrada real del juego y menu simple con niveles autodetectados. - [ ] Definir identificadores/orden de niveles de campana y continuacion entre dos escenarios. -- [ ] Resolver politica de personajes solo cuando el autor la elija; no bloquear otros trabajos. +- [x] Resolver politica: seleccion antes de cargar el nivel, conservar al morir; sin restricciones. - [ ] Separar selector de pruebas del acceso de una campana con desbloqueos. Cierre: continuar entre niveles sin editor, manteniendo las reglas de estado temporal decididas. @@ -210,8 +219,9 @@ Cierre: el progreso sobrevive al cierre, sin conservar por accidente el estado d ## LATER - decisiones y contenido -- [ ] CHAR-01: momento de seleccion, restricciones y arte/animaciones propios de integrantes. - La invisibilidad del bajista es solo una idea, no una mecanica existente. +- [x] CHAR-01: seleccion previa por nivel y apariencias/animaciones propias implementadas. +- [ ] CHAR-02: revisar transiciones, legibilidad de efectos y selector en dispositivo. + No implementar invisibilidad, proyectiles daninos ni ventajas de combate por personaje. - [ ] BOSS-01: primer boss concreto antes de abstraer un sistema de bosses. - [ ] CONTENT-01: capitulo/cancion representativo; retirar la beta cuando deje de ser util. - [ ] ENEMY-01: mecanicas nuevas como vuelo/proyectiles solo si un nivel las necesita. @@ -231,16 +241,18 @@ Player, LevelRoot y la meta beta aun pueden solicitar reinicios; resolver junto al flujo de resultado, no declarar que ya existe una sesion completa. La sala de combate no hereda LevelRoot. El workflow Android exporta pero no ejecuta los tests. -Se han pasado **73 pruebas estaticas**. La ejecucion jugable, las once suites +Se han pasado **87 pruebas estaticas**. La ejecucion jugable, las once suites y la comprobacion visual/dispositivo quedan a cargo del autor, como se ha acordado. [Evidencias](project_status.md). ## Contexto breve para continuar -Godot 4.7 / Compatibility, Player unico/singer asignado, cuatro datos provisionales. +Godot 4.7 / Compatibility, Player unico/Diego por defecto, cuatro integrantes elegibles. Movimiento/doble salto, combate normal/aereo/especial, cinco Walker, 17 objetos, kit visual y HUD thrash oculto al editar. F5intro de 10 s saltable->menu->niveles de raiz;00betaantiguo02,01verticalnuevo. F6 sigue directo. MENU/salida->menu sin intro. -Dano hasta golpe y solo mejores sustituyen; otros buffs de 30/45 s. Sin seleccion de -personaje, audio, pausa ni campana. Si hay coleccion rara permanente y barriles -rompibles: guardar solo al completar, nunca al abandonar. Seleccion aplazada expresamente. +Dano hasta golpe y solo mejores sustituyen; otros buffs de 30/45 s. Seleccion 2x2 +tras elegir nivel; al morir conserva personaje, al volver al menu se limpia. +Todos atacan igual; Ground Pound radio 108; solo efectos/poses diferentes. +Sin audio, pausa ni campana. Hay coleccion rara permanente y barriles +rompibles: guardar solo al completar, nunca al abandonar. Entregas por git apply; actualizar este backlog sin duplicarlo en otros documentos. diff --git a/docs/level_01.md b/docs/level_01.md index 680452a..a84e4cc 100644 --- a/docs/level_01.md +++ b/docs/level_01.md @@ -46,7 +46,7 @@ No hay accion de bajar atravesando plataformas: en el descenso sal por un latera | Plataformas principales de la torre | 12 | | Decoracion | 19 instancias, con barriles/cajas solidos y adornos no solidos | | Carteles de orientacion | 7, mas el cartel de salida | -| Personaje | El recurso ya asignado al Player, sin selector | +| Personaje | Elegido antes de cargar desde el menu; con F6, el recurso del Inspector | | Especial | Radio local 290; economia actual sin cambios | | Final | `Triggers/Exit`, confirma raros y vuelve al menu, sin desbloquear niveles | diff --git a/docs/level_design.md b/docs/level_design.md index 8b71824..0d06e53 100644 --- a/docs/level_design.md +++ b/docs/level_design.md @@ -224,8 +224,9 @@ La ocultacion de editor no es un sistema de pausa ni un ajuste de controles para escritorio. La validacion interactiva sigue siendo necesaria. El menu y la salida simple ya permiten probar escenarios. Las tareas de -resultado y campana estan en [la guia maestra](design_vision.md); la seleccion -de personaje queda aplazada, sin bloquear la construccion de mapas. +resultado y campana estan en [la guia maestra](design_vision.md). Todos los +niveles elegidos desde el menu muestran antes la banda; con F6 se respeta el +Character Data de la instancia de Player (Diego por defecto). ## Menu y salida de los nuevos niveles @@ -248,7 +249,8 @@ niveles ni sustituye una futura pantalla de resultado. La plantilla no obliga a colocar una salida. El nuevo [Level01](level_01.md) es un ejemplo vertical con desvios y salida. [Level00](level_00.md) conserva la calle de pruebas y su regla de meta/reinicio. No uses su script como plantilla. -Los eventos narrativos y la seleccion de personaje siguen aplazados. +Los eventos narrativos siguen aplazados. La seleccion de la banda es automatica +al entrar desde el menu; no hay que agregar un selector a cada mapa. ## Raros opcionales y recompensas al completar diff --git a/docs/pixel_combat.md b/docs/pixel_combat.md index e04abac..a045bc3 100644 --- a/docs/pixel_combat.md +++ b/docs/pixel_combat.md @@ -7,11 +7,14 @@ se detallan en [HUD thrash](thrash_hud.md); las tareas estรกn en ## Arte y escala -Los cuatro `CharacterData` comparten `prototype_sprite_frames.tres`, que utiliza -`assets/characters/ankarde/player_pixel.svg`. El atlas contiene 37 celdas de -64 x 64 y once animaciones: idle, walk, jump, fall, punch, ground_pound, land, -special_start, special, special_end y hurt. No hay aรบn un juego de animaciones -por integrante; los PNG antiguos no se han eliminado. +Cada `CharacterData` utiliza `player/characters/animations/_frames.tres` +y `assets/characters/band/.svg`. Son 40 celdas de 64 x 64 y doce +animaciones: las once originales mas `pound_land`, separada de `land`. +Diego conserva exactamente sus celdas anteriores salvo la caida ofensiva y +el nuevo impacto con guitarra. Ivan conserva las poses originales de caida y +aterrizaje, adaptadas a su aspecto. El punetazo comparte pose y tiempos. +El atlas y SpriteFrames anteriores se conservan como fuente, no se eliminan. +[Descripcion de cada integrante y efectos](characters.md). El personaje de pie mide aproximadamente 56 px de alto en el atlas. El sprite usa filtrado nearest y escala 1:1. Su cuerpo/hurtbox es de 26 x 52; los enemigos @@ -25,8 +28,9 @@ activa. El registro de objetivos impide repetir un impacto del mismo ataque. El cooldown es de 0,34 s. El daรฑo base actual es 5, antes de mejoras. **Ground Pound.** Solo comienza en el aire; al aterrizar consulta hurtboxes en -la posiciรณn fรญsica resuelta. Usa pose de caรญda, polvo, grietas y un anillo -de impacto. La fรณrmula mide altura ganada desde el despegue, no toda la caรญda +la posiciรณn fรญsica resuelta. El radio circular comun aumenta de 54 a 108, +el doble de alcance en los cuatro. Cada uno tiene pose/efecto propio, pero +ni la cupula ni las grietas/rayos generan zonas o impactos adicionales. La fรณrmula mide altura ganada desde el despegue, no toda la caรญda desde una cornisa. Aplica 7โ€“12 de daรฑo y limita tambiรฉn a 12 tras las mejoras. El campo `CharacterData.air_attack_damage` no participa. diff --git a/docs/project_status.md b/docs/project_status.md index 4d306ca..0a5ea07 100644 --- a/docs/project_status.md +++ b/docs/project_status.md @@ -1,14 +1,14 @@ # Estado de implementacion y validacion -Revision de **29 de octubre de 2026**: coleccion rara permanente y adornos rompibles. -Base: proyecto original, kit de niveles, HUD thrash, roadmap e intro/menu/vertical. +Revision de **29 de octubre de 2026**: banda de cuatro personajes y seleccion previa. +Base: entregas anteriores hasta coleccion rara permanente y adornos rompibles. No incluye cambios locales del autor que no estuvieran en esas entregas. ## Lo incorporado | Funcion | Evidencia | |---|---| -| Coleccion en menu, sin equipar ni elegir personaje | `ui/menu/rare_inventory.gd/.tscn`, `main_menu` | +| Coleccion en menu, sin equipar | `ui/menu/rare_inventory.gd/.tscn`, `main_menu` | | Pua Perdida, unico raro, +20% especial | `rare_items/data/lost_pick.tres` | | Variante arrastrable, sin colocacion en mapas | `rare_items/variants/lost_pick.tscn` | | Pendientes por intento, muerte/caida descartan | `LevelRoot.collect_rare_item`, `discard_pending_items` | @@ -21,6 +21,12 @@ No incluye cambios locales del autor que no estuvieran en esas entregas. | Colision solida y zona vulnerable independientes | World (1), BreakableHurtbox (6) | | Punetazo, golpe descendente y especial alcanzan adornos | Mascaras y grupo `breakable` en Player | | Sin cargas ni KOs por romper decoracion | SceneryProp no pertenece a enemy ni emite died | +| Cuatro retratos/nombres en cuadricula 2x2 antes de cargar | `character_select`, `character_card`, `main_menu` | +| Eleccion en memoria, conservada al morir y limpia al volver | `game/run_session.gd`, `Player._ready`, `MainMenu._ready` | +| Cuatro atlas/animaciones propios, mismos tiempos de punetazo | `assets/characters/band/`, `player/characters/animations/` | +| Ground Pound de radio 108 para todos, logica comun | `player/player.gd`, `tests/test_band_resources.py` | +| Efectos de guitarra, bateria, bajo y voz sin dano propio | `effects/combat_fx.gd`, datos de personaje | +| Vibracion grave por pulso de Fer, desactivable | `player/camera_2d.gd`, `CharacterData.special_shake_*` | La Pua Perdida todavia no esta escondida en 00/01 ni asignada como premio de meta. La geometria, enemigos y 17 consumibles de los niveles no se han modificado. @@ -38,17 +44,20 @@ todos los enemigos. Morir, caer o abandonar antes de ganar lo pierde. Si falla el guardado, la meta conserva el intento pendiente y permite reintentar. Se mantienen intro saltable, selector libre de raiz de levels, recarga al morir, -reinicio beta tras nueve segundos, salida del vertical y seleccion de personaje -aplazada. Pausa, audio, resultado completo, bosses y campana siguen pendientes. +reinicio beta tras nueve segundos y salida del vertical. El personaje se elige +tras escoger nivel; no hay restricciones y la seleccion no se guarda en disco. +Pausa, audio, resultado completo, bosses y campana siguen pendientes. ## Comprobaciones de esta entrega -- **73 pruebas estaticas de Python superadas**: referencias, geometria heredada, - catalogo, escenas, mascaras, UI, parametros y contratos textuales de progreso. +- **87 pruebas estaticas de Python superadas**: referencias, geometria heredada, + catalogo, escenas, mascaras, UI, parametros y contratos textuales de progreso; + se suman 14 de banda/selector, igualdad del combate y conservacion del arte de Diego. - Comprobacion de aplicacion del parche sobre la base reconstruida, comparacion de los archivos resultantes y reversibilidad sobre esa misma base. -- Once suites de motor preparadas. Se anaden raros/guardado y rompibles, y todas - usan un perfil temporal de pruebas para no afectar al perfil real. +- Se actualiza la suite existente de menu para exigir eleccion previa y conservar + personaje al reiniciar. Siguen once suites opcionales para ejecucion local; + usan un perfil de pruebas aislado. No se cuentan como ejecutadas. Las comprobaciones estaticas no ejecutan GDScript ni certifican comportamiento fisico, tactil o visual. Las pruebas jugables y de dispositivo las realiza el @@ -65,8 +74,8 @@ opcionales para la validacion local y no sustituyen esas comprobaciones. ## Continuar El unico backlog activo es [la guia maestra](design_vision.md). Mantener separadas -las futuras reglas de campana/seleccion del perfil de raros. Las restricciones de -personaje siguen aplazadas y no se han elegido implicitamente en este parche. +la eleccion temporal (`RunSession`) y futuras reglas de campana del perfil raro. +Todos los personajes estan disponibles en todos los niveles. [Guia de la banda](characters.md). Los informes anteriores del kit/HUD y sus hashes son historicos. La vieja Level01 era el laboratorio y Level02 es ahora la beta Level00. No reaplicar parches viejos. diff --git a/docs/start_menu.md b/docs/start_menu.md index a4b8546..8489335 100644 --- a/docs/start_menu.md +++ b/docs/start_menu.md @@ -40,15 +40,23 @@ un requisito de nombre `level_XX` ni una base de datos de capitulos. Un helper demas muestran su nombre de archivo formateado. Renombrar un nivel no exige actualizar la lista, pero si sus referencias explicitas en otros recursos. -Al pulsar un nivel, la carga asincrona muestra su progreso real sin otra demora -artificial de diez segundos. Los fallos regresan al selector con un mensaje. -La lista se reconstruye cada vez que se abre el submenu. +Al pulsar un nivel aparece la banda en 2x2: aun no se carga el mapa. Una tarjeta +con retrato, nombre y rol permite elegir al integrante mediante clic o tacto. +VOLVER A NIVELES, Escape y Atras regresan a los niveles sin cargar nada. +Al elegir personaje, la carga asincrona muestra su progreso real sin otra demora +artificial de diez segundos. Un fallo limpia la eleccion temporal y regresa a +las tarjetas con un mensaje; una doble pulsacion no lanza otra carga. +La lista de niveles se reconstruye cada vez que se abre el submenu. ## Personaje y estado de partida -No hay seleccion ni asignacion nueva de `CharacterData`. Se conserva el recurso -actual en `player/player.tscn` (`singer`). La decision de seleccionar al inicio, -por nivel, al morir o de usar personajes obligatorios queda aplazada. +La eleccion se realiza despues del nivel y antes de cargarlo: **Diego, Ivan, Fer +y Hector**. `RunSession` conserva en memoria la ruta y el recurso `CharacterData`. +Player resuelve ese recurso antes de inicializar vida, animaciones y HUD. +Morir/caer o reiniciar la beta conserva la eleccion; abrir el menu la limpia. +F6 no exige una sesion: utiliza el recurso del Inspector (Diego por defecto). +No hay restricciones por nivel ni guardado del personaje entre ejecuciones. +[Aspecto, igualdad de combate y configuracion](characters.md). Cada entrada desde el menu crea una instancia nueva del nivel. Vida, especial, escudos, mejoras temporales, enemigos y objetos comienzan de nuevo. La coleccion @@ -89,14 +97,16 @@ regresan al inicio. La lista tiene scroll y tarjetas editables en | Duracion de intro | Raiz de `game/main.tscn`, `Intro Duration Seconds` | | Texto / futuro video | Nodos de `game/main.tscn`; temporizador en `game/boot.gd` | | Botones, margenes y distribucion | `ui/menu/main_menu.tscn` | +| Banda 2x2 y tarjetas | `ui/menu/character_select.tscn`, `character_card.tscn` | +| Eleccion temporal durante el intento | `game/run_session.gd` | | Colores, tipografia y estados | `ui/menu/menu_theme.tres` | | Carpetas, etiquetas y carga | `ui/menu/main_menu.gd` | | Boton de salida en juego | `ui/menu/level_navigation.tscn` | | Activar navegacion por escenario | `Enable Level Menu` en su raiz `LevelRoot` | | Zona final colocable | `world/triggers/level_exit.tscn` | -`PlayerProgress` es el unico autoload, limitado al perfil de raros. No hay -gestor general de campana ni seleccion de personaje. `game/main.tscn` ya no es +`PlayerProgress` guarda solo raros. `RunSession` es un segundo autoload pequeno, +sin disco, para mantener la eleccion al recargar. No hay gestor general de campana. `game/main.tscn` ya no es un wrapper de `combat_test`, que se conserva como prueba independiente con F6. ## Verificacion pendiente en Godot y Android @@ -104,6 +114,8 @@ un wrapper de `combat_test`, que se conserva como prueba independiente con F6. - [ ] F5 espera diez segundos; SALTAR y Escape/Atras permiten avanzar antes. - [ ] El selector muestra 00/01, y una copia nueva guardada en la raiz aparece sin tocar codigo; plantillas, ejemplos y tests no aparecen. +- [ ] Cada nivel abre cuatro tarjetas 2x2; volver no carga nada; elegir aplica al integrante. +- [ ] Morir conserva la eleccion; volver al menu permite cambiar; F6 usa el Inspector. - [ ] Pulsar varias veces durante la carga no abre dos escenarios. - [ ] MENU y la salida regresan al inicio sin intro ni acciones tactiles retenidas. - [ ] Volver a entrar restaura vida, objetos y enemigos; morir solo reinicia el mapa. diff --git a/docs/tuning.md b/docs/tuning.md index f0e75ee..1f2bc10 100644 --- a/docs/tuning.md +++ b/docs/tuning.md @@ -1,8 +1,9 @@ # Donde ajustar cada parametro No hay una copia nueva de los valores de movimiento en otro archivo. Se mantienen -dos ambitos existentes: recursos de personaje para diferencias entre integrantes, -y propiedades exportadas del jugador para reglas comunes. Los comentarios `##` +dos ambitos existentes: recursos de personaje para aspecto/animaciones y valores +base (iguales en la banda), y propiedades del jugador para reglas comunes. +No hay multiplicadores de alcance por integrante; la seleccion es visual. Los comentarios `##` explican las propiedades desde el Inspector y la documentacion del script. ## Personaje: velocidad, salto, vida y dano base @@ -25,10 +26,12 @@ player/characters/drummer.tres | `air_attack_damage` | Campo heredado SIN USO actual en Player; modificarlo no cambia el golpe aereo | | `sprite_frames` | Animaciones del integrante | -El recurso inicial de `player/player.tscn` sigue siendo `singer.tres`, con -`move_speed = 390`, `jump_velocity = -600` y `max_health = 50`. Esos valores no se -han cambiado en esta reorganizacion. Selecciona otro `Character Data` en la -instancia de Player para cambiar de integrante. +El recurso inicial de `player/player.tscn` es `guitarist.tres` (Diego), con +`move_speed = 390`, `jump_velocity = -600`, `max_health = 50` y dano base 5. +Los cuatro perfiles tienen esos mismos valores. Cambiar uno solo romperia la +regla de igualdad; las pruebas comprueban que no ocurre por accidente. +Desde el menu se usa la eleccion de la tarjeta. Para probar con F6, selecciona +otro `Character Data` en la instancia de Player. Un `.tres` externo es compartido: editarlo afecta a todas sus referencias. Para probar solo en un nivel, haz unico el recurso de esa instancia o guarda una copia. @@ -67,6 +70,15 @@ ajustar el comportamiento aereo. `fall_gravity_multiplier` sustituye a `gravity_multiplier` durante la caida; no se multiplica por este. El golpe aereo utiliza su propio multiplicador. +`ground_pound_radius = 108` es comun a toda la banda: doble alcance respecto a +54. No cambia la forma circular, el desplazamiento, la formula, el limite de 12 +ni la velocidad de caida. Editalo una sola vez en la raiz de `player/player.tscn`. +`ground_pound_effect` y `special_effect` de CharacterData solo eligen dibujos. +`special_shake_strength/duration/frequency` solo afectan a la camara; Fer usa +3 px, 0.32 s y frecuencia 18 para una vibracion mas grave por pulso. +El ajuste global `Feedback Strength = 0` sigue apagando sacudidas/superposiciones. +[Mapa completo de los efectos](characters.md). + La gravedad base permanece en los ajustes de fisica 2D del proyecto. No se ha creado un segundo valor global que la sustituya. diff --git a/effects/combat_fx.gd b/effects/combat_fx.gd index 6237d22..09099ce 100644 --- a/effects/combat_fx.gd +++ b/effects/combat_fx.gd @@ -29,9 +29,9 @@ func _ready() -> void: z_index = 12 texture_filter = CanvasItem.TEXTURE_FILTER_NEAREST match kind: - &"ground_pound": + &"ground_pound", &"electric_pound", &"vocal_dome", &"bass_cracks": _lifetime = 0.60 - &"solo": + &"solo", &"vocal_wave", &"drum_cymbals", &"bass_pulse": _lifetime = 0.62 &"death", &"break": _lifetime = 0.48 @@ -53,6 +53,18 @@ func _draw() -> void: var progress: float = clampf(_age / _lifetime, 0.0, 1.0) var fade: float = 1.0 - progress match kind: + &"electric_pound": + _draw_electric_pound(progress, fade) + &"vocal_dome": + _draw_vocal_dome(progress, fade) + &"bass_cracks": + _draw_bass_cracks(progress, fade) + &"vocal_wave": + _draw_vocal_wave(progress, fade) + &"drum_cymbals": + _draw_drum_cymbals(progress, fade) + &"bass_pulse": + _draw_bass_pulse(progress, fade) &"ground_pound": _draw_ring(lerpf(8.0, radius, progress), 0.24, Color(1.0, 0.72, 0.34, fade), 3.0) _draw_ring(lerpf(3.0, radius * 0.72, progress), 0.32, Color(1.0, 0.94, 0.68, fade), 2.0) @@ -131,3 +143,92 @@ func _draw_note(point: Vector2, color: Color) -> void: draw_rect(Rect2(point, Vector2(5, 4)), color) draw_rect(Rect2(point + Vector2(4, -10), Vector2(2, 13)), color) draw_rect(Rect2(point + Vector2(6, -10), Vector2(5, 3)), color) + + +## Diego: descarga al suelo y rayos ramificados, sin nuevas zonas de dano. +func _draw_electric_pound(progress: float, fade: float) -> void: + var reach: float = lerpf(10.0, radius, sqrt(progress)) + _draw_ring(reach, 0.27, Color(0.30, 0.80, 1.0, fade), 3.0) + for index: int in range(9): + var angle: float = PI + PI * float(index) / 8.0 + var axis := Vector2(cos(angle), sin(angle) * 0.72) + var normal := Vector2(-axis.y, axis.x) + var bolt := PackedVector2Array([Vector2.ZERO]) + for step: int in range(1, 6): + var fraction: float = float(step) / 5.0 + var zigzag: float = (-1.0 if (step + index) % 2 == 0 else 1.0) * 5.0 + bolt.append((axis * reach * fraction + normal * zigzag).round()) + draw_polyline(bolt, Color(0.20, 0.65, 1.0, fade * 0.72), 5.0) + draw_polyline(bolt, Color(0.82, 0.98, 1.0, fade), 1.0) + var fork: Vector2 = bolt[3] + normal * (10.0 + progress * 8.0) + draw_line(bolt[2], fork.round(), Color(0.48, 0.88, 1.0, fade), 2.0) + + +## Hector: semicupula amarilla transparente que crece desde el punto de aterrizaje. +func _draw_vocal_dome(progress: float, fade: float) -> void: + var reach: float = lerpf(5.0, radius, sqrt(progress)) + var dome := PackedVector2Array() + for index: int in range(33): + var angle: float = PI + PI * float(index) / 32.0 + var point := Vector2(cos(angle) * reach, sin(angle) * reach * 0.85).round() + # Evita vertices consecutivos iguales al redondear una cupula aun pequena. + if dome.is_empty() or dome[dome.size() - 1] != point: + dome.append(point) + draw_colored_polygon(dome, Color(1.0, 0.83, 0.14, fade * 0.20)) + draw_polyline(dome, Color(1.0, 0.91, 0.40, fade * 0.95), 3.0) + _draw_ring(reach, 0.16, Color(1.0, 0.78, 0.12, fade * 0.8), 2.0) + + +## Fer: fracturas cortas que quedan ancladas al punto de impacto y luego desaparecen. +## No se modifica el TileMap, ni la colision, ni se conserva dano visual del escenario. +func _draw_bass_cracks(progress: float, fade: float) -> void: + var growth: float = minf(progress * 4.0, 1.0) + for side: float in [-1.0, 1.0]: + for branch: int in range(3): + var crack := PackedVector2Array([Vector2.ZERO]) + for step: int in range(1, 6): + var x: float = side * radius * float(step) / 5.0 * growth + var y: float = float(branch - 1) * float(step) * 2.0 + y += 3.0 if (branch + step) % 2 == 0 else -3.0 + crack.append(Vector2(x, y).round()) + draw_polyline(crack, Color(0.08, 0.06, 0.14, fade), 5.0) + draw_polyline(crack, Color(0.68, 0.50, 0.93, fade * 0.7), 1.0) + var split: Vector2 = crack[3] + Vector2(side * 10.0, -10.0) + draw_line(crack[2], split, Color(0.12, 0.09, 0.20, fade), 3.0) + _draw_debris(progress, 12, Color(0.57, 0.52, 0.64, fade), radius * 0.7) + + +## Hector: frentes de sonido concentricos; el grito sigue usando el dano de area comun. +func _draw_vocal_wave(progress: float, fade: float) -> void: + var reach: float = lerpf(9.0, radius, progress) + for index: int in range(3): + var ratio: float = 1.0 - float(index) * 0.19 + _draw_ring(reach * ratio, 0.85, Color(1.0, 0.86, 0.25, fade * (0.85 - float(index) * 0.16)), 3.0) + + +## Ivan: platos que vuelan y giran en todas direcciones. Son dibujo, no proyectiles. +## El dano lo aplica Player una sola vez por pulso, nunca por contacto con estos platos. +func _draw_drum_cymbals(progress: float, fade: float) -> void: + for index: int in range(10): + var angle: float = TAU * float(index) / 10.0 + var travel: float = lerpf(14.0, radius, progress) + var point := Vector2(cos(angle), sin(angle) * 0.78) * travel + var wobble: float = 0.30 + absf(sin(progress * TAU * 2.0 + angle)) * 0.35 + draw_set_transform(point.round(), angle + progress * 5.0, Vector2(1.0, wobble)) + draw_circle(Vector2.ZERO, 12.0, Color(0.34, 0.21, 0.06, fade)) + draw_circle(Vector2.ZERO, 10.0, Color(0.92, 0.65, 0.17, fade)) + _draw_ring(8.0, 1.0, Color(1.0, 0.89, 0.45, fade), 1.0) + draw_circle(Vector2.ZERO, 3.0, Color(1.0, 0.94, 0.65, fade)) + draw_circle(Vector2.ZERO, 1.0, Color(0.20, 0.15, 0.05, fade)) + draw_set_transform(Vector2.ZERO, 0.0, Vector2.ONE) + + +## Fer: ondas graves gruesas. La vibracion de camara se sincroniza con estos pulsos. +func _draw_bass_pulse(progress: float, fade: float) -> void: + var reach: float = lerpf(8.0, radius, progress) + _draw_ring(reach, 0.65, Color(0.64, 0.42, 0.97, fade * 0.65), 7.0) + _draw_ring(reach * 0.83, 0.65, Color(0.91, 0.76, 1.0, fade * 0.8), 2.0) + for index: int in range(8): + var angle: float = TAU * float(index) / 8.0 + var point := Vector2(cos(angle), sin(angle) * 0.65) * reach + _draw_note(point.round(), Color(0.83, 0.66, 1.0, fade)) diff --git a/game/player_progress.gd b/game/player_progress.gd index 25123d7..654d2da 100644 --- a/game/player_progress.gd +++ b/game/player_progress.gd @@ -1,7 +1,8 @@ class_name PlayerProgressStore extends Node -## Unico estado entre escenas: catalogo y objetos confirmados en el disco local. +## Estado permanente: catalogo y objetos confirmados en el disco local. +## La eleccion temporal de personaje vive separada en RunSession. ## Los hallazgos del intento pertenecen a LevelRoot; nunca se guardan aqui pendientes. signal collection_changed diff --git a/game/run_session.gd b/game/run_session.gd new file mode 100644 index 0000000..a1e8f20 --- /dev/null +++ b/game/run_session.gd @@ -0,0 +1,31 @@ +class_name RunSessionState +extends Node + +## Eleccion del intento, solo en memoria. Sobrevive a recargar por muerte o caida. +## No guarda vida, buffs, raros pendientes ni escribe en el perfil permanente. +var level_path: String = "" +var selected_character: CharacterData + + +func begin_level(path: String, character: CharacterData) -> void: + level_path = path + selected_character = character + + +## El menu limpia la eleccion; cada entrada a un nivel vuelve a mostrar la banda. +func clear() -> void: + level_path = "" + selected_character = null + + +## Busca la escena elegida entre los padres, sin depender de current_scene durante _ready. +## Ejecutar F6 o instanciar un jugador en otra escena respeta su CharacterData del Inspector. +func character_for(player: Node) -> CharacterData: + if level_path.is_empty() or selected_character == null: + return null + var ancestor: Node = player.get_parent() + while ancestor != null: + if ancestor.scene_file_path == level_path: + return selected_character + ancestor = ancestor.get_parent() + return null diff --git a/mortal_maze_rare_items_breakables.patch b/mortal_maze_rare_items_breakables.patch deleted file mode 100644 index 03aeb7b..0000000 --- a/mortal_maze_rare_items_breakables.patch +++ /dev/null @@ -1,2990 +0,0 @@ -diff --git a/README.md b/README.md -index a4f35676275f998392d26548db9164e61183c69d..4aeb3dd01619451dc29c96d65c6450324825c21b 100644 ---- a/README.md -+++ b/README.md -@@ -4,9 +4,10 @@ Plataformas y accion 2D sobre una banda de thrash metal, en Godot. Un solo - `Player` utiliza cuatro recursos `CharacterData`; los escenarios se montan - con piezas reutilizables desde el editor. - --**Estado: prototipo con intro, menu de pruebas y construccion visual de niveles.** -+**Estado: prototipo con intro, menu, coleccion permanente y construccion visual de niveles.** - Hay movimiento, combate, enemigos, objetos y HUD. Todavia no hay campana, --guardado, pausa, audio, bosses ni pantallas completas de victoria/derrota. -+guardado de campana, pausa, audio, bosses ni pantallas completas de victoria/derrota. -+Si existe guardado local de objetos raros confirmados al terminar un nivel. - La seleccion de personaje queda **aplazada por decision de diseno**: no bloquea - el trabajo de escenarios y menus; se utiliza el personaje ya asignado. - -@@ -49,9 +50,9 @@ mano. Todos esos niveles estan accesibles: no hay desbloqueos todavia. - - **F6** sigue ejecutando la escena abierta sin pasar por la intro. En escenarios - con `LevelRoot`, el boton **MENU**, Escape o Atras de Android devuelve al inicio --sin repetir la intro. No pausa ni guarda la partida: salir descarta su estado. --Morir conserva la recarga del nivel actual. La nueva salida colocable vuelve al --menu; la meta de la beta conserva su reinicio de prueba a los nueve segundos. -+sin repetir la intro. No pausa ni confirma raros: abandonar descarta su estado temporal. -+Morir conserva la recarga del nivel actual. La meta colocable confirma los raros -+y vuelve al menu; la meta de la beta tambien confirma y reinicia tras nueve segundos. - - | Teclado | Accion | - |---|---| -@@ -77,7 +78,8 @@ La copia aparece automaticamente al abrir el submenu de niveles. Una escena en - explica la edicion. No hay que copiar el script del laboratorio ni el de la beta. - - Para una salida sencilla, arrastra **`world/triggers/level_exit.tscn`**: al entrar --el jugador vuelve al menu. No equivale a victoria de campana ni guarda progreso. -+el jugador completa el intento, confirma sus raros y vuelve al menu. No desbloquea -+capitulos ni decide el siguiente nivel. - La plantilla no coloca una salida automaticamente: el autor decide su posicion. - - El kit incluye terreno redimensionable, adornos y fachadas con colision opcional, -@@ -99,7 +101,24 @@ Velocidad, salto y defensa duran ahora **30 segundos**, salvo la Lata de Feedbac - - El especial mantiene capacidad 100, +10 por baja normal y minimo 25. Consume la - carga acumulada; sus propias bajas no recargan por defecto. No se ha cambiado --su dano, duracion, pulsos ni economia en esta entrega. [HUD thrash](docs/thrash_hud.md). -+su duracion, pulsos ni economia en esta entrega. La Pua Perdida confirmada -+si aporta un +20% de dano al especial desde el siguiente intento. [HUD thrash](docs/thrash_hud.md). -+ -+## Coleccion permanente y barriles -+ -+En el inicio, **OBJETOS RAROS** muestra la coleccion y sus mejoras automaticas. -+La **Pua Perdida** aporta +20% de dano especial tras encontrarla y terminar el -+nivel con vida. Morir, caer o abandonar antes de la meta descarta el hallazgo. -+No se ha colocado en ningun mapa: arrastra `rare_items/variants/lost_pick.tscn`. -+Para concederla solo por ganar, asigna su `.tres` a `Completion Rewards` del nivel. -+ -+Los barriles son rompibles por defecto: selecciona una instancia y arrastra a -+`Drop Scene` una escena de `pickups/variants/` o `rare_items/variants/`. Vacio: no -+suelta nada. `Break Health` ajusta la resistencia y `Breakable` permite desactivarlo. -+Otros adornos de SceneryProp admiten las mismas opciones, apagadas por defecto. -+Colision y profundidad siguen siendo independientes; romper no recarga el especial. -+ -+[Guia de raros, guardado y rompibles](docs/rare_items_and_breakables.md). - - ## Donde cambiar cada cosa - -@@ -111,13 +130,15 @@ su dano, duracion, pulsos ni economia en esta entrega. [HUD thrash](docs/thrash_ - | Colocar piezas, objetos y salidas | [Niveles](docs/level_design.md) | - | Velocidad, salto, duraciones y HUD | [Ajustes](docs/tuning.md) | - | Responsabilidades y funciones | [Arquitectura](docs/architecture.md) | -+| Coleccion permanente y recompensas de barril | [Raros y rompibles](docs/rare_items_and_breakables.md) | - | Objetos / combate | [Objetos](docs/items.md) / [Combate](docs/pixel_combat.md) | - | Recorridos | [Beta 00](docs/level_00.md) / [Vertical 01](docs/level_01.md) | - - Los valores particulares de personaje viven en `player/characters/*.tres`; las - reglas comunes, en las propiedades de `player/player.tscn`. La intro se ajusta en - `game/main.tscn`; el aspecto del menu, en `ui/menu/`. No hay un segundo sistema de --configuracion en un singleton. Codigo nuevo en ingles; comentarios en espanol. -+configuracion de combate en un singleton. `PlayerProgress` solo conserva -+la coleccion y su catalogo; los efectos viven en `rare_items/data/*.tres`. Codigo nuevo en ingles; comentarios en espanol. - - **Diferencia pendiente:** el radio general del especial sigue en `100000`, pero - Level00/Level01 lo sobrescriben a `290`. La plantilla hereda el general. El filtro -@@ -130,12 +151,13 @@ python tools/run_checks.py --static-only - python tools/run_checks.py --godot /ruta/al/ejecutable/godot - ``` - --El segundo comando importa el proyecto y ejecuta las nueve suites `*_runtime.gd`. -+El segundo comando importa el proyecto y ejecuta las once suites `*_runtime.gd`. - En Windows, indica la ruta del ejecutable de consola entre comillas. El runner y - las pruebas estaticas solo requieren la biblioteca estandar de Python. - --**58 pruebas estaticas superadas en esta entrega. No se ha ejecutado Godot aqui.** --Las nueve suites estan escritas, pero pendientes de ejecucion; tampoco se ha -+**73 pruebas estaticas superadas en esta entrega.** La comprobacion jugable -+y visual corresponde a las pruebas locales del autor. -+Las once suites usan perfiles de prueba aislados y estan preparadas; tampoco se ha - exportado una APK ni probado el tacto real. Los contratos de texto/geometria - no certifican GDScript, fisica, recorrido jugable ni presentacion en pantalla. - -diff --git a/assets/rare_items/lost_pick.svg b/assets/rare_items/lost_pick.svg -new file mode 100644 -index 0000000000000000000000000000000000000000..07ef473515481d79da9c374c7a2f06b9c106fcff ---- /dev/null -+++ b/assets/rare_items/lost_pick.svg -@@ -0,0 +1,7 @@ -+ -+ -+ -+ -+ -+ -+ -diff --git a/docs/architecture.md b/docs/architecture.md -index 00aeb9ef8ac0e4beb804e07bd165bffce8163d51..57cfeda8eedcdc630d0c49d43008c45b57056c92 100644 ---- a/docs/architecture.md -+++ b/docs/architecture.md -@@ -7,14 +7,16 @@ las tareas y [la revision del proyecto](project_status.md), sus evidencias. - - `project.godot` inicia `game/main.tscn` con `boot.gd`: intro de 10 s saltable y carga - asincrona del menu. `ui/menu/main_menu.gd` descubre escenas de la raiz de levels --y carga solo la elegida. No hay autoloads de sesion, progreso o seleccion. -+y carga solo la elegida. `PlayerProgress` es el unico autoload: catalogo y -+coleccion local confirmada, sin responsabilidades de seleccion ni campana. - - `LevelRoot` aplica camara/caidas y agrega una instancia de LevelNavigation solo - al jugar. Esta ofrece MENU/Escape/Atras; la salida Area2D reutilizable tambien --vuelve al menu. Ambas van directamente al menu, no a la intro. -+vuelve al menu tras confirmar los raros. MENU abandona sin confirmarlos. -+Ambas van directamente al menu, no a la intro. - - Player._die aun recarga el mapa, la meta de beta Level00 aun reinicia tras 9 s y la nueva --salida de Level01 solo vuelve al inicio. No existe un coordinador de victoria/derrota ni -+salida de Level01 confirma raros y vuelve al inicio. No existe un coordinador de victoria/derrota ni - campana. Resolver las recargas competidoras cuando se implemente ese flujo. - La seleccion de personaje se aplaza; se usa el recurso asignado al Player. - -@@ -38,18 +40,21 @@ abrirse y ejecutarse directamente sin un generador ni un plugin de edicion. - - | Archivo / carpeta | Responsabilidad | - |---|---| -+| `game/player_progress.gd/.tscn` | Catalogo, unicidad, atributos y archivo local de raros confirmados | -+| `rare_items/` | Datos, recogida pendiente y variantes visuales de objetos raros | -+| `ui/menu/rare_inventory.gd` | Coleccion en el menu, sin equipamiento ni efectos propios | - | `game/boot.gd` | Espera provisional, salto y carga del menu | - | `ui/menu/main_menu.gd` | Inicio, descubrimiento no recursivo y carga de niveles | - | `ui/menu/level_navigation.gd` | Salida del escenario al menu, sin pausa ni guardado | - | `world/triggers/level_exit.gd` | Area colocable de salida, de una sola activacion | - | `world/terrain/terrain_piece.gd` | Sincronizar tamano, texturas y colision de una superficie | - | `world/terrain/*.tscn` | Presets de suelo, plataforma, pared y bloque | --| `world/props/scenery_prop.gd` | Imagen anclada al suelo, profundidad y colision opcional | -+| `world/props/scenery_prop.gd` | Imagen, profundidad, colision, rotura opcional y premio fijo | - | `world/props/*.tscn` | Presets decorativos y fachadas | - | `world/signs/world_sign.gd` | Texto editable sobre SceneryProp; reutiliza su fisica y profundidad | - | `world/signs/text_label.tscn` | Texto libre mediante un Label nativo | - | `world/backgrounds/city_background.tscn` | Las cuatro capas originales de parallax, ahora reutilizables | --| `levels/level_root.gd` | Camara, guia de editor, caidas y navegacion al menu al ejecutar | -+| `levels/level_root.gd` | Camara, caidas, hallazgos del intento y confirmacion de la meta | - | `levels/templates/level_template.tscn` | Punto de partida sin eventos especificos | - | `levels/examples/scenery_catalog.tscn` | Muestrario jugable para copiar instancias | - | `levels/level_01.tscn` | Mapa vertical construido con piezas; usa LevelRoot, sin script generador | -@@ -71,11 +76,12 @@ abrirse y ejecutarse directamente sin un generador ni un plugin de edicion. - - Se han extraido componentes donde existia una reutilizacion concreta: varias - superficies, varios adornos, texto sobre adornos y varios niveles con limites de --camara. Los scripts de piezas no conocen al jugador, sus ataques ni el nivel. -+camara. El terreno no conoce al jugador. SceneryProp admite el contrato `take_damage` -+para romperse; RarePickup comunica su hallazgo al LevelRoot propietario. - --No se han creado gestores globales, registros de prefabs, fabricas de niveles, --sistemas de eventos o un plugin propio para sustituir el flujo de escenas de --Godot. El catalogo es una escena normal que puedes editar. -+Solo el perfil confirmado necesita vivir entre escenas. No se han creado -+fabricas de niveles, un sistema universal de eventos ni un plugin propio para -+sustituir el flujo de escenas de Godot. El catalogo es una escena normal que puedes editar. - - Player y Walker siguen siendo controladores relativamente largos, documentados - por bloques y funciones. No se han partido artificialmente en envoltorios que -@@ -98,7 +104,8 @@ Despues aparecen nodos y estado de partida. Las funciones estan documentadas: - - Presentacion: `_update_animation`, `_update_visual_feedback`, `_draw`. - - No dupliques la formula de velocidad en un HUD: ya existe `get_move_speed()`. --No modifiques CharacterData para aplicar un buff: el estado temporal vive en el -+Usa `get_max_health()` para el maximo efectivo y `get_special_damage_multiplier()` -+para el bono permanente del solo. No modifiques CharacterData para aplicar un buff: el estado temporal vive en el - jugador. Los temporales expiran por separado; dano general/aereo se pierde al recibir un golpe valido. - - La conexion a muertes enemigas se hace al iniciar el nivel. Si en el futuro -@@ -134,7 +141,8 @@ Para cambiar el comportamiento general, modifica el script base o crea otro pres - La decoracion utiliza `z_as_relative = false`: su opcion Draw Layer tiene un - significado estable aunque cambies la instancia de carpeta de organizacion. - El terreno utiliza la capa fisica World (1); no se han cambiado las capas del --jugador, de los enemigos ni de sus zonas vulnerables. -+jugador ni de los enemigos. Se anade BreakableHurtbox (6) para adornos golpeables; -+el punetazo y Ground Pound consultan ambas capas y el solo ambos grupos. - - Los scripts de nivel y de objetos distinguen editor y partida. En el editor no - se procesan recogidas, ataques, contadores de muertes ni reinicios. LevelRoot solo -@@ -183,3 +191,22 @@ no concede ni consume carga. `_applying_special_damage` delimita la llamada - sincronica a `take_damage`; el Walker actual emite `died` antes de devolverla. - Si en el futuro se retrasa esa senal o se anaden danos persistentes, habra que - transportar la causa del dano en la recompensa en lugar de ampliar este contexto. -+ -+ -+## Progreso limitado y transaccion de meta -+ -+`LevelRoot` conserva `_pending_rare_items` solo en el intento. Las muertes y -+caidas los descartan; destruir la escena tambien elimina ese registro. Las dos -+metas diferidas comprueban al jugador vivo antes de `complete_level()`. El perfil -+confirma todos los Id de golpe solo si consigue escribir el archivo. Se emite -+`level_completed` desde la clase base; Level00 ya no declara una senal duplicada. -+ -+Player toma una copia de los bonos permanentes en `_ready`: no cambia el recurso -+compartido ni recibe mejoras antes de ganar. Los raros no usan los temporizadores -+ni las variables que un golpe elimina. No se persisten vida actual, especial, -+posiciones, barriles rotos ni hallazgos pendientes. -+ -+La rotura utiliza un cerrojo inmediato y trabajo diferido. El premio se instancia -+bajo el padre del adorno, con coordenadas locales convertidas desde su posicion -+global. No emite `died`, no pertenece a `enemy` y no participa en cargas por baja. -+[Guia y decisiones de datos](rare_items_and_breakables.md). -diff --git a/docs/design_vision.md b/docs/design_vision.md -index ccd5230344dda3cf7c15343a524480c8b1d9b0f2..e63d0dad5c35af44f961c9e9fb9eace1ebe775b2 100644 ---- a/docs/design_vision.md -+++ b/docs/design_vision.md -@@ -1,7 +1,6 @@ - # Guia maestra: vision, decisiones y tareas - --Actualizacion: **29 de octubre de 2026**, entrega de intro/menu, beta00, --vertical01 y objetos. Este es el unico backlog activo. `[x]` significa presente -+Actualizacion: **29 de octubre de 2026**, entrega de coleccion permanente y objetos rompibles. Este es el unico backlog activo. `[x]` significa presente - en la implementacion revisada, **no probado jugando**. `[ ]` queda pendiente. - La evidencia de ejecucion se registra aparte en [Estado](project_status.md). - -@@ -13,9 +12,10 @@ uno o varios niveles por capitulo y bosses segun el contenido. No imponer tres - niveles y un boss por cancion. La Muerte sigue como idea de boss final. - - No es un metroidvania ni un mundo persistente interconectado. Inicialmente no hay --checkpoints internos: reinicia el nivel. No hay experiencia, arbol de habilidades --ni mejoras permanentes de estadisticas. El progreso futuro sera de niveles, --no de buffs, vida o carga temporal. -+checkpoints internos: reinicia el nivel. No hay experiencia ni arbol de habilidades. -+**Decision nueva:** si hay mejoras permanentes asociadas a objetos raros unicos, -+confirmadas solo al completar el nivel. Esto sustituye la restriccion inicial de -+no tener mejoras permanentes. No se guardan vida actual, carga ni buffs temporales. - - **Decision expresamente aplazada: seleccion de personaje.** No se elige ahora - entre seleccion al arrancar, antes de cada nivel, tras morir o personaje impuesto -@@ -35,7 +35,8 @@ Intro 10 s, saltable -> Inicio -> Jugar -> lista de escenas en levels/ - ``` - - La lista es un selector libre de **pruebas**, no el catalogo de una campana. --La salida nueva vuelve al menu; no registra una victoria ni desbloquea contenido. -+La meta confirma los raros y vuelve al menu; MENU abandona sin confirmar. No -+registra niveles completados de campana ni desbloquea escenarios. - - ## Principios de desarrollo - -@@ -64,6 +65,11 @@ verificar el parche y separar implementacion de validacion efectiva. - - [x] 17 objetos / ocho efectos, recogida confirmada y drops fijos/ponderados. - - [x] Dano hasta golpe, sustitucion solo por mayor potencia y rechazo de peores/iguales. - - [x] Velocidad/salto/defensa 30 s; Lata de Feedback 45 s. -+- [x] Raros unicos: hallazgos pendientes por intento y confirmacion al llegar vivo a meta. -+- [x] Pua Perdida creada, +20% especial permanente; no colocada en mapas. -+- [x] Premios de meta opcionales en Completion Rewards, sin necesidad de recogerlos. -+- [x] Perfil local por Id, escritura temporal y copia anterior; sin guardar estado temporal. -+- [x] Barriles rompibles y soporte optativo en SceneryProp, con premio fijo o vacio. - - ### Construccion visual y presentacion - -@@ -78,7 +84,8 @@ verificar el parche y separar implementacion de validacion efectiva. - - [x] Inicio simple y submenu tactil/raton con carga asincrona de niveles. - - [x] Descubrimiento no recursivo de escenas de la raiz `levels/`. - - [x] MENU / Escape / Atras para abandonar escenarios sin repetir la intro. --- [x] Salida arrastrable al menu, de un solo disparo, sin sistema de campana. -+- [x] Meta arrastrable que confirma raros y vuelve al menu, sin sistema de campana. -+- [x] Submenu OBJETOS RAROS con estado/efecto, sin equipamiento ni seleccion de personaje. - - ### Escenarios y herramientas - -@@ -86,7 +93,7 @@ verificar el parche y separar implementacion de validacion efectiva. - - [x] Level01: nuevo mapa vertical con 12 enemigos, 14 objetos y desvios opcionales. - - [x] Laboratorio antiguo, su script y `lab_control.tres` retirados; tests desacoplados. - - [x] Sala de combate y catalogo fuera del selector, dentro de subcarpetas. --- [x] 58 pruebas estaticas ejecutadas y nueve suites de motor preparadas. -+- [x] 73 pruebas estaticas ejecutadas y once suites de motor preparadas, con perfil aislado. - - [x] Preset Android arm64, script de exportacion y workflow Gitea conservados. - - [x] README, guias y backlog actualizados con esta entrega. - -@@ -103,9 +110,12 @@ cornisa; dano de 7 a 12 con limite final incluso con mejoras. `air_attack_damage - existe pero no se consume. Las mejoras de dano general y aereo son canales - independientes, no potencian el especial y ambas se pierden con un golpe valido, - incluido el que absorbe un escudo. Invulnerabilidad no consume estas mejoras. -+La Pua Perdida es distinta: su bono permanente no se pierde con golpes o muerte. -+El especial tambien golpea adornos rompibles, pero romperlos no aporta carga. - - Al entrar/reentrar un nivel se crea estado temporal nuevo: no se guarda ni --transporta vida, carga o mejoras entre escenas. La muerte aun recarga el nivel; -+transporta vida actual, carga o buffs temporales entre escenas. La coleccion -+confirmada si persiste, y sus bonos se leen al crear al jugador. La muerte aun recarga el nivel; - la meta de la beta aun reinicia a los nueve segundos. El nuevo Level01 sale al menu. - MENU abandona; no se ha implementado pausa por llamarlo menu. - -@@ -120,7 +130,7 @@ MENU abandona; no se ha implementado pausa por llamarlo menu. - | Nivel completo | Beta horizontal y nuevo vertical; no campana publicada | - | Power-ups | 17 objetos, incluidos dano hasta golpe y temporales mas largos | - | Inicio/seleccion de nivel | Implementado como selector libre de pruebas | --| Progresion/guardado | No implementados | -+| Progresion/guardado | Coleccion rara local implementada; campana/desbloqueos pendientes | - | Capitulo/bosses | Pendientes; la beta no representa un capitulo final | - | Produccion visual | Kit operativo en recursos; se pueden crear nuevos mapas | - | Pulido | Hay HUD/feedback; faltan audio, UI completa y arte definitivo | -@@ -129,11 +139,13 @@ MENU abandona; no se ha implementado pausa por llamarlo menu. - - ### QA-01 - Godot y dispositivo - --- [ ] Ejecutar `tools/run_checks.py --godot ...` y resolver importacion/GDScript y nueve suites. -+- [ ] Ejecutar `tools/run_checks.py --godot ...` y resolver importacion/GDScript y once suites (ejecucion local del autor). - - [ ] Comprobar intro de 10 s, salto, selector, scroll, cargas, errores y retorno sin intro. - - [ ] Crear una copia de la plantilla en raiz y verificar que aparece sin codigo. - - [ ] Recorrer00/01: saltos, enemigos, salida, desvios y camara; repetir sin mejoras. - - [ ] Probar dano igual/peor/mejor, golpe con escudo, invulnerabilidad y expiracion de temporales. -+- [ ] Verificar raros: recoger/morir/abandonar/ganar/reabrir, premio automatico y duplicados. -+- [ ] Verificar barriles: premio normal/raro/vacio, colision opcional y ataques sin recarga. - - [ ] Probar en Android, registrar dispositivo/orientacion/resultado, botones simultaneos y salida. - - Cierre: logs del runner y pruebas manuales con entorno, no solo contratos de texto. -@@ -187,10 +199,11 @@ La salida actual es un avance parcial, no se marca esta tarea completa. - Cierre: continuar entre niveles sin editor, manteniendo las reglas de estado temporal decididas. - No crear ahora una lista manual de capitulos ni un registro de personajes permitidos sin uso. - --### PROG-01 - guardado minimo posterior al flujo -+### PROG-01 - ampliar el progreso a campana, cuando se defina - - - [ ] Registrar completados, derivar desbloqueos y reflejarlos en el acceso de campana. --- [ ] Guardar/cargar y manejar archivo ausente, corrupto o restablecido. -+- [x] Guardar/cargar la coleccion local, validar el formato y recuperar copia anterior. -+- [ ] Ampliar el formato con progreso de campana sin mezclarlo con el intento actual. - - [ ] Verificar que morir no desbloquea y que los buffs no se guardan accidentalmente. - - Cierre: el progreso sobrevive al cierre, sin conservar por accidente el estado de combate. -@@ -203,7 +216,8 @@ Cierre: el progreso sobrevive al cierre, sin conservar por accidente el estado d - - [ ] CONTENT-01: capitulo/cancion representativo; retirar la beta cuando deje de ser util. - - [ ] ENEMY-01: mecanicas nuevas como vuelo/proyectiles solo si un nivel las necesita. - - [ ] EVENTS-01: puertas, dialogos, oleadas y eventos a partir de casos reales. --- [ ] COLLECT-01: coleccionables persistentes separados de los pickups consumibles. -+- [x] COLLECT-01: coleccion persistente separada de consumibles, con Pua Perdida. -+- [ ] COLLECT-02: decidir ubicacion de raros, premios de niveles y balance tras probar. - - [ ] Intro definitiva, logo, titulo, efectos y animaciones del menu. - - ## Deuda conocida y validacion -@@ -217,8 +231,8 @@ Player, LevelRoot y la meta beta aun pueden solicitar reinicios; resolver junto - al flujo de resultado, no declarar que ya existe una sesion completa. La sala de - combate no hereda LevelRoot. El workflow Android exporta pero no ejecuta los tests. - --Se han pasado **58 pruebas estaticas**. No se ha ejecutado Godot, las nueve suites, --la revision visual ni Android en esta entrega. [Evidencias](project_status.md). -+Se han pasado **73 pruebas estaticas**. La ejecucion jugable, las once suites -+y la comprobacion visual/dispositivo quedan a cargo del autor, como se ha acordado. [Evidencias](project_status.md). - - ## Contexto breve para continuar - -@@ -227,5 +241,6 @@ Movimiento/doble salto, combate normal/aereo/especial, cinco Walker, 17 objetos, - kit visual y HUD thrash oculto al editar. F5intro de 10 s saltable->menu->niveles de - raiz;00betaantiguo02,01verticalnuevo. F6 sigue directo. MENU/salida->menu sin intro. - Dano hasta golpe y solo mejores sustituyen; otros buffs de 30/45 s. Sin seleccion de --personaje, audio, pausa, guardado ni campana. Seleccion aplazada expresamente. -+personaje, audio, pausa ni campana. Si hay coleccion rara permanente y barriles -+rompibles: guardar solo al completar, nunca al abandonar. Seleccion aplazada expresamente. - Entregas por git apply; actualizar este backlog sin duplicarlo en otros documentos. -diff --git a/docs/items.md b/docs/items.md -index 7c71bd8d408dca367a9df135adb0c04105aa8816..f2eb103844549a12e1292b4b380d1ff471228da4 100644 ---- a/docs/items.md -+++ b/docs/items.md -@@ -116,3 +116,16 @@ No uses `Color("#ffcd5b")` en un `.tres`: esa forma es valida en codigo - GDScript, pero el parser de recursos de Godot no la admite. Es lo que impedia - cargar los objetos y hacia que apareciese el cuadro blanco llamado `Item`. - La prueba `tests/test_pickup_resources.py` impide volver a introducirlo. -+ -+ -+## Raros permanentes: sistema separado -+ -+Los 17 objetos de esta guia siguen siendo consumibles o mejoras del intento. -+La **Pua Perdida** no es la Pua del Apocalipsis: vive en `rare_items/`, es unica, -+y da +20% de especial solo tras recogerla y completar el nivel. Su efecto -+confirmado sobrevive a golpes, muerte y cierre del juego. No usa duracion ni el -+estado hasta-golpe de estos consumibles. -+ -+Los barriles pueden soltar cualquiera de las escenas de `pickups/variants/`, -+un raro de `rare_items/variants/` o nada, segun `Drop Scene` de cada instancia. -+[Colocacion, premios de meta y reglas](rare_items_and_breakables.md). -diff --git a/docs/level_00.md b/docs/level_00.md -index 9034ff24181206b3f6ed7f4684d309d58bb91b2b..45d7f63364088c3fd93f577f69c22845f1fe8455 100644 ---- a/docs/level_00.md -+++ b/docs/level_00.md -@@ -137,7 +137,7 @@ aรบn para evitar cambiar demasiadas variables simultรกneamente. - - **Cรกmara:** `Camera Bounds` en la raรญz de Level00; se aplica mediante `LevelRoot`. - - **Meta:** `FinishZone` y la regla de `level_00.gd`. Muestra un resumen al entrar - el jugador, sin exigir todos los KOs, y recarga a los 9 segundos. No cambia de -- nivel ni guarda progreso; MENU permite abandonarlo sin esperar al reinicio. Para otro escenario, no copiar este script completo -+ nivel; confirma los raros del intento y los Completion Rewards antes del reinicio. MENU abandona sin confirmar hallazgos pendientes. Para otro escenario, no copiar este script completo - como sustituto de la salida simple `world/triggers/level_exit.tscn`. - Una victoria de campana con resultado y desbloqueos sigue pendiente. - -diff --git a/docs/level_01.md b/docs/level_01.md -index 787c1583f87b5cf0a6d42d98d8f6c28b15159d2e..680452a18fe2ed3ed397479ad5686d1f941b1ffc 100644 ---- a/docs/level_01.md -+++ b/docs/level_01.md -@@ -48,7 +48,7 @@ No hay accion de bajar atravesando plataformas: en el descenso sal por un latera - | Carteles de orientacion | 7, mas el cartel de salida | - | Personaje | El recurso ya asignado al Player, sin selector | - | Especial | Radio local 290; economia actual sin cambios | --| Final | `Triggers/Exit`, vuelve al menu sin desbloquear ni guardar | -+| Final | `Triggers/Exit`, confirma raros y vuelve al menu, sin desbloquear niveles | - - Al inicio hay Cuerda de Titanio; el camerino ofrece el Pedal de Distorsion mas - potente y un escudo. Tambien hay una Pua en la torre: si aun conservas el Pedal, -diff --git a/docs/level_design.md b/docs/level_design.md -index 1b489afca7d762acfac7190f517120b8533c24c1..8b718248491521e2f0bed928e9955cbea8fb4563 100644 ---- a/docs/level_design.md -+++ b/docs/level_design.md -@@ -125,8 +125,11 @@ en el origen, su desplazamiento Y suele ser `-Collision Dimensions.Y / 2`. - - Las colisiones de estos adornos son rectangulos simplificados, no siluetas exactas. - Los nuevos dibujos SVG son recursos sencillos de prototipado y se pueden sustituir --por arte definitivo sin cambiar la logica. No son objetos destructibles ni fisicos --moviles: son decoracion o barreras estaticas. -+por arte definitivo sin cambiar la logica. No son cuerpos fisicos moviles. -+Ahora admiten rotura opcional: activa **Breakable**, ajusta **Break Health** y -+arrastra una escena de objetos a **Drop Scene**, o dejala vacia. Los barriles lo -+activan por defecto; otros adornos conservan el modo decorativo. -+[Detalle y ejemplos](rare_items_and_breakables.md). - - ## 5. Carteles y texto - -@@ -238,7 +241,7 @@ Regresa directamente al inicio, sin repetir la intro y descartando la partida. - - Para terminar con una salida sencilla, arrastra `world/triggers/level_exit.tscn` - y coloca su origen sobre el suelo. Contiene cartel y area vertical de 112 x 160; al --entrar el jugador vuelve al menu una sola vez. El tamano fisico se modifica en -+entrar el jugador confirma los raros del intento y vuelve al menu una sola vez. El tamano fisico se modifica en - su CollisionShape2D (haz unica la forma si editas una instancia). No desbloquea - niveles ni sustituye una futura pantalla de resultado. - -@@ -246,3 +249,19 @@ La plantilla no obliga a colocar una salida. El nuevo [Level01](level_01.md) - es un ejemplo vertical con desvios y salida. [Level00](level_00.md) conserva la - calle de pruebas y su regla de meta/reinicio. No uses su script como plantilla. - Los eventos narrativos y la seleccion de personaje siguen aplazados. -+ -+ -+## Raros opcionales y recompensas al completar -+ -+Para esconder la Pua Perdida, arrastra `rare_items/variants/lost_pick.tscn` al -+escenario. No esta colocada en ninguno de los mapas incluidos. El jugador debe -+recogerla y llegar a la meta con vida; MENU o morir descartan ese hallazgo. Los -+raros ya confirmados no reaparecen y sus bonos se aplican en todos los personajes. -+ -+Para conceder un raro por ganar sin buscarlo, selecciona la raiz del nivel y -+anade su `.tres` a `Completion Rewards`. Puede ser el mismo Id que un hallazgo: -+se concede una sola vez. Los recursos nuevos deben registrarse en el catalogo -+de `game/player_progress.tscn`. La plantilla conserva vacio ese array. -+ -+Los barriles admiten un `Drop Scene` normal o raro. Romperlos no confirma el -+objeto raro: aun hay que recogerlo y terminar. [Guia completa](rare_items_and_breakables.md). -diff --git a/docs/project_status.md b/docs/project_status.md -index 34e05052c91f0196d730d713e772b9187de655c1..4d306ca734bc0f7830e4da6235f32130618f9452 100644 ---- a/docs/project_status.md -+++ b/docs/project_status.md -@@ -1,87 +1,72 @@ --# Estado del proyecto: intro/menu, escenarios y objetos -+# Estado de implementacion y validacion - --Revision del **29 de octubre de 2026**. Base reconstruida desde el proyecto --original mas kit visual, HUD thrash (incluida ocultacion) y parche de roadmap. --Esta entrega si modifica juego y recursos, no es solo una revision documental. --No incluye cambios locales posteriores que no se hayan compartido. -+Revision de **29 de octubre de 2026**: coleccion rara permanente y adornos rompibles. -+Base: proyecto original, kit de niveles, HUD thrash, roadmap e intro/menu/vertical. -+No incluye cambios locales del autor que no estuvieran en esas entregas. - --## Implementacion presente y evidencias -+## Lo incorporado - --| Cambio | Evidencia | -+| Funcion | Evidencia | - |---|---| --| F5 inicia intro de 10 s saltable | `project.godot`, `game/main.tscn`, `game/boot.gd` | --| Inicio, selector y carga asincrona | `ui/menu/main_menu.gd/.tscn` | --| Solo escenas de raiz, sin lista fija | `discover_level_paths()`, `ResourceLoader.list_directory` | --| MENU/Escape/Atras sin repetir intro | `LevelRoot`, `ui/menu/level_navigation.gd/.tscn` | --| Salida arrastrable al menu | `world/triggers/level_exit.gd/.tscn` | --| Calle anterior renombrada a beta00 | `levels/level_00.gd/.tscn`, fixtures de geometria conservada | --| Nuevo recorrido vertical editable | `levels/level_01.tscn`, sin script especifico de generacion | --| Laboratorio retirado | Eliminados antiguo `level_01.gd` y `lab_control.tres` | --| Dano hasta golpe, sustitucion estricta | `Player.collect_pickup`, `Player.take_damage` | --| No consumir mejora igual/inferior | `pickup.gd`, contrato booleano de `collect_pickup` | --| Temporales de 30/45 s y HUD hasta golpe | `pickups/data/*.tres`, `player_health_hud.gd` | --| Personaje sin cambios | El Player conserva `singer`, sin selector/autoload de sesion | -- --La beta mantiene su mapa de 11.000 unidades, 29 enemigos, 14 objetos y reinicio tras meta. --El vertical mide 3800 x 2760, tiene 12 enemigos, 14 objetos, descenso, camerino, sotano, torre --y salida. Sus superficies y objetos son instancias explicitas de las escenas del --kit, editables sin reconstruirlas desde un script. -- --## Reglas deliberadas de esta entrega -- --La intro se puede saltar desde el primer arranque; no hay persistencia de primera --visita. No se precargan todos los mapas durante los diez segundos: se carga el --menu y despues el mapa elegido, con progreso real. Volver del juego no repite intro. -- --Todos los niveles de la raiz estan disponibles. No se elige ni cambia personaje, --no se guarda progreso y cada carga recrea el estado temporal. La salida al menu --no equivale a una pantalla de victoria. La muerte sigue recargando. -- --Una mejora de dano superior sustituye a la previa del mismo canal, no se suma. --Iguales/inferiores quedan en el suelo. Un golpe valido quita mejoras general y --aerea incluso con escudo; golpes ignorados por invulnerabilidad no lo hacen. --Los recursos compartidos de CharacterData no se modifican. Se mantiene el limite --12 del golpe aereo y no se cambia el balance del especial. -- --## Validacion realizada -- --- **58 pruebas estaticas de Python superadas.** Referencias, contratos, recursos, -- geometria declarada, menu no recursivo, reglas de objetos y compatibilidad de la beta. --- Analisis de saltos de torre: 12 subidas de 160 px, huecos de 20 px, salto base -600, -- sin depender de objetos. Es una cota geometrica, no una simulacion del motor. --- Nueve suites Godot incluidas. Se adaptan las antiguas referencias a Level00 y se elimina -- la dependencia del laboratorio en los tests de objetos. Se anaden suites de -- menu y recorrido vertical. -- --**No se ha ejecutado Godot en este entorno.** No se afirma que el parser del --motor acepte los scripts, que se haya recorrido el mapa ni que el menu se haya --probado visualmente. No se ha exportado APK ni comprobado Android real. --Las pruebas .gd escritas no se cuentan como pruebas ejecutadas. -+| Coleccion en menu, sin equipar ni elegir personaje | `ui/menu/rare_inventory.gd/.tscn`, `main_menu` | -+| Pua Perdida, unico raro, +20% especial | `rare_items/data/lost_pick.tres` | -+| Variante arrastrable, sin colocacion en mapas | `rare_items/variants/lost_pick.tscn` | -+| Pendientes por intento, muerte/caida descartan | `LevelRoot.collect_rare_item`, `discard_pending_items` | -+| Meta confirma, MENU no | `LevelRoot.complete_level`, `level_exit`, `level_00` | -+| Premios automaticos por terminar | `LevelRoot.completion_rewards` | -+| Unicidad y persistencia local por Id | `game/player_progress.gd/.tscn`, autoload en `project.godot` | -+| JSON validado, temporal y copia anterior | `_read_progress`, `_write_progress`, `_load_progress` | -+| Bonos al crear Player, sin mutar CharacterData | `Player._ready`, getters de atributos efectivos | -+| Barriles rompibles, premio exacto o vacio | `SceneryProp.take_damage`, `_finish_break`, `barrel.tscn` | -+| Colision solida y zona vulnerable independientes | World (1), BreakableHurtbox (6) | -+| Punetazo, golpe descendente y especial alcanzan adornos | Mascaras y grupo `breakable` en Player | -+| Sin cargas ni KOs por romper decoracion | SceneryProp no pertenece a enemy ni emite died | -+ -+La Pua Perdida todavia no esta escondida en 00/01 ni asignada como premio de meta. -+La geometria, enemigos y 17 consumibles de los niveles no se han modificado. -+Los barriles existentes heredan la rotura, sin recompensa salvo configuracion. -+No se han cambiado movimiento, saltos, IA ni parametros base del especial. -+ -+## Limites deliberados -+ -+El guardado es de **coleccion local**, no de campana. No guarda niveles completados, -+posiciones, vida actual, carga del especial, buffs, enemigos ni barriles rotos. -+No hay nube, multiples ranuras, pantalla de equipamiento ni boton de borrar perfil. -+ -+El hallazgo se confirma al llegar vivo a la meta actual; no obliga a eliminar -+todos los enemigos. Morir, caer o abandonar antes de ganar lo pierde. Si falla -+el guardado, la meta conserva el intento pendiente y permite reintentar. -+ -+Se mantienen intro saltable, selector libre de raiz de levels, recarga al morir, -+reinicio beta tras nueve segundos, salida del vertical y seleccion de personaje -+aplazada. Pausa, audio, resultado completo, bosses y campana siguen pendientes. -+ -+## Comprobaciones de esta entrega -+ -+- **73 pruebas estaticas de Python superadas**: referencias, geometria heredada, -+ catalogo, escenas, mascaras, UI, parametros y contratos textuales de progreso. -+- Comprobacion de aplicacion del parche sobre la base reconstruida, comparacion -+ de los archivos resultantes y reversibilidad sobre esa misma base. -+- Once suites de motor preparadas. Se anaden raros/guardado y rompibles, y todas -+ usan un perfil temporal de pruebas para no afectar al perfil real. -+ -+Las comprobaciones estaticas no ejecutan GDScript ni certifican comportamiento -+fisico, tactil o visual. Las pruebas jugables y de dispositivo las realiza el -+autor; no se cuentan como ejecutadas en esta entrega. No se intenta lanzar Godot. - - ```bash - python tools/run_checks.py --static-only --python tools/run_checks.py --godot /ruta/al/ejecutable/godot - ``` - --El segundo comando requiere el motor, importa y recorre todas las suites. La --prueba de menu usa senales de botones; la de torre elimina enemigos/objetos para --comprobar solo saltos. Ninguna reemplaza las listas manuales de cada guia. -+Las recetas manuales de recogida, abandono, muerte, guardado, reapertura y barriles -+estan en [Raros y rompibles](rare_items_and_breakables.md). Las suites .gd son -+opcionales para la validacion local y no sustituyen esas comprobaciones. - --## Pendiente antes de dar esta version por validada -+## Continuar - --Importacion, GDScript, carga/reintento/retorno, tacto real, scroll en telefono, --partida completa en 00/01, saltos sin mejoras, comportamiento de enemigos en desnivel, --camara vertical, colisiones, carteles y legibilidad. Revisar especial con distintos --viewports: general de 100000 frente a 290 en 00/01, aunque ambos filtran pantalla. -+El unico backlog activo es [la guia maestra](design_vision.md). Mantener separadas -+las futuras reglas de campana/seleccion del perfil de raros. Las restricciones de -+personaje siguen aplazadas y no se han elegido implicitamente en este parche. - --Seleccion de personaje aplazada por decision del autor; no es un bloqueo para --este menu. Audio, pausa, ajustes, resultado, guardado, bosses y campana siguen --pendientes. El siguiente trabajo se prioriza en [la guia maestra](design_vision.md), --no en un segundo backlog dentro de este informe. -- --## Documentacion historica -- --Los informes de kit/HUD y sus hashes describen aquellas entregas. La vieja --Level01 de esos informes era un laboratorio; Level02 era la calle ahora Level00. --Las guias activas son [00](level_00.md), [01](level_01.md), [menu](start_menu.md), --[objetos](items.md) y [arquitectura](architecture.md). No reaplicar parches antiguos. -+Los informes anteriores del kit/HUD y sus hashes son historicos. La vieja Level01 -+era el laboratorio y Level02 es ahora la beta Level00. No reaplicar parches viejos. -diff --git a/docs/rare_items_and_breakables.md b/docs/rare_items_and_breakables.md -new file mode 100644 -index 0000000000000000000000000000000000000000..38526283b0a6259d0e2457827a07d4909a15b5e6 ---- /dev/null -+++ b/docs/rare_items_and_breakables.md -@@ -0,0 +1,200 @@ -+# Objetos raros permanentes y decoracion rompible -+ -+## Reglas de la coleccion -+ -+El menu de inicio incorpora **OBJETOS RAROS**, con nombre, icono, estado y efecto. -+Es una coleccion de mejoras automaticas, no una mochila de consumibles: no se -+necesita equipar ni activar nada. Los objetos son unicos por `Id` y pertenecen -+al perfil local, no a un personaje concreto. -+ -+| Accion | Resultado | -+|---|---| -+| Encontrar un raro | Queda pendiente en el intento; todavia no mejora atributos | -+| Recibir un golpe sin morir | Conserva el raro pendiente y los raros permanentes | -+| Morir o caer fuera del mapa | Se pierde lo pendiente, no la coleccion confirmada | -+| Volver con MENU / Escape / Atras | Abandona; no confirma hallazgos | -+| Llegar a la meta con vida | Confirma hallazgos y premios automaticos del nivel | -+| Repetir nivel / encontrar el mismo Id | No duplica el objeto ni su mejora | -+| Cerrar y abrir el juego | Conserva los raros confirmados en el perfil local | -+ -+**Completar** significa activar `world/triggers/level_exit.tscn` o la meta propia -+de Level00. No basta con abandonar ni con eliminar enemigos; no se exige limpiar -+a todos los enemigos porque esa regla no existia en los niveles actuales. -+Las reglas de victoria futuras deberan llamar a `LevelRoot.complete_level()`. -+ -+El registro pendiente pertenece a la instancia de LevelRoot, nunca al autoload. -+Por eso reintentar, cambiar de nivel o cerrar antes de ganar no arrastra hallazgos -+al intento siguiente. La meta confirma una unica vez. La beta mantiene su -+reinicio nueve segundos despues; la salida del vertical vuelve al menu. -+ -+Si el disco falla, no se declara conseguida la recompensa ni se abandona el -+nivel desde la meta. Aparece un mensaje y se conservan los pendientes para -+reintentar saliendo y volviendo a entrar en la zona. Abandonar por MENU en ese -+estado si pierde lo pendiente. Sin premios nuevos, repetir una meta no escribe. -+ -+## Pua Perdida -+ -+Es el **unico objeto raro incluido**. Aporta **+20% de dano del especial**. -+No aumenta la carga, el radio, la duracion ni el numero de pulsos. La atenuacion -+por distancia y el reparto entero entre pulsos se conservan: un presupuesto base -+30 pasa a 36 antes de aplicar carga/distancia. Los golpes normales no cambian. -+ -+Los atributos permanentes se leen al crear el Player del siguiente intento. -+Recoger la pua a mitad del mapa no facilita terminar ese mismo intento y ganarla -+no cambia al personaje que sigue vivo durante los nueve segundos de la beta. -+Tras reiniciar, o entrar en otro escenario, ya se aplica el bono. -+ -+No se ha colocado la pua en ningun nivel ni asignado como premio automatico. -+Para esconderla, arrastra: -+ -+```text -+rare_items/variants/lost_pick.tscn -+``` -+ -+Colocala bajo `Items` (o una subcarpeta) de un escenario con `LevelRoot`. Puedes -+ponerla en una repisa: permanece en esa posicion, con oscilacion solo visual, -+sin caerse al sotano. Se muestra en el editor para poder colocarla; al jugar, -+las copias de un objeto ya conseguido desaparecen. Si hay varias copias del -+mismo Id en un intento, recoger una elimina las otras. -+ -+Al recogerla aparece un aviso y un contador `RAROS PENDIENTES`. El aviso no es -+una confirmacion de guardado: hay que llegar a la meta. Como el HUD restante, -+esta interfaz no tapa el mapa cuando se edita. -+ -+### Premio por completar un nivel -+ -+Selecciona la **raiz del nivel** y, en `Rare Rewards -> Completion Rewards`, -+anade `rare_items/data/lost_pick.tres`. En ese caso se concede por terminar, -+sin necesidad de esconder una instancia. Puedes utilizar ambas vias para el -+mismo Id; se confirma una vez, sin duplicar su bono. -+ -+### Ajustar o ampliar el catalogo -+ -+La potencia se edita en `rare_items/data/lost_pick.tres`: -+ -+```text -+Special Damage Bonus = 0.20 # +20%, no 20 puntos ni +20 de carga -+Basic Damage Bonus = 0.00 -+Max Health Bonus = 0 -+``` -+ -+Para futuros raros, crea un recurso `RareItemData` con Id nuevo, nombre, icono -+y bonificaciones. Registralo en el array `Rare Items` de la raiz de -+`game/player_progress.tscn`. Esa es la unica lista del catalogo; el menu y los -+atributos leen la misma. Crea una variante de `rare_items/rare_pickup.tscn` y -+asigna el recurso, o usalo directamente en `Completion Rewards`. -+ -+`Basic Damage Bonus` mejora solo el punetazo. `Max Health Bonus` anade puntos -+al maximo y tambien se respeta al curar y mostrar el HUD. La Pua Perdida deja -+ambos en cero. Entre raros distintos los bonos de cada atributo se suman; -+las mejoras temporales del punetazo se aplican despues del bono permanente. -+El golpe descendente conserva su limite de 12. -+ -+**No cambies un Id publicado**: el guardado lo utiliza como identidad. Cambiar -+la potencia en el recurso reequilibra ese objeto incluso para perfiles que ya -+lo consiguieron; no hay estadisticas duplicadas dentro del archivo guardado. -+ -+## Barriles y otros objetos rompibles -+ -+Arrastra `world/props/barrel.tscn`. En la raiz de **esa instancia**: -+ -+| Propiedad | Funcion | -+|---|---| -+| `Breakable` | Puede recibir ataques y romperse; el barril lo activa por defecto | -+| `Break Health` | Resistencia; 5 equivale a un punetazo base del personaje actual | -+| `Drop Scene` | Escena exacta que aparece al romper; vacio significa sin premio | -+| `Drop Offset` | Punto de aparicion relativo a los pies del adorno | -+| `Collision Enabled` | Bloquea o permite atravesarlo, independientemente de romperse | -+| `Collision Dimensions / Offset` | Caja de obstaculo y zona golpeable | -+| `Draw Layer` | Detras/delante del personaje; no decide colision ni rotura | -+ -+En `Drop Scene` arrastra una **escena `.tscn`**, no un recurso `.tres`: -+ -+```text -+pickups/variants/beer.tscn -> cura -+pickups/variants/distortion_pedal.tscn -> mejora de dano normal -+rare_items/variants/lost_pick.tscn -> hallazgo raro pendiente de completar -+(vacio) -> solo se rompe -+``` -+ -+El objeto del barril no es aleatorio y no utiliza la tabla de los enemigos. -+El premio aparece una vez y espera 0,75 s antes de poder recogerse. Los objetos -+normales conservan su comportamiento de caida/recogida; los raros permanecen -+flotando en el punto configurado. Ajusta Drop Offset si has cambiado mucho el -+tamano del adorno. Un raro que ya pertenecia a la coleccion no vuelve a aparecer. -+ -+Se puede romper con punetazo, golpe descendente o especial. La rotura elimina -+la imagen y la colision, muestra fragmentos y deja el premio como hermano del -+adorno: no desaparece junto con el barril. Dos impactos en el mismo fotograma -+no generan dos recompensas. Romper **no es una baja enemiga** y no aporta carga -+del especial ni aumenta los contadores de KOs. -+ -+Para cajas, farolas u otros presets que hereden `SceneryProp`, activa `Breakable` -+y configura las mismas propiedades; no hace falta escribir otro script. Sus -+valores por defecto siguen siendo decorativos. Los barriles existentes pasan -+a ser rompibles sin premio; desactiva Breakable en los que deban seguir intactos. -+ -+Un objeto delante del personaje puede bloquear, atravesarse o romperse segun -+sus opciones. Si es un adorno de fondo que nunca debe recibir golpes, desactiva -+Breakable, no solo Collision Enabled. -+ -+La rotura no se guarda: al reiniciar el mapa los barriles vuelven. Solo la -+coleccion de raros confirmados persiste. -+ -+## Archivo local, recuperacion y pruebas -+ -+El autoload `PlayerProgress` se declara en `project.godot` y se carga tambien -+al ejecutar un nivel con F6. Conserva solo catalogo/coleccion; no decide personaje, -+camara, pausa, enemigos ni flujo de campana. -+ -+```text -+user://player_progress.json perfil confirmado: version e Id de raros -+user://player_progress.json.tmp escritura temporal -+user://player_progress.json.bak version anterior, a partir del segundo guardado -+``` -+ -+Primero se escribe/cierra el temporal, luego se copia el principal valido a -+`.bak` y finalmente se sustituye el principal. La coleccion en memoria solo -+cambia tras una escritura correcta. No es sincronizacion en nube ni garantia -+contra cualquier perdida del sistema operativo. Borrar los datos locales de la -+aplicacion tambien puede borrar este perfil. -+ -+Al cargar, se valida el JSON, version y tipos. Un principal corrupto intenta -+recuperarse desde `.bak`. Si no hay copia valida, o el formato es de una version -+no compatible, se conserva el archivo y se bloquean nuevos guardados en vez de -+pisarlo silenciosamente. El menu de raros muestra el aviso. No se cargan objetos -+ni scripts desde el archivo: solo cadenas de identificadores. -+ -+Para repetir pruebas manuales desde cero, con el juego cerrado, usa **Proyecto -+-> Abrir carpeta de datos de usuario** y mueve a una carpeta de respaldo los -+archivos `player_progress.json`, `.bak` y `.tmp` que existan. Mover solo el -+principal y dejar `.bak` permite que se recupere la coleccion, por eso no basta -+con quitar uno. No hay un boton de borrado accidental en el menu del juego. -+ -+Las suites `test_*_runtime.gd` preparan un perfil temporal independiente antes de -+crear jugadores. No escriben en el perfil de la partida y eliminan sus archivos -+al salir. Los tests nuevos cubren progreso y rotura; no se han ejecutado aqui. -+ -+### Revision manual de esta entrega -+ -+1. Arrastra la pua junto al inicio y un `level_exit` cerca, en una copia de prueba. -+ Recogela y vuelve por MENU: debe seguir sin conseguirse. -+2. Repite y muere: debe volver a aparecer al reiniciar. Recibir un golpe sin morir -+ debe conservar el hallazgo pendiente. -+3. Recogela y entra en la meta: abre OBJETOS RAROS, cierra el juego y vuelve a -+ abrirlo. Debe seguir conseguida y no volver a aparecer en el nivel. -+4. Comprueba el especial con la misma carga/distancia antes y despues. El bono -+ no debe desaparecer por dano ni sumar otra vez al repetir el nivel. -+5. Asigna la pua como `Completion Rewards` en otra copia. Debe concederse al -+ terminar, pero no al abandonar ni duplicarse si ya estaba conseguida. -+6. Prueba barril con cerveza, sin premio, con Breakable desactivado y sin colision -+ solida. Comprueba punetazo, golpe descendente y especial, sin carga por rotura. -+7. Mete la pua en un barril: romperlo no confirma nada; recoger el premio y -+ completar el nivel si. Revisa tacto/raton en el submenu y retorno con Atras. -+ -+## Referencias tecnicas -+ -+- https://docs.godotengine.org/en/stable/tutorials/scripting/singletons_autoload.html -+- https://docs.godotengine.org/en/stable/tutorials/io/saving_games.html -+- https://docs.godotengine.org/en/stable/classes/class_fileaccess.html -+- https://docs.godotengine.org/en/stable/classes/class_diraccess.html -diff --git a/docs/start_menu.md b/docs/start_menu.md -index 803365beaa17179fcc20ffcad128cf15347fa78e..a4b8546bba34372756ff8fa557296dcd846690d7 100644 ---- a/docs/start_menu.md -+++ b/docs/start_menu.md -@@ -11,7 +11,7 @@ su contenido por un video o animacion sin mezclarlo con el menu. - lista. Saltar evita la espera artificial, no fuerza la lectura de un recurso aun - pendiente. Si la carga falla muestra REINTENTAR. Escape/Atras equivale a saltar. - --El inicio tiene JUGAR y SALIR (SALIR se oculta en web). JUGAR abre un submenu -+El inicio tiene JUGAR, OBJETOS RAROS y SALIR (SALIR se oculta en web). JUGAR abre un submenu - con botones de nivel y VOLVER. Los botones aceptan clic/tacto; el foco tambien - permite usarlos con teclado. La lista tiene scroll para crecer sin salirse de la - pantalla. En Android, Atras vuelve del selector al inicio, y desde el inicio sale. -@@ -51,7 +51,9 @@ actual en `player/player.tscn` (`singer`). La decision de seleccionar al inicio, - por nivel, al morir o de usar personajes obligatorios queda aplazada. - - Cada entrada desde el menu crea una instancia nueva del nivel. Vida, especial, --escudos, mejoras, enemigos y objetos comienzan de nuevo; nada se guarda al salir. -+escudos, mejoras temporales, enemigos y objetos comienzan de nuevo. La coleccion -+de raros confirmados si persiste; sus bonos se aplican al crear Player. Los -+hallazgos pendientes se pierden al abandonar o morir, no al recibir un golpe. - Morir sigue recargando la escena actual. No hay pausa, derrota con opciones, - continuacion automatica ni desbloqueos. - -@@ -68,8 +70,17 @@ fisica. Los controles moviles existentes liberan sus acciones al salir. Se vuelv - a `main_menu.tscn`, **nunca a la intro**. MENU abandona la partida, no la pausa. - - `world/triggers/level_exit.tscn` es una salida colocable con cartel y Area2D. Solo --acepta el grupo player y solicita el retorno una vez. Para esta entrega no guarda --victorias, no emite un resultado de campana y no decide el siguiente nivel. -+acepta el grupo player y confirma `LevelRoot.complete_level()` antes de volver -+al inicio. Guarda los raros del intento y los premios automaticos, no una victoria -+de campana ni el siguiente nivel. MENU no llama a ese metodo: solo abandona. -+ -+## Coleccion de objetos raros -+ -+OBJETOS RAROS muestra el catalogo de `game/player_progress.tscn` y el estado -+confirmado del perfil local. No hay pantalla de equipamiento: los efectos son -+automaticos y no se duplican al conseguir de nuevo el mismo Id. VOLVER y Atras -+regresan al inicio. La lista tiene scroll y tarjetas editables en -+`ui/menu/rare_item_card.tscn`. [Reglas y colocacion](rare_items_and_breakables.md). - - ## Archivos y ajustes - -@@ -84,7 +95,8 @@ victorias, no emite un resultado de campana y no decide el siguiente nivel. - | Activar navegacion por escenario | `Enable Level Menu` en su raiz `LevelRoot` | - | Zona final colocable | `world/triggers/level_exit.tscn` | - --No se anaden autoloads ni gestores generales de sesion. `game/main.tscn` ya no es -+`PlayerProgress` es el unico autoload, limitado al perfil de raros. No hay -+gestor general de campana ni seleccion de personaje. `game/main.tscn` ya no es - un wrapper de `combat_test`, que se conserva como prueba independiente con F6. - - ## Verificacion pendiente en Godot y Android -diff --git a/docs/tuning.md b/docs/tuning.md -index b52f1d5715898e85ba1ba326d73826d44dfd0bc0..f0e75eec23946f260774df83f04de3827bf89ad1 100644 ---- a/docs/tuning.md -+++ b/docs/tuning.md -@@ -32,8 +32,8 @@ instancia de Player para cambiar de integrante. - - Un `.tres` externo es compartido: editarlo afecta a todas sus referencias. Para - probar solo en un nivel, haz unico el recurso de esa instancia o guarda una copia. --Las mejoras recogidas durante la partida siguen siendo estado temporal; no alteran --el recurso compartido. -+Los consumibles son estado temporal; los raros confirmados aportan bonos -+permanentes al crear Player. Ninguno altera el recurso compartido de personaje. - - ## Jugador: reglas comunes - -@@ -133,6 +133,10 @@ movimiento. No se han cambiado sus asociaciones. - | Solo un enemigo de un nivel | Propiedades de esa instancia en la escena | - | Probabilidad y pesos de drops | `enemies/walker/walker_drop.tres` | - | Recompensa fija | `Guaranteed Drop` en la instancia del enemigo | -+| Potencia permanente de un raro | `rare_items/data/*.tres` | -+| Catalogo unico de raros | `Rare Items` en `game/player_progress.tscn` | -+| Raro concedido por completar un nivel | `Completion Rewards` en la raiz del nivel | -+| Rotura/resistencia/premio de un adorno | `Breakable`, `Break Health`, `Drop Scene` | - | Potencia/duracion de un objeto | `pickups/data/*.tres` | - | Caida y oscilacion de objetos | `pickups/pickup.tscn` o una variante/instancia | - | Tamano de suelo y plataformas | `Dimensions` de la pieza colocada | -@@ -160,3 +164,20 @@ Para velocidad/salto/defensa, `duration` sigue siendo segundos: 30 por defecto y - para la Lata. Recoger otro no suma tiempo; conserva el maximo entre el restante y - la duracion nueva. Los iconos y nombres siguen en los mismos recursos compartidos. - Consulta [Objetos](items.md) antes de retocar la economia de recogida. -+ -+ -+## Bonos permanentes y objetos rompibles -+ -+`rare_items/data/lost_pick.tres` tiene `Special Damage Bonus = 0.20`. Se suma a -+los bonos de otros raros confirmados y multiplica el presupuesto del especial -+antes de carga/distancia y reparto por pulsos. No cambia radio, carga, duracion -+ni el valor base de `special_max_damage`. Recoger sin completar no lo activa. -+ -+`Basic Damage Bonus` queda en cero y mejora solo punetazos; `Max Health Bonus` -+queda en cero y anade puntos al maximo efectivo y a la curacion permitida. Son -+propiedades para futuros recursos, no otros objetos incluidos ahora. -+ -+En SceneryProp, `Break Health = 5` y `Breakable = true` permiten al barril romperse -+con un golpe base. Otros presets dejan Breakable apagado. Arrastra una escena -+`.tscn` de objetos a `Drop Scene`, o dejalo vacio. La colision solida es una opcion -+separada. [Guia de autor y reglas de guardado](rare_items_and_breakables.md). -diff --git a/effects/combat_fx.gd b/effects/combat_fx.gd -index d41c1b1cbe0d0a9d0bbdf2a432b51a8b393e5c00..6237d22a95df0a25c2434becab3f380e63ff36cd 100644 ---- a/effects/combat_fx.gd -+++ b/effects/combat_fx.gd -@@ -33,7 +33,7 @@ func _ready() -> void: - _lifetime = 0.60 - &"solo": - _lifetime = 0.62 -- &"death": -+ &"death", &"break": - _lifetime = 0.48 - &"dust": - _lifetime = 0.32 -@@ -76,6 +76,9 @@ func _draw() -> void: - _draw_sparks(progress / 0.35, Color(0.75, 0.91, 1.0, fade), 10, 34.0) - &"dust": - _draw_debris(progress, 7, Color(0.78, 0.76, 0.70, fade * 0.65), 22.0) -+ &"break": -+ _draw_debris(progress, 14, Color(0.72, 0.5, 0.24, fade), 52.0) -+ _draw_debris(progress, 6, Color(0.66, 0.68, 0.71, fade), 34.0) - &"death": - _draw_sparks(progress, Color(1.0, 0.73, 0.34, fade), 14, 42.0) - _draw_ring(lerpf(4.0, 27.0, progress), 0.80, Color(1.0, 0.89, 0.66, fade), 2.0) -diff --git a/game/player_progress.gd b/game/player_progress.gd -new file mode 100644 -index 0000000000000000000000000000000000000000..25123d72ab65db3b5abb84e0ab97efd61e255c6c ---- /dev/null -+++ b/game/player_progress.gd -@@ -0,0 +1,170 @@ -+class_name PlayerProgressStore -+extends Node -+ -+## Unico estado entre escenas: catalogo y objetos confirmados en el disco local. -+## Los hallazgos del intento pertenecen a LevelRoot; nunca se guardan aqui pendientes. -+signal collection_changed -+ -+const SAVE_VERSION: int = 1 -+const BONUS_PROPERTIES: Array[StringName] = [ -+ &"special_damage_bonus", &"basic_damage_bonus", &"max_health_bonus" -+] -+ -+## Edita el catalogo en game/player_progress.tscn. Un Id identifica una unica recompensa. -+@export var rare_items: Array[RareItemData] = [] -+ -+## Las pruebas pueden usar otra ruta antes de entrar al arbol, sin tocar el perfil real. -+var save_path: String = "user://player_progress.json" -+var last_error: String = "" -+var _catalog: Dictionary = {} -+var _owned_ids: Dictionary = {} -+var _save_blocked: bool = false -+var _primary_is_valid: bool = false -+ -+ -+func _ready() -> void: -+ for item: RareItemData in rare_items: -+ if item == null or item.id == &"" or _catalog.has(item.id): -+ push_warning("Catalogo raro: recurso nulo, Id vacio o Id duplicado; entrada ignorada.") -+ continue -+ _catalog[item.id] = item -+ _load_progress() -+ -+ -+func get_items() -> Array[RareItemData]: -+ var items: Array[RareItemData] = [] -+ for item: RareItemData in _catalog.values(): -+ items.append(item) -+ return items -+ -+ -+func get_item(item_id: StringName) -> RareItemData: -+ return _catalog.get(item_id) as RareItemData -+ -+ -+func has_item(item_id: StringName) -> bool: -+ return _owned_ids.has(item_id) -+ -+ -+## Las bonificaciones se suman por Id, sin modificar recursos compartidos de personaje. -+func get_total_bonus(property: StringName) -> float: -+ if property not in BONUS_PROPERTIES: -+ return 0.0 -+ var total: float = 0.0 -+ for item: RareItemData in get_items(): -+ if has_item(item.id): -+ total += maxf(float(item.get(property)), 0.0) -+ return total -+ -+ -+## Confirma todas las recompensas de una meta, o ninguna si falla la escritura. -+## Repetir un nivel o encontrar duplicados nunca vuelve a sumar el mismo objeto. -+func unlock_items(item_ids: Array[StringName]) -> Error: -+ var candidate: Dictionary = _owned_ids.duplicate() -+ for item_id: StringName in item_ids: -+ if not _catalog.has(item_id): -+ last_error = "Objeto no registrado en el catalogo: " + String(item_id) -+ return ERR_INVALID_PARAMETER -+ candidate[item_id] = true -+ if candidate == _owned_ids: -+ return OK -+ if _save_blocked: -+ return ERR_FILE_CORRUPT -+ var error: Error = _write_progress(candidate) -+ if error != OK: -+ return error -+ _owned_ids = candidate -+ last_error = "" -+ collection_changed.emit() -+ return OK -+ -+ -+## JSON plano: solo version e identificadores. Nunca deserializa objetos ejecutables. -+## Los Id desconocidos se conservan por compatibilidad, pero no aportan atributos. -+func _read_progress(path: String) -> Dictionary: -+ var file: FileAccess = FileAccess.open(path, FileAccess.READ) -+ if file == null: -+ return {"error": "No se pudo leer " + path + ": " + error_string(FileAccess.get_open_error())} -+ if file.get_length() > 1048576: -+ file.close() -+ return {"error": "El guardado supera el tamano admitido."} -+ var content: String = file.get_as_text() -+ file.close() -+ var json := JSON.new() -+ if json.parse(content) != OK or not json.data is Dictionary: -+ return {"error": "El guardado no contiene un JSON valido."} -+ var data: Dictionary = json.data -+ var version: Variant = data.get("version") -+ if not (version is int or version is float): -+ return {"error": "Version de guardado no valida."} -+ if version != SAVE_VERSION: -+ # No sobrescribir con un formato viejo un perfil de una version futura. -+ return {"error": "Version de guardado no compatible.", "unsupported": true} -+ var ids: Variant = data.get("rare_items") -+ if not ids is Array: -+ return {"error": "Lista de objetos no valida."} -+ var owned: Dictionary = {} -+ for item_id: Variant in ids: -+ if not item_id is String or String(item_id).is_empty(): -+ return {"error": "El guardado contiene un identificador no valido."} -+ owned[StringName(item_id)] = true -+ return {"owned": owned} -+ -+ -+func _load_progress() -> void: -+ var backup_path: String = save_path + ".bak" -+ if not FileAccess.file_exists(save_path) and not FileAccess.file_exists(backup_path): -+ return -+ var result: Dictionary = {"error": "Falta el archivo principal."} -+ if FileAccess.file_exists(save_path): -+ result = _read_progress(save_path) -+ if result.has("owned"): -+ _owned_ids = result["owned"] -+ _primary_is_valid = true -+ return -+ if not result.get("unsupported", false) and FileAccess.file_exists(backup_path): -+ var backup: Dictionary = _read_progress(backup_path) -+ if backup.has("owned"): -+ _owned_ids = backup["owned"] -+ last_error = "Se ha recuperado la coleccion desde la copia de seguridad." -+ return -+ _save_blocked = true -+ last_error = String(result.get("error", "Guardado no valido.")) + " Se conserva el archivo; revisalo antes de guardar de nuevo." -+ push_warning(last_error) -+ -+ -+## Escribe primero un temporal, conserva la version anterior y sustituye al final. -+## Nunca borra el principal antes del renombrado; un fallo deja el estado en memoria intacto. -+func _write_progress(owned: Dictionary) -> Error: -+ var ids: Array[String] = [] -+ for item_id: StringName in owned: -+ ids.append(String(item_id)) -+ ids.sort() -+ var temporary_path: String = save_path + ".tmp" -+ var file: FileAccess = FileAccess.open(temporary_path, FileAccess.WRITE) -+ if file == null: -+ return _save_error(FileAccess.get_open_error()) -+ file.store_string(JSON.stringify({"version": SAVE_VERSION, "rare_items": ids}, "\t")) -+ file.flush() -+ var write_error: Error = file.get_error() -+ file.close() -+ if write_error != OK: -+ return _save_error(write_error) -+ if _primary_is_valid and FileAccess.file_exists(save_path): -+ var backup_error: Error = DirAccess.copy_absolute( -+ ProjectSettings.globalize_path(save_path), -+ ProjectSettings.globalize_path(save_path + ".bak")) -+ if backup_error != OK: -+ return _save_error(backup_error) -+ var rename_error: Error = DirAccess.rename_absolute( -+ ProjectSettings.globalize_path(temporary_path), ProjectSettings.globalize_path(save_path)) -+ if rename_error != OK: -+ return _save_error(rename_error) -+ _primary_is_valid = true -+ return OK -+ -+ -+func _save_error(error: Error) -> Error: -+ last_error = "No se pudo guardar la coleccion: " + error_string(error) -+ push_warning(last_error) -+ return error -diff --git a/game/player_progress.tscn b/game/player_progress.tscn -new file mode 100644 -index 0000000000000000000000000000000000000000..80ac4378fd90d9d72707870c6adaa3fbe85db9da ---- /dev/null -+++ b/game/player_progress.tscn -@@ -0,0 +1,9 @@ -+[gd_scene load_steps=4 format=3] -+ -+[ext_resource type="Script" path="res://game/player_progress.gd" id="script"] -+[ext_resource type="Script" path="res://rare_items/rare_item_data.gd" id="item_script"] -+[ext_resource type="Resource" path="res://rare_items/data/lost_pick.tres" id="lost_pick"] -+ -+[node name="PlayerProgress" type="Node"] -+script = ExtResource("script") -+rare_items = Array[ExtResource("item_script")]([ExtResource("lost_pick")]) -diff --git a/levels/level_00.gd b/levels/level_00.gd -index 096f075bedab0fa212df8c062018f9d8a8892aac..d9355fdae1c573ed69150c70658f031bca510982 100644 ---- a/levels/level_00.gd -+++ b/levels/level_00.gd -@@ -7,7 +7,6 @@ extends LevelRoot - ## No interviene en los drops: los Walker usan su sistema habitual. - ## La meta conserva el reinicio de pruebas; Menu permite salir en cualquier momento. - --signal level_completed - - const FINISH_RESTART_SECONDS: float = 9.0 - -@@ -18,6 +17,7 @@ const FINISH_RESTART_SECONDS: float = 9.0 - - var defeated_enemies: int = 0 - var completed: bool = false -+var _finish_pending: bool = false - var _finish_timer: float = 0.0 - - -@@ -62,10 +62,18 @@ func _update_status() -> void: - - ## Muestra el resultado una sola vez al alcanzar la meta. - func _on_finish_entered(body: Node2D) -> void: -- if body != player or completed: -+ if body != player or completed or _finish_pending: -+ return -+ _finish_pending = true -+ call_deferred("_complete_finish") -+ -+ -+## Igual que LevelExit, resuelve la meta despues de todos los contactos del paso fisico. -+func _complete_finish() -> void: -+ _finish_pending = false -+ if not complete_level(): - return - completed = true -- level_completed.emit() - finish_message.text = "FIN DE LA GIRA!\nEnemigos derrotados: %d / %d\nReinicio en 9 s" % [ - defeated_enemies, enemies.get_child_count() - ] -diff --git a/levels/level_root.gd b/levels/level_root.gd -index 9abc330cbc65937851d5f1e1c4c56b619c03c5e9..1e0f90683edec3883468f2c8b0edfdab4d2e9cc7 100644 ---- a/levels/level_root.gd -+++ b/levels/level_root.gd -@@ -6,8 +6,17 @@ extends Node2D - ## La plantilla contiene Player, terreno, decoracion, enemigos y controles. - ## Los niveles con reglas propias pueden heredar y llamar a super en sus callbacks. - -+signal level_completed -+signal rare_items_changed -+signal progress_notice(message: String) -+ - const NAVIGATION_SCENE: PackedScene = preload("res://ui/menu/level_navigation.tscn") - -+@export_category("Rare rewards") -+## Objetos unicos concedidos al llegar a la meta, aunque no esten escondidos en el mapa. -+## Deben estar registrados en game/player_progress.tscn. Vacio: no hay premio automatico. -+@export var completion_rewards: Array[RareItemData] = [] -+ - @export_category("Level") - ## Boton Menu y Escape/atras. No se crea dentro del editor ni altera la escena guardada. - @export var enable_level_menu: bool = true -@@ -32,6 +41,10 @@ const NAVIGATION_SCENE: PackedScene = preload("res://ui/menu/level_navigation.ts - - var _level_player: Node2D - var _reload_pending: bool = false -+var _attempt_lost: bool = false -+var _level_completed: bool = false -+# Solo existe mientras vive esta instancia: muerte, caida o abandono lo descartan. -+var _pending_rare_items: Dictionary = {} - - - func _ready() -> void: -@@ -42,6 +55,8 @@ func _ready() -> void: - if _level_player == null: - push_error("LevelRoot necesita una instancia de player/player.tscn llamada Player.") - return -+ if _level_player.has_signal("died"): -+ _level_player.connect("died", discard_pending_items) - apply_camera_bounds() - if enable_level_menu and not has_node("LevelNavigation"): - add_child(NAVIGATION_SCENE.instantiate()) -@@ -68,10 +83,86 @@ func _process(_delta: float) -> void: - return - if _level_player.global_position.y > to_global(camera_bounds.end).y + fall_margin: - _reload_pending = true -+ discard_pending_items() - # La recarga se difiere para no destruir nodos durante un paso de fisica. - get_tree().call_deferred("reload_current_scene") - - -+## Busca el escenario propietario sin depender de la profundidad de Items/Scenery. -+static func find_for(node: Node) -> LevelRoot: -+ var current: Node = node -+ while current != null: -+ if current is LevelRoot: -+ return current as LevelRoot -+ current = current.get_parent() -+ return null -+ -+ -+func get_pending_rare_count() -> int: -+ return _pending_rare_items.size() -+ -+ -+func has_pending_rare_item(item_id: StringName) -> bool: -+ return _pending_rare_items.has(item_id) -+ -+ -+## Recoger no aplica atributos ni escribe en disco: registra el hallazgo del intento. -+func collect_rare_item(item_id: StringName, collector: Node2D) -> bool: -+ if collector != _level_player or not _can_complete() or _level_completed: -+ return false -+ var progress: PlayerProgressStore = get_node_or_null("/root/PlayerProgress") as PlayerProgressStore -+ if progress == null or progress.get_item(item_id) == null: -+ progress_notice.emit("Objeto raro no registrado en el catalogo.") -+ return false -+ if progress.has_item(item_id) or _pending_rare_items.has(item_id): -+ return false -+ _pending_rare_items[item_id] = true -+ rare_items_changed.emit() -+ progress_notice.emit(progress.get_item(item_id).display_name + ": encontrada. Termina el nivel para conservarla.") -+ return true -+ -+ -+## Solo una meta llama a este metodo; MENU, Escape y morir no completan el nivel. -+## Si falla el disco, conserva los hallazgos y permite volver a intentar la meta. -+func complete_level() -> bool: -+ if not _can_complete(): -+ return false -+ if _level_completed: -+ return true -+ var reward_ids: Array[StringName] = [] -+ for item_id: StringName in _pending_rare_items: -+ reward_ids.append(item_id) -+ for reward: RareItemData in completion_rewards: -+ if reward != null and reward.id not in reward_ids: -+ reward_ids.append(reward.id) -+ if not reward_ids.is_empty(): -+ var progress: PlayerProgressStore = get_node_or_null("/root/PlayerProgress") as PlayerProgressStore -+ if progress == null: -+ progress_notice.emit("No se encontro PlayerProgress. No se ha confirmado la recompensa.") -+ return false -+ if progress.unlock_items(reward_ids) != OK: -+ progress_notice.emit(progress.last_error + " Sal y vuelve a entrar en la meta para reintentar.") -+ return false -+ _level_completed = true -+ _pending_rare_items.clear() -+ rare_items_changed.emit() -+ level_completed.emit() -+ return true -+ -+ -+func _can_complete() -> bool: -+ return is_inside_tree() and not is_queued_for_deletion() and not Engine.is_editor_hint() \ -+ and not _attempt_lost and not _reload_pending \ -+ and is_instance_valid(_level_player) and not bool(_level_player.get("is_dead")) -+ -+ -+## Un golpe no pierde un raro pendiente; morir o salir del escenario si. -+func discard_pending_items() -> void: -+ _attempt_lost = true -+ _pending_rare_items.clear() -+ rare_items_changed.emit() -+ -+ - func _draw() -> void: - if not Engine.is_editor_hint() or not show_editor_bounds: - return -@@ -87,4 +178,7 @@ func _get_configuration_warnings() -> PackedStringArray: - warnings.append("Falta Player. Arrastra player/player.tscn y conserva ese nombre en la raiz del nivel.") - if not scale.is_equal_approx(Vector2.ONE) or not is_zero_approx(rotation): - warnings.append("No escales ni rotes la raiz del nivel; edita las piezas individualmente.") -+ for reward: RareItemData in completion_rewards: -+ if reward == null or reward.id == &"": -+ warnings.append("Completion Rewards contiene una entrada sin datos o sin Id.") - return warnings -diff --git a/player/player.gd b/player/player.gd -index 5df23e066258e3d9fdcb5e3de0301426d68492a4..b4295aaccedcfd5f2a28bb715931a81529a8a09e 100644 ---- a/player/player.gd -+++ b/player/player.gd -@@ -13,9 +13,10 @@ signal pickup_collected(data: PickupData) - - - # Capas de fisica: 1 escenario, 2 cuerpo del jugador, 3 cuerpo enemigo, --# 4 zona vulnerable del jugador y 5 zona vulnerable del enemigo. -+# 4 zona vulnerable del jugador, 5 del enemigo y 6 de objetos rompibles. - # Los bits de las mascaras empiezan en cero; no confundir bit con numero de capa. - const ENEMY_HURTBOX_MASK: int = 1 << 4 -+const BREAKABLE_HURTBOX_MASK: int = 1 << 5 - const COMBAT_FX = preload("res://effects/combat_fx.gd") - - -@@ -206,6 +207,11 @@ const COMBAT_FX = preload("res://effects/combat_fx.gd") - # ESTADO DE LA PARTIDA - # ============================================================================ - -+# Copia de los bonos confirmados al iniciar el intento. No se toca CharacterData. -+var _permanent_special_damage_bonus: float = 0.0 -+var _permanent_basic_damage_bonus: float = 0.0 -+var _permanent_max_health_bonus: int = 0 -+ - var current_health: int = 1 - var facing_direction: float = 1.0 - -@@ -265,7 +271,12 @@ func _ready() -> void: - push_error("Player needs a CharacterData resource.") - return - -- current_health = character_data.max_health -+ var progress: PlayerProgressStore = get_node_or_null("/root/PlayerProgress") as PlayerProgressStore -+ if progress != null: -+ _permanent_special_damage_bonus = progress.get_total_bonus(&"special_damage_bonus") -+ _permanent_basic_damage_bonus = progress.get_total_bonus(&"basic_damage_bonus") -+ _permanent_max_health_bonus = roundi(progress.get_total_bonus(&"max_health_bonus")) -+ current_health = get_max_health() - if character_data.sprite_frames != null: - animated_sprite.sprite_frames = character_data.sprite_frames - -@@ -274,7 +285,7 @@ func _ready() -> void: - _setup_attack_hitboxes() - _update_facing() - _update_animation() -- health_changed.emit(current_health, character_data.max_health) -+ health_changed.emit(current_health, get_max_health()) - special_charge_changed.emit(special_charge, special_max_charge) - # Conecta los enemigos que ya pertenecen al grupo al iniciar el nivel. - # Un futuro sistema de aparicion dinamica debera conectar tambien sus nuevas instancias. -@@ -494,7 +505,7 @@ func _update_punch_damage() -> void: - COMBAT_FX.spawn(get_parent(), punch_hitbox.global_position, &"swing", facing_direction) - - for area in punch_hitbox.get_overlapping_areas(): -- _damage_target(area, roundi(character_data.basic_attack_damage * (1.0 + _damage_boost_multiplier)), punch_hit_targets) -+ _damage_target(area, get_basic_attack_damage(), punch_hit_targets) - - - # ============================================================================ -@@ -545,7 +556,7 @@ func _ground_pound_impact() -> void: - var query := PhysicsShapeQueryParameters2D.new() - query.shape = ground_pound_collision.shape - query.transform = ground_pound_collision.global_transform -- query.collision_mask = ENEMY_HURTBOX_MASK -+ query.collision_mask = ENEMY_HURTBOX_MASK | BREAKABLE_HURTBOX_MASK - query.collide_with_areas = true - query.collide_with_bodies = false - for hit: Dictionary in get_world_2d().direct_space_state.intersect_shape(query, 64): -@@ -601,40 +612,57 @@ func _update_special_attack(delta: float) -> void: - _special_damage_dealt.clear() - - --## Mantiene un presupuesto de dano por enemigo para no multiplicarlo por el numero de pulsos. -+## Mantiene un presupuesto de dano por objetivo para no multiplicarlo por el numero de pulsos. - func _apply_special_attack(charge_used: int, pulse_index: int = 0) -> void: - var charge_ratio: float = clampf(float(charge_used) / float(maxi(special_max_charge, 1)), 0.0, 1.0) - var viewport_rect: Rect2 = get_viewport().get_visible_rect() - var max_distance: float = maxf(maxf(viewport_rect.size.x, viewport_rect.size.y) * 0.8, 1.0) - var pulse_count: int = maxi(special_pulse_count, 1) - -- for node: Node in get_tree().get_nodes_in_group("enemy"): -- var enemy := node as Node2D -- if enemy == null or not enemy.has_method("take_damage") or bool(enemy.get("is_dead")): -+ var targets: Array[Node] = get_tree().get_nodes_in_group("enemy") -+ targets.append_array(get_tree().get_nodes_in_group("breakable")) -+ for node: Node in targets: -+ var target := node as Node2D -+ if target == null or not target.has_method("take_damage") or (target.is_in_group("enemy") and bool(target.get("is_dead"))): - continue -- var distance: float = global_position.distance_to(enemy.global_position) -+ var distance: float = global_position.distance_to(target.global_position) - if special_radius > 0.0 and distance > special_radius: - continue -- # Solo afecta a enemigos visibles; no debe golpear a distancia al otro extremo del mapa. -- if not viewport_rect.grow(28.0).has_point(enemy.get_global_transform_with_canvas().origin): -+ # Solo afecta a enemigos y objetos rompibles visibles; no debe golpear a distancia al otro extremo del mapa. -+ if not viewport_rect.grow(28.0).has_point(target.get_global_transform_with_canvas().origin): - continue - -- var enemy_id: int = enemy.get_instance_id() -- if not _special_damage_budgets.has(enemy_id): -+ var target_id: int = target.get_instance_id() -+ if not _special_damage_budgets.has(target_id): - var distance_factor: float = maxf(0.1, 1.0 - clampf(distance / max_distance, 0.0, 1.0)) -- _special_damage_budgets[enemy_id] = maxi(1, int(special_max_damage * charge_ratio * distance_factor)) -+ _special_damage_budgets[target_id] = maxi(1, int(special_max_damage * get_special_damage_multiplier() * charge_ratio * distance_factor)) - # Fija el presupuesto al primer contacto: el retroceso posterior no cambia el dano total. -- var total_damage: int = int(_special_damage_budgets[enemy_id]) -+ var total_damage: int = int(_special_damage_budgets[target_id]) - var cumulative_damage: int = ceili(float(total_damage) * float(pulse_index + 1) / float(pulse_count)) -- var damage: int = cumulative_damage - int(_special_damage_dealt.get(enemy_id, 0)) -+ var damage: int = cumulative_damage - int(_special_damage_dealt.get(target_id, 0)) - if damage <= 0: - continue -- _special_damage_dealt[enemy_id] = cumulative_damage -+ _special_damage_dealt[target_id] = cumulative_damage - _applying_special_damage = true -- enemy.call("take_damage", damage, global_position) -+ target.call("take_damage", damage, global_position) - _applying_special_damage = false - - -+## Atributos efectivos del intento; los raros pendientes no intervienen en estos valores. -+func get_max_health() -> int: -+ return maxi(character_data.max_health + _permanent_max_health_bonus, 1) if character_data != null else 1 -+ -+ -+func get_basic_attack_damage() -> int: -+ if character_data == null: -+ return 0 -+ return roundi(character_data.basic_attack_damage * (1.0 + _permanent_basic_damage_bonus) * (1.0 + _damage_boost_multiplier)) -+ -+ -+func get_special_damage_multiplier() -> float: -+ return 1.0 + _permanent_special_damage_bonus -+ -+ - ## Devuelve true solo si se aplica el efecto. False conserva el objeto para otra oportunidad. - func collect_pickup(data: PickupData) -> bool: - if is_dead or data == null or character_data == null: -@@ -642,11 +670,11 @@ func collect_pickup(data: PickupData) -> bool: - - match data.effect_type: - "heal": -- var heal_amount: int = mini(int(data.value), character_data.max_health - current_health) -+ var heal_amount: int = mini(int(data.value), get_max_health() - current_health) - if heal_amount <= 0: - return false - current_health += heal_amount -- health_changed.emit(current_health, character_data.max_health) -+ health_changed.emit(current_health, get_max_health()) - _spawn_floating_text("+" + str(heal_amount), Color(0.2, 1.0, 0.3)) - "speed_boost": - if data.value <= 0.0 or data.duration <= 0.0: -@@ -794,7 +822,7 @@ func take_damage(amount: int, source_position: Vector2, knockback_multiplier: fl - COMBAT_FX.spawn(get_parent(), global_position, &"hit", knockback_direction) - feedback_camera.call("impact", 1.5 * clampf(push_scale, 0.8, 1.6), 0.18) - -- health_changed.emit(current_health, character_data.max_health) -+ health_changed.emit(current_health, get_max_health()) - - if current_health == 0: - _die() -@@ -894,7 +922,7 @@ func _setup_attack_hitboxes() -> void: - punch_shape.size = punch_hitbox_size - punch_collision.shape = punch_shape - punch_hitbox.collision_layer = 0 -- punch_hitbox.collision_mask = ENEMY_HURTBOX_MASK -+ punch_hitbox.collision_mask = ENEMY_HURTBOX_MASK | BREAKABLE_HURTBOX_MASK - punch_hitbox.monitoring = true - - var pound_shape: CircleShape2D = CircleShape2D.new() -@@ -902,7 +930,7 @@ func _setup_attack_hitboxes() -> void: - ground_pound_collision.shape = pound_shape - ground_pound_hitbox.position = ground_pound_offset - ground_pound_hitbox.collision_layer = 0 -- ground_pound_hitbox.collision_mask = ENEMY_HURTBOX_MASK -+ ground_pound_hitbox.collision_mask = ENEMY_HURTBOX_MASK | BREAKABLE_HURTBOX_MASK - ground_pound_hitbox.monitoring = true - - -diff --git a/player/player.tscn b/player/player.tscn -index ac0601c1059135cd899a4a33034fa3c48c7537ab..c9b5e18610c638c1a3fb657917c6a8831ff17e76 100644 ---- a/player/player.tscn -+++ b/player/player.tscn -@@ -29,14 +29,14 @@ shape = SubResource("PlayerShape") - - [node name="PunchHitbox" type="Area2D" parent="." unique_id=184501519] - collision_layer = 0 --collision_mask = 16 -+collision_mask = 48 - monitorable = false - - [node name="CollisionShape2D" type="CollisionShape2D" parent="PunchHitbox" unique_id=126348432] - - [node name="GroundPoundHitbox" type="Area2D" parent="." unique_id=1822904824] - collision_layer = 0 --collision_mask = 16 -+collision_mask = 48 - monitorable = false - - [node name="CollisionShape2D" type="CollisionShape2D" parent="GroundPoundHitbox" unique_id=2120510285] -diff --git a/project.godot b/project.godot -index 842c671eef4f7a95aff095dafa99f7a61d861816..f6eb8dbfeeb49488d71efb36cfc2f64cb02daf9b 100644 ---- a/project.godot -+++ b/project.godot -@@ -16,6 +16,10 @@ run/main_scene="res://game/main.tscn" - config/features=PackedStringArray("4.7", "GL Compatibility") - config/icon="res://icon.svg" - -+[autoload] -+ -+PlayerProgress="*res://game/player_progress.tscn" -+ - [display] - - window/stretch/mode="canvas_items" -@@ -70,6 +74,7 @@ pointing/emulate_mouse_from_touch=true - 2d_physics/layer_3="EnemyBody" - 2d_physics/layer_4="PlayerHurtbox" - 2d_physics/layer_5="EnemyHurtbox" -+2d_physics/layer_6="BreakableHurtbox" - - [physics] - -diff --git a/rare_items/data/lost_pick.tres b/rare_items/data/lost_pick.tres -new file mode 100644 -index 0000000000000000000000000000000000000000..1f55f6abfca299df663fad66531688209e981016 ---- /dev/null -+++ b/rare_items/data/lost_pick.tres -@@ -0,0 +1,13 @@ -+[gd_resource type="Resource" script_class="RareItemData" load_steps=3 format=3] -+ -+[ext_resource type="Script" path="res://rare_items/rare_item_data.gd" id="script"] -+[ext_resource type="Texture2D" path="res://assets/rare_items/lost_pick.svg" id="icon"] -+ -+[resource] -+script = ExtResource("script") -+id = &"lost_pick" -+display_name = "Pรบa Perdida" -+description = "La pua que faltaba para llevar el solo un poco mas lejos. Encuentrala y termina el nivel para conservarla." -+icon = ExtResource("icon") -+color = Color(1, 0.77, 0.26, 1) -+special_damage_bonus = 0.2 -diff --git a/rare_items/rare_item_data.gd b/rare_items/rare_item_data.gd -new file mode 100644 -index 0000000000000000000000000000000000000000..84046f60a2ba581414ee1da2042d524e3b51ab79 ---- /dev/null -+++ b/rare_items/rare_item_data.gd -@@ -0,0 +1,44 @@ -+@tool -+class_name RareItemData -+extends Resource -+ -+## Definicion compartida de un objeto unico. El guardado almacena su Id, no copias -+## del recurso ni estadisticas calculadas. No cambies el Id una vez publicado. -+@export_category("Identity") -+@export var id: StringName = &"": -+ set(value): -+ id = value -+ emit_changed() -+@export var display_name: String = "Objeto raro": -+ set(value): -+ display_name = value -+ emit_changed() -+@export_multiline var description: String = "" -+@export var icon: Texture2D: -+ set(value): -+ icon = value -+ emit_changed() -+@export var color: Color = Color(1.0, 0.77, 0.26): -+ set(value): -+ color = value -+ emit_changed() -+ -+@export_category("Permanent bonuses") -+## Fraccion adicional: 0.20 significa +20%. No aumenta carga ni numero de pulsos. -+@export_range(0.0, 3.0, 0.05) var special_damage_bonus: float = 0.0 -+## Reservado para futuros objetos: mejora el punetazo, no el golpe descendente. -+@export_range(0.0, 3.0, 0.05) var basic_damage_bonus: float = 0.0 -+## Puntos adicionales de vida maxima para todos los personajes del perfil local. -+@export_range(0, 1000, 1) var max_health_bonus: int = 0 -+ -+ -+## La coleccion muestra el efecto del recurso, sin mantener otra descripcion numerica. -+func get_bonus_text() -> String: -+ var parts: Array[String] = [] -+ if special_damage_bonus > 0.0: -+ parts.append("Dano especial +%d%%" % roundi(special_damage_bonus * 100.0)) -+ if basic_damage_bonus > 0.0: -+ parts.append("Dano de punetazo +%d%%" % roundi(basic_damage_bonus * 100.0)) -+ if max_health_bonus > 0: -+ parts.append("Vida maxima +%d" % max_health_bonus) -+ return " | ".join(parts) if not parts.is_empty() else "Sin mejora de atributos" -diff --git a/rare_items/rare_pickup.gd b/rare_items/rare_pickup.gd -new file mode 100644 -index 0000000000000000000000000000000000000000..2880ceec256246b5f7d58bfff55c723ce8f82bc1 ---- /dev/null -+++ b/rare_items/rare_pickup.gd -@@ -0,0 +1,102 @@ -+@tool -+class_name RarePickup -+extends Area2D -+ -+## Hallazgo opcional: no es un consumible ni otorga atributos en el mismo intento. -+## Se mantiene en la posicion elegida por el autor, con oscilacion solo de su dibujo. -+@export var rare_item: RareItemData: -+ set(value): -+ if rare_item != null and rare_item.changed.is_connected(_update_preview): -+ rare_item.changed.disconnect(_update_preview) -+ rare_item = value -+ if rare_item != null: -+ rare_item.changed.connect(_update_preview) -+ if is_inside_tree(): -+ call_deferred("_update_preview") -+@export_range(0.0, 5.0, 0.05) var collection_delay_seconds: float = 0.0 -+ -+var _level: LevelRoot -+var _collected: bool = false -+var _age: float = 0.0 -+ -+ -+func _ready() -> void: -+ _update_preview() -+ if Engine.is_editor_hint(): -+ set_physics_process(false) -+ return -+ _level = LevelRoot.find_for(self) -+ if rare_item == null or _level == null: -+ push_warning("RarePickup necesita Rare Item y un escenario con LevelRoot.") -+ set_physics_process(false) -+ return -+ var progress: PlayerProgressStore = get_node_or_null("/root/PlayerProgress") as PlayerProgressStore -+ if progress == null or progress.get_item(rare_item.id) == null: -+ push_warning("RarePickup: registra el recurso en game/player_progress.tscn.") -+ set_physics_process(false) -+ return -+ _level.rare_items_changed.connect(_hide_if_unavailable) -+ _hide_if_unavailable() -+ body_entered.connect(_on_body_entered) -+ -+ -+func _physics_process(delta: float) -> void: -+ if Engine.is_editor_hint() or _collected: -+ return -+ _age += delta -+ $Sprite2D.position.y = sin(_age * 2.5) * 3.0 -+ if _age < collection_delay_seconds: -+ return -+ # Al terminar la espera de un drop tambien se acepta al jugador que sigue encima. -+ for body: Node2D in get_overlapping_bodies(): -+ _on_body_entered(body) -+ if _collected: -+ break -+ -+ -+func _on_body_entered(body: Node2D) -> void: -+ if _collected or _age < collection_delay_seconds or rare_item == null or _level == null: -+ return -+ if not body.is_in_group("player"): -+ return -+ if _level.collect_rare_item(rare_item.id, body): -+ _collected = true -+ hide() -+ queue_free() -+ -+ -+## Si el autor coloco dos copias, al recoger una desaparecen ambas en ese intento. -+func _hide_if_unavailable() -> void: -+ var progress: PlayerProgressStore = get_node_or_null("/root/PlayerProgress") as PlayerProgressStore -+ if rare_item == null or progress == null: -+ return -+ if progress.has_item(rare_item.id) or _level.has_pending_rare_item(rare_item.id): -+ _collected = true -+ hide() -+ queue_free() -+ -+ -+func _update_preview() -> void: -+ if not is_inside_tree() or not has_node("Sprite2D"): -+ return -+ var sprite: Sprite2D = $Sprite2D -+ var label: Label = $Label -+ sprite.texture = rare_item.icon if rare_item != null else null -+ if sprite.texture != null: -+ sprite.scale = Vector2(40.0, 40.0) / sprite.texture.get_size() -+ label.text = rare_item.display_name if rare_item != null else "ASIGNA RARE ITEM" -+ label.modulate = rare_item.color if rare_item != null else Color.MAGENTA -+ queue_redraw() -+ update_configuration_warnings() -+ -+ -+func _draw() -> void: -+ var color: Color = rare_item.color if rare_item != null else Color.MAGENTA -+ color.a = 0.5 -+ draw_arc(Vector2.ZERO, 25.0, 0.0, TAU, 24, color, 2.0) -+ -+ -+func _get_configuration_warnings() -> PackedStringArray: -+ if rare_item == null or rare_item.id == &"": -+ return PackedStringArray(["Asigna un RareItemData con Id unico. Registralo tambien en game/player_progress.tscn."]) -+ return PackedStringArray() -diff --git a/rare_items/rare_pickup.tscn b/rare_items/rare_pickup.tscn -new file mode 100644 -index 0000000000000000000000000000000000000000..bb25032ab83d16154951a04c29b4ece6ea32cbc3 ---- /dev/null -+++ b/rare_items/rare_pickup.tscn -@@ -0,0 +1,33 @@ -+[gd_scene load_steps=3 format=3] -+ -+[ext_resource type="Script" path="res://rare_items/rare_pickup.gd" id="script"] -+ -+[sub_resource type="CircleShape2D" id="shape"] -+resource_local_to_scene = true -+radius = 24.0 -+ -+[node name="RarePickup" type="Area2D"] -+z_index = 3 -+texture_filter = 1 -+collision_layer = 0 -+collision_mask = 2 -+monitorable = false -+script = ExtResource("script") -+ -+[node name="CollisionShape2D" type="CollisionShape2D" parent="."] -+shape = SubResource("shape") -+ -+[node name="Sprite2D" type="Sprite2D" parent="."] -+ -+[node name="Label" type="Label" parent="."] -+offset_left = -130.0 -+offset_top = -53.0 -+offset_right = 130.0 -+offset_bottom = -27.0 -+mouse_filter = 2 -+theme_override_colors/font_shadow_color = Color(0, 0, 0, 1) -+theme_override_constants/shadow_offset_x = 2 -+theme_override_constants/shadow_offset_y = 2 -+theme_override_font_sizes/font_size = 16 -+text = "OBJETO RARO" -+horizontal_alignment = 1 -diff --git a/rare_items/variants/lost_pick.tscn b/rare_items/variants/lost_pick.tscn -new file mode 100644 -index 0000000000000000000000000000000000000000..0b1cb351bfc7f7f8b927232482b829c71d86fdf5 ---- /dev/null -+++ b/rare_items/variants/lost_pick.tscn -@@ -0,0 +1,7 @@ -+[gd_scene load_steps=3 format=3] -+ -+[ext_resource type="PackedScene" path="res://rare_items/rare_pickup.tscn" id="base"] -+[ext_resource type="Resource" path="res://rare_items/data/lost_pick.tres" id="data"] -+ -+[node name="LostPick" instance=ExtResource("base")] -+rare_item = ExtResource("data") -diff --git a/tests/runtime_test_profile.gd b/tests/runtime_test_profile.gd -new file mode 100644 -index 0000000000000000000000000000000000000000..4b9604413d217fe80264bbe08ca9a76545676cfe ---- /dev/null -+++ b/tests/runtime_test_profile.gd -@@ -0,0 +1,28 @@ -+extends RefCounted -+ -+## Aisla todas las suites del perfil del jugador. Nunca escribe ni borra su guardado. -+## Funciona tanto si el runner cargo autoloads como si usa un SceneTree independiente. -+static func prepare(tree: SceneTree) -> PlayerProgressStore: -+ var path: String = "user://__test_progress_%d_%d.json" % [OS.get_process_id(), Time.get_ticks_usec()] -+ var profile: PlayerProgressStore = tree.root.get_node_or_null("PlayerProgress") as PlayerProgressStore -+ if profile == null: -+ profile = preload("res://game/player_progress.tscn").instantiate() as PlayerProgressStore -+ profile.name = "PlayerProgress" -+ profile.save_path = path -+ tree.root.add_child(profile) -+ else: -+ profile.save_path = path -+ profile.set("_owned_ids", {}) -+ profile.set("_save_blocked", false) -+ profile.set("_primary_is_valid", false) -+ profile.last_error = "" -+ profile.tree_exiting.connect(_remove_test_files.bind(path)) -+ return profile -+ -+ -+static func _remove_test_files(path: String) -> void: -+ if not path.begins_with("user://__test_progress_"): -+ return -+ for suffix: String in ["", ".tmp", ".bak"]: -+ if FileAccess.file_exists(path + suffix): -+ DirAccess.remove_absolute(ProjectSettings.globalize_path(path + suffix)) -diff --git a/tests/test_breakables_runtime.gd b/tests/test_breakables_runtime.gd -new file mode 100644 -index 0000000000000000000000000000000000000000..165aa1b15dd26e26574d409ad8a8d407e2de6309 ---- /dev/null -+++ b/tests/test_breakables_runtime.gd -@@ -0,0 +1,93 @@ -+extends SceneTree -+ -+## Impactos sobre SceneryProp y drops reales, con el perfil aislado de la partida. -+const BARREL: PackedScene = preload("res://world/props/barrel.tscn") -+const PLAYER: PackedScene = preload("res://player/player.tscn") -+const REWARD: PackedScene = preload("res://pickups/variants/beer.tscn") -+var _failures: int = 0 -+var _arena: Node2D -+ -+ -+func _initialize() -> void: -+ call_deferred("_run") -+ -+ -+func _run() -> void: -+ preload("res://tests/runtime_test_profile.gd").prepare(self) -+ _arena = Node2D.new() -+ _arena.position = Vector2(140, 80) -+ root.add_child(_arena) -+ current_scene = _arena -+ var barrel: SceneryProp = _barrel(Vector2(400, 300), REWARD) -+ barrel.collision_enabled = false -+ await process_frame -+ _check((barrel.get_node("Body") as StaticBody2D).collision_layer == 0, "La colision solida es opcional") -+ _check((barrel.get_node("Hurtbox") as Area2D).collision_layer == 32, "Sin colision solida sigue siendo golpeable") -+ barrel.take_damage(0, Vector2.ZERO) -+ _check(barrel.current_health == 5, "Cero dano no rompe") -+ barrel.take_damage(2, Vector2.ZERO) -+ _check(barrel.current_health == 3 and not barrel.is_broken, "Se acumula dano hasta la resistencia") -+ barrel.take_damage(3, Vector2.ZERO) -+ barrel.take_damage(100, Vector2.ZERO) -+ _check(barrel.is_broken, "El bloqueo de rotura es inmediato") -+ await process_frame -+ await process_frame -+ var drops: Array[Node] = get_nodes_in_group("pickup") -+ _check(drops.size() == 1, "Dos impactos simultaneos solo crean un premio") -+ if not drops.is_empty(): -+ var pickup: Pickup = drops[0] as Pickup -+ _check(pickup.pickup_data.id == &"beer", "Usa exactamente el objeto asignado") -+ _check(is_equal_approx(pickup.global_position.x, 540.0), "Convierte la posicion del padre trasladado") -+ _check(is_equal_approx(pickup.collection_delay_seconds, 0.75), "Deja ver el objeto antes de recogerlo") -+ pickup.queue_free() -+ await process_frame -+ -+ var empty: SceneryProp = _barrel(Vector2(500, 300), null) -+ empty.take_damage(5, Vector2.ZERO) -+ await process_frame -+ await process_frame -+ _check(get_nodes_in_group("pickup").is_empty(), "Un barril sin premio solo se rompe") -+ var decoration: SceneryProp = _barrel(Vector2(600, 300), REWARD) -+ decoration.breakable = false -+ decoration.take_damage(999, Vector2.ZERO) -+ _check(not decoration.is_broken, "Breakable desactivado conserva la decoracion") -+ decoration.queue_free() -+ -+ # El mismo contrato usado por el punetazo alcanza la hurtbox de un adorno. -+ var player: CharacterBody2D = PLAYER.instantiate() as CharacterBody2D -+ player.position = Vector2(0, 0) -+ _arena.add_child(player) -+ player.set_physics_process(false) -+ var target: SceneryProp = _barrel(Vector2(40, 26), null) -+ player.call("_damage_target", target.get_node("Hurtbox"), 5, {}) -+ _check(target.is_broken, "El ataque resuelve la entidad propietaria de la hurtbox") -+ _check(int(player.get("special_charge")) == 0, "Romper no cuenta como una baja enemiga") -+ await process_frame -+ await process_frame -+ -+ var solo_target: SceneryProp = _barrel(Vector2(40, 26), null) -+ await physics_frame -+ player.call("_apply_special_attack", 100, 0) -+ _check(solo_target.is_broken, "El solo alcanza objetos rompibles visibles") -+ _check(int(player.get("special_charge")) == 0, "El solo tampoco gana carga al romper adornos") -+ await process_frame -+ current_scene = null -+ _arena.queue_free() -+ await process_frame -+ if _failures == 0: -+ print("OK BREAKABLES: resistencia, colision opcional, premio unico, vacio, punetazo y solo") -+ quit(0 if _failures == 0 else 1) -+ -+ -+func _barrel(at: Vector2, reward: PackedScene) -> SceneryProp: -+ var barrel: SceneryProp = BARREL.instantiate() as SceneryProp -+ barrel.position = at -+ barrel.drop_scene = reward -+ _arena.add_child(barrel) -+ return barrel -+ -+ -+func _check(condition: bool, message: String) -> void: -+ if not condition: -+ _failures += 1 -+ push_error(message) -diff --git a/tests/test_editor_ui_runtime.gd b/tests/test_editor_ui_runtime.gd -index caf86d664d7123c66828dd050693d2be307a6540..6532a13d2ecffa28328be842fe6d7bfbba9f7cc3 100644 ---- a/tests/test_editor_ui_runtime.gd -+++ b/tests/test_editor_ui_runtime.gd -@@ -13,6 +13,7 @@ func _initialize() -> void: - - - func _run() -> void: -+ preload("res://tests/runtime_test_profile.gd").prepare(self) - var canvas_layer := CanvasLayer.new() - canvas_layer.visible = false - var panel := Control.new() -diff --git a/tests/test_enemy_ai_runtime.gd b/tests/test_enemy_ai_runtime.gd -index 2101c910af68e5a341bce3ca31da5cfde08dcc89..218364437a0efc53792829d75d38db0e4d967695 100644 ---- a/tests/test_enemy_ai_runtime.gd -+++ b/tests/test_enemy_ai_runtime.gd -@@ -15,6 +15,7 @@ func _initialize() -> void: - - - func _run() -> void: -+ preload("res://tests/runtime_test_profile.gd").prepare(self) - await _test_safe_start() - await _test_chasing_and_return() - await _test_jumping() -diff --git a/tests/test_level_00_runtime.gd b/tests/test_level_00_runtime.gd -index acc8f02fa4e7d57a5457080326bc1c6be793b5b3..2362c44d5552551f3abb568111af6a1967bb99c8 100644 ---- a/tests/test_level_00_runtime.gd -+++ b/tests/test_level_00_runtime.gd -@@ -9,6 +9,7 @@ func _initialize() -> void: - - - func _run() -> void: -+ preload("res://tests/runtime_test_profile.gd").prepare(self) - var packed: PackedScene = load("res://levels/level_00.tscn") as PackedScene - if packed == null: - _fail("No se pudo cargar levels/level_00.tscn") -diff --git a/tests/test_level_01_runtime.gd b/tests/test_level_01_runtime.gd -index 62495bdf451c3f2960bc8a33e47b7e7ceb51d919..1380acc5d3dbc0793e8e95bac27a45293de6855b 100644 ---- a/tests/test_level_01_runtime.gd -+++ b/tests/test_level_01_runtime.gd -@@ -11,6 +11,7 @@ func _initialize() -> void: - - - func _run() -> void: -+ preload("res://tests/runtime_test_profile.gd").prepare(self) - var level: LevelRoot = (load("res://levels/level_01.tscn") as PackedScene).instantiate() as LevelRoot - root.add_child(level) - current_scene = level -diff --git a/tests/test_level_kit_runtime.gd b/tests/test_level_kit_runtime.gd -index 1980350672ac918be4cd894483ca0defd7ab3f19..44f527f1858593d2534d3ee548c180a1c600ce26 100644 ---- a/tests/test_level_kit_runtime.gd -+++ b/tests/test_level_kit_runtime.gd -@@ -12,6 +12,7 @@ func _initialize() -> void: - - - func _run() -> void: -+ preload("res://tests/runtime_test_profile.gd").prepare(self) - await _verify_terrain() - await _verify_props_and_signs() - await _verify_one_way_physics() -diff --git a/tests/test_menu_resources.py b/tests/test_menu_resources.py -index 6e0cce58aea98f848035d4e9b1ceed9b6f18b0a7..e1a6011cccc7d935ccf29b4a7be92164a7f2c60f 100644 ---- a/tests/test_menu_resources.py -+++ b/tests/test_menu_resources.py -@@ -26,8 +26,11 @@ class MenuResourceTests(unittest.TestCase): - self.assertNotIn('DirAccess', code) - self.assertIn('load_threaded_get_status', code) - self.assertIn('ResourceLoader.THREAD_LOAD_FAILED', code) -- # No se ha introducido un singleton de campana ni un selector de personaje. -- self.assertNotIn('[autoload]', (ROOT / 'project.godot').read_text()) -+ # El unico autoload es el perfil de raros; no impone campana ni personaje. -+ project = (ROOT / 'project.godot').read_text() -+ self.assertIn('PlayerProgress="*res://game/player_progress.tscn"', project) -+ autoloads = project.split('[autoload]', 1)[1].split('[display]', 1)[0] -+ self.assertEqual(len(re.findall(r'^\w+="\*res://', autoloads, re.M)), 1) - self.assertNotIn('CharacterData', code) - - def test_menu_uses_scroll_and_touch_sized_buttons(self): -diff --git a/tests/test_menu_runtime.gd b/tests/test_menu_runtime.gd -index 3c119edae498a5535e06ca4f0c7c05ea20440b22..25bba93a0df4ea45eda71c5df360d4d8cc498acf 100644 ---- a/tests/test_menu_runtime.gd -+++ b/tests/test_menu_runtime.gd -@@ -1,6 +1,6 @@ - extends SceneTree - --## Integracion de intro, menu, cambios de escena y retorno. No necesita autoloads. -+## Integracion de intro, menu, cambios de escena y retorno. Utiliza un perfil de pruebas aislado. - ## Los botones se activan por su senal; el tacto real se comprueba en dispositivo. - const MENU_SCRIPT: Script = preload("res://ui/menu/main_menu.gd") - const BOOT_PATH: String = "res://game/main.tscn" -@@ -15,6 +15,7 @@ func _initialize() -> void: - - - func _run() -> void: -+ preload("res://tests/runtime_test_profile.gd").prepare(self) - _check(change_scene_to_file(BOOT_PATH) == OK, "Debe abrirse la intro") - var boot: Node = await _wait_for_scene(BOOT_PATH) - if boot == null: -diff --git a/tests/test_pickup_runtime.gd b/tests/test_pickup_runtime.gd -index 26c9273f1215c6b728faabffa451285714e97997..c1c4cfea3da44d2ca0d59848ac491132063b2b46 100644 ---- a/tests/test_pickup_runtime.gd -+++ b/tests/test_pickup_runtime.gd -@@ -18,6 +18,7 @@ func _initialize() -> void: - - - func _run() -> void: -+ preload("res://tests/runtime_test_profile.gd").prepare(self) - _arena = Node2D.new() - root.add_child(_arena) - current_scene = _arena -diff --git a/tests/test_pixel_combat_runtime.gd b/tests/test_pixel_combat_runtime.gd -index ed950afd49e25524728d44704725f3471ae8696c..41ded102338f06149cc6135ee11ffc8ed7304a0f 100644 ---- a/tests/test_pixel_combat_runtime.gd -+++ b/tests/test_pixel_combat_runtime.gd -@@ -13,6 +13,7 @@ func _initialize() -> void: - - - func _run() -> void: -+ preload("res://tests/runtime_test_profile.gd").prepare(self) - var packed: PackedScene = load("res://levels/level_00.tscn") as PackedScene - if packed == null: - push_error("Cannot load Level00") -diff --git a/tests/test_rare_items_resources.py b/tests/test_rare_items_resources.py -new file mode 100644 -index 0000000000000000000000000000000000000000..7bfc5f2ebc197b4882d74257b22bb449fe691de5 ---- /dev/null -+++ b/tests/test_rare_items_resources.py -@@ -0,0 +1,160 @@ -+"""Contratos de recursos e integracion textual, sin ejecutar GDScript ni el motor.""" -+from pathlib import Path -+import re -+import unittest -+from xml.etree import ElementTree -+ -+ROOT = Path(__file__).resolve().parents[1] -+ -+ -+def source(path: str) -> str: -+ return (ROOT / path).read_text(encoding="utf-8") -+ -+ -+class RareItemResourceTests(unittest.TestCase): -+ def test_one_unique_rare_item_registered_once(self): -+ items = list((ROOT / 'rare_items/data').glob('*.tres')) -+ self.assertEqual(len(items), 1) -+ data = source('rare_items/data/lost_pick.tres') -+ self.assertIn('id = &"lost_pick"', data) -+ self.assertIn('special_damage_bonus = 0.2', data) -+ self.assertNotIn('max_health_bonus =', data) -+ catalog = source('game/player_progress.tscn') -+ self.assertEqual(catalog.count('path="res://rare_items/data/lost_pick.tres"'), 1) -+ self.assertIn('rare_items = Array[ExtResource("item_script")]', catalog) -+ self.assertIn('rare_item = ExtResource("data")', source('rare_items/variants/lost_pick.tscn')) -+ -+ def test_rare_not_placed_in_any_existing_map(self): -+ for scene in (ROOT / 'levels').rglob('*.tscn'): -+ text = scene.read_text(encoding='utf-8') -+ self.assertNotIn('res://rare_items/', text, scene) -+ self.assertNotIn('completion_rewards =', text, scene) -+ -+ def test_rare_icon_is_self_contained_svg(self): -+ element = ElementTree.parse(ROOT / 'assets/rare_items/lost_pick.svg').getroot() -+ self.assertEqual(element.attrib['viewBox'], '0 0 48 48') -+ self.assertEqual(element.attrib['shape-rendering'], 'crispEdges') -+ for node in element.iter(): -+ self.assertNotIn(node.tag.split('}')[-1], {'image', 'script', 'text'}) -+ self.assertFalse(any(key.endswith('href') for key in node.attrib)) -+ -+ def test_collected_items_stay_in_level_until_confirmed(self): -+ level = source('levels/level_root.gd') -+ collect = level.split('func collect_rare_item(', 1)[1].split('\nfunc ', 1)[0] -+ self.assertIn('_pending_rare_items[item_id] = true', collect) -+ self.assertNotIn('unlock_items(', collect) -+ self.assertNotIn('FileAccess', level) -+ store = source('game/player_progress.gd') -+ self.assertNotIn('_pending_rare_items', store) -+ self.assertIn('level_completed.emit()', level) -+ -+ def test_death_and_fall_invalidate_the_attempt(self): -+ level = source('levels/level_root.gd') -+ self.assertIn('_level_player.connect("died", discard_pending_items)', level) -+ self.assertIn('_reload_pending = true\n\t\tdiscard_pending_items()', level) -+ discard = level.split('func discard_pending_items()', 1)[1].split('\nfunc ', 1)[0] -+ self.assertIn('_attempt_lost = true', discard) -+ self.assertIn('_pending_rare_items.clear()', discard) -+ self.assertIn('bool(_level_player.get("is_dead"))', level) -+ -+ def test_both_goals_confirm_but_menu_abandon_does_not(self): -+ for path in ('world/triggers/level_exit.gd', 'levels/level_00.gd'): -+ text = source(path) -+ self.assertIn('complete_level()', text) -+ self.assertIn('call_deferred(', text) -+ navigation = source('ui/menu/level_navigation.gd') -+ self.assertNotIn('complete_level()', navigation) -+ self.assertNotIn('unlock_items(', navigation) -+ -+ def test_disk_write_precedes_memory_commit(self): -+ text = source('game/player_progress.gd') -+ unlock = text.split('func unlock_items(', 1)[1].split('\n\n##', 1)[0] -+ self.assertLess(unlock.index('_write_progress(candidate)'), unlock.index('_owned_ids = candidate')) -+ self.assertIn('if error != OK:\n\t\treturn error', unlock) -+ self.assertIn('candidate[item_id] = true', unlock) -+ self.assertIn('candidate == _owned_ids', unlock) -+ self.assertIn('"user://player_progress.json"', text) -+ self.assertIn('DirAccess.rename_absolute(', text) -+ self.assertIn('file.flush()', text) -+ self.assertIn('file.close()', text) -+ self.assertNotIn('get_var(', text) -+ -+ def test_corrupt_and_unknown_data_are_not_silently_destroyed(self): -+ text = source('game/player_progress.gd') -+ self.assertIn('json.parse(content) != OK', text) -+ self.assertIn('if not ids is Array:', text) -+ self.assertIn('not item_id is String', text) -+ self.assertIn('_save_blocked = true', text) -+ self.assertIn('_read_progress(backup_path)', text) -+ self.assertIn('owned[StringName(item_id)] = true', text) -+ self.assertIn('if property not in BONUS_PROPERTIES:', text) -+ -+ def test_permanent_attributes_are_separate_from_temporary_buffs(self): -+ player = source('player/player.gd') -+ ready = player.split('func _ready()', 1)[1].split('\n\n##', 1)[0] -+ self.assertIn('progress.get_total_bonus(&"special_damage_bonus")', ready) -+ self.assertIn('current_health = get_max_health()', ready) -+ self.assertNotRegex(player, r'character_data\.(?:max_health|basic_attack_damage)\s*[+*/-]?=') -+ damage = player.split('func take_damage(', 1)[1].split('func _die()', 1)[0] -+ self.assertNotIn('_permanent_', damage) -+ self.assertIn('get_special_damage_multiplier() * charge_ratio * distance_factor', player) -+ self.assertIn('get_max_health() - current_health', player) -+ -+ def test_inventory_reads_same_catalog_and_supports_back(self): -+ menu = source('ui/menu/main_menu.gd') -+ view = source('ui/menu/rare_inventory.gd') -+ self.assertIn('inventory_panel.visible', menu) -+ self.assertIn('inventory_panel.call("show_collection")', menu) -+ self.assertIn('progress.get_items()', view) -+ self.assertIn('item.get_bonus_text()', view) -+ self.assertIn('progress.has_item(item.id)', view) -+ self.assertIn('type="ScrollContainer"', source('ui/menu/rare_inventory.tscn')) -+ -+ def test_new_resource_load_steps_match(self): -+ paths = [ROOT/'game/player_progress.tscn', * (ROOT/'rare_items').rglob('*.tscn'), * (ROOT/'rare_items').rglob('*.tres'), * (ROOT/'ui/menu').glob('rare_*.tscn')] -+ for path in paths: -+ text = path.read_text(encoding='utf-8') -+ self.assertEqual(int(re.search(r'load_steps=(\d+)', text)[1]), 1 + len(re.findall(r'^\[(?:ext|sub)_resource ', text, re.M)), path) -+ -+ -+class BreakableResourceTests(unittest.TestCase): -+ def test_barrel_is_breakable_but_other_props_opt_in(self): -+ self.assertIn('breakable = true', source('world/props/barrel.tscn')) -+ prop = source('world/props/scenery_prop.gd') -+ self.assertIn('var breakable: bool = false', prop) -+ self.assertIn('var break_health: int = 5', prop) -+ self.assertIn('var drop_scene: PackedScene', prop) -+ self.assertNotIn('drop_scene =', source('world/props/barrel.tscn')) -+ self.assertIn('[node name="Hurtbox" type="Area2D" parent="."]', source('world/props/scenery_prop.tscn')) -+ -+ def test_attack_masks_cover_breakables_without_marking_them_enemies(self): -+ player = source('player/player.gd') -+ self.assertEqual(player.count('collision_mask = ENEMY_HURTBOX_MASK | BREAKABLE_HURTBOX_MASK'), 3) -+ self.assertIn('get_nodes_in_group("breakable")', player) -+ prop = source('world/props/scenery_prop.gd') -+ self.assertNotIn('add_to_group("enemy")', prop) -+ self.assertNotIn('signal died', prop) -+ self.assertIn('2d_physics/layer_6="BreakableHurtbox"', source('project.godot')) -+ -+ def test_break_is_latched_before_deferred_drop_and_removes_collision(self): -+ text = source('world/props/scenery_prop.gd') -+ damage = text.split('func take_damage(', 1)[1].split('func _finish_break()', 1)[0] -+ self.assertIn('or is_broken or amount <= 0:', damage) -+ self.assertLess(damage.index('is_broken = true'), damage.index('call_deferred("_finish_break")')) -+ self.assertIn('$Body/CollisionShape2D.set_deferred("disabled", true)', damage) -+ self.assertIn('$Hurtbox/CollisionShape2D.set_deferred("disabled", true)', damage) -+ self.assertIn('container.add_child(drop)', text) -+ self.assertNotIn('randf(', text) -+ -+ def test_regular_and_rare_drops_are_supported_without_extra_reward_tables(self): -+ text = source('world/props/scenery_prop.gd') -+ self.assertIn('if drop_scene != null:', text) -+ self.assertIn('if drop is Pickup:', text) -+ self.assertIn('elif drop is RarePickup:', text) -+ self.assertIn('to_global(drop_offset)', text) -+ self.assertIn('(container as Node2D).to_local(spawn_position)', text) -+ self.assertIn('instance.free()', text) -+ -+ -+if __name__ == '__main__': -+ unittest.main() -diff --git a/tests/test_rare_items_runtime.gd b/tests/test_rare_items_runtime.gd -new file mode 100644 -index 0000000000000000000000000000000000000000..bae35b751ce6af716c615186d74f65413eae5a98 ---- /dev/null -+++ b/tests/test_rare_items_runtime.gd -@@ -0,0 +1,161 @@ -+extends SceneTree -+ -+## Contratos de progreso y atributos con un archivo temporal exclusivo de esta suite. -+## La existencia de este script no implica que se haya ejecutado. -+const PLAYER_SCENE: PackedScene = preload("res://player/player.tscn") -+const RARE_SCENE: PackedScene = preload("res://rare_items/variants/lost_pick.tscn") -+const PROGRESS_SCENE: PackedScene = preload("res://game/player_progress.tscn") -+var _failures: int = 0 -+var _profile: PlayerProgressStore -+var _level: LevelRoot -+var _player: CharacterBody2D -+ -+ -+func _initialize() -> void: -+ call_deferred("_run") -+ -+ -+func _run() -> void: -+ _profile = preload("res://tests/runtime_test_profile.gd").prepare(self) -+ _new_level() -+ _check(_level.collect_rare_item(&"lost_pick", _player), "Se registra el hallazgo") -+ _check(_level.get_pending_rare_count() == 1, "El hallazgo sigue pendiente") -+ _check(not _profile.has_item(&"lost_pick"), "Recoger no desbloquea") -+ _check(not FileAccess.file_exists(_profile.save_path), "Recoger no escribe") -+ _check(is_equal_approx(float(_player.call("get_special_damage_multiplier")), 1.0), "Recoger no mejora el intento actual") -+ _check(not _level.collect_rare_item(&"lost_pick", _player), "No se recoge el mismo Id dos veces") -+ # Muerte logica sin solicitar la recarga de la escena de prueba. -+ _player.set("is_dead", true) -+ _player.emit_signal("died") -+ _check(_level.get_pending_rare_count() == 0, "Morir descarta el hallazgo") -+ _check(not _level.complete_level(), "Un muerto no puede confirmar la meta") -+ _close_level() -+ -+ _new_level() -+ _check(_level.collect_rare_item(&"lost_pick", _player), "Otro intento puede recoger de nuevo") -+ _close_level() # Abandonar: el unico registro pendiente pertenecia al nivel destruido. -+ _check(not _profile.has_item(&"lost_pick"), "Abandonar no confirma nada") -+ -+ _new_level() -+ _check(_level.collect_rare_item(&"lost_pick", _player), "Recogida del intento ganador") -+ _check(_level.complete_level(), "La meta confirma la recogida") -+ _check(_profile.has_item(&"lost_pick"), "La coleccion conserva el Id") -+ _check(FileAccess.file_exists(_profile.save_path), "La meta escribe el perfil") -+ var saved_once: String = FileAccess.get_file_as_string(_profile.save_path) -+ _check(_level.complete_level(), "La meta repetida es idempotente") -+ _check(FileAccess.get_file_as_string(_profile.save_path) == saved_once, "No reescribe ni acumula la misma recompensa") -+ _check(is_equal_approx(float(_player.call("get_special_damage_multiplier")), 1.0), "Los atributos se actualizan al siguiente intento") -+ _close_level() -+ -+ _new_level() -+ _check(is_equal_approx(float(_player.call("get_special_damage_multiplier")), 1.2), "El intento siguiente tiene +20% de especial") -+ _player.call("take_damage", 1, Vector2(-50, 0)) -+ _check(is_equal_approx(float(_player.call("get_special_damage_multiplier")), 1.2), "Recibir un golpe no elimina un raro permanente") -+ var repeated: RarePickup = RARE_SCENE.instantiate() as RarePickup -+ _level.add_child(repeated) -+ _check(repeated.is_queued_for_deletion(), "Un objeto ya obtenido no aparece de nuevo") -+ _close_level() -+ -+ # Premios automaticos y futuras estadisticas, sin colocar nuevos objetos en el catalogo real. -+ var reward := RareItemData.new() -+ reward.id = &"test_badge" -+ reward.max_health_bonus = 10 -+ reward.basic_damage_bonus = 0.2 -+ _profile.rare_items.append(reward) -+ var catalog: Dictionary = _profile.get("_catalog") -+ catalog[reward.id] = reward -+ _new_level() -+ _level.completion_rewards.append(reward) -+ _check(_level.complete_level(), "Un premio automatico no necesita una recogida") -+ _close_level() -+ _new_level() -+ var data: CharacterData = _player.get("character_data") as CharacterData -+ _check(data.max_health == 50 and data.basic_attack_damage == 5, "Los datos compartidos no se mutan") -+ _check(int(_player.call("get_max_health")) == 60, "Se aplica vida maxima adicional") -+ _check(int(_player.call("get_basic_attack_damage")) == 6, "Se aplica dano base adicional") -+ _player.set("current_health", 10) -+ _player.call("collect_pickup", load("res://pickups/data/beer.tres")) -+ _check(int(_player.get("current_health")) <= 60, "La cura respeta el maximo efectivo") -+ _close_level() -+ -+ # Reabrir el archivo demuestra el contrato de carga, no solo el estado de la misma instancia. -+ var loaded: PlayerProgressStore = PROGRESS_SCENE.instantiate() as PlayerProgressStore -+ loaded.save_path = _profile.save_path -+ loaded.rare_items.append(reward) -+ root.add_child(loaded) -+ _check(loaded.has_item(&"lost_pick") and loaded.has_item(reward.id), "Recarga de disco por Id") -+ _check(is_equal_approx(loaded.get_total_bonus(&"special_damage_bonus"), 0.2), "Recargar no duplica el bono") -+ loaded.free() -+ -+ _test_failed_save() -+ _test_backup_and_bad_data() -+ if _failures == 0: -+ print("OK RARE ITEMS: pendientes, muerte, abandono, meta, guardado, duplicados, premios y atributos") -+ quit(0 if _failures == 0 else 1) -+ -+ -+func _test_failed_save() -> void: -+ var reward := RareItemData.new() -+ reward.id = &"test_retry" -+ var catalog: Dictionary = _profile.get("_catalog") -+ catalog[reward.id] = reward -+ _new_level() -+ _check(_level.collect_rare_item(reward.id, _player), "Recogida para probar el fallo de disco") -+ var real_test_path: String = _profile.save_path -+ # No se crea este directorio: abrir un archivo dentro de el debe fallar. -+ _profile.save_path = "user://__missing_test_directory_%d/profile.json" % Time.get_ticks_usec() -+ _check(not _level.complete_level(), "Un fallo de escritura bloquea la confirmacion") -+ _check(not _profile.has_item(reward.id), "No concede un premio que no ha guardado") -+ _check(_level.get_pending_rare_count() == 1, "Conserva el hallazgo para reintentar") -+ _profile.save_path = real_test_path -+ _check(_level.complete_level(), "Se puede reintentar tras resolver el error") -+ _check(_profile.has_item(reward.id), "El premio se confirma una vez") -+ _close_level() -+ -+ -+func _test_backup_and_bad_data() -> void: -+ _check(FileAccess.file_exists(_profile.save_path + ".bak"), "Un segundo guardado conserva copia anterior") -+ var file: FileAccess = FileAccess.open(_profile.save_path, FileAccess.WRITE) -+ file.store_string("not valid JSON") -+ file.close() -+ var loaded: PlayerProgressStore = PROGRESS_SCENE.instantiate() as PlayerProgressStore -+ loaded.save_path = _profile.save_path -+ root.add_child(loaded) -+ _check(loaded.has_item(&"lost_pick"), "Recupera los objetos de la copia valida") -+ _check(not loaded.last_error.is_empty(), "Informa de la recuperacion") -+ loaded.free() -+ # Una version futura nunca se rebaja sobreescribiendola con la copia antigua. -+ file = FileAccess.open(_profile.save_path, FileAccess.WRITE) -+ file.store_string('{"version":999,"rare_items":[]}') -+ file.close() -+ loaded = PROGRESS_SCENE.instantiate() as PlayerProgressStore -+ loaded.save_path = _profile.save_path -+ root.add_child(loaded) -+ var ids: Array[StringName] = [&"lost_pick"] -+ _check(loaded.unlock_items(ids) != OK, "No pisa un formato desconocido") -+ _check(FileAccess.get_file_as_string(_profile.save_path).contains("999"), "Conserva el archivo incompatible") -+ loaded.free() -+ -+ -+func _new_level() -> void: -+ _level = LevelRoot.new() -+ _level.enable_level_menu = false -+ _level.reset_after_fall = false -+ _player = PLAYER_SCENE.instantiate() as CharacterBody2D -+ _player.name = "Player" -+ _level.add_child(_player) -+ root.add_child(_level) -+ _player.set_physics_process(false) -+ -+ -+func _close_level() -> void: -+ if is_instance_valid(_level): -+ _level.free() -+ _level = null -+ _player = null -+ -+ -+func _check(condition: bool, message: String) -> void: -+ if not condition: -+ _failures += 1 -+ push_error(message) -diff --git a/tests/test_thrash_hud_resources.py b/tests/test_thrash_hud_resources.py -index c0111c1e16ba299713782f918ecf23bc750fa883..0d121bf676037de03e0709c065ba87bcf90dba8a 100644 ---- a/tests/test_thrash_hud_resources.py -+++ b/tests/test_thrash_hud_resources.py -@@ -70,7 +70,7 @@ class ThrashHUDResourceTests(unittest.TestCase): - - def test_special_reward_context_does_not_gate_all_deaths_during_solo(self): - script = (ROOT / "player/player.gd").read_text() -- damage_call = '\t\t_applying_special_damage = true\n\t\tenemy.call("take_damage", damage, global_position)\n\t\t_applying_special_damage = false' -+ damage_call = '\t\t_applying_special_damage = true\n\t\ttarget.call("take_damage", damage, global_position)\n\t\t_applying_special_damage = false' - self.assertIn(damage_call, script) - callback = script.split("func _on_enemy_died(", 1)[1].split("\nfunc ", 1)[0] - self.assertIn("_applying_special_damage and not special_kills_grant_charge", callback) -diff --git a/tests/test_thrash_hud_runtime.gd b/tests/test_thrash_hud_runtime.gd -index befae76a68351f3c2ad22e338f19511a31b98cfd..1de3cf59ac8125a39777a54a061bb4b31d9bd8a3 100644 ---- a/tests/test_thrash_hud_runtime.gd -+++ b/tests/test_thrash_hud_runtime.gd -@@ -13,6 +13,7 @@ func _initialize() -> void: - - - func _run() -> void: -+ preload("res://tests/runtime_test_profile.gd").prepare(self) - root.size = Vector2i(1152, 648) - var arena := Node2D.new() - var player: CharacterBody2D = load("res://player/player.tscn").instantiate() as CharacterBody2D -diff --git a/ui/hud/player_health_hud.gd b/ui/hud/player_health_hud.gd -index aa6f546d190629d6a7a1f39a09c6b52e0ecdab9d..de65570779d007c411ff1241dccaa46271678707 100644 ---- a/ui/hud/player_health_hud.gd -+++ b/ui/hud/player_health_hud.gd -@@ -32,7 +32,7 @@ func _ready() -> void: - if player_ref.is_node_ready(): - var data: Resource = player_ref.get("character_data") as Resource - if data != null: -- _on_health_changed(int(player_ref.get("current_health")), int(data.get("max_health"))) -+ _on_health_changed(int(player_ref.get("current_health")), int(player_ref.call("get_max_health"))) - - - ## Muestra segundos solo para efectos temporales; dano indica hasta recibir un golpe. -diff --git a/ui/menu/level_navigation.gd b/ui/menu/level_navigation.gd -index d984eed5b598c932404656d0ca44828d76ff925d..650c52d51b42722d0873c8e5b6a412cbac3f0959 100644 ---- a/ui/menu/level_navigation.gd -+++ b/ui/menu/level_navigation.gd -@@ -1,13 +1,21 @@ - extends CanvasLayer - --## Salida minima de los escenarios de prueba. No es un menu de pausa ni guardado. -+## Salida minima de los escenarios de prueba. Abandonar no confirma los raros encontrados. - ## Se usa una escena compartida para que el boton se pueda editar visualmente. - const MENU_PATH: String = "res://ui/menu/main_menu.tscn" - var _leaving: bool = false -+var _notice_seconds: float = 0.0 - - - func _ready() -> void: - $Overlay/Menu.pressed.connect(return_to_menu) -+ # No referencia LevelRoot por tipo: esta escena se precarga desde esa clase. -+ var level: Node = get_parent() -+ if level.has_signal("progress_notice"): -+ level.connect("progress_notice", _show_notice) -+ if level.has_signal("rare_items_changed"): -+ level.connect("rare_items_changed", _refresh_pending) -+ _refresh_pending() - - - func _unhandled_input(event: InputEvent) -> void: -@@ -34,3 +42,23 @@ func _change_scene() -> void: - if error != OK: - _leaving = false - push_error("No se pudo volver al menu: " + error_string(error)) -+ -+ -+func _refresh_pending() -> void: -+ var level: Node = get_parent() -+ var count: int = int(level.call("get_pending_rare_count")) if level.has_method("get_pending_rare_count") else 0 -+ $Overlay/Pending.text = "RAROS PENDIENTES: %d\nCompleta el nivel para guardarlos" % count -+ $Overlay/Pending.visible = count > 0 -+ -+ -+func _show_notice(message: String) -> void: -+ $Overlay/Notice.text = message -+ $Overlay/Notice.show() -+ _notice_seconds = 8.0 -+ -+ -+func _process(delta: float) -> void: -+ if _notice_seconds > 0.0: -+ _notice_seconds -= delta -+ if _notice_seconds <= 0.0: -+ $Overlay/Notice.hide() -diff --git a/ui/menu/level_navigation.tscn b/ui/menu/level_navigation.tscn -index 1155c5d724feab828be0898309641b4a9cf1a191..865cd10b08d79b35633f6141aff210091f1504e0 100644 ---- a/ui/menu/level_navigation.tscn -+++ b/ui/menu/level_navigation.tscn -@@ -30,3 +30,41 @@ offset_bottom = 76.0 - grow_horizontal = 0 - focus_mode = 0 - text = "MENU" -+ -+ -+[node name="Pending" type="Label" parent="Overlay"] -+visible = false -+layout_mode = 1 -+anchor_left = 1.0 -+anchor_right = 1.0 -+offset_left = -330.0 -+offset_top = 88.0 -+offset_right = -16.0 -+offset_bottom = 150.0 -+grow_horizontal = 0 -+mouse_filter = 2 -+theme_override_colors/font_color = Color(1, 0.8, 0.35, 1) -+theme_override_colors/font_shadow_color = Color(0, 0, 0, 1) -+theme_override_constants/shadow_offset_x = 2 -+theme_override_constants/shadow_offset_y = 2 -+theme_override_font_sizes/font_size = 16 -+horizontal_alignment = 2 -+autowrap_mode = 3 -+ -+[node name="Notice" type="Label" parent="Overlay"] -+visible = false -+layout_mode = 1 -+anchor_left = 0.2 -+anchor_top = 0.5 -+anchor_right = 0.8 -+anchor_bottom = 0.5 -+offset_top = -32.0 -+offset_bottom = 48.0 -+mouse_filter = 2 -+theme_override_colors/font_color = Color(1, 0.9, 0.55, 1) -+theme_override_colors/font_shadow_color = Color(0, 0, 0, 1) -+theme_override_constants/shadow_offset_x = 2 -+theme_override_constants/shadow_offset_y = 2 -+theme_override_font_sizes/font_size = 20 -+horizontal_alignment = 1 -+autowrap_mode = 3 -diff --git a/ui/menu/main_menu.gd b/ui/menu/main_menu.gd -index 8b43997265ea780ab2c92409b600bfea7ad0ad33..5eefe5204006f7be87ffcd1dd36af55519275473 100644 ---- a/ui/menu/main_menu.gd -+++ b/ui/menu/main_menu.gd -@@ -1,6 +1,6 @@ - extends Control - --## Menu provisional sin seleccion de personaje, progreso ni lista manual de niveles. -+## Menu provisional, coleccion persistente y selector de niveles sin lista manual. - ## Solo descubre escenas directamente dentro de levels, nunca sus subcarpetas. - const LEVEL_DIRECTORY: String = "res://levels" - -@@ -10,6 +10,8 @@ const LEVEL_DIRECTORY: String = "res://levels" - @onready var level_list: VBoxContainer = $Margin/Layout/Levels/Scroll/LevelList - @onready var empty_label: Label = $Margin/Layout/Levels/Empty - @onready var play_button: Button = $Margin/Layout/Home/Play -+@onready var inventory_panel: VBoxContainer = $Margin/Layout/RareInventory -+@onready var inventory_button: Button = $Margin/Layout/Home/RareItems - @onready var quit_button: Button = $Margin/Layout/Home/Quit - @onready var back_button: Button = $Margin/Layout/Levels/Back - @onready var error_label: Label = $Margin/Layout/Error -@@ -24,6 +26,8 @@ func _ready() -> void: - set_process(false) - play_button.pressed.connect(_show_levels) - back_button.pressed.connect(_show_home) -+ inventory_button.pressed.connect(_show_inventory) -+ inventory_panel.connect("back_requested", _show_home) - quit_button.pressed.connect(_quit_game) - # En web no se puede cerrar la pestana desde el juego. - quit_button.visible = not OS.has_feature("web") -@@ -54,6 +58,7 @@ static func level_label(path: String) -> String: - func _show_home() -> void: - if not _loading_path.is_empty(): - return -+ inventory_panel.hide() - home_panel.show() - levels_panel.hide() - loading_panel.hide() -@@ -81,6 +86,7 @@ func _show_levels() -> void: - button.pressed.connect(_load_level.bind(path)) - level_list.add_child(button) - empty_label.visible = paths.is_empty() -+ inventory_panel.hide() - home_panel.hide() - levels_panel.show() - error_label.hide() -@@ -91,6 +97,16 @@ func _show_levels() -> void: - back_button.grab_focus() - - -+func _show_inventory() -> void: -+ if not _loading_path.is_empty(): -+ return -+ home_panel.hide() -+ levels_panel.hide() -+ error_label.hide() -+ title_label.text = "OBJETOS RAROS" -+ inventory_panel.call("show_collection") -+ -+ - ## La pantalla de carga real no introduce otros diez segundos artificiales. - func _load_level(path: String) -> void: - if not _loading_path.is_empty(): -@@ -142,14 +158,14 @@ func _show_load_error(message: String) -> void: - - - func _unhandled_input(event: InputEvent) -> void: -- if event.is_action_pressed("ui_cancel") and _loading_path.is_empty() and levels_panel.visible: -+ if event.is_action_pressed("ui_cancel") and _loading_path.is_empty() and (levels_panel.visible or inventory_panel.visible): - _show_home() - get_viewport().set_input_as_handled() - - - func _notification(what: int) -> void: - if what == NOTIFICATION_WM_GO_BACK_REQUEST and is_node_ready() and _loading_path.is_empty(): -- if levels_panel.visible: -+ if levels_panel.visible or inventory_panel.visible: - _show_home() - else: - _quit_game() -diff --git a/ui/menu/main_menu.tscn b/ui/menu/main_menu.tscn -index c5f35265c50ad08aab09d5f7a5e23e3a93bba27f..c0dac8091fdcd7690858f26ae571fcc0aa7c9bde 100644 ---- a/ui/menu/main_menu.tscn -+++ b/ui/menu/main_menu.tscn -@@ -1,8 +1,10 @@ --[gd_scene load_steps=3 format=3] -+[gd_scene load_steps=4 format=3] - - [ext_resource type="Script" path="res://ui/menu/main_menu.gd" id="script"] - [ext_resource type="Theme" path="res://ui/menu/menu_theme.tres" id="theme"] - -+[ext_resource type="PackedScene" path="res://ui/menu/rare_inventory.tscn" id="inventory"] -+ - [node name="MainMenu" type="Control"] - layout_mode = 3 - anchors_preset = 15 -@@ -58,6 +60,11 @@ custom_minimum_size = Vector2(0, 64) - layout_mode = 2 - text = "JUGAR" - -+[node name="RareItems" type="Button" parent="Margin/Layout/Home"] -+custom_minimum_size = Vector2(0, 64) -+layout_mode = 2 -+text = "OBJETOS RAROS" -+ - [node name="Quit" type="Button" parent="Margin/Layout/Home"] - custom_minimum_size = Vector2(0, 64) - layout_mode = 2 -@@ -92,6 +99,10 @@ custom_minimum_size = Vector2(0, 64) - layout_mode = 2 - text = "VOLVER" - -+[node name="RareInventory" parent="Margin/Layout" instance=ExtResource("inventory")] -+visible = false -+layout_mode = 2 -+ - [node name="Error" type="Label" parent="Margin/Layout"] - visible = false - layout_mode = 2 -diff --git a/ui/menu/rare_inventory.gd b/ui/menu/rare_inventory.gd -new file mode 100644 -index 0000000000000000000000000000000000000000..d6f8dbf3e0758820340e025680e7646fdb6dc448 ---- /dev/null -+++ b/ui/menu/rare_inventory.gd -@@ -0,0 +1,42 @@ -+extends VBoxContainer -+ -+## Vista de la coleccion permanente. No equipa, consume ni modifica los objetos. -+## Las tarjetas se crean desde el catalogo del perfil, no desde una segunda lista. -+signal back_requested -+const ITEM_CARD: PackedScene = preload("res://ui/menu/rare_item_card.tscn") -+ -+ -+func _ready() -> void: -+ $Back.pressed.connect(func() -> void: back_requested.emit()) -+ -+ -+func show_collection() -> void: -+ for child: Node in $Scroll/Items.get_children(): -+ $Scroll/Items.remove_child(child) -+ child.queue_free() -+ var progress: PlayerProgressStore = get_node_or_null("/root/PlayerProgress") as PlayerProgressStore -+ if progress == null: -+ $Status.text = "No se encontro el perfil de objetos raros." -+ $Status.show() -+ show() -+ return -+ var owned_count: int = 0 -+ var items: Array[RareItemData] = progress.get_items() -+ for item: RareItemData in items: -+ var owned: bool = progress.has_item(item.id) -+ if owned: -+ owned_count += 1 -+ var card: PanelContainer = ITEM_CARD.instantiate() as PanelContainer -+ $Scroll/Items.add_child(card) -+ var icon: TextureRect = card.get_node("Margin/Row/Icon") as TextureRect -+ icon.texture = item.icon -+ icon.modulate = Color.WHITE if owned else Color(0.45, 0.45, 0.45) -+ (card.get_node("Margin/Row/Text/Name") as Label).text = item.display_name -+ (card.get_node("Margin/Row/Text/State") as Label).text = "CONSEGUIDO - SIEMPRE ACTIVO" if owned else "SIN CONSEGUIR" -+ (card.get_node("Margin/Row/Text/Bonus") as Label).text = item.get_bonus_text() -+ (card.get_node("Margin/Row/Text/Description") as Label).text = item.description -+ $Count.text = "%d / %d objetos conseguidos" % [owned_count, items.size()] -+ $Status.text = progress.last_error -+ $Status.visible = not progress.last_error.is_empty() -+ show() -+ $Back.grab_focus() -diff --git a/ui/menu/rare_inventory.tscn b/ui/menu/rare_inventory.tscn -new file mode 100644 -index 0000000000000000000000000000000000000000..119300e006c10bd5fb1dba9426cb0b13d94950ee ---- /dev/null -+++ b/ui/menu/rare_inventory.tscn -@@ -0,0 +1,41 @@ -+[gd_scene load_steps=2 format=3] -+ -+[ext_resource type="Script" path="res://ui/menu/rare_inventory.gd" id="script"] -+ -+[node name="RareInventory" type="VBoxContainer"] -+size_flags_vertical = 3 -+theme_override_constants/separation = 16 -+script = ExtResource("script") -+ -+[node name="Count" type="Label" parent="."] -+layout_mode = 2 -+text = "0 / 1 objetos conseguidos" -+horizontal_alignment = 1 -+ -+[node name="Hint" type="Label" parent="."] -+layout_mode = 2 -+text = "Encuentra el objeto y completa el nivel para conservarlo.\nSus mejoras son permanentes, automaticas y compartidas por todos los personajes." -+horizontal_alignment = 1 -+autowrap_mode = 3 -+ -+[node name="Scroll" type="ScrollContainer" parent="."] -+layout_mode = 2 -+size_flags_vertical = 3 -+follow_focus = true -+horizontal_scroll_mode = 0 -+ -+[node name="Items" type="VBoxContainer" parent="Scroll"] -+layout_mode = 2 -+size_flags_horizontal = 3 -+theme_override_constants/separation = 16 -+ -+[node name="Status" type="Label" parent="."] -+visible = false -+layout_mode = 2 -+theme_override_colors/font_color = Color(1, 0.7, 0.4, 1) -+autowrap_mode = 3 -+ -+[node name="Back" type="Button" parent="."] -+custom_minimum_size = Vector2(0, 64) -+layout_mode = 2 -+text = "VOLVER" -diff --git a/ui/menu/rare_item_card.tscn b/ui/menu/rare_item_card.tscn -new file mode 100644 -index 0000000000000000000000000000000000000000..fa38b5113708ae8ec04cb9cc316b3b9b9ba7dd43 ---- /dev/null -+++ b/ui/menu/rare_item_card.tscn -@@ -0,0 +1,57 @@ -+[gd_scene load_steps=2 format=3] -+ -+[sub_resource type="StyleBoxFlat" id="panel"] -+bg_color = Color(0.085, 0.095, 0.12, 1) -+border_width_left = 3 -+border_width_top = 1 -+border_width_right = 1 -+border_width_bottom = 1 -+border_color = Color(0.65, 0.48, 0.18, 1) -+ -+[node name="RareItemCard" type="PanelContainer"] -+size_flags_horizontal = 3 -+theme_override_styles/panel = SubResource("panel") -+ -+[node name="Margin" type="MarginContainer" parent="."] -+layout_mode = 2 -+theme_override_constants/margin_left = 16 -+theme_override_constants/margin_top = 16 -+theme_override_constants/margin_right = 16 -+theme_override_constants/margin_bottom = 16 -+ -+[node name="Row" type="HBoxContainer" parent="Margin"] -+layout_mode = 2 -+theme_override_constants/separation = 16 -+ -+[node name="Icon" type="TextureRect" parent="Margin/Row"] -+custom_minimum_size = Vector2(64, 64) -+layout_mode = 2 -+size_flags_vertical = 4 -+texture_filter = 1 -+expand_mode = 1 -+stretch_mode = 5 -+ -+[node name="Text" type="VBoxContainer" parent="Margin/Row"] -+layout_mode = 2 -+size_flags_horizontal = 3 -+theme_override_constants/separation = 8 -+ -+[node name="Name" type="Label" parent="Margin/Row/Text"] -+layout_mode = 2 -+theme_override_font_sizes/font_size = 24 -+autowrap_mode = 3 -+text = "Objeto raro" -+ -+[node name="State" type="Label" parent="Margin/Row/Text"] -+layout_mode = 2 -+theme_override_colors/font_color = Color(1, 0.77, 0.26, 1) -+autowrap_mode = 3 -+ -+[node name="Bonus" type="Label" parent="Margin/Row/Text"] -+layout_mode = 2 -+theme_override_colors/font_color = Color(0.7, 1, 0.55, 1) -+autowrap_mode = 3 -+ -+[node name="Description" type="Label" parent="Margin/Row/Text"] -+layout_mode = 2 -+autowrap_mode = 3 -diff --git a/world/README.md b/world/README.md -index 16f72394f2f1d287d545e477628e694c53d9ab6e..f52c54e9b0aa8d6c8229ee87dd9d6504bd85ad67 100644 ---- a/world/README.md -+++ b/world/README.md -@@ -17,3 +17,15 @@ Catalogo jugable: `levels/examples/scenery_catalog.tscn`. - Las superficies se colocan por su centro. Decoracion y carteles con poste se - colocan por sus pies. El tamano de terreno se cambia con Dimensions; no mediante - escalado del nodo. -+ -+ -+Los barriles son rompibles por defecto, con resistencia 5 y sin premio asignado. -+En su raiz puedes editar Breakable / Break Health / Drop Scene. Otros adornos -+admiten lo mismo activando Breakable. Colision solida y profundidad son opciones -+independientes. Arrastra a Drop Scene una escena de pickups/variants o -+rare_items/variants; vacio significa sin objeto. Mas detalles en -+`docs/rare_items_and_breakables.md`. -+ -+`triggers/level_exit.tscn` es la meta: confirma raros y vuelve al menu. El boton -+MENU solo abandona. Para objetos ocultos utiliza `rare_items/variants/lost_pick.tscn`; -+para premios de victoria usa Completion Rewards de la raiz del nivel. -diff --git a/world/props/barrel.tscn b/world/props/barrel.tscn -index cc3044f293f78a3475b5cba2ce30e63292b4d66b..227884b25030aa6ce72ed0d9e20366ad29b4bbd2 100644 ---- a/world/props/barrel.tscn -+++ b/world/props/barrel.tscn -@@ -8,3 +8,5 @@ draw_layer = -2 - collision_enabled = true - collision_dimensions = Vector2(54, 76) - collision_offset = Vector2(0, -38) -+breakable = true -+break_health = 5 -diff --git a/world/props/scenery_prop.gd b/world/props/scenery_prop.gd -index 886d91fc44c7246caa4474f88e557be36aea0061..b373bd70bd2e3d170f46a7ec1dbe990a99eb337b 100644 ---- a/world/props/scenery_prop.gd -+++ b/world/props/scenery_prop.gd -@@ -5,6 +5,11 @@ extends Node2D - ## Decoracion reutilizable con colision opcional e independiente de su profundidad. - ## El origen esta abajo, en el centro: colocar el nodo sobre la superficie del suelo. - ## Los presets de barril, farola, caja y fachadas reutilizan este mismo comportamiento. -+## La colision solida, el orden visual y recibir golpes son tres ajustes independientes. -+ -+signal broken -+const COMBAT_FX = preload("res://effects/combat_fx.gd") -+const HURTBOX_LAYER: int = 1 << 5 - - @export_category("Appearance") - @export var texture: Texture2D: -@@ -51,10 +56,27 @@ extends Node2D - preview_collision = value - queue_redraw() - -+@export_category("Breakable") -+## Desactivado conserva una decoracion normal; activado acepta ataques del jugador. -+@export var breakable: bool = false: -+ set(value): -+ breakable = value -+ _queue_refresh() -+## Resistencia. El barril usa 5: un punetazo base lo rompe. -+@export_range(1, 1000, 1) var break_health: int = 5 -+## Arrastra una escena de pickups/variants o rare_items/variants. Vacio: no suelta nada. -+## Se instancia una unica vez; no utiliza probabilidades ni la tabla de los enemigos. -+@export var drop_scene: PackedScene -+## Posicion local del premio respecto a los pies, no respecto a la camara. -+@export var drop_offset: Vector2 = Vector2(0.0, -28.0) -+ -+var current_health: int = 0 -+var is_broken: bool = false - var _refresh_pending: bool = false - - - func _ready() -> void: -+ current_health = break_health - _refresh() - - -@@ -81,18 +103,76 @@ func _refresh() -> void: - visual.scale = display_size / texture.get_size() - - var body: StaticBody2D = $Body -- body.collision_layer = 1 if collision_enabled else 0 -+ body.collision_layer = 1 if collision_enabled and not is_broken else 0 - body.collision_mask = 0 - body.position = collision_offset - var collision: CollisionShape2D = $Body/CollisionShape2D - var rectangle := RectangleShape2D.new() - rectangle.size = collision_dimensions - collision.shape = rectangle -- collision.disabled = not collision_enabled -+ collision.disabled = not collision_enabled or is_broken -+ var hurtbox: Area2D = $Hurtbox -+ hurtbox.position = collision_offset -+ hurtbox.collision_layer = HURTBOX_LAYER if breakable and not is_broken else 0 -+ hurtbox.collision_mask = 0 -+ hurtbox.monitorable = breakable and not is_broken -+ var hurt_shape := RectangleShape2D.new() -+ hurt_shape.size = collision_dimensions -+ ($Hurtbox/CollisionShape2D as CollisionShape2D).shape = hurt_shape -+ ($Hurtbox/CollisionShape2D as CollisionShape2D).disabled = not breakable or is_broken -+ if not Engine.is_editor_hint(): -+ if breakable and not is_broken: -+ add_to_group("breakable") -+ elif is_in_group("breakable"): -+ remove_from_group("breakable") - queue_redraw() - update_configuration_warnings() - - -+## Comparte el contrato de impacto de los enemigos, pero no emite died ni concede carga. -+func take_damage(amount: int, source_position: Vector2) -> void: -+ if Engine.is_editor_hint() or not breakable or is_broken or amount <= 0: -+ return -+ current_health = maxi(current_health - amount, 0) -+ if current_health > 0: -+ COMBAT_FX.spawn(get_parent(), to_global(collision_offset), &"hit", signf(global_position.x - source_position.x)) -+ return -+ # Este cerrojo es inmediato: dos golpes/pulsos en el mismo frame solo producen un drop. -+ is_broken = true -+ hide() -+ if is_in_group("breakable"): -+ remove_from_group("breakable") -+ $Body/CollisionShape2D.set_deferred("disabled", true) -+ $Hurtbox/CollisionShape2D.set_deferred("disabled", true) -+ $Hurtbox.set_deferred("monitorable", false) -+ call_deferred("_finish_break") -+ -+ -+## La rotura y el alta del premio salen del callback de fisica. -+## El premio es hermano del adorno: no se destruye cuando desaparece este nodo. -+func _finish_break() -> void: -+ if not is_broken or not is_inside_tree() or is_queued_for_deletion(): -+ return -+ var container: Node = get_parent() -+ COMBAT_FX.spawn(container, to_global(collision_offset), &"break") -+ if drop_scene != null: -+ var instance: Node = drop_scene.instantiate() -+ if not (instance is Pickup or instance is RarePickup): -+ push_warning("Drop Scene debe ser una escena de Pickup o RarePickup, no un nivel ni una decoracion.") -+ instance.free() -+ else: -+ var drop := instance as Node2D -+ var spawn_position: Vector2 = to_global(drop_offset) -+ drop.position = (container as Node2D).to_local(spawn_position) if container is Node2D else spawn_position -+ if drop is Pickup: -+ (drop as Pickup).collection_delay_seconds = Pickup.DROP_COLLECTION_DELAY_SECONDS -+ elif drop is RarePickup: -+ (drop as RarePickup).collection_delay_seconds = Pickup.DROP_COLLECTION_DELAY_SECONDS -+ container.add_child(drop) -+ broken.emit() -+ queue_free() -+ -+ - func _draw() -> void: - if Engine.is_editor_hint() and preview_collision: - var bounds := Rect2(collision_offset - collision_dimensions * 0.5, collision_dimensions) -@@ -106,4 +186,6 @@ func _get_configuration_warnings() -> PackedStringArray: - warnings.append("Asigna Texture o utiliza uno de los presets de world/props.") - if not scale.is_equal_approx(Vector2.ONE): - warnings.append("Usa Display Size y Collision Dimensions; deja Scale en (1, 1).") -+ if drop_scene != null and not breakable: -+ warnings.append("Hay un Drop Scene asignado pero Breakable esta desactivado: no se soltara.") - return warnings -diff --git a/world/props/scenery_prop.tscn b/world/props/scenery_prop.tscn -index 9f1da403dd043d58024d8ef6579d24ea0a77e1e5..118e8ef663b3a439343c6460b14f8d139e70295d 100644 ---- a/world/props/scenery_prop.tscn -+++ b/world/props/scenery_prop.tscn -@@ -17,3 +17,14 @@ collision_mask = 0 - [node name="CollisionShape2D" type="CollisionShape2D" parent="Body"] - shape = SubResource("shape") - disabled = true -+ -+[node name="Hurtbox" type="Area2D" parent="."] -+position = Vector2(0, -28) -+collision_layer = 0 -+collision_mask = 0 -+monitoring = false -+monitorable = false -+ -+[node name="CollisionShape2D" type="CollisionShape2D" parent="Hurtbox"] -+shape = SubResource("shape") -+disabled = true -diff --git a/world/triggers/level_exit.gd b/world/triggers/level_exit.gd -index 672cfab5bc31e9eb2473679d5c9e524a59b39d5a..bc72a1757e08ee7406defe7252ee38da7362b93d 100644 ---- a/world/triggers/level_exit.gd -+++ b/world/triggers/level_exit.gd -@@ -1,7 +1,7 @@ - extends Area2D - --## Salida provisional: vuelve al menu, sin desbloqueos ni seleccion de personaje. --## Su cartel y su forma se pueden editar en la escena reutilizable. -+## Meta reutilizable: confirma los raros del intento antes de volver al menu. -+## No es el boton MENU (abandonar). Las reglas futuras deben llamar a complete_level. - var _triggered: bool = false - - -@@ -17,6 +17,15 @@ func _on_body_entered(body: Node2D) -> void: - - - func _return_to_menu() -> void: -+ var level: LevelRoot = LevelRoot.find_for(self) -+ if level == null: -+ push_warning("LevelExit necesita estar dentro de un escenario con LevelRoot.") -+ _triggered = false -+ return -+ # Comprobar otra vez tras diferir evita dar premios si se murio en ese paso de fisica. -+ if not level.complete_level(): -+ _triggered = false -+ return - var error: Error = get_tree().change_scene_to_file("res://ui/menu/main_menu.tscn") - if error != OK: - _triggered = false -diff --git a/world/triggers/level_exit.tscn b/world/triggers/level_exit.tscn -index d9b4293cb590cd4de2266a4685c33c5ef9558820..249e2212bc59f281a62db24c2b5e40e113d84a1f 100644 ---- a/world/triggers/level_exit.tscn -+++ b/world/triggers/level_exit.tscn -@@ -17,5 +17,5 @@ position = Vector2(0, -80) - shape = SubResource("shape") - - [node name="Sign" parent="." instance=ExtResource("sign")] --text = "SALIDA\nVOLVER AL MENU" -+text = "META\nCOMPLETAR NIVEL" - collision_enabled = false diff --git a/player/camera_2d.gd b/player/camera_2d.gd index bc2a8cf..830709b 100644 --- a/player/camera_2d.gd +++ b/player/camera_2d.gd @@ -8,6 +8,8 @@ var _shake_remaining: float = 0.0 var _shake_duration: float = 0.16 var _shake_amplitude: float = 0.0 var _clock: float = 0.0 +var _shake_frequency: float = 83.0 +var _solo_color: Color = Color(0.66, 0.85, 1.0) var _solo_remaining: float = 0.0 var _flash_color := Color(1.0, 0.82, 0.50) var _overlay: Control @@ -31,7 +33,9 @@ func _ready() -> void: ## Acumula la sacudida mas intensa sin reiniciar a menor fuerza un impacto existente. func impact(strength: float = 1.5, duration: float = 0.16, - color: Color = Color(1.0, 0.82, 0.50)) -> void: + color: Color = Color(1.0, 0.82, 0.50), frequency: float = 83.0) -> void: + if strength >= _shake_amplitude or _shake_remaining <= 0.0: + _shake_frequency = maxf(frequency, 1.0) _shake_amplitude = maxf(_shake_amplitude, strength) _shake_remaining = maxf(_shake_remaining, duration) _shake_duration = maxf(_shake_remaining, 0.01) @@ -39,8 +43,9 @@ func impact(strength: float = 1.5, duration: float = 0.16, ## Activa la superposicion del especial durante el tiempo solicitado. -func start_solo(duration: float) -> void: +func start_solo(duration: float, color: Color = Color(0.66, 0.85, 1.0)) -> void: _solo_remaining = duration + _solo_color = color ## Amortigua las sacudidas alrededor del desplazamiento inicial de la camara. @@ -50,7 +55,7 @@ func _process(delta: float) -> void: _solo_remaining = maxf(0.0, _solo_remaining - delta) var envelope: float = _shake_remaining / _shake_duration var amplitude: float = minf(_shake_amplitude, 3.0) * envelope * envelope * feedback_strength - offset = _base_offset + Vector2(sin(_clock * 83.0), cos(_clock * 67.0)) * amplitude + offset = _base_offset + Vector2(sin(_clock * _shake_frequency), cos(_clock * _shake_frequency * 0.807)) * amplitude if _shake_remaining == 0.0: _shake_amplitude = 0.0 _overlay.queue_redraw() @@ -73,7 +78,7 @@ func _draw_feedback() -> void: if _solo_remaining <= 0.0: return var solo_alpha: float = minf(_solo_remaining / 0.25, 1.0) * feedback_strength - _overlay.draw_rect(Rect2(Vector2.ZERO, size), Color(0.18, 0.08, 0.32, 0.07 * solo_alpha)) + _overlay.draw_rect(Rect2(Vector2.ZERO, size), Color(_solo_color.r * 0.3, _solo_color.g * 0.2, _solo_color.b * 0.35, 0.07 * solo_alpha)) for side: float in [-1.0, 1.0]: var edge_x: float = 0.0 if side > 0.0 else size.x for index: int in range(7): @@ -81,4 +86,4 @@ func _draw_feedback() -> void: var length: float = (32.0 + float(index % 3) * 19.0) * (0.7 + pulse) var start := Vector2(edge_x, y) var end := Vector2(edge_x + side * length, lerpf(y, size.y * 0.5, 0.1)) - _overlay.draw_line(start, end, Color(0.66, 0.85, 1.0, 0.24 * solo_alpha), 3.0) + _overlay.draw_line(start, end, Color(_solo_color.r, _solo_color.g, _solo_color.b, 0.24 * solo_alpha), 3.0) diff --git a/player/character_data.gd b/player/character_data.gd index 5e161dd..0dda52d 100644 --- a/player/character_data.gd +++ b/player/character_data.gd @@ -10,10 +10,11 @@ class_name CharacterData @export_category("Identity") @export var id: StringName = &"character" @export var display_name: String = "Character" +## Etiqueta para el selector; no se usa para decidir el comportamiento. +@export var role_name: String = "" @export_category("Visuals") -## Los cuatro recursos apuntan por ahora a las mismas animaciones de Diego. -## Mรกs adelante cada integrante podrรก tener su propio SpriteFrames sin tocar Player. +## Cada integrante aporta sus fotogramas, sin duplicar movimiento ni combate. @export var sprite_frames: SpriteFrames @export_category("Stats") @@ -28,3 +29,19 @@ class_name CharacterData ## Campo heredado sin uso actual en Player; se conserva por compatibilidad. ## El golpe aereo usa Ground Pound (dano por altura y limites), no este valor. @export_range(0, 100, 1) var air_attack_damage: int = 10 + + +@export_category("Ground Pound Presentation") +## Solo el dibujo cambia por integrante. Radio, forma, dano y tiempos viven en Player. +@export_enum("ground_pound", "electric_pound", "vocal_dome", "bass_cracks") var ground_pound_effect: String = "ground_pound" + +@export_category("Special Presentation") +## Solo cambia la presentacion: los cuatro usan el mismo presupuesto de dano por pulsos. +@export_enum("solo", "vocal_wave", "drum_cymbals", "bass_pulse") var special_effect: String = "solo" +@export var special_label: String = "GUITAR SOLO!" +@export var special_color: Color = Color(0.61, 0.82, 1.0) +## Limite visual de Camera2D: 3 px. Feedback Strength permite reducirlo o anularlo. +@export_range(0.0, 3.0, 0.1) var special_shake_strength: float = 2.0 +@export_range(0.05, 0.6, 0.01) var special_shake_duration: float = 0.18 +## Frecuencia angular, no cantidad de impactos: Fer usa una vibracion mas grave. +@export_range(8.0, 100.0, 1.0) var special_shake_frequency: float = 83.0 diff --git a/player/characters/animations/bassist_frames.tres b/player/characters/animations/bassist_frames.tres new file mode 100644 index 0000000..a2f5176 --- /dev/null +++ b/player/characters/animations/bassist_frames.tres @@ -0,0 +1,266 @@ +[gd_resource type="SpriteFrames" load_steps=42 format=3] + +[ext_resource type="Texture2D" path="res://assets/characters/band/bassist.svg" id="atlas"] + +[sub_resource type="AtlasTexture" id="idle_0"] +atlas = ExtResource("atlas") +region = Rect2(0, 0, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="idle_1"] +atlas = ExtResource("atlas") +region = Rect2(64, 0, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="idle_2"] +atlas = ExtResource("atlas") +region = Rect2(128, 0, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="idle_3"] +atlas = ExtResource("atlas") +region = Rect2(192, 0, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="walk_0"] +atlas = ExtResource("atlas") +region = Rect2(256, 0, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="walk_1"] +atlas = ExtResource("atlas") +region = Rect2(320, 0, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="walk_2"] +atlas = ExtResource("atlas") +region = Rect2(384, 0, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="walk_3"] +atlas = ExtResource("atlas") +region = Rect2(448, 0, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="walk_4"] +atlas = ExtResource("atlas") +region = Rect2(0, 64, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="walk_5"] +atlas = ExtResource("atlas") +region = Rect2(64, 64, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="jump_0"] +atlas = ExtResource("atlas") +region = Rect2(128, 64, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="jump_1"] +atlas = ExtResource("atlas") +region = Rect2(192, 64, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="fall_0"] +atlas = ExtResource("atlas") +region = Rect2(256, 64, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="fall_1"] +atlas = ExtResource("atlas") +region = Rect2(320, 64, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="punch_0"] +atlas = ExtResource("atlas") +region = Rect2(384, 64, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="punch_1"] +atlas = ExtResource("atlas") +region = Rect2(448, 64, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="punch_2"] +atlas = ExtResource("atlas") +region = Rect2(0, 128, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="punch_3"] +atlas = ExtResource("atlas") +region = Rect2(64, 128, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="punch_4"] +atlas = ExtResource("atlas") +region = Rect2(128, 128, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="ground_pound_0"] +atlas = ExtResource("atlas") +region = Rect2(192, 128, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="ground_pound_1"] +atlas = ExtResource("atlas") +region = Rect2(256, 128, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="land_0"] +atlas = ExtResource("atlas") +region = Rect2(320, 128, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="land_1"] +atlas = ExtResource("atlas") +region = Rect2(384, 128, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="land_2"] +atlas = ExtResource("atlas") +region = Rect2(448, 128, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="special_start_0"] +atlas = ExtResource("atlas") +region = Rect2(0, 192, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="special_start_1"] +atlas = ExtResource("atlas") +region = Rect2(64, 192, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="special_start_2"] +atlas = ExtResource("atlas") +region = Rect2(128, 192, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="special_0"] +atlas = ExtResource("atlas") +region = Rect2(192, 192, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="special_1"] +atlas = ExtResource("atlas") +region = Rect2(256, 192, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="special_2"] +atlas = ExtResource("atlas") +region = Rect2(320, 192, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="special_3"] +atlas = ExtResource("atlas") +region = Rect2(384, 192, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="special_4"] +atlas = ExtResource("atlas") +region = Rect2(448, 192, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="special_5"] +atlas = ExtResource("atlas") +region = Rect2(0, 256, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="special_end_0"] +atlas = ExtResource("atlas") +region = Rect2(64, 256, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="special_end_1"] +atlas = ExtResource("atlas") +region = Rect2(128, 256, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="hurt_0"] +atlas = ExtResource("atlas") +region = Rect2(192, 256, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="hurt_1"] +atlas = ExtResource("atlas") +region = Rect2(256, 256, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="pound_land_0"] +atlas = ExtResource("atlas") +region = Rect2(320, 256, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="pound_land_1"] +atlas = ExtResource("atlas") +region = Rect2(384, 256, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="pound_land_2"] +atlas = ExtResource("atlas") +region = Rect2(448, 256, 64, 64) +filter_clip = true + +[resource] +animations = [{ +"frames": [{"duration": 1.0, "texture": SubResource("fall_0")}, {"duration": 1.0, "texture": SubResource("fall_1")}], +"loop": true, +"name": &"fall", +"speed": 7.0 +}, { +"frames": [{"duration": 1.0, "texture": SubResource("ground_pound_0")}, {"duration": 1.0, "texture": SubResource("ground_pound_1")}], +"loop": true, +"name": &"ground_pound", +"speed": 12.0 +}, { +"frames": [{"duration": 1.0, "texture": SubResource("hurt_0")}, {"duration": 1.0, "texture": SubResource("hurt_1")}], +"loop": false, +"name": &"hurt", +"speed": 12.0 +}, { +"frames": [{"duration": 1.0, "texture": SubResource("idle_0")}, {"duration": 1.0, "texture": SubResource("idle_1")}, {"duration": 1.0, "texture": SubResource("idle_2")}, {"duration": 1.0, "texture": SubResource("idle_3")}], +"loop": true, +"name": &"idle", +"speed": 5.0 +}, { +"frames": [{"duration": 1.0, "texture": SubResource("jump_0")}, {"duration": 1.0, "texture": SubResource("jump_1")}], +"loop": false, +"name": &"jump", +"speed": 9.0 +}, { +"frames": [{"duration": 1.0, "texture": SubResource("land_0")}, {"duration": 1.0, "texture": SubResource("land_1")}, {"duration": 1.0, "texture": SubResource("land_2")}], +"loop": false, +"name": &"land", +"speed": 16.0 +}, { +"frames": [{"duration": 1.0, "texture": SubResource("punch_0")}, {"duration": 0.75, "texture": SubResource("punch_1")}, {"duration": 1.15, "texture": SubResource("punch_2")}, {"duration": 0.8, "texture": SubResource("punch_3")}, {"duration": 1.3, "texture": SubResource("punch_4")}], +"loop": false, +"name": &"punch", +"speed": 18.0 +}, { +"frames": [{"duration": 1.0, "texture": SubResource("special_0")}, {"duration": 1.0, "texture": SubResource("special_1")}, {"duration": 1.0, "texture": SubResource("special_2")}, {"duration": 1.0, "texture": SubResource("special_3")}, {"duration": 1.0, "texture": SubResource("special_4")}, {"duration": 1.0, "texture": SubResource("special_5")}], +"loop": false, +"name": &"special", +"speed": 12.0 +}, { +"frames": [{"duration": 1.0, "texture": SubResource("special_end_0")}, {"duration": 1.0, "texture": SubResource("special_end_1")}], +"loop": false, +"name": &"special_end", +"speed": 7.0 +}, { +"frames": [{"duration": 1.0, "texture": SubResource("special_start_0")}, {"duration": 1.0, "texture": SubResource("special_start_1")}, {"duration": 1.0, "texture": SubResource("special_start_2")}], +"loop": false, +"name": &"special_start", +"speed": 9.0 +}, { +"frames": [{"duration": 1.0, "texture": SubResource("walk_0")}, {"duration": 1.0, "texture": SubResource("walk_1")}, {"duration": 1.0, "texture": SubResource("walk_2")}, {"duration": 1.0, "texture": SubResource("walk_3")}, {"duration": 1.0, "texture": SubResource("walk_4")}, {"duration": 1.0, "texture": SubResource("walk_5")}], +"loop": true, +"name": &"walk", +"speed": 10.0 +}, { +"frames": [{"duration": 1.0, "texture": SubResource("pound_land_0")}, {"duration": 1.0, "texture": SubResource("pound_land_1")}, {"duration": 1.0, "texture": SubResource("pound_land_2")}], +"loop": false, +"name": &"pound_land", +"speed": 12.0 +}] diff --git a/player/characters/animations/drummer_frames.tres b/player/characters/animations/drummer_frames.tres new file mode 100644 index 0000000..89d52b4 --- /dev/null +++ b/player/characters/animations/drummer_frames.tres @@ -0,0 +1,266 @@ +[gd_resource type="SpriteFrames" load_steps=42 format=3] + +[ext_resource type="Texture2D" path="res://assets/characters/band/drummer.svg" id="atlas"] + +[sub_resource type="AtlasTexture" id="idle_0"] +atlas = ExtResource("atlas") +region = Rect2(0, 0, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="idle_1"] +atlas = ExtResource("atlas") +region = Rect2(64, 0, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="idle_2"] +atlas = ExtResource("atlas") +region = Rect2(128, 0, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="idle_3"] +atlas = ExtResource("atlas") +region = Rect2(192, 0, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="walk_0"] +atlas = ExtResource("atlas") +region = Rect2(256, 0, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="walk_1"] +atlas = ExtResource("atlas") +region = Rect2(320, 0, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="walk_2"] +atlas = ExtResource("atlas") +region = Rect2(384, 0, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="walk_3"] +atlas = ExtResource("atlas") +region = Rect2(448, 0, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="walk_4"] +atlas = ExtResource("atlas") +region = Rect2(0, 64, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="walk_5"] +atlas = ExtResource("atlas") +region = Rect2(64, 64, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="jump_0"] +atlas = ExtResource("atlas") +region = Rect2(128, 64, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="jump_1"] +atlas = ExtResource("atlas") +region = Rect2(192, 64, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="fall_0"] +atlas = ExtResource("atlas") +region = Rect2(256, 64, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="fall_1"] +atlas = ExtResource("atlas") +region = Rect2(320, 64, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="punch_0"] +atlas = ExtResource("atlas") +region = Rect2(384, 64, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="punch_1"] +atlas = ExtResource("atlas") +region = Rect2(448, 64, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="punch_2"] +atlas = ExtResource("atlas") +region = Rect2(0, 128, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="punch_3"] +atlas = ExtResource("atlas") +region = Rect2(64, 128, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="punch_4"] +atlas = ExtResource("atlas") +region = Rect2(128, 128, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="ground_pound_0"] +atlas = ExtResource("atlas") +region = Rect2(192, 128, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="ground_pound_1"] +atlas = ExtResource("atlas") +region = Rect2(256, 128, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="land_0"] +atlas = ExtResource("atlas") +region = Rect2(320, 128, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="land_1"] +atlas = ExtResource("atlas") +region = Rect2(384, 128, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="land_2"] +atlas = ExtResource("atlas") +region = Rect2(448, 128, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="special_start_0"] +atlas = ExtResource("atlas") +region = Rect2(0, 192, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="special_start_1"] +atlas = ExtResource("atlas") +region = Rect2(64, 192, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="special_start_2"] +atlas = ExtResource("atlas") +region = Rect2(128, 192, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="special_0"] +atlas = ExtResource("atlas") +region = Rect2(192, 192, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="special_1"] +atlas = ExtResource("atlas") +region = Rect2(256, 192, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="special_2"] +atlas = ExtResource("atlas") +region = Rect2(320, 192, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="special_3"] +atlas = ExtResource("atlas") +region = Rect2(384, 192, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="special_4"] +atlas = ExtResource("atlas") +region = Rect2(448, 192, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="special_5"] +atlas = ExtResource("atlas") +region = Rect2(0, 256, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="special_end_0"] +atlas = ExtResource("atlas") +region = Rect2(64, 256, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="special_end_1"] +atlas = ExtResource("atlas") +region = Rect2(128, 256, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="hurt_0"] +atlas = ExtResource("atlas") +region = Rect2(192, 256, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="hurt_1"] +atlas = ExtResource("atlas") +region = Rect2(256, 256, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="pound_land_0"] +atlas = ExtResource("atlas") +region = Rect2(320, 256, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="pound_land_1"] +atlas = ExtResource("atlas") +region = Rect2(384, 256, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="pound_land_2"] +atlas = ExtResource("atlas") +region = Rect2(448, 256, 64, 64) +filter_clip = true + +[resource] +animations = [{ +"frames": [{"duration": 1.0, "texture": SubResource("fall_0")}, {"duration": 1.0, "texture": SubResource("fall_1")}], +"loop": true, +"name": &"fall", +"speed": 7.0 +}, { +"frames": [{"duration": 1.0, "texture": SubResource("ground_pound_0")}, {"duration": 1.0, "texture": SubResource("ground_pound_1")}], +"loop": true, +"name": &"ground_pound", +"speed": 12.0 +}, { +"frames": [{"duration": 1.0, "texture": SubResource("hurt_0")}, {"duration": 1.0, "texture": SubResource("hurt_1")}], +"loop": false, +"name": &"hurt", +"speed": 12.0 +}, { +"frames": [{"duration": 1.0, "texture": SubResource("idle_0")}, {"duration": 1.0, "texture": SubResource("idle_1")}, {"duration": 1.0, "texture": SubResource("idle_2")}, {"duration": 1.0, "texture": SubResource("idle_3")}], +"loop": true, +"name": &"idle", +"speed": 5.0 +}, { +"frames": [{"duration": 1.0, "texture": SubResource("jump_0")}, {"duration": 1.0, "texture": SubResource("jump_1")}], +"loop": false, +"name": &"jump", +"speed": 9.0 +}, { +"frames": [{"duration": 1.0, "texture": SubResource("land_0")}, {"duration": 1.0, "texture": SubResource("land_1")}, {"duration": 1.0, "texture": SubResource("land_2")}], +"loop": false, +"name": &"land", +"speed": 16.0 +}, { +"frames": [{"duration": 1.0, "texture": SubResource("punch_0")}, {"duration": 0.75, "texture": SubResource("punch_1")}, {"duration": 1.15, "texture": SubResource("punch_2")}, {"duration": 0.8, "texture": SubResource("punch_3")}, {"duration": 1.3, "texture": SubResource("punch_4")}], +"loop": false, +"name": &"punch", +"speed": 18.0 +}, { +"frames": [{"duration": 1.0, "texture": SubResource("special_0")}, {"duration": 1.0, "texture": SubResource("special_1")}, {"duration": 1.0, "texture": SubResource("special_2")}, {"duration": 1.0, "texture": SubResource("special_3")}, {"duration": 1.0, "texture": SubResource("special_4")}, {"duration": 1.0, "texture": SubResource("special_5")}], +"loop": true, +"name": &"special", +"speed": 12.0 +}, { +"frames": [{"duration": 1.0, "texture": SubResource("special_end_0")}, {"duration": 1.0, "texture": SubResource("special_end_1")}], +"loop": false, +"name": &"special_end", +"speed": 7.0 +}, { +"frames": [{"duration": 1.0, "texture": SubResource("special_start_0")}, {"duration": 1.0, "texture": SubResource("special_start_1")}, {"duration": 1.0, "texture": SubResource("special_start_2")}], +"loop": false, +"name": &"special_start", +"speed": 9.0 +}, { +"frames": [{"duration": 1.0, "texture": SubResource("walk_0")}, {"duration": 1.0, "texture": SubResource("walk_1")}, {"duration": 1.0, "texture": SubResource("walk_2")}, {"duration": 1.0, "texture": SubResource("walk_3")}, {"duration": 1.0, "texture": SubResource("walk_4")}, {"duration": 1.0, "texture": SubResource("walk_5")}], +"loop": true, +"name": &"walk", +"speed": 10.0 +}, { +"frames": [{"duration": 1.0, "texture": SubResource("pound_land_0")}, {"duration": 1.0, "texture": SubResource("pound_land_1")}, {"duration": 1.0, "texture": SubResource("pound_land_2")}], +"loop": false, +"name": &"pound_land", +"speed": 12.0 +}] diff --git a/player/characters/animations/guitarist_frames.tres b/player/characters/animations/guitarist_frames.tres new file mode 100644 index 0000000..26b2bf8 --- /dev/null +++ b/player/characters/animations/guitarist_frames.tres @@ -0,0 +1,266 @@ +[gd_resource type="SpriteFrames" load_steps=42 format=3] + +[ext_resource type="Texture2D" path="res://assets/characters/band/guitarist.svg" id="atlas"] + +[sub_resource type="AtlasTexture" id="idle_0"] +atlas = ExtResource("atlas") +region = Rect2(0, 0, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="idle_1"] +atlas = ExtResource("atlas") +region = Rect2(64, 0, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="idle_2"] +atlas = ExtResource("atlas") +region = Rect2(128, 0, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="idle_3"] +atlas = ExtResource("atlas") +region = Rect2(192, 0, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="walk_0"] +atlas = ExtResource("atlas") +region = Rect2(256, 0, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="walk_1"] +atlas = ExtResource("atlas") +region = Rect2(320, 0, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="walk_2"] +atlas = ExtResource("atlas") +region = Rect2(384, 0, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="walk_3"] +atlas = ExtResource("atlas") +region = Rect2(448, 0, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="walk_4"] +atlas = ExtResource("atlas") +region = Rect2(0, 64, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="walk_5"] +atlas = ExtResource("atlas") +region = Rect2(64, 64, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="jump_0"] +atlas = ExtResource("atlas") +region = Rect2(128, 64, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="jump_1"] +atlas = ExtResource("atlas") +region = Rect2(192, 64, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="fall_0"] +atlas = ExtResource("atlas") +region = Rect2(256, 64, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="fall_1"] +atlas = ExtResource("atlas") +region = Rect2(320, 64, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="punch_0"] +atlas = ExtResource("atlas") +region = Rect2(384, 64, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="punch_1"] +atlas = ExtResource("atlas") +region = Rect2(448, 64, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="punch_2"] +atlas = ExtResource("atlas") +region = Rect2(0, 128, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="punch_3"] +atlas = ExtResource("atlas") +region = Rect2(64, 128, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="punch_4"] +atlas = ExtResource("atlas") +region = Rect2(128, 128, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="ground_pound_0"] +atlas = ExtResource("atlas") +region = Rect2(192, 128, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="ground_pound_1"] +atlas = ExtResource("atlas") +region = Rect2(256, 128, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="land_0"] +atlas = ExtResource("atlas") +region = Rect2(320, 128, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="land_1"] +atlas = ExtResource("atlas") +region = Rect2(384, 128, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="land_2"] +atlas = ExtResource("atlas") +region = Rect2(448, 128, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="special_start_0"] +atlas = ExtResource("atlas") +region = Rect2(0, 192, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="special_start_1"] +atlas = ExtResource("atlas") +region = Rect2(64, 192, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="special_start_2"] +atlas = ExtResource("atlas") +region = Rect2(128, 192, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="special_0"] +atlas = ExtResource("atlas") +region = Rect2(192, 192, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="special_1"] +atlas = ExtResource("atlas") +region = Rect2(256, 192, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="special_2"] +atlas = ExtResource("atlas") +region = Rect2(320, 192, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="special_3"] +atlas = ExtResource("atlas") +region = Rect2(384, 192, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="special_4"] +atlas = ExtResource("atlas") +region = Rect2(448, 192, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="special_5"] +atlas = ExtResource("atlas") +region = Rect2(0, 256, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="special_end_0"] +atlas = ExtResource("atlas") +region = Rect2(64, 256, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="special_end_1"] +atlas = ExtResource("atlas") +region = Rect2(128, 256, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="hurt_0"] +atlas = ExtResource("atlas") +region = Rect2(192, 256, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="hurt_1"] +atlas = ExtResource("atlas") +region = Rect2(256, 256, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="pound_land_0"] +atlas = ExtResource("atlas") +region = Rect2(320, 256, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="pound_land_1"] +atlas = ExtResource("atlas") +region = Rect2(384, 256, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="pound_land_2"] +atlas = ExtResource("atlas") +region = Rect2(448, 256, 64, 64) +filter_clip = true + +[resource] +animations = [{ +"frames": [{"duration": 1.0, "texture": SubResource("fall_0")}, {"duration": 1.0, "texture": SubResource("fall_1")}], +"loop": true, +"name": &"fall", +"speed": 7.0 +}, { +"frames": [{"duration": 1.0, "texture": SubResource("ground_pound_0")}, {"duration": 1.0, "texture": SubResource("ground_pound_1")}], +"loop": true, +"name": &"ground_pound", +"speed": 12.0 +}, { +"frames": [{"duration": 1.0, "texture": SubResource("hurt_0")}, {"duration": 1.0, "texture": SubResource("hurt_1")}], +"loop": false, +"name": &"hurt", +"speed": 12.0 +}, { +"frames": [{"duration": 1.0, "texture": SubResource("idle_0")}, {"duration": 1.0, "texture": SubResource("idle_1")}, {"duration": 1.0, "texture": SubResource("idle_2")}, {"duration": 1.0, "texture": SubResource("idle_3")}], +"loop": true, +"name": &"idle", +"speed": 5.0 +}, { +"frames": [{"duration": 1.0, "texture": SubResource("jump_0")}, {"duration": 1.0, "texture": SubResource("jump_1")}], +"loop": false, +"name": &"jump", +"speed": 9.0 +}, { +"frames": [{"duration": 1.0, "texture": SubResource("land_0")}, {"duration": 1.0, "texture": SubResource("land_1")}, {"duration": 1.0, "texture": SubResource("land_2")}], +"loop": false, +"name": &"land", +"speed": 16.0 +}, { +"frames": [{"duration": 1.0, "texture": SubResource("punch_0")}, {"duration": 0.75, "texture": SubResource("punch_1")}, {"duration": 1.15, "texture": SubResource("punch_2")}, {"duration": 0.8, "texture": SubResource("punch_3")}, {"duration": 1.3, "texture": SubResource("punch_4")}], +"loop": false, +"name": &"punch", +"speed": 18.0 +}, { +"frames": [{"duration": 1.0, "texture": SubResource("special_0")}, {"duration": 1.0, "texture": SubResource("special_1")}, {"duration": 1.0, "texture": SubResource("special_2")}, {"duration": 1.0, "texture": SubResource("special_3")}, {"duration": 1.0, "texture": SubResource("special_4")}, {"duration": 1.0, "texture": SubResource("special_5")}], +"loop": true, +"name": &"special", +"speed": 12.0 +}, { +"frames": [{"duration": 1.0, "texture": SubResource("special_end_0")}, {"duration": 1.0, "texture": SubResource("special_end_1")}], +"loop": false, +"name": &"special_end", +"speed": 7.0 +}, { +"frames": [{"duration": 1.0, "texture": SubResource("special_start_0")}, {"duration": 1.0, "texture": SubResource("special_start_1")}, {"duration": 1.0, "texture": SubResource("special_start_2")}], +"loop": false, +"name": &"special_start", +"speed": 9.0 +}, { +"frames": [{"duration": 1.0, "texture": SubResource("walk_0")}, {"duration": 1.0, "texture": SubResource("walk_1")}, {"duration": 1.0, "texture": SubResource("walk_2")}, {"duration": 1.0, "texture": SubResource("walk_3")}, {"duration": 1.0, "texture": SubResource("walk_4")}, {"duration": 1.0, "texture": SubResource("walk_5")}], +"loop": true, +"name": &"walk", +"speed": 10.0 +}, { +"frames": [{"duration": 1.0, "texture": SubResource("pound_land_0")}, {"duration": 1.0, "texture": SubResource("pound_land_1")}, {"duration": 1.0, "texture": SubResource("pound_land_2")}], +"loop": false, +"name": &"pound_land", +"speed": 12.0 +}] diff --git a/player/characters/animations/singer_frames.tres b/player/characters/animations/singer_frames.tres new file mode 100644 index 0000000..06418df --- /dev/null +++ b/player/characters/animations/singer_frames.tres @@ -0,0 +1,266 @@ +[gd_resource type="SpriteFrames" load_steps=42 format=3] + +[ext_resource type="Texture2D" path="res://assets/characters/band/singer.svg" id="atlas"] + +[sub_resource type="AtlasTexture" id="idle_0"] +atlas = ExtResource("atlas") +region = Rect2(0, 0, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="idle_1"] +atlas = ExtResource("atlas") +region = Rect2(64, 0, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="idle_2"] +atlas = ExtResource("atlas") +region = Rect2(128, 0, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="idle_3"] +atlas = ExtResource("atlas") +region = Rect2(192, 0, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="walk_0"] +atlas = ExtResource("atlas") +region = Rect2(256, 0, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="walk_1"] +atlas = ExtResource("atlas") +region = Rect2(320, 0, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="walk_2"] +atlas = ExtResource("atlas") +region = Rect2(384, 0, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="walk_3"] +atlas = ExtResource("atlas") +region = Rect2(448, 0, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="walk_4"] +atlas = ExtResource("atlas") +region = Rect2(0, 64, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="walk_5"] +atlas = ExtResource("atlas") +region = Rect2(64, 64, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="jump_0"] +atlas = ExtResource("atlas") +region = Rect2(128, 64, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="jump_1"] +atlas = ExtResource("atlas") +region = Rect2(192, 64, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="fall_0"] +atlas = ExtResource("atlas") +region = Rect2(256, 64, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="fall_1"] +atlas = ExtResource("atlas") +region = Rect2(320, 64, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="punch_0"] +atlas = ExtResource("atlas") +region = Rect2(384, 64, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="punch_1"] +atlas = ExtResource("atlas") +region = Rect2(448, 64, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="punch_2"] +atlas = ExtResource("atlas") +region = Rect2(0, 128, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="punch_3"] +atlas = ExtResource("atlas") +region = Rect2(64, 128, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="punch_4"] +atlas = ExtResource("atlas") +region = Rect2(128, 128, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="ground_pound_0"] +atlas = ExtResource("atlas") +region = Rect2(192, 128, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="ground_pound_1"] +atlas = ExtResource("atlas") +region = Rect2(256, 128, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="land_0"] +atlas = ExtResource("atlas") +region = Rect2(320, 128, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="land_1"] +atlas = ExtResource("atlas") +region = Rect2(384, 128, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="land_2"] +atlas = ExtResource("atlas") +region = Rect2(448, 128, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="special_start_0"] +atlas = ExtResource("atlas") +region = Rect2(0, 192, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="special_start_1"] +atlas = ExtResource("atlas") +region = Rect2(64, 192, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="special_start_2"] +atlas = ExtResource("atlas") +region = Rect2(128, 192, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="special_0"] +atlas = ExtResource("atlas") +region = Rect2(192, 192, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="special_1"] +atlas = ExtResource("atlas") +region = Rect2(256, 192, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="special_2"] +atlas = ExtResource("atlas") +region = Rect2(320, 192, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="special_3"] +atlas = ExtResource("atlas") +region = Rect2(384, 192, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="special_4"] +atlas = ExtResource("atlas") +region = Rect2(448, 192, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="special_5"] +atlas = ExtResource("atlas") +region = Rect2(0, 256, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="special_end_0"] +atlas = ExtResource("atlas") +region = Rect2(64, 256, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="special_end_1"] +atlas = ExtResource("atlas") +region = Rect2(128, 256, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="hurt_0"] +atlas = ExtResource("atlas") +region = Rect2(192, 256, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="hurt_1"] +atlas = ExtResource("atlas") +region = Rect2(256, 256, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="pound_land_0"] +atlas = ExtResource("atlas") +region = Rect2(320, 256, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="pound_land_1"] +atlas = ExtResource("atlas") +region = Rect2(384, 256, 64, 64) +filter_clip = true + +[sub_resource type="AtlasTexture" id="pound_land_2"] +atlas = ExtResource("atlas") +region = Rect2(448, 256, 64, 64) +filter_clip = true + +[resource] +animations = [{ +"frames": [{"duration": 1.0, "texture": SubResource("fall_0")}, {"duration": 1.0, "texture": SubResource("fall_1")}], +"loop": true, +"name": &"fall", +"speed": 7.0 +}, { +"frames": [{"duration": 1.0, "texture": SubResource("ground_pound_0")}, {"duration": 1.0, "texture": SubResource("ground_pound_1")}], +"loop": true, +"name": &"ground_pound", +"speed": 12.0 +}, { +"frames": [{"duration": 1.0, "texture": SubResource("hurt_0")}, {"duration": 1.0, "texture": SubResource("hurt_1")}], +"loop": false, +"name": &"hurt", +"speed": 12.0 +}, { +"frames": [{"duration": 1.0, "texture": SubResource("idle_0")}, {"duration": 1.0, "texture": SubResource("idle_1")}, {"duration": 1.0, "texture": SubResource("idle_2")}, {"duration": 1.0, "texture": SubResource("idle_3")}], +"loop": true, +"name": &"idle", +"speed": 5.0 +}, { +"frames": [{"duration": 1.0, "texture": SubResource("jump_0")}, {"duration": 1.0, "texture": SubResource("jump_1")}], +"loop": false, +"name": &"jump", +"speed": 9.0 +}, { +"frames": [{"duration": 1.0, "texture": SubResource("land_0")}, {"duration": 1.0, "texture": SubResource("land_1")}, {"duration": 1.0, "texture": SubResource("land_2")}], +"loop": false, +"name": &"land", +"speed": 16.0 +}, { +"frames": [{"duration": 1.0, "texture": SubResource("punch_0")}, {"duration": 0.75, "texture": SubResource("punch_1")}, {"duration": 1.15, "texture": SubResource("punch_2")}, {"duration": 0.8, "texture": SubResource("punch_3")}, {"duration": 1.3, "texture": SubResource("punch_4")}], +"loop": false, +"name": &"punch", +"speed": 18.0 +}, { +"frames": [{"duration": 1.0, "texture": SubResource("special_0")}, {"duration": 1.0, "texture": SubResource("special_1")}, {"duration": 1.0, "texture": SubResource("special_2")}, {"duration": 1.0, "texture": SubResource("special_3")}, {"duration": 1.0, "texture": SubResource("special_4")}, {"duration": 1.0, "texture": SubResource("special_5")}], +"loop": true, +"name": &"special", +"speed": 12.0 +}, { +"frames": [{"duration": 1.0, "texture": SubResource("special_end_0")}, {"duration": 1.0, "texture": SubResource("special_end_1")}], +"loop": false, +"name": &"special_end", +"speed": 7.0 +}, { +"frames": [{"duration": 1.0, "texture": SubResource("special_start_0")}, {"duration": 1.0, "texture": SubResource("special_start_1")}, {"duration": 1.0, "texture": SubResource("special_start_2")}], +"loop": false, +"name": &"special_start", +"speed": 9.0 +}, { +"frames": [{"duration": 1.0, "texture": SubResource("walk_0")}, {"duration": 1.0, "texture": SubResource("walk_1")}, {"duration": 1.0, "texture": SubResource("walk_2")}, {"duration": 1.0, "texture": SubResource("walk_3")}, {"duration": 1.0, "texture": SubResource("walk_4")}, {"duration": 1.0, "texture": SubResource("walk_5")}], +"loop": true, +"name": &"walk", +"speed": 10.0 +}, { +"frames": [{"duration": 1.0, "texture": SubResource("pound_land_0")}, {"duration": 1.0, "texture": SubResource("pound_land_1")}, {"duration": 1.0, "texture": SubResource("pound_land_2")}], +"loop": false, +"name": &"pound_land", +"speed": 12.0 +}] diff --git a/player/characters/bassist.tres b/player/characters/bassist.tres index f5864c1..cec61e0 100644 --- a/player/characters/bassist.tres +++ b/player/characters/bassist.tres @@ -1,15 +1,23 @@ [gd_resource type="Resource" script_class="CharacterData" load_steps=3 format=3] [ext_resource type="Script" path="res://player/character_data.gd" id="1_data"] -[ext_resource type="SpriteFrames" path="res://player/characters/shared/prototype_sprite_frames.tres" id="2_frames"] +[ext_resource type="SpriteFrames" path="res://player/characters/animations/bassist_frames.tres" id="2_frames"] [resource] script = ExtResource("1_data") id = &"bassist" -display_name = "Bassist" +display_name = "Fer" +role_name = "BAJISTA" sprite_frames = ExtResource("2_frames") max_health = 50 move_speed = 390.0 jump_velocity = -600.0 basic_attack_damage = 5 air_attack_damage = 10 +ground_pound_effect = "bass_cracks" +special_effect = "bass_pulse" +special_label = "BASS QUAKE!" +special_color = Color(0.76, 0.52, 1.0, 1) +special_shake_strength = 3.0 +special_shake_duration = 0.32 +special_shake_frequency = 18.0 diff --git a/player/characters/drummer.tres b/player/characters/drummer.tres index cb27943..4bb9215 100644 --- a/player/characters/drummer.tres +++ b/player/characters/drummer.tres @@ -1,15 +1,23 @@ [gd_resource type="Resource" script_class="CharacterData" load_steps=3 format=3] [ext_resource type="Script" path="res://player/character_data.gd" id="1_data"] -[ext_resource type="SpriteFrames" path="res://player/characters/shared/prototype_sprite_frames.tres" id="2_frames"] +[ext_resource type="SpriteFrames" path="res://player/characters/animations/drummer_frames.tres" id="2_frames"] [resource] script = ExtResource("1_data") id = &"drummer" -display_name = "Drummer" +display_name = "Ivan" +role_name = "BATERIA" sprite_frames = ExtResource("2_frames") max_health = 50 move_speed = 390.0 jump_velocity = -600.0 basic_attack_damage = 5 air_attack_damage = 10 +ground_pound_effect = "ground_pound" +special_effect = "drum_cymbals" +special_label = "CYMBAL STORM!" +special_color = Color(1.0, 0.76, 0.3, 1) +special_shake_strength = 2.0 +special_shake_duration = 0.18 +special_shake_frequency = 83.0 diff --git a/player/characters/guitarist.tres b/player/characters/guitarist.tres index 28fe385..fe6b2f6 100644 --- a/player/characters/guitarist.tres +++ b/player/characters/guitarist.tres @@ -1,15 +1,23 @@ [gd_resource type="Resource" script_class="CharacterData" load_steps=3 format=3] [ext_resource type="Script" path="res://player/character_data.gd" id="1_data"] -[ext_resource type="SpriteFrames" path="res://player/characters/shared/prototype_sprite_frames.tres" id="2_frames"] +[ext_resource type="SpriteFrames" path="res://player/characters/animations/guitarist_frames.tres" id="2_frames"] [resource] script = ExtResource("1_data") id = &"guitarist" -display_name = "Guitarist" +display_name = "Diego" +role_name = "GUITARRISTA" sprite_frames = ExtResource("2_frames") max_health = 50 move_speed = 390.0 jump_velocity = -600.0 basic_attack_damage = 5 air_attack_damage = 10 +ground_pound_effect = "electric_pound" +special_effect = "solo" +special_label = "GUITAR SOLO!" +special_color = Color(0.61, 0.82, 1.0, 1) +special_shake_strength = 2.0 +special_shake_duration = 0.18 +special_shake_frequency = 83.0 diff --git a/player/characters/singer.tres b/player/characters/singer.tres index 82e9c2e..89b2899 100644 --- a/player/characters/singer.tres +++ b/player/characters/singer.tres @@ -1,15 +1,23 @@ [gd_resource type="Resource" script_class="CharacterData" load_steps=3 format=3] [ext_resource type="Script" path="res://player/character_data.gd" id="1_data"] -[ext_resource type="SpriteFrames" path="res://player/characters/shared/prototype_sprite_frames.tres" id="2_frames"] +[ext_resource type="SpriteFrames" path="res://player/characters/animations/singer_frames.tres" id="2_frames"] [resource] script = ExtResource("1_data") id = &"singer" -display_name = "Singer" +display_name = "Hector" +role_name = "CANTANTE" sprite_frames = ExtResource("2_frames") max_health = 50 move_speed = 390.0 jump_velocity = -600.0 basic_attack_damage = 5 air_attack_damage = 10 +ground_pound_effect = "vocal_dome" +special_effect = "vocal_wave" +special_label = "THRASH SCREAM!" +special_color = Color(1.0, 0.88, 0.25, 1) +special_shake_strength = 2.0 +special_shake_duration = 0.18 +special_shake_frequency = 83.0 diff --git a/player/player.gd b/player/player.gd index b4295aa..619679e 100644 --- a/player/player.gd +++ b/player/player.gd @@ -134,8 +134,9 @@ const COMBAT_FX = preload("res://effects/combat_fx.gd") ## Fraccion del control horizontal que se mantiene durante la caida ofensiva. @export_range(0.0, 1.0) var ground_pound_horizontal_control: float = 0.25 -## Radio del impacto al aterrizar, en pixeles. -@export var ground_pound_radius: float = 54.0 +## Radio comun en pixeles: 108, el doble del anterior (54), para toda la banda. +## El circulo fisico y el efecto comparten este alcance; no depende del personaje. +@export var ground_pound_radius: float = 108.0 ## Centro del impacto respecto al cuerpo del jugador. @export var ground_pound_offset: Vector2 = Vector2(0.0, 24.0) @@ -262,11 +263,19 @@ var _special_damage_budgets: Dictionary = {} var _special_damage_dealt: Dictionary = {} var _hurt_animation_timer: float = 0.0 var _landing_animation_timer: float = 0.0 +# Pose exclusiva del impacto ofensivo; un aterrizaje normal sigue usando land. +var _pound_landing_timer: float = 0.0 var _punch_swing_shown: bool = false ## Carga el personaje y prepara ataques, animacion y senales iniciales del HUD. func _ready() -> void: + # Resuelve la eleccion antes de vida, animaciones y senales iniciales del HUD. + var session: RunSessionState = get_node_or_null("/root/RunSession") as RunSessionState + if session != null: + var selected: CharacterData = session.character_for(self) + if selected != null: + character_data = selected if character_data == null: push_error("Player needs a CharacterData resource.") return @@ -529,9 +538,13 @@ func _start_ground_pound() -> void: func _ground_pound_impact() -> void: ground_pound_active = false ground_pound_debug_timer = debug_impact_duration - _landing_animation_timer = 0.20 + _pound_landing_timer = 0.28 + # La pose especifica no reemplaza la animacion de un salto normal. + if animated_sprite.sprite_frames.has_animation(&"pound_land"): + animated_sprite.play(&"pound_land") + animated_sprite.set_frame_and_progress(0, 0.0) COMBAT_FX.spawn(get_parent(), global_position + Vector2(0, 26), - &"ground_pound", facing_direction, ground_pound_radius) + StringName(character_data.ground_pound_effect), facing_direction, ground_pound_radius) feedback_camera.call("impact", 2.8, 0.24) # Calcula el dano a partir de la altura maxima sobre el punto de despegue y aplica sus limites. @@ -584,8 +597,8 @@ func _start_special_attack() -> void: _special_damage_dealt.clear() punch_timer = 0.0 velocity.x = 0.0 - feedback_camera.call("start_solo", special_duration) - _spawn_floating_text("GUITAR SOLO!", Color(0.76, 0.85, 1.0)) + feedback_camera.call("start_solo", special_duration, character_data.special_color) + _spawn_floating_text(character_data.special_label, character_data.special_color) ## Avanza las fases visuales del solo y emite cada pulso una sola vez. @@ -602,9 +615,17 @@ func _update_special_attack(delta: float) -> void: break _apply_special_attack(_special_charge_used, _special_pulses_sent) _special_pulses_sent += 1 + # Cada nota grave visible coincide con su pulso y sacudida, no con un temporizador aparte. + if character_data.special_effect == "bass_pulse": + animated_sprite.play(&"special") + animated_sprite.set_frame_and_progress(0, 0.0) var effect_radius: float = minf(special_radius, 300.0) if special_radius > 0.0 else 300.0 - COMBAT_FX.spawn(get_parent(), global_position, &"solo", facing_direction, effect_radius) - feedback_camera.call("impact", 2.0, 0.18, Color(0.61, 0.82, 1.0)) + COMBAT_FX.spawn(get_parent(), global_position, + StringName(character_data.special_effect), facing_direction, effect_radius) + # Un movimiento de camara por pulso; los platos y ondas nunca aplican dano adicional. + feedback_camera.call("impact", character_data.special_shake_strength, + character_data.special_shake_duration, character_data.special_color, + character_data.special_shake_frequency) velocity.x = -facing_direction * 35.0 if _special_elapsed >= special_duration: _special_active = false @@ -852,6 +873,7 @@ func _reload_level() -> void: func _update_timers(delta: float) -> void: _hurt_animation_timer = maxf(0.0, _hurt_animation_timer - delta) _landing_animation_timer = maxf(0.0, _landing_animation_timer - delta) + _pound_landing_timer = maxf(0.0, _pound_landing_timer - delta) punch_timer = max(punch_timer - delta, 0.0) attack_cooldown_timer = max(attack_cooldown_timer - delta, 0.0) ground_pound_debug_timer = max(ground_pound_debug_timer - delta, 0.0) @@ -887,6 +909,8 @@ func _update_animation() -> void: animation_name = &"punch" elif not is_on_floor(): animation_name = &"jump" if velocity.y < 0.0 else &"fall" + elif _pound_landing_timer > 0.0: + animation_name = &"pound_land" elif _landing_animation_timer > 0.0: animation_name = &"land" elif absf(velocity.x) > 10.0: @@ -942,7 +966,8 @@ func _setup_attack_hitboxes() -> void: func _draw() -> void: if is_on_floor(): draw_rect(Rect2(-14, 24, 28, 3), Color(0.05, 0.06, 0.10, 0.25)) - if ground_pound_active: + # Los trazos dorados tipo baqueta pertenecen solo a Ivan. + if ground_pound_active and character_data != null and character_data.ground_pound_effect == "ground_pound": for side: float in [-1.0, 1.0]: draw_line(Vector2(17 * side, -30), Vector2(17 * side, -9), Color(1.0, 0.8, 0.45, 0.75), 2.0) # Los mensajes de objetos se muestran aunque este desactivada la depuracion de colisiones. diff --git a/player/player.tscn b/player/player.tscn index c9b5e18..b198f37 100644 --- a/player/player.tscn +++ b/player/player.tscn @@ -1,9 +1,9 @@ [gd_scene format=3 uid="uid://nwbjxttgghpq"] [ext_resource type="Script" uid="uid://dccfebno1gvh7" path="res://player/player.gd" id="1_player"] -[ext_resource type="SpriteFrames" uid="uid://s2xmt6mpri5c" path="res://player/characters/shared/prototype_sprite_frames.tres" id="2_frames"] +[ext_resource type="SpriteFrames" path="res://player/characters/animations/guitarist_frames.tres" id="2_frames"] [ext_resource type="Script" uid="uid://kg3i7b0dj2p8" path="res://player/camera_2d.gd" id="3_camera"] -[ext_resource type="Resource" path="res://player/characters/singer.tres" id="4_character"] +[ext_resource type="Resource" path="res://player/characters/guitarist.tres" id="4_character"] [ext_resource type="PackedScene" path="res://ui/hud/player_health_hud.tscn" id="5_health_hud"] [ext_resource type="PackedScene" path="res://ui/hud/special_charge_hud.tscn" id="6_special_charge_hud"] diff --git a/project.godot b/project.godot index f6eb8db..62dd00a 100644 --- a/project.godot +++ b/project.godot @@ -19,6 +19,7 @@ config/icon="res://icon.svg" [autoload] PlayerProgress="*res://game/player_progress.tscn" +RunSession="*res://game/run_session.gd" [display] diff --git a/tests/test_band_resources.py b/tests/test_band_resources.py new file mode 100644 index 0000000..7d5ed4e --- /dev/null +++ b/tests/test_band_resources.py @@ -0,0 +1,190 @@ +"""Contratos estaticos de la banda. No ejecutan GDScript ni simulan la fisica.""" +from pathlib import Path +import re +import unittest +import xml.etree.ElementTree as ET + +ROOT = Path(__file__).resolve().parents[1] +ROLES = ('guitarist', 'drummer', 'bassist', 'singer') +NAMES = ('Diego', 'Ivan', 'Fer', 'Hector') +SVG_NS = '{http://www.w3.org/2000/svg}' + + +def source(path): + return (ROOT / path).read_text(encoding='utf-8') + + +def cell_groups(path): + return {group.attrib['id']: group for group in ET.parse(ROOT / path).getroot().findall(SVG_NS + 'g')} + + +class BandResourceTests(unittest.TestCase): + def test_named_profiles_have_independent_frames(self): + for role, name in zip(ROLES, NAMES): + data = source(f'player/characters/{role}.tres') + self.assertIn(f'id = &"{role}"', data) + self.assertIn(f'display_name = "{name}"', data) + self.assertIn(f'res://player/characters/animations/{role}_frames.tres', data) + self.assertNotIn('prototype_sprite_frames', data) + self.assertIn('role_name = ', data) + + def test_base_stats_remain_shared(self): + for role in ROLES: + data = source(f'player/characters/{role}.tres') + for stat in ('max_health = 50', 'move_speed = 390.0', 'jump_velocity = -600.0', 'basic_attack_damage = 5'): + self.assertIn(stat, data) + player = source('player/player.gd') + for stat in ('special_charge_per_kill: int = 10', 'special_min_use_charge: int = 25', + 'special_max_damage: int = 30', 'special_pulse_count: int = 4', + 'ground_pound_max_damage: int = 12'): + self.assertIn(stat, player) + + def test_visual_mapping_and_shared_doubled_radius(self): + expected = { + 'guitarist': ('electric_pound', 'solo'), + 'drummer': ('ground_pound', 'drum_cymbals'), + 'bassist': ('bass_cracks', 'bass_pulse'), + 'singer': ('vocal_dome', 'vocal_wave'), + } + for role, (pound, special) in expected.items(): + text = source(f'player/characters/{role}.tres') + self.assertNotIn('ground_pound_radius', text) + self.assertIn(f'ground_pound_effect = "{pound}"', text) + self.assertIn(f'special_effect = "{special}"', text) + player = source('player/player.gd') + self.assertIn('ground_pound_radius: float = 108.0', player) + self.assertIn('pound_shape.radius = ground_pound_radius', player) + self.assertIn('query.shape = ground_pound_collision.shape', player) + self.assertIn('StringName(character_data.ground_pound_effect), facing_direction, ground_pound_radius)', player) + self.assertNotIn('ground_pound_radius_multiplier', source('player/character_data.gd')) + self.assertNotIn('ground_pound_radius_multiplier', player) + + def test_attack_resolution_never_branches_on_character_or_effect(self): + player = source('player/player.gd') + # El efecto no elige objetivos, no decide dano y no genera colisiones nuevas. + functions = ('_apply_special_attack', '_update_punch_damage', '_damage_target') + for name in functions: + body = player.split(f'func {name}(', 1)[1].split('\nfunc ', 1)[0] + self.assertNotIn('character_data.id', body) + self.assertNotIn('character_data.special_effect', body) + self.assertNotIn('character_data.ground_pound_effect', body) + pound = player.split('func _ground_pound_impact()', 1)[1] + pound = pound.split('var height_reached:', 1)[1].split('func _start_special_attack', 1)[0] + self.assertNotIn('character_data', pound) + for token in ('query.shape', 'query.collision_mask', 'final_damage', '_damage_target'): + self.assertIn(token, pound) + + def test_only_ivan_keeps_the_stick_trails(self): + code = source('player/player.gd') + self.assertIn('if ground_pound_active and character_data != null and character_data.ground_pound_effect == "ground_pound":', code) + + def test_four_atlases_are_self_contained_and_all_regions_fit(self): + expected_names = {'idle', 'walk', 'jump', 'fall', 'punch', 'ground_pound', + 'land', 'pound_land', 'special_start', 'special', 'special_end', 'hurt'} + for role in ROLES: + atlas = ET.parse(ROOT / f'assets/characters/band/{role}.svg').getroot() + self.assertEqual((atlas.attrib['width'], atlas.attrib['height']), ('512', '320')) + self.assertEqual(atlas.attrib['shape-rendering'], 'crispEdges') + self.assertFalse(list(atlas.iter(SVG_NS + 'image'))) + self.assertFalse(list(atlas.iter(SVG_NS + 'text'))) + text = source(f'player/characters/animations/{role}_frames.tres') + self.assertEqual(set(re.findall(r'"name": &"([^"]+)"', text)), expected_names) + declared = re.findall(r'\[sub_resource type="AtlasTexture" id="([^"]+)"\]', text) + self.assertEqual(len(declared), 40) + self.assertEqual(set(declared), set(re.findall(r'SubResource\("([^"]+)"\)', text))) + self.assertEqual(set(declared), set(cell_groups(f'assets/characters/band/{role}.svg'))) + for x, y, w, h in re.findall(r'region = Rect2\((\d+), (\d+), (\d+), (\d+)\)', text): + x, y, w, h = map(int, (x, y, w, h)) + self.assertEqual((w, h), (64, 64)) + self.assertLessEqual(x+w, 512) + self.assertLessEqual(y+h, 320) + self.assertEqual(int(re.search(r'load_steps=(\d+)', text)[1]), + 1+len(re.findall(r'^\[(?:ext|sub)_resource ', text, re.M))) + + def test_diego_keeps_every_original_cell_except_pound(self): + old = cell_groups('assets/characters/ankarde/player_pixel.svg') + new = cell_groups('assets/characters/band/guitarist.svg') + for name in old: + if name.startswith('ground_pound'): + self.assertNotEqual(ET.tostring(old[name]), ET.tostring(new[name])) + else: + # El texto conserva las celdas, incluidas sus coordenadas de atlas. + self.assertEqual(ET.tostring(old[name]), ET.tostring(new[name]), name) + + def test_punch_uses_identical_timing_in_every_profile(self): + expected = [('1.0', 'punch_0'), ('0.75', 'punch_1'), ('1.15', 'punch_2'), + ('0.8', 'punch_3'), ('1.3', 'punch_4')] + for role in ROLES: + text = source(f'player/characters/animations/{role}_frames.tres') + self.assertEqual(re.findall(r'"duration": ([\d.]+), "texture": SubResource\("(punch_\d)"\)', text), expected) + self.assertIn('"name": &"punch",\n"speed": 18.0', text) + # El controlador unico mantiene la ventana danina compartida. + self.assertEqual(source('player/player.gd').count('func _update_punch_damage()'), 1) + + def test_new_pound_pose_does_not_replace_regular_landing(self): + code = source('player/player.gd') + self.assertIn('animation_name = &"pound_land"', code) + self.assertIn('animation_name = &"land"', code) + self.assertIn('_pound_landing_timer = 0.28', code) + + def test_effects_have_no_damage_or_collision_authority(self): + fx = source('effects/combat_fx.gd') + for identifier in ('take_damage', 'Area2D', 'PhysicsShapeQuery', 'CharacterBody2D'): + self.assertNotIn(identifier, fx) + for kind in ('electric_pound', 'vocal_dome', 'bass_cracks', 'vocal_wave', 'drum_cymbals', 'bass_pulse'): + self.assertIn(f'func _draw_{kind}(', fx) + self.assertIn('draw_colored_polygon(dome', fx) + self.assertIn('draw_set_transform(Vector2.ZERO, 0.0, Vector2.ONE)', fx) + + def test_bass_notes_and_camera_share_the_combat_pulse(self): + player = source('player/player.gd') + self.assertIn('if character_data.special_effect == "bass_pulse":', player) + self.assertIn('animated_sprite.set_frame_and_progress(0, 0.0)', player) + self.assertIn('character_data.special_shake_frequency', player) + self.assertIn('special_shake_frequency = 18.0', source('player/characters/bassist.tres')) + frames = source('player/characters/animations/bassist_frames.tres') + self.assertIn('"loop": false,\n"name": &"special"', frames) + camera = source('player/camera_2d.gd') + self.assertIn('minf(_shake_amplitude, 3.0)', camera) + self.assertIn('* feedback_strength', camera) + + def test_selector_is_four_data_driven_touch_cards_in_two_columns(self): + scene = source('ui/menu/character_select.tscn') + self.assertIn('columns = 2', scene) + self.assertEqual(scene.count('instance=ExtResource("card")'), 4) + self.assertIn('follow_focus = true', scene) + for name, role in zip(NAMES, ROLES): + self.assertIn(f'[node name="{name}" ', scene) + self.assertIn(f'res://player/characters/{role}.tres', scene) + card = source('ui/menu/character_card.gd') + self.assertIn('frames.get_frame_texture(&"idle", 0)', card) + self.assertEqual(source('ui/menu/character_card.tscn').count('mouse_filter = 2'), 5) + + def test_menu_waits_for_character_and_has_back_and_failure_paths(self): + menu = source('ui/menu/main_menu.gd') + self.assertIn('button.pressed.connect(_show_characters.bind(path))', menu) + self.assertIn('_load_level(_selected_level_path, character)', menu) + self.assertIn('session.begin_level(path, character)', menu) + select = menu.split('func _show_characters(', 1)[1].split('\n\nfunc ', 1)[0] + self.assertNotIn('load_threaded_request', select) + self.assertGreaterEqual(menu.count('if characters_panel.visible:'), 2) + error = menu.split('func _show_load_error(', 1)[1].split('\n\nfunc ', 1)[0] + self.assertIn('session.clear()', error) + self.assertIn('_show_characters(_selected_level_path)', error) + + def test_ephemeral_selection_does_not_change_the_save_format(self): + session = source('game/run_session.gd') + for name in ('FileAccess', 'user://', 'JSON', 'PlayerProgress', 'unlock_items'): + self.assertNotIn(name, session) + self.assertIn('ancestor.scene_file_path == level_path', session) + player = source('player/player.gd') + self.assertLess(player.index('session.character_for(self)'), player.index('current_health = get_max_health()')) + self.assertLess(player.index('character_data = selected'), player.index('_setup_attack_hitboxes()')) + reload = player.split('func _reload_level()', 1)[1].split('\n\n', 1)[0] + self.assertNotIn('session.clear', reload) + self.assertIn('SAVE_VERSION: int = 1', source('game/player_progress.gd')) + self.assertIn('res://player/characters/guitarist.tres', source('player/player.tscn')) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/test_menu_resources.py b/tests/test_menu_resources.py index e1a6011..2bd0b1d 100644 --- a/tests/test_menu_resources.py +++ b/tests/test_menu_resources.py @@ -26,12 +26,13 @@ class MenuResourceTests(unittest.TestCase): self.assertNotIn('DirAccess', code) self.assertIn('load_threaded_get_status', code) self.assertIn('ResourceLoader.THREAD_LOAD_FAILED', code) - # El unico autoload es el perfil de raros; no impone campana ni personaje. + # Perfil persistente y eleccion de intento separados; no se agrega una campana. project = (ROOT / 'project.godot').read_text() self.assertIn('PlayerProgress="*res://game/player_progress.tscn"', project) autoloads = project.split('[autoload]', 1)[1].split('[display]', 1)[0] - self.assertEqual(len(re.findall(r'^\w+="\*res://', autoloads, re.M)), 1) - self.assertNotIn('CharacterData', code) + self.assertEqual(len(re.findall(r'^\w+="\*res://', autoloads, re.M)), 2) + self.assertIn('RunSession="*res://game/run_session.gd"', autoloads) + self.assertIn('button.pressed.connect(_show_characters.bind(path))', code) def test_menu_uses_scroll_and_touch_sized_buttons(self): scene = (ROOT / 'ui/menu/main_menu.tscn').read_text() diff --git a/tests/test_menu_runtime.gd b/tests/test_menu_runtime.gd index 25bba93..2b9b44a 100644 --- a/tests/test_menu_runtime.gd +++ b/tests/test_menu_runtime.gd @@ -7,6 +7,8 @@ const BOOT_PATH: String = "res://game/main.tscn" const MENU_PATH: String = "res://ui/menu/main_menu.tscn" const BETA_PATH: String = "res://levels/level_00.tscn" const VERTICAL_PATH: String = "res://levels/level_01.tscn" +const DIEGO: CharacterData = preload("res://player/characters/guitarist.tres") +const FER: CharacterData = preload("res://player/characters/bassist.tres") var _failures: int = 0 @@ -43,19 +45,36 @@ func _run() -> void: (menu.get_node("Margin/Layout/Levels/Back") as Button).pressed.emit() _check((menu.get_node("Margin/Layout/Home") as Control).visible, "Volver debe mostrar el inicio") menu.call("_show_levels") - menu.call("_load_level", "res://levels/no_such_level.tscn") + menu.call("_load_level", "res://levels/no_such_level.tscn", DIEGO) _check((menu.get_node("Margin/Layout/Error") as Label).visible, "Un nivel inexistente debe mostrar un error recuperable") _check((menu.get_node("Margin/Layout/Levels") as Control).visible, "Un fallo debe conservar el selector") - menu.call("_load_level", BETA_PATH) - menu.call("_load_level", VERTICAL_PATH) + menu.call("_show_characters", BETA_PATH) + _check(String(menu.get("_loading_path")).is_empty(), "Elegir nivel no carga sin personaje") + var grid: GridContainer = menu.get_node("Margin/Layout/Characters/Scroll/Grid") as GridContainer + _check(grid.columns == 2 and grid.get_child_count() == 4, "La banda aparece en 2x2") + (menu.get_node("Margin/Layout/Characters/Back") as Button).pressed.emit() + _check((menu.get_node("Margin/Layout/Levels") as Control).visible, "Volver desde la banda muestra niveles") + menu.call("_show_characters", BETA_PATH) + (grid.get_node("Diego") as Button).pressed.emit() + (grid.get_node("Fer") as Button).pressed.emit() _check(String(menu.get("_loading_path")) == BETA_PATH, "Una doble pulsacion no inicia dos niveles") var level: Node = await _wait_for_scene(BETA_PATH) if level == null: quit(1) return var player: Node = level.get_node("Player") - _check((player.get("character_data") as CharacterData).id == &"singer", "Se conserva el personaje asignado, sin selector") + _check((player.get("character_data") as CharacterData).id == &"guitarist", "La tarjeta aplica Diego antes de inicializar Player") _check(int(player.get("special_charge")) == 0, "Cada nueva escena inicia su estado de combate") + var session: RunSessionState = root.get_node("RunSession") as RunSessionState + _check(session.selected_character == DIEGO, "La doble pulsacion no reemplaza al personaje") + # El mismo camino utilizado tras morir conserva al integrante elegido. + _check(reload_current_scene() == OK, "Debe poder reiniciar el escenario") + level = await _wait_for_scene(BETA_PATH) + if level == null: + quit(1) + return + _check((level.get_node("Player").get("character_data") as CharacterData) == DIEGO, + "Recargar conserva la eleccion del intento") Input.action_press("move_right") level.get_node("LevelNavigation").call("return_to_menu") menu = await _wait_for_scene(MENU_PATH) @@ -64,11 +83,14 @@ func _run() -> void: quit(1) return menu.call("_show_levels") - menu.call("_load_level", VERTICAL_PATH) + _check(session.selected_character == null, "Regresar al menu limpia la eleccion") + menu.call("_show_characters", VERTICAL_PATH) + (menu.get_node("Margin/Layout/Characters/Scroll/Grid/Fer") as Button).pressed.emit() level = await _wait_for_scene(VERTICAL_PATH) if level == null: quit(1) return + _check((level.get_node("Player").get("character_data") as CharacterData) == FER, "Se aplica Fer al siguiente nivel") _check(level.has_node("Triggers/Exit"), "El nuevo nivel necesita una salida") # La salida es de un solo disparo; no vuelve a la intro. var exit_area: Node = level.get_node("Triggers/Exit") diff --git a/tools/generate_band_art.py b/tools/generate_band_art.py new file mode 100644 index 0000000..b5be6c0 --- /dev/null +++ b/tools/generate_band_art.py @@ -0,0 +1,386 @@ +"""Genera los cuatro atlas SVG y SpriteFrames a partir del pixel art original. + +Uso: python tools/generate_band_art.py (requiere Pillow solo para regenerar arte). +El juego consume los SVG/.tres ya versionados; nunca ejecuta este programa. +Diego conserva exactamente sus celdas originales salvo la caida ofensiva. +Las demas apariencias reutilizan las poses comunes y el mismo punetazo. +""" +from __future__ import annotations + +from collections import defaultdict +from pathlib import Path +import math +import re +import xml.etree.ElementTree as ET + +from PIL import Image, ImageDraw + +ROOT = Path(__file__).resolve().parents[1] +SOURCE = ROOT / "assets/characters/ankarde/player_pixel.svg" +DESTINATION = ROOT / "assets/characters/band" +ROLES = ("guitarist", "drummer", "bassist", "singer") +OUTLINE = "#161723" +SKIN = "#ecb78b" +SKIN_LIGHT = "#ffdab0" +SKIN_DARK = "#b57964" +SHIRT = "#252b39" +SHIRT_LIGHT = "#3e475c" +HAIR = ("#30242a", "#543933", "#805345") +CELL = 64 + + +def rgba(color: str) -> tuple[int, int, int, int]: + return tuple(bytes.fromhex(color[1:])) + (255,) + + +def read_source() -> dict[str, Image.Image]: + """Reconstruye las celdas originales sin rasterizadores ni dependencias de SVG.""" + result = {} + for group in ET.parse(SOURCE).getroot().findall("{*}g"): + image = Image.new("RGBA", (CELL, CELL)) + draw = ImageDraw.Draw(image) + for path in group: + if not path.tag.endswith("path"): + continue + commands = path.attrib["d"] + pattern = r"M(-?\d+) (-?\d+)h(\d+)v(\d+)h-\d+z" + if re.sub(pattern, "", commands): + raise ValueError("El atlas original ya no usa rectangulos enteros: " + group.attrib["id"]) + for x, y, width, height in re.findall(pattern, commands): + x, y, width, height = map(int, (x, y, width, height)) + draw.rectangle((x, y, x + width - 1, y + height - 1), fill=path.attrib["fill"]) + result[group.attrib["id"]] = image + return result + + +def appearance(source: Image.Image, role: str, pose_name: str) -> Image.Image: + """Cambia pelo/ropa sin alterar la trayectoria de brazos del punetazo comun.""" + if role == "guitarist": + return source.copy() + image = source.copy() + pixels = image.load() + hair_colors = tuple(rgba(color) for color in HAIR) + hair_points = [(x, y) for y in range(35) for x in range(CELL) if pixels[x, y] in hair_colors] + top = min(y for _, y in hair_points) - 1 + left = min(x for x, _ in hair_points) + right = max(x for x, _ in hair_points) + new_hair = ("#78532b", "#d5a442", "#ffe07c") if role == "singer" else ("#10121a", "#20212c", "#3f4353") + palette = dict(zip(hair_colors, map(rgba, new_hair))) + shirt_palette = {rgba(SHIRT): rgba(SKIN_DARK), rgba(SHIRT_LIGHT): rgba(SKIN), rgba("#667185"): rgba(SKIN_LIGHT)} + for y in range(CELL): + for x in range(CELL): + color = pixels[x, y] + if y < top + 30 and color in palette: + pixels[x, y] = palette[color] + # Las camisetas acaban a mitad del brazo: el antebrazo queda descubierto. + if role in ("singer", "bassist") and color in shirt_palette: + forearm = top + 31 <= y <= top + 41 and (x < 28 or x >= 40) + extended = pose_name.startswith("punch") and x >= 45 and top + 23 <= y <= top + 33 + if forearm or extended: + pixels[x, y] = shirt_palette[color] + if color == rgba("#35576d"): + pixels[x, y] = rgba("#424b36" if role == "singer" else "#363849") + elif color == rgba("#60869c"): + pixels[x, y] = rgba("#7a8664" if role == "singer" else "#686b83") + draw = ImageDraw.Draw(image) + if role == "bassist": + # Rizos a ambos lados hasta los hombros, no solo un cambio de color de Diego. + for side, x in ((-1, left - 1), (1, right + 1)): + for index, y in enumerate(range(top + 6, top + 34, 5)): + cx = x + (index % 2) * side + draw.ellipse((cx - 3, y - 2, cx + 3, y + 3), fill="#10121a") + draw.line((cx - 1, y - 1, cx + 1, y - 1, cx + 1, y + 1), fill="#414454", width=1) + for index in range(5): + x = left + 3 + index * 3 + y = top + 2 + index % 2 + draw.rectangle((x, y, x + 2, y + 2), fill="#20212c") + draw.point((x, y), fill="#454957") + elif role == "drummer": + # Hebras rectas, negras y largas; el brillo no se convierte en rizos. + for x in (left + 1, left + 3): + for y in range(top + 10, top + 25): + if pixels[x, y] in tuple(map(rgba, new_hair)): + pixels[x, y] = rgba("#3b3e4b") + add_wristbands(image, top) + return image + + +def add_wristbands(image: Image.Image, head_top: int) -> None: + """Localiza manos de las poses originales y coloca la munequera junto al punio.""" + skin_colors = {rgba(SKIN), rgba(SKIN_LIGHT), rgba(SKIN_DARK)} + pending = {(x, y) for y in range(head_top + 23, min(head_top + 43, 48)) + for x in range(CELL) if image.getpixel((x, y)) in skin_colors and (x < 29 or x > 39)} + draw = ImageDraw.Draw(image) + while pending: + start = pending.pop() + component, stack = [start], [start] + while stack: + x, y = stack.pop() + for point in ((x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1)): + if point in pending: + pending.remove(point) + stack.append(point) + component.append(point) + if len(component) < 5: + continue + x0, x1 = min(x for x, _ in component), max(x for x, _ in component) + y0, y1 = min(y for _, y in component), max(y for _, y in component) + if x1 - x0 > 10 or y1 - y0 > 9: + continue + if x0 > 44 and y0 < 40: + draw.rectangle((x0 - 2, y0 - 1, x0, y1 + 1), fill="#10121a") + draw.point((x0 - 1, y0 + 1), fill="#a0a5b3") + else: + draw.rectangle((x0 - 1, y0 - 2, x1 + 1, y0), fill="#10121a") + draw.point((x0, y0 - 1), fill="#a0a5b3") + + +def limb(draw: ImageDraw.ImageDraw, points: list[tuple[int, int]], color: str, width: int = 6) -> None: + draw.line(points, fill=OUTLINE, width=width + 2) + draw.line(points, fill=color, width=width) + + +def arm(draw: ImageDraw.ImageDraw, points: list[tuple[int, int]], role: str) -> None: + shoulder, elbow, hand = points + limb(draw, points, SHIRT) + if role in ("singer", "bassist"): + limb(draw, [elbow, hand], SKIN, 5) + sleeve = ((shoulder[0] + elbow[0]) // 2, (shoulder[1] + elbow[1]) // 2) + draw.line([shoulder, sleeve], fill=SHIRT_LIGHT, width=4) + x, y = hand + if role == "drummer": + band = (round(elbow[0] * .22 + x * .78), round(elbow[1] * .22 + y * .78)) + draw.rectangle((band[0] - 3, band[1] - 2, band[0] + 3, band[1] + 2), fill="#10121a") + draw.point((band[0] - 2, band[1] - 1), fill="#b7bfcb") + draw.rectangle((x - 3, y - 3, x + 3, y + 2), fill=OUTLINE) + draw.rectangle((x - 2, y - 2, x + 2, y + 1), fill=SKIN) + draw.line((x - 1, y - 2, x + 2, y - 2), fill=SKIN_LIGHT) + + +def posed_body(idle: Image.Image, role: str, *, shift=(0, 0), hip=44, + legs=None, arms=None) -> Image.Image: + """Poses exclusivas de ataques; el cuerpo de colision no cambia de tamano.""" + dx, dy = shift + image = Image.new("RGBA", (CELL, CELL)) + draw = ImageDraw.Draw(image) + if legs is None: + legs = [[(27, hip), (26, 51), (27, 57)], [(38, hip), (40, 51), (41, 57)]] + shorts = "#424b36" if role == "singer" else "#363849" + for thigh, knee, ankle in legs: + limb(draw, [thigh, knee, ankle], SKIN, 6) + midpoint = ((thigh[0] + knee[0]) // 2, (thigh[1] + knee[1]) // 2) + draw.line([thigh, midpoint], fill=shorts, width=7) + x, y = ankle + draw.rectangle((x - 4, y - 2, x + 7, y + 3), fill=OUTLINE) + draw.rectangle((x - 2, y - 2, x + 3, y), fill=SHIRT_LIGHT) + draw.line((x - 3, y + 3, x + 7, y + 3), fill="#667185") + shoulder_y = 30 + dy + draw.polygon([(25 + dx, shoulder_y - 2), (39 + dx, shoulder_y - 2), + (42 + dx, hip - 1), (23 + dx, hip - 1)], fill=OUTLINE) + draw.polygon([(26 + dx, shoulder_y), (38 + dx, shoulder_y), + (40 + dx, hip - 3), (25 + dx, hip - 3)], fill=SHIRT) + draw.line((27 + dx, shoulder_y, 26 + dx, hip - 4), fill=SHIRT_LIGHT, width=2) + draw.rectangle((25 + dx, hip - 2, 40 + dx, hip + 2), fill=OUTLINE) + draw.rectangle((26 + dx, hip - 1, 39 + dx, hip + 1), fill=shorts) + draw.point((33 + dx, hip - 1), fill="#b4b6bd") + # Pequeno emblema metalero, dibujado en pixeles y sin fuentes externas. + cy = shoulder_y + 3 + draw.rectangle((31 + dx, cy, 35 + dx, cy + 4), fill="#f6ead4") + draw.point((32 + dx, cy + 1), fill=OUTLINE) + draw.point((35 + dx, cy + 1), fill=OUTLINE) + draw.rectangle((32 + dx, cy + 5, 34 + dx, cy + 6), fill="#f6ead4") + head = idle.crop((0, 0, 64, 29)) + image.alpha_composite(head, (dx, dy)) + if arms is None: + arms = [[(24 + dx, shoulder_y), (22 + dx, shoulder_y + 8), (23 + dx, hip - 1)], + [(40 + dx, shoulder_y), (43 + dx, shoulder_y + 8), (43 + dx, hip - 1)]] + for points in arms: + arm(draw, points, role) + return image + + +def instrument(image: Image.Image, body: tuple[int, int], neck: tuple[int, int], *, bass=False) -> None: + """Guitarra roja o bajo de cuatro cuerdas; geometria entera para conservar el pixel art.""" + draw = ImageDraw.Draw(image) + bx, by = body + nx, ny = neck + length = math.hypot(nx - bx, ny - by) + ux, uy = (nx - bx) / length, (ny - by) / length + px, py = -uy, ux + def point(a, b): + return (round(bx + px * a + ux * b), round(by + py * a + uy * b)) + shape = [(-8, -6), (-8, 2), (-3, 9), (1, 6), (7, 8), (6, -7), (2, -4), (-2, -8)] + if bass: + shape = [(-6, -7), (-8, -1), (-6, 6), (-2, 9), (2, 6), (6, 8), (7, -1), (4, -7)] + draw.polygon([point(a, b) for a, b in shape], fill=OUTLINE) + inner = [point(a * .78, b * .80) for a, b in shape] + draw.polygon(inner, fill="#635486" if bass else "#e54f64") + draw.line([point(0, -5), neck], fill=OUTLINE, width=6 if bass else 5) + draw.line([point(0, -4), neck], fill="#b59164", width=3) + draw.line([point(-1, -3), (nx - 1, ny)], fill="#efe0b2", width=1) + draw.line([point(1, -3), (nx + 1, ny)], fill="#f7ecc8", width=1) + draw.polygon([point(-3, length - 2), point(-3, length + 4), point(2, length + 5), + point(3, length - 2)], fill=OUTLINE) + draw.line([point(0, length - 1), point(0, length + 3)], fill="#f0cd7b", width=3) + for index in range(4 if bass else 3): + draw.line([point(-3, length - 1 + index), point(-5, length - 1 + index)], fill="#b5bfca", width=1) + draw.line([point(-4, -2), point(4, -2)], fill="#efe7df", width=2) + draw.point(point(4, -4), fill="#efc45e") + + +def special_pose(idle: Image.Image, role: str, phase: str, index: int) -> Image.Image: + """Sacar instrumento, tocar/gritar y recogerlo conservan las fases comunes del especial.""" + progress = (index + 1) / 3 if phase == "special_start" else (1 - (index + 1) / 3 if phase == "special_end" else 1) + beat = index % 2 if phase == "special" else 0 + if role == "singer": + hand_y = round(42 - 17 * progress) + beat + image = posed_body(idle, role, arms=[[(24, 30), (19, 37), (20, 32 + beat)], + [(40, 30), (47, 35), (47, hand_y)]]) + draw = ImageDraw.Draw(image) + draw.line([(48, hand_y + 3), (52, 48), (49, 56), (39, 58)], fill="#697080", width=1) + draw.line((48, hand_y + 2, 46, hand_y - 5), fill=OUTLINE, width=5) + draw.line((48, hand_y + 1, 46, hand_y - 5), fill="#9ea8b9", width=2) + draw.ellipse((42, hand_y - 10, 49, hand_y - 4), fill=OUTLINE) + draw.rectangle((44, hand_y - 9, 47, hand_y - 5), fill="#c6d1df") + draw.line((44, hand_y - 7, 47, hand_y - 7), fill="#697584") + if phase == "special": + draw.rectangle((37, 21, 40, 23 + beat), fill=OUTLINE) + draw.point((38, 23), fill="#e8868c") + return image + if role == "drummer": + left = (18, round(40 - 18 * progress) + beat * 12) + right = (48, round(40 - 6 * progress) - beat * 12) + image = posed_body(idle, role, arms=[[(24, 30), (18, 29), left], [(40, 30), (47, 29), right]]) + draw = ImageDraw.Draw(image) + for hand, side in ((left, -1), (right, 1)): + tip = (hand[0] + side * 6, max(2, hand[1] - 16)) + draw.line([hand, tip], fill=OUTLINE, width=3) + draw.line([hand, tip], fill="#e7bd76", width=1) + draw.point(tip, fill="#fff0bd") + return image + strum = (3, 2, 0, -1, -1, 0)[index] if phase == "special" else 0 + image = posed_body(idle, role, arms=[[(24, 30), (25, 40), (30, 45 + strum)], + [(40, 30), (44, 35), (46, 30)]]) + instrument(image, (29, 49), (55, round(33 - 12 * progress)), bass=True) + draw = ImageDraw.Draw(image) + draw.rectangle((28, 43 + strum, 33, 45 + strum), fill=SKIN_LIGHT) + draw.rectangle((44, 31, 47, 34), fill=SKIN) + return image + + +def pound_pose(idle: Image.Image, role: str, index: int, *, landing=False) -> Image.Image: + if role == "guitarist": + if landing: + image = posed_body(idle, role, shift=(-1, 4), hip=47, + legs=[[(26, 46), (22, 51), (20, 57)], [(37, 46), (40, 51), (42, 57)]], + arms=[[(23, 34), (29, 39), (38, 38)], [(39, 34), (43, 38), (44, 45)]]) + instrument(image, (50 - index, 53 - max(index - 1, 0) * 5), (37, 26)) + ImageDraw.Draw(image).rectangle((38, 36, 42, 39), fill=SKIN_LIGHT) + else: + image = posed_body(idle, role, arms=[[(24, 30), (24, 18), (40, 22)], + [(40, 30), (47, 30), (48, 21 + index * 3)]]) + instrument(image, (51, 25 + index * 4), (47 - index * 3, 5 + index)) + return image + if role == "singer": + if landing: + image = posed_body(idle, role, shift=(-4, 8 - (2 if index == 2 else 0)), hip=51, + legs=[[(24, 50), (19, 54), (17, 57)], [(35, 50), (39, 52), (36, 57)]], + arms=[[(20, 38), (17, 43), (24, 42)], [(36, 38), (44, 45), (48, 57 - index)]]) + else: + image = posed_body(idle, role, hip=43, + legs=[[(27, 43), (22, 47), (25, 53)], [(38, 43), (43, 46), (46, 51)]], + arms=[[(24, 30), (18, 34), (22, 30)], [(40, 30), (45, 38), (47, 46 + index)]]) + return image + if landing: + return posed_body(idle, role, shift=(-1, 11 - index // 2), hip=55, + legs=[[(27, 55), (35, 54), (39, 57)], [(38, 55), (49, 51), (52, 57)]], + arms=[[(23, 41), (20, 49), (24, 54)], [(39, 41), (45, 47), (44, 52)]]) + return posed_body(idle, role, hip=43, + legs=[[(27, 43), (22, 42), (23, 51)], [(38, 43), (47, 42), (50, 51)]], + arms=[[(24, 30), (20, 36), (23, 41)], [(40, 30), (46, 36), (46, 41)]]) + + +def svg_group(name: str, image: Image.Image, index: int) -> str: + """Agrupa tramos horizontales por color para obtener SVG de texto compacto.""" + paths = defaultdict(list) + for y in range(CELL): + x = 0 + while x < CELL: + color = image.getpixel((x, y)) + end = x + 1 + while end < CELL and image.getpixel((end, y)) == color: + end += 1 + if color[3]: + hex_color = "#%02x%02x%02x" % color[:3] + paths[hex_color].append(f"M{x} {y}h{end-x}v1h-{end-x}z") + x = end + result = [f''] + for color, runs in sorted(paths.items()): + result.append(f'') + result.append("") + return "\n".join(result) + + +def write_frames(role: str, names: list[str]) -> None: + """Los tiempos y duraciones comunes son los mismos que en el atlas original.""" + text = ['[gd_resource type="SpriteFrames" load_steps=42 format=3]', '', + f'[ext_resource type="Texture2D" path="res://assets/characters/band/{role}.svg" id="atlas"]', ''] + for index, name in enumerate(names): + text += [f'[sub_resource type="AtlasTexture" id="{name}"]', 'atlas = ExtResource("atlas")', + f'region = Rect2({index%8*64}, {index//8*64}, 64, 64)', 'filter_clip = true', ''] + animations = { + 'fall': (7, True), 'ground_pound': (12, True), 'hurt': (12, False), 'idle': (5, True), + 'jump': (9, False), 'land': (16, False), 'punch': (18, False), 'special': (12, True), + 'special_end': (7, False), 'special_start': (9, False), 'walk': (10, True), + 'pound_land': (12, False), + } + serialized = [] + for animation, (speed, loop) in animations.items(): + # Fer toca una nota por pulso; Player reinicia la pose, no un bucle visual. + if role == 'bassist' and animation == 'special': + loop = False + cells = [n for n in names if n.rsplit('_', 1)[0] == animation] + durations = [1.0, .75, 1.15, .8, 1.3] if animation == 'punch' else [1.0] * len(cells) + frames = ', '.join('{"duration": %s, "texture": SubResource("%s")}' % (duration, name) + for duration, name in zip(durations, cells)) + serialized.append('{\n"frames": [' + frames + '],\n"loop": ' + str(loop).lower() + + f',\n"name": &"{animation}",\n"speed": {speed}.0\n' + '}') + text += ['[resource]', 'animations = [' + ', '.join(serialized) + ']\n'] + (ROOT/'player/characters/animations').mkdir(parents=True, exist_ok=True) + (ROOT/f'player/characters/animations/{role}_frames.tres').write_text('\n'.join(text), encoding='utf-8') + + +def main() -> None: + originals = read_source() + # Para Diego se conserva tambien el texto SVG de cada celda no modificada. + raw_groups = {name: match.group(0) for name in originals + if (match := re.search(r'', SOURCE.read_text(), re.S))} + DESTINATION.mkdir(parents=True, exist_ok=True) + for role in ROLES: + frames = {name: appearance(image, role, name) for name, image in originals.items()} + idle = frames['idle_0'] + for index in range(2): + if role != 'drummer': + frames[f'ground_pound_{index}'] = pound_pose(idle, role, index) + for index in range(3): + frames[f'pound_land_{index}'] = frames[f'land_{index}'].copy() if role == 'drummer' else pound_pose(idle, role, index, landing=True) + if role != 'guitarist': + for phase, count in (('special_start', 3), ('special', 6), ('special_end', 2)): + for index in range(count): + frames[f'{phase}_{index}'] = special_pose(idle, role, phase, index) + output = ['', + f'{role}: band member animations', + ''] + for index, (name, image) in enumerate(frames.items()): + if role == 'guitarist' and name in originals and not name.startswith('ground_pound'): + output.append(raw_groups[name]) + else: + output.append(svg_group(name, image, index)) + output.append('\n') + (DESTINATION/f'{role}.svg').write_text('\n'.join(output), encoding='utf-8') + write_frames(role, list(frames)) + print('Generados cuatro atlas y cuatro recursos SpriteFrames; no se ha ejecutado Godot.') + + +if __name__ == '__main__': + main() diff --git a/ui/menu/character_card.gd b/ui/menu/character_card.gd new file mode 100644 index 0000000..cd2f4e7 --- /dev/null +++ b/ui/menu/character_card.gd @@ -0,0 +1,25 @@ +class_name CharacterCard +extends Button + +## Una tarjeta es un boton completo: imagen y etiquetas no interceptan el tacto. +## Su retrato usa el primer idle del mismo SpriteFrames que se vera durante la partida. +signal character_chosen(character: CharacterData) +@export var character_data: CharacterData + + +func _ready() -> void: + if character_data == null: + disabled = true + return + $Content/Layout/Name.text = character_data.display_name + $Content/Layout/Role.text = character_data.role_name + var frames: SpriteFrames = character_data.sprite_frames + if frames != null and frames.has_animation(&"idle") and frames.get_frame_count(&"idle") > 0: + $Content/Layout/Portrait.texture = frames.get_frame_texture(&"idle", 0) + tooltip_text = character_data.display_name + " - " + character_data.role_name + pressed.connect(_choose) + + +func _choose() -> void: + if character_data != null: + character_chosen.emit(character_data) diff --git a/ui/menu/character_card.tscn b/ui/menu/character_card.tscn new file mode 100644 index 0000000..085c56d --- /dev/null +++ b/ui/menu/character_card.tscn @@ -0,0 +1,47 @@ +[gd_scene load_steps=2 format=3] + +[ext_resource type="Script" path="res://ui/menu/character_card.gd" id="script"] + +[node name="CharacterCard" type="Button"] +custom_minimum_size = Vector2(140, 184) +size_flags_horizontal = 3 +script = ExtResource("script") + +[node name="Content" type="MarginContainer" parent="."] +layout_mode = 1 +anchors_preset = 15 +anchor_right = 1.0 +anchor_bottom = 1.0 +mouse_filter = 2 +theme_override_constants/margin_left = 12 +theme_override_constants/margin_top = 8 +theme_override_constants/margin_right = 12 +theme_override_constants/margin_bottom = 10 + +[node name="Layout" type="VBoxContainer" parent="Content"] +layout_mode = 2 +mouse_filter = 2 +theme_override_constants/separation = 4 + +[node name="Portrait" type="TextureRect" parent="Content/Layout"] +custom_minimum_size = Vector2(0, 112) +layout_mode = 2 +size_flags_vertical = 3 +mouse_filter = 2 +texture_filter = 1 +expand_mode = 1 +stretch_mode = 5 + +[node name="Name" type="Label" parent="Content/Layout"] +layout_mode = 2 +mouse_filter = 2 +theme_override_font_sizes/font_size = 22 +text = "PERSONAJE" +horizontal_alignment = 1 + +[node name="Role" type="Label" parent="Content/Layout"] +layout_mode = 2 +mouse_filter = 2 +theme_override_font_sizes/font_size = 14 +text = "INTEGRANTE" +horizontal_alignment = 1 diff --git a/ui/menu/character_select.gd b/ui/menu/character_select.gd new file mode 100644 index 0000000..5208ae1 --- /dev/null +++ b/ui/menu/character_select.gd @@ -0,0 +1,27 @@ +extends VBoxContainer + +## Cuadricula fija de cuatro integrantes. No carga niveles ni conserva progreso. +signal character_chosen(character: CharacterData) +signal back_requested + +@onready var grid: GridContainer = $Scroll/Grid + + +func _ready() -> void: + $Back.pressed.connect(func() -> void: back_requested.emit()) + for child: Node in grid.get_children(): + var card: CharacterCard = child as CharacterCard + if card != null: + card.character_chosen.connect(_on_character_chosen) + + +func show_roster(level_name: String) -> void: + $LevelName.text = level_name + show() + $Scroll.scroll_vertical = 0 + if grid.get_child_count() > 0: + (grid.get_child(0) as Control).grab_focus() + + +func _on_character_chosen(character: CharacterData) -> void: + character_chosen.emit(character) diff --git a/ui/menu/character_select.tscn b/ui/menu/character_select.tscn new file mode 100644 index 0000000..6d984b2 --- /dev/null +++ b/ui/menu/character_select.tscn @@ -0,0 +1,54 @@ +[gd_scene load_steps=7 format=3] + +[ext_resource type="Script" path="res://ui/menu/character_select.gd" id="script"] +[ext_resource type="PackedScene" path="res://ui/menu/character_card.tscn" id="card"] +[ext_resource type="Resource" path="res://player/characters/guitarist.tres" id="diego"] +[ext_resource type="Resource" path="res://player/characters/drummer.tres" id="ivan"] +[ext_resource type="Resource" path="res://player/characters/bassist.tres" id="fer"] +[ext_resource type="Resource" path="res://player/characters/singer.tres" id="hector"] + +[node name="CharacterSelect" type="VBoxContainer"] +size_flags_vertical = 3 +theme_override_constants/separation = 12 +script = ExtResource("script") + +[node name="LevelName" type="Label" parent="."] +layout_mode = 2 +theme_override_font_sizes/font_size = 16 +text = "Elige quien entra en el nivel" +horizontal_alignment = 1 +autowrap_mode = 3 + +[node name="Scroll" type="ScrollContainer" parent="."] +layout_mode = 2 +size_flags_vertical = 3 +follow_focus = true +horizontal_scroll_mode = 0 + +[node name="Grid" type="GridContainer" parent="Scroll"] +layout_mode = 2 +size_flags_horizontal = 3 +theme_override_constants/h_separation = 12 +theme_override_constants/v_separation = 12 +columns = 2 + +[node name="Diego" parent="Scroll/Grid" instance=ExtResource("card")] +layout_mode = 2 +character_data = ExtResource("diego") + +[node name="Ivan" parent="Scroll/Grid" instance=ExtResource("card")] +layout_mode = 2 +character_data = ExtResource("ivan") + +[node name="Fer" parent="Scroll/Grid" instance=ExtResource("card")] +layout_mode = 2 +character_data = ExtResource("fer") + +[node name="Hector" parent="Scroll/Grid" instance=ExtResource("card")] +layout_mode = 2 +character_data = ExtResource("hector") + +[node name="Back" type="Button" parent="."] +custom_minimum_size = Vector2(0, 64) +layout_mode = 2 +text = "VOLVER A NIVELES" diff --git a/ui/menu/main_menu.gd b/ui/menu/main_menu.gd index 5eefe52..5d15081 100644 --- a/ui/menu/main_menu.gd +++ b/ui/menu/main_menu.gd @@ -4,6 +4,7 @@ extends Control ## Solo descubre escenas directamente dentro de levels, nunca sus subcarpetas. const LEVEL_DIRECTORY: String = "res://levels" +@onready var characters_panel: VBoxContainer = $Margin/Layout/Characters @onready var title_label: Label = $Margin/Layout/Title @onready var home_panel: VBoxContainer = $Margin/Layout/Home @onready var levels_panel: VBoxContainer = $Margin/Layout/Levels @@ -20,10 +21,17 @@ const LEVEL_DIRECTORY: String = "res://levels" @onready var loading_progress: ProgressBar = $Loading/Content/Progress var _loading_path: String = "" +var _selected_level_path: String = "" func _ready() -> void: set_process(false) + # Volver desde una meta o abandonar exige una nueva eleccion, no un guardado de personaje. + var session: RunSessionState = get_node_or_null("/root/RunSession") as RunSessionState + if session != null: + session.clear() + characters_panel.connect("back_requested", _show_levels) + characters_panel.connect("character_chosen", _on_character_chosen) play_button.pressed.connect(_show_levels) back_button.pressed.connect(_show_home) inventory_button.pressed.connect(_show_inventory) @@ -58,6 +66,8 @@ static func level_label(path: String) -> String: func _show_home() -> void: if not _loading_path.is_empty(): return + _selected_level_path = "" + characters_panel.hide() inventory_panel.hide() home_panel.show() levels_panel.hide() @@ -71,6 +81,8 @@ func _show_home() -> void: func _show_levels() -> void: if not _loading_path.is_empty(): return + _selected_level_path = "" + characters_panel.hide() for child: Node in level_list.get_children(): level_list.remove_child(child) child.queue_free() @@ -83,7 +95,7 @@ func _show_levels() -> void: button.size_flags_horizontal = Control.SIZE_EXPAND_FILL # El texto no fuerza el ancho: sigue cabiendo en pantallas estrechas. button.clip_text = true - button.pressed.connect(_load_level.bind(path)) + button.pressed.connect(_show_characters.bind(path)) level_list.add_child(button) empty_label.visible = paths.is_empty() inventory_panel.hide() @@ -102,15 +114,39 @@ func _show_inventory() -> void: return home_panel.hide() levels_panel.hide() + characters_panel.hide() error_label.hide() title_label.text = "OBJETOS RAROS" inventory_panel.call("show_collection") -## La pantalla de carga real no introduce otros diez segundos artificiales. -func _load_level(path: String) -> void: +## Elegir nivel no inicia su carga: primero se elige una de las cuatro tarjetas. +func _show_characters(path: String) -> void: if not _loading_path.is_empty(): return + _selected_level_path = path + home_panel.hide() + levels_panel.hide() + inventory_panel.hide() + error_label.hide() + title_label.text = "ELEGIR PERSONAJE" + characters_panel.call("show_roster", level_label(path)) + + +func _on_character_chosen(character: CharacterData) -> void: + if _selected_level_path.is_empty() or character == null: + return + _load_level(_selected_level_path, character) + + +## La pantalla de carga real no introduce otros diez segundos artificiales. +func _load_level(path: String, character: CharacterData) -> void: + if not _loading_path.is_empty(): + return + var session: RunSessionState = get_node_or_null("/root/RunSession") as RunSessionState + if session == null or character == null: + _show_load_error("No se pudo preparar la seleccion de personaje.") + return if not ResourceLoader.exists(path, "PackedScene"): _show_load_error("No se encuentra el nivel: " + path.get_file()) return @@ -119,6 +155,8 @@ func _load_level(path: String) -> void: _show_load_error("No se pudo iniciar la carga: " + error_string(error)) return _loading_path = path + session.begin_level(path, character) + characters_panel.hide() # Ocultar el panel tambien evita activaciones por teclado mientras se carga. levels_panel.hide() loading_panel.show() @@ -152,20 +190,33 @@ func _show_load_error(message: String) -> void: _loading_path = "" set_process(false) loading_panel.hide() - _show_levels() + var session: RunSessionState = get_node_or_null("/root/RunSession") as RunSessionState + if session != null: + session.clear() + if not _selected_level_path.is_empty() and ResourceLoader.exists(_selected_level_path, "PackedScene"): + _show_characters(_selected_level_path) + else: + _show_levels() error_label.text = message error_label.show() func _unhandled_input(event: InputEvent) -> void: - if event.is_action_pressed("ui_cancel") and _loading_path.is_empty() and (levels_panel.visible or inventory_panel.visible): - _show_home() + if event.is_action_pressed("ui_cancel") and _loading_path.is_empty(): + if characters_panel.visible: + _show_levels() + elif levels_panel.visible or inventory_panel.visible: + _show_home() + else: + return get_viewport().set_input_as_handled() func _notification(what: int) -> void: if what == NOTIFICATION_WM_GO_BACK_REQUEST and is_node_ready() and _loading_path.is_empty(): - if levels_panel.visible or inventory_panel.visible: + if characters_panel.visible: + _show_levels() + elif levels_panel.visible or inventory_panel.visible: _show_home() else: _quit_game() diff --git a/ui/menu/main_menu.tscn b/ui/menu/main_menu.tscn index c0dac80..b23f1cf 100644 --- a/ui/menu/main_menu.tscn +++ b/ui/menu/main_menu.tscn @@ -1,9 +1,10 @@ -[gd_scene load_steps=4 format=3] +[gd_scene load_steps=5 format=3] [ext_resource type="Script" path="res://ui/menu/main_menu.gd" id="script"] [ext_resource type="Theme" path="res://ui/menu/menu_theme.tres" id="theme"] [ext_resource type="PackedScene" path="res://ui/menu/rare_inventory.tscn" id="inventory"] +[ext_resource type="PackedScene" path="res://ui/menu/character_select.tscn" id="characters"] [node name="MainMenu" type="Control"] layout_mode = 3 @@ -103,6 +104,10 @@ text = "VOLVER" visible = false layout_mode = 2 +[node name="Characters" parent="Margin/Layout" instance=ExtResource("characters")] +visible = false +layout_mode = 2 + [node name="Error" type="Label" parent="Margin/Layout"] visible = false layout_mode = 2 -- 2.54.0