[英]'int' object is not subscriptable. Tuple error
如何解決我的代碼中產生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
為什么object播放器需要多個位置?
Int constrictor self.pos
是一個元組列表:
self.pos = [(self.x, self.y)]
但是當你在movement
中改變它時,它是一個單一的位置,有 2 個坐標存儲在一個列表中:
self.pos = [self.x, self.y]
這就是導致錯誤的原因。 將后者更改為self.pos = [(self.x, self.y)]
可以解決問題,但是...
由於您想在 position ( self.x
, self.y
) 上畫一個圓圈,因此無需將列表中的位置與 ( self.x
, self.y
) 進行比較。 請注意,( self.x
, self.y
)始終存儲在列表中,那么您為什么要嘗試驗證呢?
只需在 ( self.x
, self.y
) 處繪制圓圈。 例如:
class Player(object):
# [...]
def draw(self):
pygame.draw.circle(self.board.window, (255, 255, 0), (self.x, self.y), 8)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.