【问题标题】:TypeError: 'int' object has no attribute '__getitem__'TypeError:“int”对象没有属性“__getitem__”
【发布时间】:2012-08-11 04:35:21
【问题描述】:

我正在尝试用 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__'

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

【问题讨论】:

    标签: python pygame


    【解决方案1】:

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

    【讨论】:

    • 肯定是self.playfield
    • 非常感谢你们!我已经为此烦恼了好几个小时。
    • [... for i ... for i...] 这不需要两个不同的变量吗?
    • @thefritobandit 请确保接受答案(单击箭头下方的复选标记),以便我们知道此问题已得到解答。您还可以通过接受获得 +2 代表 :)
    猜你喜欢
    • 2014-06-10
    • 2016-07-28
    • 1970-01-01
    • 1970-01-01
    • 2012-12-04
    • 2012-10-15
    • 2014-01-16
    • 2017-02-27
    • 2018-01-28
    相关资源
    最近更新 更多