From e1e29f02f12b3ba138393e716e7c3b94cbeacb54 Mon Sep 17 00:00:00 2001 From: Diego De la Viuda Llorente Date: Wed, 21 Oct 2026 12:53:19 +0200 Subject: [PATCH] Fix para los items que no caen --- README.md | 14 ++++- docs/test_level_01.md | 60 +++++++++++++++------ enemies/walker/walker.gd | 13 +++-- levels/level_01.gd | 70 +++++++++++++++++++----- levels/level_01.tscn | 19 ++++++- pickups/data/lab_control.tres | 14 +++++ player/player.gd | 4 +- tests/test_level_01_resources.py | 13 +++++ tests/test_pickup_runtime.gd | 91 +++++++++++++++++++++----------- 9 files changed, 233 insertions(+), 65 deletions(-) create mode 100644 pickups/data/lab_control.tres diff --git a/README.md b/README.md index c796204..7efdb64 100644 --- a/README.md +++ b/README.md @@ -1975,12 +1975,24 @@ Catálogo, pesos, estados e instrucciones: **[docs/items.md](docs/items.md)**. Recorrido de Android (17 estaciones, orden y checklist): **[docs/test_level_01.md](docs/test_level_01.md)**. +**Diagnostico de objetos (LAB DROPS v2):** el nivel muestra en su HUD la +version activa, KOs observados, senales recibidas, drops creados y objetos +presentes en el suelo. Incluye un pickup de control al principio que no +depende de matar enemigos y no cuenta para los 17 objetos. El nivel de pruebas +crea las recompensas fijas al observar `is_dead`, una unica vez por enemigo; +los drops aleatorios fuera de este nivel no cambian. Esta correccion necesita +validacion real en Godot/Android: las comprobaciones estaticas no sustituyen +una partida. + + Comprobacion estatica reproducible (sin arrancar Godot): `python -m unittest discover -s tests -v`. Prueba de drops dentro del motor (necesita Godot instalado): `godot --headless --path . --script res://tests/test_pickup_runtime.gd`. -Esta comprobacion crea los 17 drops garantizados y verifica sus recursos, +Esta comprobacion fuerza 17 muertes, desconecta una senal de forma +intencionada y verifica el contador de KOs, los 17 drops, el pickup de +control y que no se dupliquen recursos, iconos y presencia en escena. Los pickups se generan fuera de la fase de colisiones y no se pueden recoger durante sus primeros 0,75 segundos. diff --git a/docs/test_level_01.md b/docs/test_level_01.md index 55d0687..8b2278d 100644 --- a/docs/test_level_01.md +++ b/docs/test_level_01.md @@ -7,7 +7,13 @@ APK sin alterar el codigo entre partidas. Es la escena inicial configurada en `project.godot`. - **17 enemigos / 17 objetos diferentes**, uno por enemigo, en este orden. +- Un **pickup de control adicional** (x=270) aparece sin matar a nadie: + sirve para diferenciar un problema de dibujo/recogida de uno de muerte/drop. + Es un objeto de pruebas (`lab_control.tres`) y **no cuenta** entre los 17. - Cada enemigo suelta **siempre** su objeto asignado al morir y **no reaparece**. + En este laboratorio, el nivel observa `is_dead` y crea el objeto **una vez**; + no depende de la senal `died` ni de la tabla aleatoria. En otras escenas, + Walker mantiene intactos sus drops habituales. - La tabla normal `enemies/walker/walker_drop.tres` conserva su 50% aleatorio en las otras escenas (no se ha desactivado globalmente). - Suelo continuo para no quedarse atascado, con 7 plataformas opcionales. @@ -44,6 +50,16 @@ APK sin alterar el codigo entre partidas. Es la escena inicial configurada en ## Que comprobar en la APK +- [ ] Antes de matar a nadie debe verse un objeto con el cartel + **CONTROL: objeto SIN matar**. Al recogerlo se concede un escudo, pero + el contador de los 17 objetos de estaciones no cambia. +- [ ] En la esquina superior derecha se ve **LAB DROPS v2**. Si aparece + **script SIN iniciar**, el `level_01.gd` no se ha ejecutado. Si no aparece + **LAB DROPS v2**, estas usando otra version del proyecto/APK. +- [ ] Al matar el primer enemigo: `KOs: 01`, `Creados: 01` y `Suelo` suma + un pickup (salvo que ya se haya recogido). `Senales` es un diagnostico + adicional, no controla los drops. + - [ ] La APK abre directamente `level_01`, se puede caminar a derecha durante todo el nivel y la camara no se detiene en x=4000. - [ ] Los 17 enemigos tienen apariencia humanoide visible y ataques legibles. @@ -100,26 +116,40 @@ Para generar un APK en un entorno que tenga Godot y el SDK Android configurados: El script admite una ruta de salida opcional; por defecto escribe `build/android/mortal-maze-debug.apk`. No se ha compilado la APK aqui. -## Diagnostico de los drops +## Diagnostico de los drops (version 2) -El HUD muestra **KOs**, **DROPS EN SUELO** y **objetos recogidos** por separado. -Al matar al primer enemigo deberias ver 1 KO y, durante al menos 0,75 s, -un objeto visible en el suelo. Tras recogerlo, el numero de recogidos sube -si su efecto puede aplicarse. Los objetos de curacion no se consumen a vida -completa y los de carga especial no se consumen con la barra llena. +**Orden de comprobacion, sin modificar el proyecto:** -Los pickups se agregan al arbol **en diferido** porque un enemigo puede morir -mientras Godot procesa colisiones. Nacen con la deteccion desactivada y la -activan 0,75 s mas tarde para evitar recogidas instantaneas invisibles. +1. Al entrar en el nivel, verifica que el HUD empieza con `LAB DROPS v2`. + Si pone `script SIN iniciar`, hay un problema de carga de `level_01.gd`. + Si no pone `LAB DROPS v2`, no estas ejecutando esta version del nivel. +2. Sin matar a nadie, camina a la derecha hasta el objeto **CONTROL** (x=270). + Es una instancia directa de `pickup.tscn`. Si tampoco aparece, el fallo + esta en el renderizado/instanciacion del pickup, no en los drops de enemigos. +3. Mata al primer enemigo. El HUD distingue **KOs** (enemigos observados + muertos), **Senales** (senales `died` recibidas), **Creados** (objetos + solicitados) y **Suelo** (pickups vivos, incluido el de control). + - `KOs=0`, `Senales=0`: el estado `is_dead` no ha cambiado, o el codigo del + nivel no se esta ejecutando. Comprueba que el enemigo se vuelva invisible + y que su barra de vida se agote. + - `KOs=1`, `Creados=1`, pero no hay objeto: el problema esta en la creacion + o el dibujo del pickup. Mira las lineas `LAB DROPS v2:` de la consola. + - `KOs=1`, `Senales=0`, `Creados=1`: la senal se perdio, pero el laboratorio + ha creado el objeto igualmente gracias a la observacion de `is_dead`. -Si en el HUD suben los KOs pero los objetos en suelo siguen en cero y no -suben los recogidos, comprueba si aparecen errores de `guaranteed_drop` al -abrir el nivel y ejecuta la prueba de integracion con Godot: +El objeto de control concede escudo y **no cuenta** entre las 17 recompensas. +Las curaciones y cargas de especial no pueden recogerse si esas barras estan +llenas; no es un fallo del drop. Un nuevo pickup espera 0,75 s antes de ser +recogible y permanece en el suelo indefinidamente. + +Pruebas automaticas (con Godot 4.7 instalado e iconos SVG importados): ```bash +godot --headless --path . --editor --quit godot --headless --path . --script res://tests/test_pickup_runtime.gd ``` -Esta prueba mata los 17 enemigos, espera a que se creen sus drops y verifica -que los 17 recursos diferentes existen, son visibles y tienen icono. No -reemplaza la comprobacion visual en Android. +La prueba desconecta **una** senal `died` intencionadamente y verifica que se +siguen creando exactamente los 17 drops, que el contador marca 17 KOs, que +existe el pickup de control y que no hay duplicados. Esta prueba **no se ha +podido ejecutar en este entorno**: aqui no existe el ejecutable de Godot. diff --git a/enemies/walker/walker.gd b/enemies/walker/walker.gd index 9d0b829..b426b78 100644 --- a/enemies/walker/walker.gd +++ b/enemies/walker/walker.gd @@ -98,6 +98,10 @@ enum AttackState { ## object drops with 100% probability INSTEAD of the random table. @export var guaranteed_drop: PickupData +## In the Android lab, Level01 watches deaths and spawns the fixed reward. +## Other levels keep using this enemy's own random/guaranteed drop logic. +var drops_handled_by_level: bool = false + @export_category("Respawn") @@ -510,10 +514,11 @@ func _die() -> void: # Test encounters always drop their assigned item, including the two items # absent from the normal Walker table. Other levels keep their random loot. var drops: Array[PickupData] = [] - if guaranteed_drop != null: - drops.append(guaranteed_drop) - elif drop_table != null: - drops = DROP_MANAGER.roll_drop(drop_table) + if not drops_handled_by_level: + if guaranteed_drop != null: + drops.append(guaranteed_drop) + elif drop_table != null: + drops = DROP_MANAGER.roll_drop(drop_table) if not drops.is_empty(): var parent: Node = get_tree().current_scene if parent == null: diff --git a/levels/level_01.gd b/levels/level_01.gd index 97044cd..22a477f 100644 --- a/levels/level_01.gd +++ b/levels/level_01.gd @@ -1,14 +1,18 @@ extends Node2D ## Android test course: 17 stations / 17 different guaranteed items. -## Encounters are configured in the scene, not spawned by code, so designers can -## freely move a station or switch its drop in the Godot inspector. +## Encounters are configured in the scene, not spawned by code. +## This laboratory intentionally owns fixed drops: each death is observed from +## the actual is_dead state, even when a died signal is missed. signal level_completed const TEST_ITEM_COUNT: int = 17 const LEVEL_WIDTH: int = 8500 const FINISH_RESTART_SECONDS: float = 8.0 +const LAB_BUILD: String = "LAB DROPS v2" +const CONTROL_ITEM_ID: StringName = &"lab_control" +const PICKUP_SCENE: PackedScene = preload("res://pickups/pickup.tscn") @onready var player: Node2D = $Player @onready var test_enemies: Node2D = $TestEnemies @@ -17,11 +21,17 @@ const FINISH_RESTART_SECONDS: float = 8.0 var collected_items: Dictionary = {} # PickupData.id -> true; count each only once var defeated_enemies: int = 0 +var death_signals: int = 0 +var spawned_drops: int = 0 +var _processed_deaths: Dictionary = {} # enemy instance id -> true var showing_victory: bool = false var victory_timer: float = 0.0 func _ready() -> void: + # These two markers distinguish an actually loaded script from an old APK. + status_label.text = "%s: script iniciado" % LAB_BUILD + print("%s: Level01 script iniciado" % LAB_BUILD) finish_message.visible = false # Player Camera2D sets its own provisional limit (4000) in _ready. # Override it here, after child _ready, for the long Android route. @@ -32,15 +42,22 @@ func _ready() -> void: $DeathZone.body_entered.connect(_on_death_entered) player.connect(&"pickup_collected", _on_pickup_collected) for enemy in test_enemies.get_children(): - # Catch missing scene overrides as soon as the level starts rather than - # silently falling back to the normal random drop table. + # The laboratory, not Walker, owns the fixed drop. Only this level sets + # the flag: normal enemies still generate their usual random drops. + enemy.set("drops_handled_by_level", true) if enemy.get("guaranteed_drop") == null: push_error("%s has no guaranteed_drop assigned." % enemy.name) - enemy.died.connect(_on_station_enemy_died) + if enemy.has_signal(&"died"): + enemy.connect(&"died", _on_station_enemy_died) + else: + push_error("%s no expone la senal died" % enemy.name) _update_status() func _process(delta: float) -> void: + # Do not depend on the died signal to count KOs or create the object. + # A transition to is_dead can only be processed once per enemy. + _process_station_deaths() if showing_victory: victory_timer += delta if victory_timer >= FINISH_RESTART_SECONDS: @@ -65,21 +82,50 @@ func _update_status() -> void: next_item = data.display_name break - # Two independent counters reveal whether an object failed to spawn or - # simply got collected. Useful for diagnosing drops on an Android APK. + # S is the number of died signals received. KOs come from is_dead, + # not signals. A difference between them pinpoints a signal problem. var loose_drops: int = get_tree().get_nodes_in_group("pickup").size() - status_label.text = "LAB: %02d/%02d objetos | %02d KOs\nDROPS EN SUELO: %02d\nSIGUIENTE: %s" % [ - collected_items.size(), TEST_ITEM_COUNT, defeated_enemies, - loose_drops, next_item + status_label.text = "%s | %02d/%02d objetos\nKOs: %02d | Senales: %02d | Creados: %02d | Suelo: %02d\nSIGUIENTE: %s" % [ + LAB_BUILD, collected_items.size(), TEST_ITEM_COUNT, + defeated_enemies, death_signals, spawned_drops, loose_drops, next_item ] +func _process_station_deaths() -> void: + for enemy in test_enemies.get_children(): + if not bool(enemy.get("is_dead")): + continue + var instance_id: int = enemy.get_instance_id() + if _processed_deaths.has(instance_id): + continue + _processed_deaths[instance_id] = true + defeated_enemies += 1 + + var data: PickupData = enemy.get("guaranteed_drop") as PickupData + if data == null: + push_error("%s: %s ha muerto sin objeto asignado" % [LAB_BUILD, enemy.name]) + continue + + # Adding an Area2D during a physics step is unsafe. Set position and + # data before adding it, then defer its entry into the scene tree. + var pickup: Pickup = PICKUP_SCENE.instantiate() as Pickup + pickup.pickup_data = data + pickup.position = to_local(enemy.global_position + Vector2(34.0, -12.0)) + call_deferred("add_child", pickup) + spawned_drops += 1 + print("%s: KO %s -> %s" % [LAB_BUILD, enemy.name, data.display_name]) + + func _on_station_enemy_died() -> void: - defeated_enemies += 1 - _update_status() + # Diagnostic counter only; the actual reward is managed above. + death_signals += 1 func _on_pickup_collected(data: PickupData) -> void: + # The extra pickup at the start checks rendering and collection independently + # of enemy deaths. It is not one of the 17 rewards. + if data.id == CONTROL_ITEM_ID: + return # A heal at full HP or a charge item with a full meter isn't consumed and # doesn't count. The object remains on the floor for later collection. collected_items[data.id] = true diff --git a/levels/level_01.tscn b/levels/level_01.tscn index 8e6cf77..a96ae35 100644 --- a/levels/level_01.tscn +++ b/levels/level_01.tscn @@ -1,8 +1,10 @@ -[gd_scene load_steps=31 format=3] +[gd_scene load_steps=33 format=3] [ext_resource type="PackedScene" path="res://player/player.tscn" id="1_player"] [ext_resource type="PackedScene" path="res://ui/mobile_controls/mobile_controls.tscn" id="2_mobile"] [ext_resource type="Script" path="res://levels/level_01.gd" id="3_level"] +[ext_resource type="PackedScene" path="res://pickups/pickup.tscn" id="4_pickup"] +[ext_resource type="Resource" path="res://pickups/data/lab_control.tres" id="lab_control"] [ext_resource type="PackedScene" path="res://enemies/variants/roadie.tscn" id="v0"] [ext_resource type="PackedScene" path="res://enemies/variants/pogo_fan.tscn" id="v1"] [ext_resource type="PackedScene" path="res://enemies/variants/feedback_tech.tscn" id="v2"] @@ -85,6 +87,19 @@ position = Vector2(140, 557) show_debug_hitboxes = false special_radius = 290.0 +[node name="ControlPickup" parent="." instance=ExtResource("4_pickup")] +position = Vector2(270, 548) +pickup_data = ExtResource("lab_control") + +[node name="ControlSign" type="Label" parent="."] +offset_left = 173.0 +offset_top = 461.0 +offset_right = 368.0 +offset_bottom = 500.0 +text = "CONTROL: objeto SIN matar" +horizontal_alignment = 1 +theme_override_font_sizes/font_size = 11 + [node name="TestEnemies" type="Node2D" parent="."] [node name="Station01" parent="TestEnemies" instance=ExtResource("v0")] @@ -419,7 +434,7 @@ theme_override_colors/font_shadow_color = Color(0.02, 0.02, 0.02, 0.95) theme_override_constants/shadow_offset_x = 2 theme_override_constants/shadow_offset_y = 2 theme_override_font_sizes/font_size = 17 -text = "LAB THRASH 00 / 17" +text = "LAB DROPS v2: script SIN iniciar" horizontal_alignment = 2 [node name="FinishMessage" type="Label" parent="TestHUD/Overlay"] diff --git a/pickups/data/lab_control.tres b/pickups/data/lab_control.tres new file mode 100644 index 0000000..57ad9fd --- /dev/null +++ b/pickups/data/lab_control.tres @@ -0,0 +1,14 @@ +[gd_resource type="Resource" script_class="PickupData" load_steps=3 format=3] + +[ext_resource type="Script" path="res://pickups/pickup_data.gd" id="1_data"] +[ext_resource type="Texture2D" path="res://assets/pickups/cinta_americana.svg" id="2_icon"] + +[resource] +script = ExtResource("1_data") +id = &"lab_control" +display_name = "Testigo del Laboratorio" +description = "Un objeto de control para comprobar los pickups sin combatir." +icon = ExtResource("2_icon") +color = Color("#a1c1cc") +effect_type = "shield" +value = 1.0 diff --git a/player/player.gd b/player/player.gd index a1bccd5..2010781 100644 --- a/player/player.gd +++ b/player/player.gd @@ -609,7 +609,9 @@ func _update_floating_texts(delta: float) -> void: func _connect_to_enemies() -> void: for enemy in get_tree().get_nodes_in_group("enemy"): if is_instance_valid(enemy) and enemy.has_signal(&"died"): - enemy.died.connect(_on_enemy_died.bind(enemy)) + # The group yields Node references, not a statically typed Walker. + # Node.connect also works with any future enemy exposing this signal. + enemy.connect(&"died", _on_enemy_died.bind(enemy)) func _on_enemy_died(enemy: Node) -> void: diff --git a/tests/test_level_01_resources.py b/tests/test_level_01_resources.py index 0e81b93..e440eae 100644 --- a/tests/test_level_01_resources.py +++ b/tests/test_level_01_resources.py @@ -72,6 +72,19 @@ class Level01ConfigurationTests(unittest.TestCase): self.assertEqual(root.attrib["viewBox"], "0 0 32 56") self.assertTrue(len(root) > 20, svg.name) + def test_control_pickup_and_death_tracking_are_separate(self): + # The independent control object distinguishes a rendering fault from + # a death/drop fault without relying on running the Python test in Godot. + self.assertIn('name="ControlPickup"', self.scene) + self.assertIn('pickup_data = ExtResource("lab_control")', self.scene) + self.assertTrue((ROOT / 'pickups/data/lab_control.tres').is_file()) + level_code = (ROOT / 'levels/level_01.gd').read_text(encoding='utf-8') + enemy_code = (ROOT / 'enemies/walker/walker.gd').read_text(encoding='utf-8') + self.assertIn('_process_station_deaths()', level_code) + self.assertIn('enemy.get("is_dead")', level_code) + self.assertIn('call_deferred("add_child", pickup)', level_code) + self.assertIn('drops_handled_by_level', enemy_code) + def test_all_external_scene_references_exist(self): for path in self.resources: self.assertTrue((ROOT / path).is_file(), path) diff --git a/tests/test_pickup_runtime.gd b/tests/test_pickup_runtime.gd index 63b7a6c..9b19d26 100644 --- a/tests/test_pickup_runtime.gd +++ b/tests/test_pickup_runtime.gd @@ -1,68 +1,99 @@ extends SceneTree -## Godot integration smoke test. Run from the project root with: -## godot --headless --path . --script res://tests/test_pickup_runtime.gd -## It checks actual instantiation after enemy death, not merely text in a .tscn. +## Full Godot integration test. Requires the real engine and imported SVGs. +## Run: godot --headless --path . --script res://tests/test_pickup_runtime.gd + func _initialize() -> void: call_deferred("_run") func _run() -> void: - var packed_level := load("res://levels/level_01.tscn") as PackedScene + var packed_level: PackedScene = load("res://levels/level_01.tscn") as PackedScene if packed_level == null: - _fail("Could not load Level 01") + _fail("No se pudo cargar level_01") return - var level := packed_level.instantiate() + var level: Node2D = packed_level.instantiate() as Node2D root.add_child(level) current_scene = level await process_frame - var enemies := level.get_node("TestEnemies").get_children() + var status: Label = level.get_node("TestHUD/Overlay/Status") as Label + if not status.text.contains("LAB DROPS v2"): + _fail("No se esta ejecutando level_01.gd") + return + + # The pre-placed control pickup must work even without any enemy death. + var control: Pickup = level.get_node("ControlPickup") as Pickup + if control == null or control.pickup_data == null or control.pickup_data.id != &"lab_control": + _fail("El pickup de control no se instancio") + return + if not control.visible or control.get_node("Sprite2D").texture == null: + _fail("El pickup de control no tiene icono visible") + return + + var enemies: Array[Node] = level.get_node("TestEnemies").get_children() if enemies.size() != 17: - _fail("Expected 17 test enemies, found %d" % enemies.size()) + _fail("Se esperaban 17 enemigos, hay %d" % enemies.size()) return var expected_ids: Dictionary = {} for enemy in enemies: - var item: PickupData = enemy.get("guaranteed_drop") as PickupData - if item == null: - _fail("Missing guaranteed_drop on %s" % enemy.name) + var data: PickupData = enemy.get("guaranteed_drop") as PickupData + if data == null or not bool(enemy.get("drops_handled_by_level")): + _fail("Configuracion de drop incorrecta: %s" % enemy.name) return - expected_ids[item.id] = true - # Force a kill independently of enemy movement, AI and the camera. + expected_ids[data.id] = true + + # Simulate a missed signal for station 01. The polling of is_dead must + # still register its KO and create the guaranteed drop. + var lab_callback: Callable = Callable(level, "_on_station_enemy_died") + enemies[0].disconnect(&"died", lab_callback) + for enemy in enemies: enemy.call("take_damage", int(enemy.get("max_health")), Vector2.ZERO) - # Deferred add_child runs during the idle step, after the physics callback. - await create_timer(0.2).timeout - var pickups := get_nodes_in_group("pickup") - if pickups.size() != 17: - _fail("Expected 17 spawned pickups, found %d" % pickups.size()) + await create_timer(0.25).timeout + if level.defeated_enemies != 17 or level.spawned_drops != 17: + _fail("KO/drops incorrectos: %d KOs, %d drops" % [level.defeated_enemies, level.spawned_drops]) + return + if level.death_signals != 16: + _fail("Se esperaban 16 senales despues de desconectar una, hay %d" % level.death_signals) return - var spawned_ids: Dictionary = {} + var pickups: Array[Node] = get_nodes_in_group("pickup") + if pickups.size() != 18: + _fail("Se esperaban 17 drops mas el control, hay %d" % pickups.size()) + return + + var actual_ids: Dictionary = {} for node in pickups: - var pickup := node as Pickup - if pickup == null or pickup.pickup_data == null: - _fail("Spawned a pickup without PickupData") + var pickup: Pickup = node as Pickup + if pickup == null or pickup.pickup_data == null or not pickup.visible: + _fail("Hay un pickup invalido o invisible") return - if not pickup.visible or pickup.get_node("Sprite2D").texture == null: - _fail("Pickup has no visible sprite: %s" % pickup.pickup_data.id) + if pickup.get_node("Sprite2D").texture == null: + _fail("Pickup sin icono: %s" % pickup.pickup_data.id) return if pickup.monitoring: - _fail("Pickup collection activated before grace period: %s" % pickup.pickup_data.id) + _fail("Pickup activo antes de los 0.75 s: %s" % pickup.pickup_data.id) return - spawned_ids[pickup.pickup_data.id] = true + if pickup.pickup_data.id != &"lab_control": + actual_ids[pickup.pickup_data.id] = true - if spawned_ids.size() != expected_ids.size() or spawned_ids != expected_ids: - _fail("Drops do not match the 17 assigned resources") + if actual_ids != expected_ids: + _fail("Los 17 drops no corresponden a las estaciones") return - print("OK: all 17 guaranteed drops spawned, visible and correctly assigned.") + await create_timer(0.2).timeout + if get_nodes_in_group("pickup").size() != 18: + _fail("Se duplicaron o perdieron drops al procesar frames adicionales") + return + + print("OK LAB DROPS v2: 17 KOs, 17 recompensas distintas, 1 control, 1 senal desconectada") quit(0) func _fail(message: String) -> void: - push_error("Pickup runtime test: " + message) + push_error("Prueba runtime de pickups: " + message) quit(1)