TypeError:'int'对象没有属性'__getitem__'

时间:2012-08-10 20:29:56

标签: python pygame

我正试图在pygame中创建一个游戏界面。我不确定问题究竟是什么,但我相信它与创建rects时列表的实际迭代有关。对不起,诺布在这里。 :)

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__'

任何帮助将不胜感激。谢谢!

1 个答案:

答案 0 :(得分:10)

您的第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。 (但是......为什么你还要使用全局变量?)