在 python 中将函数作为有限状态机的变量分配



我正在尝试用python制作游戏,并遇到了让对象根据游戏中的操作切换状态的问题。

我发现最好的方法是最有可能有某种方法将函数(对象的状态(定义为变量,并根据操作为对象提供状态。 不幸的是,我不确定这是否可能,或者可能有一个概念,当涉及到这个主题时,我还没有学习。如果有人能为我的问题提供解决方案,或者只是为我指明方向,以学习解决问题的方法。

有没有办法将某些函数/方法与名称相关联并避免多个if语句?

class stateUser:
def __init__(self,state):
self.state = state
def executeState(self):
if self.state == "Print Something":
self.printSomething()
elif self.state == "Not Print Something":
self.dontPrint()
else:
self.notUnderstand()
'''
would like this function to simply call
a function that is defined as the object's state,
instead of using a bunch of if statements
'''
def printSomething(self):
print("Something")
def dontPrint(self):
print("No")
def notUnderstand(self):
print("I didn't understand that")
runner = stateUser(None)
a = True
while a:
runner.state = input("Enter the state you would like to change ton")
runner.executeState()

上面的代码显然不是我正在制作的游戏项目的直接片段,而只是我输入的在情况上非常相似的东西。任何意见或解决方案将不胜感激地欢迎。

您可以创建一个字典来存储所有操作和匹配的函数/方法。

然后,您只需要使用dict.get()来查找用户给出的匹配操作或使用默认self.notUnderstand(作为第二个参数传递(:

dict 结构允许将函数存储为引用,无需(),因此您只需要在结果action上添加这些括号即可。(或直接添加 以self.actions.get(self.state, self.notUnderstand)()保存一行(。

class stateUser:
def __init__(self,state):
self.state = state
self.actions = {
'printSomething': self.printSomething,
'Not Print Something': self.dontPrint,
}
def executeState(self):
action = self.actions.get(self.state, self.notUnderstand)
action()

另一个优点是您可以使用此字典的键为用户提供选择:

while a:
runner.state = input("Enter the state you would like to change ton"+
' - '.join(runner.actions.keys()))
runner.executeState()
#>>> Enter the state you would like to change to
#printSomething - Not Print Something

首先,感谢您创建一个较小的代码段,它有助于使问题更容易管理。

您本质上是希望将状态"映射"到操作。 字典非常适合此用例。创建一个字典/映射,其中"键"是状态,然后"操作"是实际函数。只需使用该映射即可根据需要执行正确的函数。

一个简单的例子如下:

class stateUser:
def __init__(self,state):
self.state = state
def executeState(self):
map_state_to_action = {
"Print Something": self.printSomething,  # note that no brackets were used. 
"Not Print Something": self.dontPrint,  # we are interested in the function itself.
}
#a dict.get takes a key, returns the value if the key is present in the dict, or returns the other argument if key was not found.
map_state_to_action.get(self.state, self.notUnderstand)()  # note the brackets at the end to call the func.        
def printSomething(self):
print("Something")
def dontPrint(self):
print("No")
def notUnderstand(self):
print("I didn't understand that")
runner = stateUser(None)
a = True
while a: #could just change this to while True:
runner.state = input("Enter the state you would like to change ton")
runner.executeState()

请注意,您必须在某处建立状态和所需操作之间的链接,除非您在游戏运行时直接调用该操作,而不是设置状态。

最新更新