我正在尝试编写一个将随机俄罗斯方块形状绘制到板上的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中定义了它。
答案 0 :(得分: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)
答案 1 :(得分:1)
the_shape
是create_new_shape
函数的本地函数,一旦函数退出,该名称就会超出范围。
答案 2 :(得分: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。 thing 访问它们。所以我们想要访问电路板,并告诉它要绘制的形状。我们通过 self.board 来实现,然后我们添加 draw_shape 方法。最后,我们需要告诉它要绘制什么。 the_shape 超出范围,它仅存在于 create_new_shape 方法中。该方法返回一个形状,我们分配给 self.current_shape 。因此,当您想要在类中的任何位置再次引用该形状时,请使用 self.current_shape 。