我有一个很大的游戏对象列表(30-50个),它们以超连续的顺序在5-7个状态之间变化,从根本上改变了它们的行为。
我最初的天真方法是为每个游戏对象提供一个state变量,然后每个操作命令都会通过一个if-else块来查找与状态相对应的正确操作。
选项1(朴素方法)
class Bot:
def action(self):
if self.state == 1:
action1()
if condition1_to_2():
self.state = 2
elif self.state == 2:
action2()
#...
list_of_bots = [Bot(), Bot(), ...]
for bot in list_of_bots:
bot.action()但我想,有50个游戏对象,这种if-else遍历不是开始占用大量时间吗?
难道我不能通过直接转到state的正确代码来提高性能吗?
我能想到的实现这一点的唯一方法是使用继承(接口或子类),并使每个游戏对象的每个游戏状态都有自己的子类,每次状态改变时销毁并创建一个新对象。
选项2(继承)
class Bot:
def action(): raise NotImplementedError
class Bot1(Bot):
def action():
action1()
class Bot2(Bot):
def action():
action2()
#...
list_of_bots = [Bot1(), Bot2(), ...]
for bot in list_of_bots:
bot.action()这样,每个游戏对象就不必检查它在游戏的每个节拍中处于什么状态,这样每个节拍就可以节省大约300次操作。
我唯一的问题是,创建这么多新类感觉有点过头了。对于这个问题,有没有更紧凑但同样有效的解决方案?
我认为状态字典或列表(假设它们的访问时间为O(1) ),但是如何将列表链接到代码块?
选项3(不可能?)
class Bot:
def __init__(self):
self.action_list = [action1(), action2(), ...]
self.state = 1
def action():
self.action_list[self.state]解决方案必须在原始python3中完成(无pip安装)。
发布于 2018-10-27 00:55:07
你的选项3可以与函数引用一起工作,但是我不确定这种程序结构是否最好使用。但是要完成函数引用列表的存储,您可以这样做:
class Bot:
def __init__(self, game_map):
self.action_list = [self.action1, self.action2] # Stores function references
self.state = 1
self.game_map = game_map # Pass in game_map object that the class can use
def action(self):
self.action_list[self.state]() # Calls function reference
def action1(self):
# Does something
def action2(self):
# Does something编辑:我添加了一个如何传入您在注释中提到的game_map对象的示例。然后,你可以在动作函数中的任何地方使用self.game_map,只要你每次都在修改那个地图,而不是创建一个新的地图,这个对象就是你的游戏控制器正在更新的对象。
https://stackoverflow.com/questions/53013141
复制相似问题