试图比较python中不同类的两个属性,得到错误;TypeError:列表索引必须是整数或切片,而不是Sheep“;
我正在做一个项目,羊在平原上游荡,吃草,而狼在追逐羊。一切都很顺利,直到我找到狼AI,试图将羊的位置与它们自己的位置进行比较。以下是导致错误的代码:试图比较python中不同类的两个属性,得到错误;TypeError:列表索引必须是整数或切片,而不是Sheep“;,python,Python,我正在做一个项目,羊在平原上游荡,吃草,而狼在追逐羊。一切都很顺利,直到我找到狼AI,试图将羊的位置与它们自己的位置进行比较。以下是导致错误的代码: def trackSheep(self, sheepList): sheepFound = 0#0 = false, 1 = true for s in sheepList: if sheepFound == 0: if sheepList[s].x == self.x and she
def trackSheep(self, sheepList):
sheepFound = 0#0 = false, 1 = true
for s in sheepList:
if sheepFound == 0:
if sheepList[s].x == self.x and sheepList[s].y == self.y:
self.energy = self.energy + sheepList[s].energy
else:
distanceToSheep = sheepList[s].x + sheepList[s].y
if distanceToSheep < SHEEP_DETECTED_RANGE:
return [(sheepList[s].x, sheepList[s].y)]
sheepFound = 1
else:
break
if sheepFound == 0:
return False
这是由我的主要功能触发的:
def update(self, sheepList):#all logic for the wolves
if self.isAlive():
nearbySheep = self.trackSheep(sheepList)
if not nearbySheep == False:
self.huntSheep(nearbySheep)
else:
self.move()
else:
#add death behavior later
self.color = p.Color("black")
def main():
framerate = 30
p.init
clock=p.time.Clock()
screen=p.display.set_mode((WIDTH,HEIGHT))
screen.fill((0,0,0))
p.display.set_caption("Wolf Sheep Simulation")
running = True
#testSheep = s(5,3)
#testSheep.draw(screen)
SheepList = spawnInitialSheep()
WolfList = spawnInitialWolves()
testGrass = Grass(3,5)
spawnGrass()
while running:
for event in p.event.get():
if event.type == p.QUIT:
running = False
print(grassList)
print(SheepList)
for s in SheepList:
s.update(grassList)
for w in WolfList:
w.update(SheepList)
testGrass.draw(screen)
#updte things
#draw things
for grassRow in grassList:
for grassSquare in grassRow:
grassSquare.update()
grassSquare.draw(screen)
for i in range (len(SheepList)):
SheepList[i].draw(screen)
for i in range (len(WolfList)):
WolfList[i].draw(screen)
p.display.flip()
clock.tick(framerate)
p.quit()
main()
我假设这是一个简单的格式错误,有人知道如何解决吗?这行是baa-a-a-ad:
for s in sheepList:
if sheepFound == 0:
if sheepList[s].x == self.x and sheepList[s].y == self.y:
# ^^^^^^^^^^^^^^
# s is already a sheep object
self.energy = self.energy + sheepList[s].energy
相反,您可以简单地使用sheep对象,而无需反复返回sheepList:
for sheep in sheepList:
if sheepFound == 0:
if sheep.x == self.x and sheep.y == self.y:
self.energy = self.energy + sheep.energy
类似地,在主函数中,而不是此函数中:
for i in range (len(SheepList)):
SheepList[i].draw(screen)
for i in range (len(WolfList)):
WolfList[i].draw(screen)
…更传统的做法是简单地写:
for sheep in SheepList:
sheep.draw(screen)
for wolf in WolfList:
wolf.draw(screen)
或者,进一步简化:
for animal in itertools.chain(SheepList, WolfList):
# Watch out for wolf in sheep's clothing.
animal.draw(screen)
谢谢现在我遇到了另一个完全不同的错误,每次程序启动后不久就会崩溃,但至少现在可以正常工作了。如果你不能解决下一个问题,你可以发布另一个问题。通常,缩小范围以形成问题的过程会导致您找到解决方案。祝你好运事实上,你有没有可能帮我解决我现在遇到的错误?编辑:Nvm我将提出一个新问题,我无法在这里正确格式化代码。