-1

我正在尝试编写一个 python 程序,它将随机俄罗斯方块形状绘制到板上。这是我的代码:

def __init__(self, win):
    self.board = Board(win, self.BOARD_WIDTH, self.BOARD_HEIGHT)
    self.win = win
    self.delay = 1000 

    self.current_shape = self.create_new_shape()

    # Draw the current_shape oan the board 
    self.current_shape = Board.draw_shape(the_shape)

def create_new_shape(self):
    ''' Return value: type: Shape

        Create a random new shape that is centered
         at y = 0 and x = int(self.BOARD_WIDTH/2)
        return the shape
    '''

    y = 0
    x = int(self.BOARD_WIDTH/2)
    self.shapes = [O_shape,
                  T_shape,
                  L_shape,
                  J_shape,
                  Z_shape,
                  S_shape,
                  I_shape]

    the_shape = random.choice(self.shapes)
    return the_shape

我的问题在于“self.current_shape = Board.draw_shape(the_shape)。它说 the_shape 没有定义,但我认为我在 create_new_shape 中定义了它。

4

3 回答 3

5

你做了,但变量the_shape是该函数范围的本地变量。当您调用create_new_shape()将结果存储在字段中时,您应该使用它来引用形状:

self.current_shape = self.create_new_shape()

# Draw the current_shape oan the board 
self.current_shape = Board.draw_shape(self.current_shape)
于 2012-01-24T19:31:52.380 回答
1

the_shape是您的函数的本地create_new_shape名称,一旦函数退出,该名称就会超出范围。

于 2012-01-24T19:31:24.523 回答
0

你有两个问题。首先是其他人指出的范围问题。另一个问题是您从不实例化形状,而是返回对类的引用。首先,让我们实例化形状:

y = 0
x = int(self.BOARD_WIDTH/2)
self.shapes = [O_shape,
              T_shape,
              L_shape,
              J_shape,
              Z_shape,
              S_shape,
              I_shape]

the_shape = random.choice(self.shapes)
return the_shape(Point(x, y))

现在该形状已实例化,具有正确的起点。接下来,范围。

self.current_shape = self.create_new_shape()

# Draw the current_shape oan the board 
self.board.draw_shape(self.current_shape)

当您引用同一对象(此处为板)中的数据片段时,您需要通过 self. 东西。所以我们想要访问板子,并告诉它要绘制的形状。我们通过self.board这样做,然后我们添加draw_shape方法。最后,我们需要告诉它要画什么。 the_shape超出范围,它只存在于create_new_shape方法中。该方法返回一个形状,我们将其分配给self.current_shape。因此,当您想在类内的任何位置再次引用该形状时,请使用self.current_shape

于 2014-07-26T03:32:43.287 回答