2012-01-24 97 views
-1

我想写一个蟒蛇程序,将随机俄罗斯方块的形状绘制到板上。 这里是我的代码:随机俄罗斯方块形状

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定义它

回答

1

the_shape。是您的本地create_new_shape功能,这个名字超出范围,一旦函数退出。

5

你没有,但变量the_shape是局部的功能范围。当你调用create_new_shape()你把结果保存在一个领域,你应该用它来引用sha pe:

self.current_shape = self.create_new_shape() 

# Draw the current_shape oan the board 
self.current_shape = Board.draw_shape(self.current_shape) 
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.board,然后我们在上加上draw_shape的方法。最后,我们需要告诉它要画什么。 the_shape超出范围,它只存在于create_new_shape方法中。该方法返回一个形状,但我们分配给self.current_shape。因此,当您想要在班级内的任何地方再次参考该形状时,请使用self.current_shape