Mejoras en los enemigos

This commit is contained in:
Diego De la Viuda Llorente committed 2026-10-27 11:36:26 +01:00
1 parent 8a5290c5ef
commit 56f9b475b6
12 files changed
+631 -51

No files matched your search

+237
View File
@@ -0,0 +1,237 @@
extends SceneTree
## Real-engine integration checks; Python resource tests do not execute these.
## godot --headless --path . --script res://tests/test_enemy_ai_runtime.gd
var _failures: int = 0
var _checks: int = 0
var _world: Node2D
var _player: CharacterBody2D
var _enemy: CharacterBody2D
func _initialize() -> void:
call_deferred("_run")
func _run() -> void:
await _test_safe_start()
await _test_chasing_and_return()
await _test_jumping()
await _test_damage_and_push()
await _clear_world()
print("ENEMY AI: %d checks, %d failures" % [_checks, _failures])
quit(0 if _failures == 0 else 1)
func _test_safe_start() -> void:
var packed: PackedScene = load("res://levels/level_02.tscn") as PackedScene
if packed == null:
_check(false, "Level02 could not be loaded")
return
_world = packed.instantiate() as Node2D
if _world == null:
_check(false, "Level02 could not be instantiated")
return
root.add_child(_world)
current_scene = _world
_player = _world.get_node("Player") as CharacterBody2D
_player.set_physics_process(false)
var enemies: Node = _world.get_node("Enemies")
_check(enemies.get_child_count() == 29, "Keep all 29 encounters")
_check(is_equal_approx((enemies.get_node("Enemy01") as Node2D).position.x, 1260.0),
"First enemy was not relocated")
# Notifier callbacks do not run in headless mode. Waking EVERY enemy also
# proves that a wide window cannot bypass the new proximity check.
for node: Node in enemies.get_children():
node.set("is_awake", true)
await _frames(90)
_check(int(_player.get("current_health")) == 50, "No damage at the starting point")
for node: Node in enemies.get_children():
_check(not bool(node.get("_is_pursuing")), "Spawn aggro: " + str(node.name))
func _test_chasing_and_return() -> void:
if not await _arena("roadie", [Rect2(-500, 300, 1500, 200)], Vector2(100, 270), Vector2(350, 274)):
return
var result: Dictionary = await _advance(60)
_check(_enemy.position.x > 150.0, "Roadie must approach within detection range")
_check(float(result["minimum_y"]) > 260.0, "Roadie must never jump")
_player.position.x = 2000.0
await _advance(120)
_check(not bool(_enemy.get("_is_pursuing")), "Lose target outside the leash")
_check(absf(_enemy.position.x - 100.0) < 12.0, "Return towards spawn, do not teleport")
func _test_jumping() -> void:
var flat: Array[Rect2] = [Rect2(-500, 300, 1500, 200)]
if not await _arena("pogo_fan", flat, Vector2(100, 270), Vector2(430, 274)):
return
var pogo_result: Dictionary = await _advance(55)
_check(bool(pogo_result["jump_seen"]), "Pogo must hop while pursuing on flat ground")
_check(float(pogo_result["minimum_y"]) < 210.0, "Pogo must physically leave the floor")
_check(_enemy.position.x > 200.0, "Pogo jump must advance towards the target")
_player.position = _enemy.position + Vector2(40, 0)
_check(not bool(_enemy.call("_is_target_in_attack_trigger")), "Do not start ground sweeps in mid-air")
var step: Array[Rect2] = [Rect2(-500, 300, 700, 200), Rect2(200, 250, 800, 250)]
if not await _arena("rival_guitarist", step, Vector2(120, 270), Vector2(400, 224)):
return
await _advance(125)
_check(_enemy.position.x > 230.0 and _enemy.position.y < 235.0,
"Rival must climb a reachable step to continue chasing")
_check(_enemy.is_on_floor(), "Rival must land after climbing")
if not await _arena("roadie", step, Vector2(120, 270), Vector2(400, 224)):
return
var roadie_result: Dictionary = await _advance(125)
_check(not bool(roadie_result["jump_seen"]), "Roadie must not copy the rival's jump")
_check(_enemy.position.x < 200.0, "Roadie cannot pass through a solid step")
if not await _arena("rival_guitarist", flat, Vector2(100, 270), Vector2(240, 154),
[Rect2(120, 180, 220, 20)]):
return
await _advance(125)
_check(_enemy.position.y < 165.0 and _enemy.is_on_floor(),
"Reach and land on a one-way platform from below")
var gap: Array[Rect2] = [Rect2(-500, 300, 700, 200), Rect2(280, 300, 720, 200)]
if not await _arena("rival_guitarist", gap, Vector2(180, 270), Vector2(430, 274)):
return
await _advance(140)
_check(_enemy.position.x > 300.0 and _enemy.is_on_floor(), "Cross a small gap with a valid landing")
if not await _arena("rival_guitarist", [Rect2(-500, 300, 700, 200)],
Vector2(180, 270), Vector2(430, 274)):
return
var void_result: Dictionary = await _advance(100)
_check(not bool(void_result["jump_seen"]), "Do not jump without a landing")
_check(_enemy.position.x < 200.0 and _enemy.position.y < 290.0, "Do not walk into a bottomless gap")
var ceiling: Array[Rect2] = [Rect2(-500, 300, 1500, 200), Rect2(70, 165, 180, 30)]
if not await _arena("pogo_fan", ceiling, Vector2(100, 270), Vector2(430, 274)):
return
var ceiling_result: Dictionary = await _advance(20)
_check(not bool(ceiling_result["jump_seen"]), "No jump into a solid ceiling")
func _test_damage_and_push() -> void:
if not await _arena("backstage_guard", [Rect2(-500, 300, 1500, 200)],
Vector2(100, 270), Vector2(152, 274)):
return
_enemy.set_physics_process(false)
_enemy.call("_face_target")
_enemy.set("attack_direction", 1.0)
_enemy.call("_set_attack_hitbox_progress", 0.5)
await _frames(3)
# This puts the sweep centre PAST the player. Push must still be away from
# the enemy, not towards it. Exercise the real Area2D overlap path.
_enemy.call("_update_attack_damage")
_check(int(_player.get("current_health")) == 44, "Guard hit must deal six HP")
_check(is_equal_approx(_player.velocity.x, 558.0), "Guard must push away with 1.8x horizontal impulse")
_check(_player.velocity.y < -270.0, "Guard also has a slightly stronger upward impulse")
_player.set("invulnerability_timer", 0.0)
_enemy.call("_update_attack_damage")
_check(int(_player.get("current_health")) == 44, "One sweep must not hit twice")
_player.call("take_damage", 2, _enemy.global_position)
_check(int(_player.get("current_health")) == 42, "Old two-argument damage callers still work")
_check(is_equal_approx(_player.velocity.x, 310.0), "Default impulse remains unchanged")
_player.set("invulnerability_timer", 0.0)
_player.set("_shield_hits", 1)
_player.velocity = Vector2.ZERO
_player.call("take_damage", 6, _enemy.global_position, 1.8)
_check(int(_player.get("current_health")) == 42 and _player.velocity == Vector2.ZERO,
"A shield must block both damage and impulse")
_enemy.set("_jump_in_progress", true)
_enemy.call("take_damage", 1, _player.global_position)
_check(not bool(_enemy.get("_jump_in_progress")), "Hit must cancel jump steering, preserving knockback")
_enemy.call("take_damage", 100, _player.global_position)
_check(bool(_enemy.get("is_dead")) and _enemy.visible, "Retain the delayed death animation")
_enemy.call("_respawn")
_enemy.set_physics_process(false)
_check(not bool(_enemy.get("_is_pursuing")) and not bool(_enemy.get("_jump_in_progress")),
"Respawn must reset pursuit and jump state")
_check(is_zero_approx(float(_enemy.get("_jump_cooldown_timer"))), "Respawn must reset the jump cooldown")
func _arena(variant: String, floors: Array[Rect2], enemy_position: Vector2,
player_position: Vector2, one_way: Array[Rect2] = []) -> bool:
await _clear_world()
var player_scene: PackedScene = load("res://player/player.tscn") as PackedScene
var enemy_scene: PackedScene = load("res://enemies/variants/%s.tscn" % variant) as PackedScene
if player_scene == null or enemy_scene == null:
_check(false, "Cannot load arena resources: " + variant)
return false
_world = Node2D.new()
root.add_child(_world)
current_scene = _world
for bounds: Rect2 in floors:
_add_floor(bounds, false)
for bounds: Rect2 in one_way:
_add_floor(bounds, true)
_player = player_scene.instantiate() as CharacterBody2D
_player.position = player_position
_world.add_child(_player)
_player.set_physics_process(false)
_enemy = enemy_scene.instantiate() as CharacterBody2D
_enemy.position = enemy_position
_enemy.set("drops_handled_by_level", true)
_enemy.set("show_debug_enemy_info", false)
_world.add_child(_enemy)
_enemy.set("is_awake", false)
# Settle onto the floor before enabling pursuit. Ground sweep checks use
# the collision state from move_and_slide(), not merely the spawn position.
await _frames(10)
_enemy.set("attack_cooldown_timer", 1000.0)
_enemy.set("is_awake", true)
return true
func _add_floor(bounds: Rect2, one_way: bool) -> void:
var body := StaticBody2D.new()
body.position = bounds.get_center()
body.collision_layer = 1
body.collision_mask = 0
var collider := CollisionShape2D.new()
var shape := RectangleShape2D.new()
shape.size = bounds.size
collider.shape = shape
collider.one_way_collision = one_way
body.add_child(collider)
_world.add_child(body)
func _advance(count: int) -> Dictionary:
var minimum_y: float = _enemy.position.y
var jump_seen: bool = false
for _frame: int in range(count):
await _frames(1)
minimum_y = minf(minimum_y, _enemy.position.y)
jump_seen = jump_seen or bool(_enemy.get("_jump_in_progress"))
return {"minimum_y": minimum_y, "jump_seen": jump_seen}
func _frames(count: int) -> void:
for _frame: int in range(count):
await physics_frame
await process_frame
func _clear_world() -> void:
if is_instance_valid(_world):
_world.queue_free()
current_scene = null
await process_frame
await physics_frame
_world = null
_player = null
_enemy = null
func _check(condition: bool, message: String) -> void:
_checks += 1
if not condition:
_failures += 1
push_error(message)
+100
View File
@@ -0,0 +1,100 @@
"""Configuration regressions only; actual physics is tested by the .gd suite."""
from pathlib import Path
import math
import re
import unittest
ROOT = Path(__file__).resolve().parents[1]
VARIANTS = ROOT / 'enemies/variants'
LEVEL = (ROOT / 'levels/level_02.tscn').read_text(encoding='utf-8')
def properties(text):
result = {}
for key, value in re.findall(r'^(\w+) = ([^\n]+)$', text, re.M):
if value in ('true', 'false'):
result[key] = value == 'true'
elif re.fullmatch(r'-?\d+(?:\.\d+)?', value):
result[key] = float(value)
return result
class EnemyProfileTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.profiles = {p.stem: properties(p.read_text(encoding='utf-8'))
for p in VARIANTS.glob('*.tscn')}
def test_only_two_agile_variants_jump(self):
jumpers = {name for name, p in self.profiles.items() if p.get('can_jump', False)}
self.assertEqual(jumpers, {'pogo_fan', 'rival_guitarist'})
hoppers = {name for name, p in self.profiles.items() if p.get('hop_while_chasing', False)}
self.assertEqual(hoppers, {'pogo_fan'})
def test_chase_is_longer_but_not_unlimited(self):
for name, p in self.profiles.items():
self.assertGreater(p['chase_radius'], p['aggro_range'], name)
self.assertLessEqual(p['chase_radius'], 1100, name)
self.assertEqual(p['respawn_delay'], 0.0, name)
self.assertGreater(self.profiles['rival_guitarist']['move_speed'],
self.profiles['roadie']['move_speed'] * 2)
def test_difficulty_damage_and_push_are_distinct(self):
roadie = self.profiles['roadie']
guard = self.profiles['backstage_guard']
rival = self.profiles['rival_guitarist']
self.assertEqual(roadie['attack_damage'], 2)
self.assertEqual(guard['attack_damage'], 6)
self.assertGreater(guard['attack_knockback_multiplier'], rival['attack_knockback_multiplier'])
self.assertGreater(rival['attack_knockback_multiplier'], roadie['attack_knockback_multiplier'])
self.assertGreater(guard['max_health'], roadie['max_health'])
for p in self.profiles.values():
self.assertLessEqual(p['attack_damage'], 6)
self.assertLessEqual(p['attack_knockback_multiplier'], 1.8)
self.assertGreaterEqual(p['attack_windup_duration'], 0.28)
def test_heavy_enemies_do_not_take_two_second_stun_from_each_punch(self):
for name in ('backstage_guard', 'rival_guitarist'):
profile = self.profiles[name]
self.assertGreater(profile['stun_damage_threshold'], 5)
self.assertLessEqual(profile['strong_hit_stun_duration'], 0.9)
def test_first_enemy_relocated_without_deleting_encounters(self):
enemies = re.findall(
r'\[node name="(Enemy\d+)" parent="Enemies" instance=ExtResource\("enemy_([^"]+)"\)\]\n'
r'position = Vector2\(([^,]+), ([^)]+)\)', LEVEL)
self.assertEqual(len(enemies), 29)
self.assertEqual(len({e[0] for e in enemies}), 29)
first = next(e for e in enemies if e[0] == 'Enemy01')
self.assertEqual((float(first[2]), float(first[3])), (1260, 811))
# Even with a wide screen waking every notifier, no enemy starts in aggro range.
for name, variant, x, y in enemies:
distance = math.hypot(float(x) - 125.0, float(y) - 795.0)
self.assertGreater(distance - self.profiles[variant]['aggro_range'], 200.0, name)
def test_jumps_can_climb_the_street_steps(self):
heights = [float(y) - 250 for y in re.findall(
r'parent="World/Ground"\]\nposition = Vector2\([^,]+, ([^)]+)\)', LEVEL)]
largest_step = max(a - b for a, b in zip(heights, heights[1:]))
for name in ('pogo_fan', 'rival_guitarist'):
jump = self.profiles[name]['jump_velocity']
self.assertGreater(jump * jump / (2.0 * 980.0) - 10, largest_step)
def test_attack_phases_leave_a_readable_pause(self):
for name, p in self.profiles.items():
phases = p['attack_windup_duration'] + p.get('attack_duration', 0.22) + p.get('attack_recovery_duration', 0.30)
self.assertLess(phases, p['attack_interval'], name)
def test_lab_keeps_its_small_leash(self):
lab = (ROOT / 'levels/level_01.gd').read_text(encoding='utf-8')
self.assertIn('enemy.set("chase_radius", 135.0)', lab)
def test_damage_api_keeps_old_callers_compatible(self):
player = (ROOT / 'player/player.gd').read_text(encoding='utf-8')
self.assertIn('knockback_multiplier: float = 1.0', player)
enemy = (ROOT / 'enemies/walker/walker.gd').read_text(encoding='utf-8')
self.assertIn('take_damage(attack_damage, global_position, attack_knockback_multiplier)', enemy)
if __name__ == '__main__':
unittest.main()
+2 -1
View File
@@ -43,7 +43,8 @@ class Level01ConfigurationTests(unittest.TestCase):
scene_path = self.by_id[station[1]]
enemy_scene = (ROOT / scene_path).read_text(encoding="utf-8")
self.assertIn("respawn_delay = 0.0", enemy_scene)
self.assertIn("chase_radius = 135.0", enemy_scene)
level_code = (ROOT / "levels/level_01.gd").read_text(encoding="utf-8")
self.assertIn('enemy.set("chase_radius", 135.0)', level_code)
def test_floor_covers_all_encounters_and_finish(self):
xs = [float(station[2]) for station in self.stations]