“ int”对象不可下标。元组错误

时间:2019-09-29 12:51:42

标签: python list pygame tuples

如何解决我的代码中产生TypeError的问题?

class Player(object):
    def __init__(self, board):
        self.board = board
        self.x = 607
        self.y = 420
        self.pos = [(self.x, self.y)]

    def movement(self, x, y):
        self.x += x
        self.y += y
        self.pos = [self.x, self.y]

    def draw(self):
        for tup in self.pos:
            if (tup[0] == self.x) and (tup[1] == self.y):
                pygame.draw.circle(self.board.window, (255, 255, 0), (self.x, self.y), 8)

    def update(self):
        pygame.display.update()
  
Traceback (most recent call last):
   File "C:/Users/fotio_000/PycharmProjects/Pacman/main.py", line 4, in <module>
   board = Board()
   File "C:\Users\fotio_000\PycharmProjects\Pacman\Game.py", line 32, in __init__
   self.all_events()
   File "C:\Users\fotio_000\PycharmProjects\Pacman\Game.py", line 38, in all_events
   self.draw()
   File "C:\Users\fotio_000\PycharmProjects\Pacman\Game.py", line 65, in draw
   self.player.draw()
   File "C:\Users\fotio_000\PycharmProjects\Pacman\Player.py", line 18, in draw
   if (tup[0] == self.x) and (tup[1] == self.y):
TypeError: 'int' object is not subscriptable

1 个答案:

答案 0 :(得分:1)

为什么要为对象播放器设置多个位置?

int压缩器self.pos是元组列表:

  
self.pos = [(self.x, self.y)]

但是当您在movement中进行更改时,它是一个单独的位置,列表中存储了2个坐标:

  
self.pos = [self.x, self.y]

这就是导致错误的原因。将后者更改为self.pos = [(self.x, self.y)]可以解决此问题,但是...

由于您想在位置(self.xself.y处绘制一个圆,因此无需将列表中的位置与(self.x,{{ 1}})。请注意,{self.yself.x)始终存储在列表中,所以为什么要尝试验证呢?
只需在(self.yself.x)处画一个圆。例如:

self.y