class_name EnemyBehaviors extends RefCounted const PathfindingType = preload("res://scripts/domain/ai/pathfinding.gd") const MELEE_RANGE := 1 # C3 deliberately only selects movement and melee. Ranged attacks remain C4. static func decide(enemy: ActorState, player: ActorState, map: GridMapState, blocked_cells: Dictionary[Vector2i, bool] = {}) -> Dictionary: var behavior := enemy.ai_behavior if behavior == &"legacy": return _legacy_decide(enemy, player, map, blocked_cells) if behavior == &"passive" or behavior == &"defensive": return {"kind": &"idle"} var distance := _manhattan_distance(enemy.cell, player.cell) # Enemy data defines tactical detection distance. Pathfinding subsequently # handles occluders rather than treating a wall/door as a reason to forget a # target that is already within the enemy's vision range. if distance > enemy.vision_range: return {"kind": &"idle"} if behavior == &"ranged": if distance <= enemy.attack_range: return {"kind": &"idle"} return _move_toward(enemy, player, map, blocked_cells) if distance == MELEE_RANGE: return {"kind": &"melee"} return _move_toward(enemy, player, map, blocked_cells) static func _legacy_decide(enemy: ActorState, player: ActorState, map: GridMapState, blocked_cells: Dictionary[Vector2i, bool]) -> Dictionary: var delta := player.cell - enemy.cell if _manhattan_distance(enemy.cell, player.cell) == MELEE_RANGE: return {"kind": &"melee"} var step := Vector2i(int(sign(delta.x)), int(sign(delta.y))) if abs(delta.x) >= abs(delta.y): step.y = 0 else: step.x = 0 var target: Vector2i = enemy.cell + step if map.is_walkable(target) and target != player.cell and not blocked_cells.has(target): return {"kind": &"move", "to_cell": target} return {"kind": &"idle"} static func _move_toward(enemy: ActorState, player: ActorState, map: GridMapState, blocked_cells: Dictionary[Vector2i, bool]) -> Dictionary: var occupied := blocked_cells.duplicate() occupied.erase(enemy.cell) occupied[player.cell] = true var target_cells: Array[Vector2i] = [] for direction: Vector2i in PathfindingType.CARDINAL_DIRECTIONS: var target: Vector2i = player.cell + direction if map.is_walkable(target) and not occupied.has(target): target_cells.append(target) var path := PathfindingType.find_path_to_any(map, enemy.cell, target_cells, occupied) if path.is_empty(): return {"kind": &"idle"} return {"kind": &"move", "to_cell": path.front()} static func _manhattan_distance(first: Vector2i, second: Vector2i) -> int: return abs(first.x - second.x) + abs(first.y - second.y)