227 lines
7.7 KiB
Python
227 lines
7.7 KiB
Python
"""
|
||
行为树和状态机插件使用示例
|
||
演示如何在项目中使用行为树和状态机插件
|
||
"""
|
||
|
||
import sys
|
||
import os
|
||
|
||
# 添加项目根目录到Python路径
|
||
sys.path.insert(0, '/home/hello/EG')
|
||
|
||
def main():
|
||
"""
|
||
主函数,演示插件的使用方法
|
||
"""
|
||
print("行为树和状态机插件使用示例")
|
||
print("=" * 40)
|
||
|
||
# 导入插件管理器
|
||
from plugins.plugin_manager import PluginManager
|
||
|
||
# 创建一个虚拟的世界对象(模拟项目中的世界对象)
|
||
class MockWorld:
|
||
def __init__(self):
|
||
# 模拟世界对象的属性和方法
|
||
self.render = None
|
||
self.accept = lambda event, handler: None
|
||
self.ignore = lambda event: None
|
||
|
||
# 创建世界实例
|
||
world = MockWorld()
|
||
|
||
# 创建插件管理器
|
||
plugin_manager = PluginManager(world)
|
||
|
||
# 启用插件系统
|
||
plugin_manager.enable_plugin_system()
|
||
|
||
# 加载行为树插件
|
||
print("\n1. 加载行为树插件...")
|
||
bt_plugin = plugin_manager.load_plugin("behavior_tree")
|
||
if bt_plugin:
|
||
print("✅ 行为树插件加载成功")
|
||
# 启用行为树插件
|
||
if plugin_manager.enable_plugin("behavior_tree"):
|
||
print("✅ 行为树插件启用成功")
|
||
else:
|
||
print("❌ 行为树插件启用失败")
|
||
else:
|
||
print("❌ 行为树插件加载失败")
|
||
return
|
||
|
||
# 加载状态机插件
|
||
print("\n2. 加载状态机插件...")
|
||
sm_plugin = plugin_manager.load_plugin("state_machine")
|
||
if sm_plugin:
|
||
print("✅ 状态机插件加载成功")
|
||
# 启用状态机插件
|
||
if plugin_manager.enable_plugin("state_machine"):
|
||
print("✅ 状态机插件启用成功")
|
||
else:
|
||
print("❌ 状态机插件启用失败")
|
||
else:
|
||
print("❌ 状态机插件加载失败")
|
||
return
|
||
|
||
# 使用行为树插件创建一个简单的AI行为
|
||
print("\n3. 使用行为树插件创建AI行为...")
|
||
try:
|
||
# 导入行为树节点类
|
||
from plugins.user.behavior_tree import (
|
||
SelectorNode, SequenceNode,
|
||
ConditionNode, ActionNode,
|
||
RepeaterNode
|
||
)
|
||
|
||
# 创建行为树结构
|
||
# 根节点:选择节点
|
||
root = SelectorNode("Root")
|
||
|
||
# 创建巡逻行为序列
|
||
patrol_sequence = SequenceNode("Patrol")
|
||
patrol_condition = ConditionNode("PatrolCondition",
|
||
lambda bb: bb.get("should_patrol", True))
|
||
patrol_action = ActionNode("PatrolAction",
|
||
lambda bb: print("🤖 AI正在巡逻...") or True)
|
||
|
||
patrol_sequence.add_child(patrol_condition)
|
||
patrol_sequence.add_child(patrol_action)
|
||
|
||
# 创建重复节点,重复巡逻3次
|
||
patrol_repeater = RepeaterNode(patrol_sequence, count=3)
|
||
|
||
# 创建休息行为序列
|
||
rest_sequence = SequenceNode("Rest")
|
||
rest_condition = ConditionNode("RestCondition",
|
||
lambda bb: bb.get("should_rest", False))
|
||
rest_action = ActionNode("RestAction",
|
||
lambda bb: print("😴 AI正在休息...") or True)
|
||
|
||
rest_sequence.add_child(rest_condition)
|
||
rest_sequence.add_child(rest_action)
|
||
|
||
# 组装行为树
|
||
root.add_child(patrol_repeater)
|
||
root.add_child(rest_sequence)
|
||
|
||
# 创建行为树实例
|
||
behavior_tree = bt_plugin.create_behavior_tree("ai_behavior", root)
|
||
|
||
# 创建黑板并设置初始数据
|
||
blackboard = bt_plugin.create_blackboard("ai_blackboard")
|
||
blackboard.set("should_patrol", True)
|
||
blackboard.set("should_rest", False)
|
||
|
||
# 关联黑板到行为树
|
||
behavior_tree.set_blackboard(blackboard)
|
||
|
||
print("✅ 行为树创建成功")
|
||
|
||
# 执行行为树
|
||
print("\n4. 执行行为树...")
|
||
for i in range(5):
|
||
print(f"\n--- 第 {i+1} 次执行 ---")
|
||
result = behavior_tree.run()
|
||
print(f"执行结果: {result.value}")
|
||
|
||
# 每隔几次切换状态
|
||
if i == 2:
|
||
blackboard.set("should_patrol", False)
|
||
blackboard.set("should_rest", True)
|
||
print("🔄 切换到休息状态")
|
||
|
||
except Exception as e:
|
||
print(f"❌ 行为树使用示例失败: {e}")
|
||
import traceback
|
||
traceback.print_exc()
|
||
|
||
# 使用状态机插件创建一个简单的状态管理
|
||
print("\n5. 使用状态机插件创建状态管理...")
|
||
try:
|
||
# 导入状态机类
|
||
from plugins.user.state_machine import State
|
||
|
||
# 定义状态类
|
||
class IdleState(State):
|
||
def enter(self, context):
|
||
print("🎮 进入空闲状态")
|
||
|
||
def execute(self, context):
|
||
print("⏸️ 空闲中...")
|
||
# 检查是否需要切换到移动状态
|
||
if context.get("want_move", False):
|
||
return context["states"]["move"]
|
||
return None
|
||
|
||
def exit(self, context):
|
||
print("🔚 退出空闲状态")
|
||
|
||
class MoveState(State):
|
||
def enter(self, context):
|
||
print("🚗 进入移动状态")
|
||
|
||
def execute(self, context):
|
||
print("➡️ 移动中...")
|
||
# 检查是否需要切换到空闲状态
|
||
if not context.get("want_move", True):
|
||
return context["states"]["idle"]
|
||
return None
|
||
|
||
def exit(self, context):
|
||
print("🔚 退出移动状态")
|
||
|
||
# 创建状态机
|
||
state_machine = sm_plugin.create_state_machine("game_character")
|
||
|
||
# 创建状态实例
|
||
states = {
|
||
"idle": IdleState("Idle"),
|
||
"move": MoveState("Move")
|
||
}
|
||
|
||
# 创建上下文
|
||
context = {
|
||
"want_move": False,
|
||
"states": states
|
||
}
|
||
|
||
# 设置状态机上下文
|
||
state_machine.set_context(context)
|
||
|
||
# 设置初始状态
|
||
state_machine.change_state(states["idle"])
|
||
|
||
print("✅ 状态机创建成功")
|
||
|
||
# 更新状态机
|
||
print("\n6. 更新状态机...")
|
||
for i in range(4):
|
||
print(f"\n--- 第 {i+1} 次更新 ---")
|
||
print(f"当前状态: {state_machine.get_current_state().name}")
|
||
state_machine.update()
|
||
|
||
# 模拟状态切换
|
||
if i == 1:
|
||
context["want_move"] = True
|
||
print("🔄 设置为想要移动")
|
||
elif i == 2:
|
||
context["want_move"] = False
|
||
print("🔄 设置为想要空闲")
|
||
|
||
except Exception as e:
|
||
print(f"❌ 状态机使用示例失败: {e}")
|
||
import traceback
|
||
traceback.print_exc()
|
||
|
||
# 禁用和卸载插件
|
||
print("\n7. 清理资源...")
|
||
plugin_manager.disable_plugin("behavior_tree")
|
||
plugin_manager.disable_plugin("state_machine")
|
||
plugin_manager.unload_plugin("behavior_tree")
|
||
plugin_manager.unload_plugin("state_machine")
|
||
|
||
print("\n🎉 示例运行完成!")
|
||
|
||
if __name__ == "__main__":
|
||
main() |