Random Tetris Shape

839 views Asked by At

I am trying to write a python program that will draw a random Tetris shape onto a board. Here's my code:

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

My problem is in the "self.current_shape = Board.draw_shape(the_shape). It says the_shape is not defined but I thought I defined it in the create_new_shape.

3

There are 3 answers

0
yas On

the_shape is local to your create_new_shape function, the name falls out of scope once the function exits.

0
yurib On

you did but the variable the_shape is local to the scope of that function. when you call create_new_shape() you store the result in a field, you should use it to reference the shape:

self.current_shape = self.create_new_shape()

# Draw the current_shape oan the board 
self.current_shape = Board.draw_shape(self.current_shape)
0
Keen On

You have two issues. The first is the scope issue that others have pointed out. The other issue is that you never instantiate the shape, you return a reference to the class. First, let's instantiate 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(Point(x, y))

Now the shape is instantiated, with the proper starting point. Next, scope.

self.current_shape = self.create_new_shape()

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

When you refer to pieces of data in the same object (here the board), you need to access them via self.thing. So we want to access the board, and tell it the shape to draw. We do so by self.board, then we add on the draw_shape method. Lastly, we need to tell it what to draw. the_shape is out of scope, it only exists in the create_new_shape method. That method returns a shape though, which we assigned to self.current_shape. So when you want to refer to that shape again anywhere inside the class, use self.current_shape.