3

我不明白出了什么问题。我将发布相关的代码部分。

错误:

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]]
4

3 回答 3

1

给定 的初始化portal,循环

for i in portal:
    ...

只会做两次迭代。在第一次迭代中,i[[100,100],[200,200]]. 尝试做portal[i]将等同于portal[[[100,100],[200,200]]],这是没有意义的。您可能只想使用i而不是portal[i]. (您可能也想将其重命名为比 更有意义的名称i。)

于 2012-03-05T17:02:55.013 回答
1

当您说时,在每次迭代中,实际上是 的元素,而不是您可能想到for i in portal的索引。所以它不是整数,会导致.portaliportalportal[i][0]

所以一个快速的解决方法就是用 替换它for i in xrange(len(portal)),其中i是索引。

于 2012-03-05T17:05:56.890 回答
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]循环的第一次迭代中。

于 2012-03-05T17:08:02.410 回答