2012-03-05 110 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]

相關問題