1

pygame の四角形からプレイ サーフェスを作成しようとしています。問題が正確に何であるかはわかりませんが、四角形を作成するときのリストの実際の反復と関係があると思います。すみません、ここのノブ。:)

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

どんな助けでも大歓迎です。ありがとう!

4

1 に答える 1

10

Your line playfield = [list(None for i in xrange(22)) for i in xrange(10)] creates a local variable inside the __init__ function. That variable disappears after the __init__ function returns. Later in draw when you do playfield[i][j], you are accessing the global value of playfield, which is still 0 (since you initialized it to 0 at the beginning).

If you want to overwrite the global playfield from inside your __init__, you need to do global playfield before you assign to it. (But. . . why are you using a global variable for this anyway?)

于 2012-08-10T20:34:11.420 に答える