随机方块形状
我正在尝试写一个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里定义过它。
3 个回答
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。
1
the_shape
这个变量只在你的 create_new_shape
函数里面有效,一旦这个函数结束,the_shape
这个名字就不再被使用了。
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)