![](/img/trans.png)
[英]TypeError 'int' object has no attribute '__getitem__'
[英]TypeError: 'int' object has no attribute '__getitem__'
我正在嘗試使用pygame中的rects來制作游戲表面。 我不確定問題到底出在哪里,但我相信這與創建rect時列表的實際迭代有關。 抱歉,這是菜鳥。 :)
import pygame
w = 800
h = 600
board_pos = 0, 0
tile = 27
playfield = 0
class Board(object):
def __init__(self, surface, pos, tile_size):
self.surface = surface
self.x, self.y = pos
self.tsize = tile_size
self.color = 50, 50, 50
playfield = [list(None for i in xrange(22)) for i in xrange(10)]
def draw(self):
for i in xrange(10):
for j in xrange(22):
playfield[i][j] = pygame.draw.rect(self.surface, self.color,
(self.x + (i * self.tsize),
self.y + (j * self.tsize),
self.tsize, self.tsize))
pygame.display.init()
screen = pygame.display.set_mode((w, h))
board = Board(screen, board_pos, tile)
board.draw()
while __name__ == '__main__':
pygame.display.flip()
我不斷收到此錯誤:
Traceback (most recent call last):
File "C:\Documents and Settings\Administrator\My
Documents\Dropbox\Programming\DeathTris
\test2.py", line 30, in <module>
board.draw()
File "C:\Documents and Settings\Administrator\My
Documents\Dropbox\Programming\DeathTris
\test2.py", line 24, in draw
self.tsize, self.tsize))
TypeError: 'int' object has no attribute '__getitem__'
任何幫助,將不勝感激。 謝謝!
您的行playfield = [list(None for i in xrange(22)) for i in xrange(10)]
在__init__
函數內創建局部變量。 __init__
函數返回后,該變量消失。 在draw
稍后部分,當您執行playfield[i][j]
,您將訪問playfield
的全局值,該值仍為0(因為在開始時將其初始化為0)。
如果要從__init__
內部覆蓋全局運動場,則需要先執行global playfield
然后再分配給它。 (但是……為什么您仍然為此使用全局變量?)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.