对于我的pygame脚本,我创建了一个字典来存储对类实例的引用,所以我可以通过在字典中添加或删除它们来添加和删除游戏循环中的对象,因为在游戏循环中,我会迭代在那个字典上并运行那里的每个实例。 至少这是理论。在实践中,我得到“第89行,在启动时
key.run()
AttributeError:'str'对象没有属性'run'“
我没有让我感到惊讶。但是我想知道,如果在监视活动实例的dict中是否实际能够只运行该类的实例?
def startup(self):
pygame.init()
...
# Read out the entity definitions from the file, where they are stored.
entFile = open("inits/initObjs.txt","r")
# Write each line, (which corresponds to one entity be design of the file) into a list "entities"
entities = list()
for line in entFile:
entities.append(line)
# create a name for every instance of an object defined in the file
for i in range(len(entities)):
ID = "entity_%d" %(i)
# Add ID and entity definition to self.entDict
self.entDict[ID] = repr(entities[i])
# Now initiate the object instance (entity_<ID> = <instance definition>)
exec("entity_%d = %s" % (i, repr(entities[i])))
while True:
# Get every active instance (every instance in the dict is.).
# The ID is the name of the instance, like unit1 = Unit(arg1,arg2...).
# run() is a method of the class. Now run it.
# Instaces will be taken out of the game loop be deletion of their ID in self.entDict
for key, value in self.entDict.iteritems():
key.run()
...
这是initObjs.txt中的单行:
Button(ID,"data/sprites/buttons/launch_off.png","data/sprites/buttons/launch_on.png",0.01*self.width,0.01*self.height,90,26,0,game1,False,True)
答案 0 :(得分:1)
存储它的最佳方法可能是先将其序列化,而不是尝试从命令字符串执行它。
答案 1 :(得分:0)
你不会喜欢我的解决方案。但这足以达到我的目的。
def startup(self):
pygame.init()
...
# Read out the entity definitions from the file, where tehy are stored.
entFile = open("inits/initObjs.txt","r")
# Write each line, (which corresponds to one entity be design of the file) into a list "entities"
entities = list()
for line in entFile:
entities.append(line)
# create a name for every instance of an object defined in the file
for i in range(len(entities)):
ID = "entity_%d" %(i)
# Add ID and entity definition to self.entDict
self.entDict[ID] = entities[i]
# Now initiate the object instance (entity_<ID> = <instance definition>)
exec("entity_%d = %s" % (i, entities[i]))
screen.blit(background, backgroundRect)
# Get every active instance (every instance in the dict is.).
# The ID is the name of the instance, like unit1 = Unit(arg1,arg2...).
# run() is a method of the class. Now run it.
# Instaces will be taken out of the game loop be deletion of their ID in self.entDict
for key, value in self.entDict.iteritems():
key = eval(key)
key.run()
...