我正在使用 Python 制作一个简单的进化模拟器。
有一个名为 的列表engine.All
,其中存储了单位/动物和食物。我遍历它,如果我遇到一只动物,我会再次遍历它,看看它是否与任何食物块发生碰撞。
如果是这样,那么我会增加他的能量,将食物标记为已吃,并将其添加到toRemove
列表中,稍后我会使用该列表从engine.All
.
这是代码,但删除了所有多余的东西:
def remove(l, who): #This should remove all the elements contained in who from the list l
offset = 0
for i in who:
l.pop(i + offset)
offset -= 1
return l
for ob in engine.All:
if ob.skip:
continue;
if ob.drawable:
ob.draw()
if isinstance(ob, Flatlander): #If it is an animal
#Do speed stuff
ob.energy -= decay #Lower its energy
for i in range(len(engine.All)): #Iterate through the list again
if collides(ob.pos, ob.r, engine.All[i].pos, engine.All[i].r) and isinstance(engine.All[i], Food) and ob.energy + engine.All[i].r < ob.r**2*3.14 and not engine.All[i].skip: #If it collides with a food piece, the food piece isn't about to be deleted and it can take the energy in (their maximum is defined by their radiuses)
ob.energy += engine.All[i].r #Increase the his energy
toRemove.append(i) #Add the food piece to the toRemove list
engine.All[i].skip = True #Flag it as skipped
if ob.energy < 0 and not ob.skip: #If its energy is 0 and if it isn't already about to be deleted
toRemove.append(engine.All.index(ob)) #Add it to the toRemove list
ob.skip = True #Flag it as skipped
engine.All = remove(engine.All, toRemove)
我几乎可以肯定这不起作用,并且有更好的方法来做到这一点。我如此确定的原因是,有时,我看到屏幕上的东西只是“闪烁”——突然消失又出现。此外,似乎有“幽灵”动物(在代码中称为 Flatlanders),我得出结论是因为有时食物会永久消失。
请推荐一种更有效的方法。