EG/plugins/user/state_machine/README.md
2025-10-30 11:46:41 +08:00

86 lines
1.9 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# 状态机插件使用文档
## 简介
状态机插件提供了一套完整的有限状态机系统,用于管理对象的不同状态和状态之间的转换。状态机是一种常用的编程模式,特别适用于管理游戏角色的行为状态。
## 核心概念
### 状态State
状态表示对象在特定时刻所处的状况。每个状态都有三个主要方法:
- `enter(context)`:进入状态时调用
- `execute(context)`:执行状态逻辑时调用
- `exit(context)`:退出状态时调用
### 状态机StateMachine
状态机负责管理当前状态和状态转换。主要功能包括:
- 状态切换
- 状态更新
- 状态历史记录
### 状态转换Transition
状态转换定义了从一个状态到另一个状态的条件和规则。
## 使用方法
### 1. 加载和启用插件
```python
# 在主程序中加载插件
plugin_manager.load_plugin("state_machine")
plugin_manager.enable_plugin("state_machine")
# 获取插件实例
sm_plugin = plugin_manager.get_plugin("state_machine")
```
### 2. 创建状态
```python
from plugins.user.state_machine import State
class IdleState(State):
def enter(self, context):
print("进入空闲状态")
def execute(self, context):
print("执行空闲状态逻辑")
# 返回下一个状态如果为None则保持当前状态
return None
def exit(self, context):
print("退出空闲状态")
```
### 3. 创建状态机
```python
# 创建状态机
state_machine = sm_plugin.create_state_machine("ai_state_machine")
# 创建上下文
context = {"data": {}}
# 设置状态机上下文
state_machine.set_context(context)
# 创建状态实例
idle_state = IdleState("Idle")
# 切换到初始状态
state_machine.change_state(idle_state)
```
### 4. 更新状态机
```python
# 更新状态机
state_machine.update()
```
## 示例
查看 `examples/ai_example.py` 文件了解完整的使用示例。