2012-03-05 46 views
3

我不明白什么是错的。我将发布相关代码的一部分。python - TypeError:元组索引必须是整数

错误:

Traceback (most recent call last): 
    File "C:\Python\pygame\hygy.py", line 104, in <module> 
    check_action() 
    File "C:\Python\pygame\hygy.py", line 71, in check_action 
    check_portal() 
    File "C:\Python\pygame\hygy.py", line 75, in check_portal 
    if [actor.x - 16, actor.y - 16] > portal[i][0] and [actor.x + 16, actor.y + 16] < portal[i][0]: 
TypeError: tuple indices must be integers 

功能:

def check_portal(): 
    for i in portal: 
     if [actor.x - 16, actor.y - 16] > portal[i][0] and [actor.x + 16, actor.y + 16] < portal[i][0]: 
      if in_portal == False: 
       actor.x,actor.y=portal[i][1] 
       in_portal = True 
     elif [actor.x - 16, actor.y - 16] > portal[i][1] and [actor.x + 16, actor.y + 16] < portal[i][1]: 
      if in_portal == False: 
       actor.x,actor.y=portal[i][1] 
       in_portal = True 
     else: 
      in_portal = False 

初始化演员:

class xy: 
    def __init__(self): 
    self.x = 0 
    self.y = 0 
actor = xy() 

初始化门户网站:

portal = [[100,100],[200,200]],[[300,300],[200,100]] 

回答

1

鉴于portal初始化,循环

for i in portal: 
    ... 

只会做两次迭代。在第一次迭代中,i将是[[100,100],[200,200]]。试图做portal[i]将相当于portal[[[100,100],[200,200]]],这是没有意义的。您可能只想使用i而不是portal[i]。 (你可能想将它重命名为东西比i更有意义了。)

1

当你说for i in portal,在每次迭代中,而不是在portal,你可能想到的指标,i实际上是portal元素。所以它不是整数,并在portal[i][0]中导致错误。

所以一个快速修复只是用for i in xrange(len(portal))代替,其中i是索引。

0

在for循环中,i = ([100, 100], [200, 200])不是列表的有效索引。

鉴于该if语句比较,它看起来像你的用意更像是:

for coords in portal: 
    if [actor.x - 16, actor.y - 16] > coords[0] and [actor.x + 16, actor.y + 16] < coords[0]: 

,其中在循环的第一次迭代coords[0] == [100, 100]

相关问题