87 lines
2.6 KiB
Python
87 lines
2.6 KiB
Python
"""
|
||
状态转换类
|
||
定义状态之间的转换条件和规则
|
||
"""
|
||
|
||
class Transition:
|
||
"""
|
||
状态转换类
|
||
"""
|
||
|
||
def __init__(self, to_state, condition_func=None):
|
||
self.to_state = to_state # 目标状态
|
||
self.condition_func = condition_func # 转换条件函数
|
||
|
||
def is_triggered(self, context):
|
||
"""
|
||
检查转换条件是否满足
|
||
:param context: 状态上下文
|
||
:return: 是否满足转换条件
|
||
"""
|
||
if self.condition_func:
|
||
try:
|
||
return self.condition_func(context)
|
||
except Exception as e:
|
||
print(f"转换条件检查出错: {e}")
|
||
return False
|
||
else:
|
||
# 如果没有提供条件函数,默认满足转换条件
|
||
return True
|
||
|
||
class StateWithTransitions:
|
||
"""
|
||
带有转换条件的状态类
|
||
扩展基础状态类,添加状态转换功能
|
||
"""
|
||
|
||
def __init__(self, name="StateWithTransitions"):
|
||
self.name = name
|
||
self.transitions = [] # 状态转换列表
|
||
|
||
def add_transition(self, transition):
|
||
"""添加状态转换"""
|
||
self.transitions.append(transition)
|
||
|
||
def remove_transition(self, transition):
|
||
"""移除状态转换"""
|
||
if transition in self.transitions:
|
||
self.transitions.remove(transition)
|
||
|
||
def get_transitions(self):
|
||
"""获取状态转换列表"""
|
||
return self.transitions
|
||
|
||
def check_transitions(self, context):
|
||
"""
|
||
检查所有转换条件,返回满足条件的目标状态
|
||
:param context: 状态上下文
|
||
:return: 目标状态,如果没有满足条件的转换则返回None
|
||
"""
|
||
for transition in self.transitions:
|
||
if transition.is_triggered(context):
|
||
return transition.to_state
|
||
return None
|
||
|
||
def enter(self, context):
|
||
"""
|
||
进入状态时调用
|
||
:param context: 状态上下文
|
||
"""
|
||
pass
|
||
|
||
def execute(self, context):
|
||
"""
|
||
执行状态逻辑
|
||
:param context: 状态上下文
|
||
:return: 下一个状态,如果为None则保持当前状态
|
||
"""
|
||
# 检查状态转换
|
||
next_state = self.check_transitions(context)
|
||
return next_state
|
||
|
||
def exit(self, context):
|
||
"""
|
||
退出状态时调用
|
||
:param context: 状态上下文
|
||
"""
|
||
pass |