From 56f9b475b6a2bb39f2d5735cfbd85a5773bdf7ee Mon Sep 17 00:00:00 2001 From: Diego De la Viuda Llorente Date: Tue, 27 Oct 2026 11:36:26 +0100 Subject: [PATCH] Mejoras en los enemigos --- enemies/variants/backstage_guard.tscn | 20 ++- enemies/variants/feedback_tech.tscn | 17 +- enemies/variants/pogo_fan.tscn | 21 ++- enemies/variants/rival_guitarist.tscn | 23 ++- enemies/variants/roadie.tscn | 11 +- enemies/walker/walker.gd | 233 ++++++++++++++++++++++--- levels/level_01.gd | 2 + levels/level_02.tscn | 2 +- player/player.gd | 13 +- tests/test_enemy_ai_runtime.gd | 237 ++++++++++++++++++++++++++ tests/test_enemy_profiles.py | 100 +++++++++++ tests/test_level_01_resources.py | 3 +- 12 files changed, 631 insertions(+), 51 deletions(-) create mode 100644 tests/test_enemy_ai_runtime.gd create mode 100644 tests/test_enemy_profiles.py diff --git a/enemies/variants/backstage_guard.tscn b/enemies/variants/backstage_guard.tscn index 1ab7961..4d311f5 100644 --- a/enemies/variants/backstage_guard.tscn +++ b/enemies/variants/backstage_guard.tscn @@ -5,10 +5,22 @@ [node name="Walker" instance=ExtResource("1_walker")] enemy_display_name = "Guardia del Camerino" -move_speed = 70.0 -max_health = 21 -attack_damage = 3 -chase_radius = 135.0 +move_speed = 90.0 +max_health = 28 +attack_damage = 6 +aggro_range = 390.0 +chase_radius = 650.0 +attack_knockback_multiplier = 1.8 +attack_trigger_distance = 110.0 +attack_reach = 95.0 +attack_vertical_tolerance = 42.0 +attack_interval = 2.2 +attack_windup_duration = 0.6 +attack_duration = 0.26 +attack_recovery_duration = 0.55 +stun_damage_threshold = 10 +hit_stun_duration = 0.12 +strong_hit_stun_duration = 0.9 respawn_delay = 0.0 show_debug_hitboxes = false diff --git a/enemies/variants/feedback_tech.tscn b/enemies/variants/feedback_tech.tscn index 324e698..0797f70 100644 --- a/enemies/variants/feedback_tech.tscn +++ b/enemies/variants/feedback_tech.tscn @@ -5,10 +5,21 @@ [node name="Walker" instance=ExtResource("1_walker")] enemy_display_name = "Tecnico del Feedback" -move_speed = 55.0 +move_speed = 70.0 max_health = 16 -attack_damage = 2 -chase_radius = 135.0 +attack_damage = 4 +aggro_range = 380.0 +chase_radius = 650.0 +attack_knockback_multiplier = 1.25 +attack_trigger_distance = 175.0 +attack_reach = 160.0 +attack_vertical_tolerance = 40.0 +attack_interval = 1.7 +attack_windup_duration = 0.48 +attack_duration = 0.3 +stun_damage_threshold = 8 +hit_stun_duration = 0.18 +strong_hit_stun_duration = 1.2 respawn_delay = 0.0 show_debug_hitboxes = false diff --git a/enemies/variants/pogo_fan.tscn b/enemies/variants/pogo_fan.tscn index c8b5121..fe966b2 100644 --- a/enemies/variants/pogo_fan.tscn +++ b/enemies/variants/pogo_fan.tscn @@ -5,10 +5,25 @@ [node name="Walker" instance=ExtResource("1_walker")] enemy_display_name = "Fan del Pogo Eterno" -move_speed = 105.0 +move_speed = 175.0 max_health = 11 -attack_damage = 2 -chase_radius = 135.0 +attack_damage = 3 +aggro_range = 420.0 +chase_radius = 900.0 +attack_knockback_multiplier = 1.1 +can_jump = true +jump_velocity = -560.0 +jump_cooldown = 0.95 +hop_while_chasing = true +attack_trigger_distance = 80.0 +attack_reach = 68.0 +attack_vertical_tolerance = 42.0 +attack_interval = 1.35 +attack_windup_duration = 0.3 +attack_recovery_duration = 0.28 +stun_damage_threshold = 7 +hit_stun_duration = 0.18 +strong_hit_stun_duration = 1.2 respawn_delay = 0.0 show_debug_hitboxes = false diff --git a/enemies/variants/rival_guitarist.tscn b/enemies/variants/rival_guitarist.tscn index aa17f6c..d047976 100644 --- a/enemies/variants/rival_guitarist.tscn +++ b/enemies/variants/rival_guitarist.tscn @@ -5,10 +5,25 @@ [node name="Walker" instance=ExtResource("1_walker")] enemy_display_name = "Guitarrista Rival" -move_speed = 87.0 -max_health = 17 -attack_damage = 3 -chase_radius = 135.0 +move_speed = 200.0 +max_health = 22 +attack_damage = 5 +aggro_range = 500.0 +chase_radius = 1100.0 +attack_knockback_multiplier = 1.45 +can_jump = true +jump_velocity = -610.0 +jump_cooldown = 0.75 +attack_trigger_distance = 100.0 +attack_reach = 86.0 +attack_vertical_tolerance = 42.0 +attack_interval = 1.2 +attack_windup_duration = 0.28 +attack_duration = 0.2 +attack_recovery_duration = 0.28 +stun_damage_threshold = 8 +hit_stun_duration = 0.14 +strong_hit_stun_duration = 0.8 respawn_delay = 0.0 show_debug_hitboxes = false diff --git a/enemies/variants/roadie.tscn b/enemies/variants/roadie.tscn index 9dd6fab..7d3ebf6 100644 --- a/enemies/variants/roadie.tscn +++ b/enemies/variants/roadie.tscn @@ -5,10 +5,17 @@ [node name="Walker" instance=ExtResource("1_walker")] enemy_display_name = "Roadie del Mas Alla" -move_speed = 65.0 +move_speed = 70.0 max_health = 14 attack_damage = 2 -chase_radius = 135.0 +aggro_range = 300.0 +chase_radius = 520.0 +attack_knockback_multiplier = 0.85 +attack_trigger_distance = 95.0 +attack_reach = 82.0 +attack_vertical_tolerance = 42.0 +attack_interval = 2.0 +attack_windup_duration = 0.45 respawn_delay = 0.0 show_debug_hitboxes = false diff --git a/enemies/walker/walker.gd b/enemies/walker/walker.gd index c19d5c2..8fb82fd 100644 --- a/enemies/walker/walker.gd +++ b/enemies/walker/walker.gd @@ -4,9 +4,8 @@ extends CharacterBody2D signal died -# First real enemy on purpose: no generic Enemy base class yet. -# Once a second/third enemy exists, we can extract only the behaviour they -# actually share instead of guessing an abstraction in advance. +# The five scene variants share this controller. Their movement, jump and +# attack settings live in enemies/variants; no separate AI hierarchy is needed. const PLAYER_HURTBOX_MASK: int = 1 << 3 const DROP_MANAGER := preload("res://pickups/drop_manager.gd") @@ -30,6 +29,19 @@ enum AttackState { @export var move_speed: float = 78.0 @export var max_fall_speed: float = 800.0 +## Seeing an enemy on screen wakes it, but proximity starts the pursuit. +## Once engaged it keeps chasing up to 1.5 times this distance, within its leash. +@export_range(80.0, 1200.0, 10.0) var aggro_range: float = 340.0 + +## Only agile variants jump. Others still stop at walls and platform edges. +@export var can_jump: bool = false +@export_range(-900.0, -100.0, 10.0) var jump_velocity: float = -560.0 +@export_range(0.2, 3.0, 0.05) var jump_cooldown: float = 0.9 +@export var hop_while_chasing: bool = false + +## A landing must exist within this drop; never jump into an unbounded pit. +@export_range(0.0, 400.0, 10.0) var max_jump_drop: float = 200.0 + # ============================================================================ # COMBAT @@ -40,6 +52,9 @@ enum AttackState { @export_range(1, 100, 1) var max_health: int = 20 @export_range(0, 100, 1) var attack_damage: int = 1 +## Outgoing push on the player, independent of damage and enemy knockback. +@export_range(0.0, 3.0, 0.05) var attack_knockback_multiplier: float = 1.0 + ## Minimum time between the beginning of two attacks. @export var attack_interval: float = 2.0 @@ -112,8 +127,8 @@ var drops_handled_by_level: bool = false ## Visible launch, collapse and fade before the body disappears. @export_range(0.3, 2.5, 0.05) var death_animation_duration: float = 0.9 -## Limits how far the enemy may chase from its spawn point; 0 = unrestricted. -## Small limits keep independent testing encounters from piling up. +## Horizontal leash from spawn; 0 = unrestricted. Losing the target or +## reaching the leash makes the enemy return home rather than follow forever. @export var chase_radius: float = 0.0 ## Only used to describe enemy variants in test HUDs. @@ -167,6 +182,10 @@ var is_dead: bool = false var spawn_position: Vector2 var target: Node2D +var _is_pursuing: bool = false +var _jump_cooldown_timer: float = 0.0 +var _jump_in_progress: bool = false +var _jump_target_x: float = 0.0 ## Prevents one sweep from damaging the same target once per physics frame. var attack_hit_targets: Dictionary = {} @@ -223,8 +242,7 @@ func _physics_process(delta: float) -> void: _apply_gravity(delta) # The enemy deliberately does nothing until the camera has shown it once. - # After waking up it stays active, even if the player later runs away from - # the screen area where the enemy was first seen. + # After waking up it may pursue or return home even outside the screen. if not is_awake: velocity.x = 0.0 move_and_slide() @@ -255,11 +273,12 @@ func _physics_process(delta: float) -> void: return if attack_state == AttackState.IDLE: - _update_idle_behaviour() + _update_idle_behaviour(delta) else: _update_attack(delta) move_and_slide() + _update_jump_visual() queue_redraw() @@ -310,35 +329,170 @@ func _apply_gravity(delta: float) -> void: velocity.y = min(velocity.y, max_fall_speed) -func _update_idle_behaviour() -> void: - _face_target() +func _update_idle_behaviour(delta: float) -> void: + var offset_to_target: Vector2 = target.global_position - global_position + var detection_distance: float = aggro_range * (1.5 if _is_pursuing else 1.0) + var target_inside_leash: bool = ( + chase_radius <= 0.0 + or absf(target.global_position.x - spawn_position.x) <= chase_radius + ) + _is_pursuing = ( + not bool(target.get("is_dead")) + and target_inside_leash + and offset_to_target.length_squared() <= detection_distance * detection_distance + ) - if attack_cooldown_timer <= 0.0 and _is_target_in_attack_trigger(): - _start_attack() + if _is_pursuing: + _face_target() + if attack_cooldown_timer <= 0.0 and _is_target_in_attack_trigger(): + _start_attack() + return + _move_towards(target.global_position, delta) + else: + # Return naturally, without teleporting or healing. Non-jumpers still + # refuse ledges; this is local steering, not a global pathfinding system. + _move_towards(spawn_position, delta) + + +func _move_towards(destination: Vector2, delta: float) -> void: + # Commit to the chosen landing instead of homing onto a moving player in + # mid-air. A hit clears this goal so it never cancels received knockback. + if _jump_in_progress and not is_on_floor(): + velocity.x = clampf((_jump_target_x - global_position.x) / delta, -move_speed, move_speed) return - _chase_target() + var offset: Vector2 = destination - global_position + if absf(offset.x) > 8.0: + facing_direction = signf(offset.x) + _update_facing() + if not is_on_floor(): + velocity.x = move_toward(velocity.x, signf(offset.x) * move_speed, move_speed * 3.0 * delta) + return -func _chase_target() -> void: - # Limit chasing to the current testing station when chase_radius is set. - # Going back towards the spawn point is always allowed. - var distance_from_spawn: float = global_position.x - spawn_position.x - if chase_radius > 0.0 and absf(distance_from_spawn) >= chase_radius and signf(distance_from_spawn) == facing_direction: + var stopping_distance: float = 38.0 if _is_pursuing else 8.0 + if absf(offset.x) <= stopping_distance and absf(offset.y) <= 36.0: velocity.x = 0.0 return - # Do not blindly walk off a platform while chasing. Proper pathfinding is - # intentionally postponed until levels actually require it. - if is_on_floor() and not floor_probe.is_colliding(): - velocity.x = 0.0 + # Refresh after turning: the previous physics frame's probe points the + # other way. Look ahead early enough to jump BEFORE touching a step. + floor_probe.force_raycast_update() + var edge_ahead: bool = not floor_probe.is_colliding() + var look_ahead: Vector2 = Vector2(facing_direction * maxf(32.0, move_speed * 0.25), 0.0) + var wall_ahead: bool = test_move(global_transform, look_ahead) + if _try_jump(destination, wall_ahead, edge_ahead): return - if is_on_wall(): + if absf(offset.x) <= stopping_distance or edge_ahead: velocity.x = 0.0 return + # Use a fresh forward test, not is_on_wall() from the previous direction. + if test_move(global_transform, Vector2(facing_direction * 3.0, 0.0)): + velocity.x = 0.0 + return + velocity.x = facing_direction * minf(move_speed, absf(offset.x) / delta) - velocity.x = facing_direction * move_speed + +func _try_jump(destination: Vector2, wall_ahead: bool, edge_ahead: bool) -> bool: + if not can_jump or not is_on_floor() or _jump_cooldown_timer > 0.0: + return false + var offset: Vector2 = destination - global_position + var climb_needed: bool = offset.y < -36.0 + var wants_hop: bool = ( + hop_while_chasing and _is_pursuing + and absf(offset.x) > attack_trigger_distance + 40.0 + and absf(offset.y) < 48.0 + ) + if not wall_ahead and not edge_ahead and not climb_needed and not wants_hop: + return false + + # Failed attempts are throttled too: no terrain scans every physics frame. + _jump_cooldown_timer = 0.25 + var gravity_y: float = get_gravity().y + if gravity_y <= 0.0 or jump_velocity >= 0.0: + return false + var max_rise: float = jump_velocity * jump_velocity / (2.0 * gravity_y) - 10.0 + if max_rise <= 0.0 or test_move(global_transform, Vector2(0.0, -max_rise)): + return false + + var landing: Vector2 = _find_jump_landing(destination, max_rise, gravity_y, climb_needed) + if not landing.is_finite(): + return false + + _jump_target_x = landing.x + _jump_in_progress = true + _jump_cooldown_timer = jump_cooldown + velocity = Vector2(facing_direction * move_speed, jump_velocity) + COMBAT_FX.spawn(get_parent(), global_position + Vector2(0.0, 26.0), &"dust") + return true + + +func _find_jump_landing(destination: Vector2, max_rise: float, gravity_y: float, climbing: bool) -> Vector2: + var body_shape: RectangleShape2D = body_collision.shape as RectangleShape2D + var half_size: Vector2 = body_shape.size * 0.5 + var feet_y: float = global_position.y + half_size.y + var best_landing: Vector2 = Vector2.INF + var best_score: float = INF + var space: PhysicsDirectSpaceState2D = get_world_2d().direct_space_state + # A handful of local candidates covers steps, nearby platforms and small + # gaps. Both feet must fit, and flight time must permit the horizontal move. + for distance: float in [48.0, 80.0, 120.0, 160.0, 200.0, 240.0]: + var x: float = global_position.x + facing_direction * distance + if chase_radius > 0.0 and absf(x - spawn_position.x) > chase_radius: + continue + var query := PhysicsRayQueryParameters2D.create( + Vector2(x, feet_y - max_rise), Vector2(x, feet_y + max_jump_drop + 2.0), + collision_mask, [get_rid()] + ) + var hit: Dictionary = space.intersect_ray(query) + if hit.is_empty() or (hit["normal"] as Vector2).y > -0.7: + continue + var surface: Vector2 = hit["position"] + if climbing and surface.y >= feet_y - 16.0: + continue + var flight_squared: float = jump_velocity * jump_velocity + 2.0 * gravity_y * (surface.y - feet_y) + if flight_squared <= 0.0: + continue + var flight_time: float = (-jump_velocity + sqrt(flight_squared)) / gravity_y + if distance > move_speed * flight_time * 0.9: + continue + + var stable_landing: bool = true + for side: float in [-1.0, 1.0]: + var foot_x: float = x + side * (half_size.x + 3.0) + query.from = Vector2(foot_x, surface.y - 4.0) + query.to = Vector2(foot_x, surface.y + 4.0) + var foot_hit: Dictionary = space.intersect_ray(query) + if foot_hit.is_empty() or (foot_hit["normal"] as Vector2).y > -0.7: + stable_landing = false + break + if not stable_landing: + continue + + var landing: Vector2 = Vector2(x, surface.y - half_size.y - 2.0) + var landing_transform: Transform2D = global_transform + landing_transform.origin = landing + if test_move(landing_transform, Vector2.UP * 2.0, null, 0.08, true): + continue + var score: float = landing.distance_squared_to(destination) + if score < best_score: + best_score = score + best_landing = landing + return best_landing + + +func _update_jump_visual() -> void: + if not _jump_in_progress: + visual.scale = _visual_scale + return + if is_on_floor(): + _jump_in_progress = false + visual.scale = _visual_scale + COMBAT_FX.spawn(get_parent(), global_position + Vector2(0.0, 26.0), &"dust") + else: + # A small airborne pose without changing collision sizes or sprite art. + visual.scale = _visual_scale * Vector2(0.9, 1.08) # ============================================================================ @@ -347,10 +501,17 @@ func _chase_target() -> void: func _is_target_in_attack_trigger() -> bool: var offset_to_target: Vector2 = target.global_position - global_position - return ( - abs(offset_to_target.x) <= attack_trigger_distance - and abs(offset_to_target.y) <= attack_vertical_tolerance + if ( + not is_on_floor() + or absf(offset_to_target.x) > attack_trigger_distance + or absf(offset_to_target.y) > attack_vertical_tolerance + ): + return false + # A player behind a step should trigger navigation, not attacks through it. + var query := PhysicsRayQueryParameters2D.create( + global_position, target.global_position, collision_mask, [get_rid()] ) + return get_world_2d().direct_space_state.intersect_ray(query).is_empty() func _start_attack() -> void: @@ -446,8 +607,16 @@ func _update_attack_damage() -> void: if attack_hit_targets.has(target_id): continue + # A swept hitbox must not reach through solid walls. Use the enemy's + # body as the source: a hitbox past the player could push them backwards. + var query := PhysicsRayQueryParameters2D.create( + global_position, (damage_target as Node2D).global_position, + collision_mask, [get_rid()] + ) + if not get_world_2d().direct_space_state.intersect_ray(query).is_empty(): + continue attack_hit_targets[target_id] = true - damage_target.take_damage(attack_damage, attack_hitbox.global_position) + damage_target.take_damage(attack_damage, global_position, attack_knockback_multiplier) func _interrupt_attack() -> void: @@ -463,6 +632,7 @@ func _interrupt_attack() -> void: func _update_timers(delta: float) -> void: attack_cooldown_timer = max(attack_cooldown_timer - delta, 0.0) hit_stun_timer = max(hit_stun_timer - delta, 0.0) + _jump_cooldown_timer = maxf(_jump_cooldown_timer - delta, 0.0) # Updates floating damage numbers: they drift upward and fade out over time. @@ -485,6 +655,9 @@ func take_damage(amount: int, source_position: Vector2) -> void: current_health = max(current_health - amount, 0) _hit_flash_timer = 0.09 is_awake = true + _is_pursuing = true + _jump_in_progress = false + visual.scale = _visual_scale _last_hit_direction = signf(global_position.x - source_position.x) if _last_hit_direction == 0.0: _last_hit_direction = -facing_direction @@ -599,6 +772,10 @@ func _respawn() -> void: set_physics_process(true) _death_elapsed = 0.0 _hit_flash_timer = 0.0 + _is_pursuing = false + _jump_in_progress = false + _jump_cooldown_timer = 0.0 + _jump_target_x = spawn_position.x visual.position = _visual_position visual.scale = _visual_scale visual.rotation = _visual_rotation diff --git a/levels/level_01.gd b/levels/level_01.gd index eb076f5..7bf2bdd 100644 --- a/levels/level_01.gd +++ b/levels/level_01.gd @@ -42,6 +42,8 @@ func _ready() -> void: $DeathZone.body_entered.connect(_on_death_entered) player.connect(&"pickup_collected", _on_pickup_collected) for enemy in test_enemies.get_children(): + # Keep item-testing stations isolated despite the stronger game profiles. + enemy.set("chase_radius", 135.0) # 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) diff --git a/levels/level_02.tscn b/levels/level_02.tscn index b07944c..a6d8cc8 100644 --- a/levels/level_02.tscn +++ b/levels/level_02.tscn @@ -540,7 +540,7 @@ special_radius = 290.0 [node name="Enemies" type="Node2D" parent="."] [node name="Enemy01" parent="Enemies" instance=ExtResource("enemy_roadie")] -position = Vector2(410, 811) +position = Vector2(1260, 811) show_debug_enemy_info = true diff --git a/player/player.gd b/player/player.gd index b39e7a2..12659bd 100644 --- a/player/player.gd +++ b/player/player.gd @@ -729,7 +729,7 @@ func _damage_target(collider: Node, damage: int, hit_targets: Dictionary) -> voi target.take_damage(damage, global_position) -func take_damage(amount: int, source_position: Vector2) -> void: +func take_damage(amount: int, source_position: Vector2, knockback_multiplier: float = 1.0) -> void: if amount <= 0 or is_dead or invulnerability_timer > 0.0: return @@ -751,13 +751,16 @@ func take_damage(amount: int, source_position: Vector2) -> void: if knockback_direction == 0.0: knockback_direction = -facing_direction - velocity.x = knockback_direction * damage_knockback.x - velocity.y = -damage_knockback.y - _hurt_animation_timer = 0.18 + # Enemy variants choose their push independently of HP damage. Existing + # two-argument calls (hazards, tests) retain the original impulse. + var push_scale: float = clampf(knockback_multiplier, 0.0, 3.0) + velocity.x = knockback_direction * damage_knockback.x * push_scale + velocity.y = -damage_knockback.y * sqrt(push_scale) + _hurt_animation_timer = 0.18 * clampf(push_scale, 1.0, 1.5) punch_timer = 0.0 ground_pound_active = false COMBAT_FX.spawn(get_parent(), global_position, &"hit", knockback_direction) - feedback_camera.call("impact", 1.5, 0.18) + feedback_camera.call("impact", 1.5 * clampf(push_scale, 0.8, 1.6), 0.18) health_changed.emit(current_health, character_data.max_health) diff --git a/tests/test_enemy_ai_runtime.gd b/tests/test_enemy_ai_runtime.gd new file mode 100644 index 0000000..a13e13a --- /dev/null +++ b/tests/test_enemy_ai_runtime.gd @@ -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) diff --git a/tests/test_enemy_profiles.py b/tests/test_enemy_profiles.py new file mode 100644 index 0000000..b9dbcef --- /dev/null +++ b/tests/test_enemy_profiles.py @@ -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() diff --git a/tests/test_level_01_resources.py b/tests/test_level_01_resources.py index e440eae..9f4ae33 100644 --- a/tests/test_level_01_resources.py +++ b/tests/test_level_01_resources.py @@ -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]