Tutorial #3

Subscribe to Tech With Tim!


This function is going to display the next falling shape on the right side of the screen.

def draw_next_shape(shape, surface):
    font = pygame.font.SysFont('comicsans', 30)
    label = font.render('Next Shape', 1, (255,255,255))

    sx = top_left_x + play_width + 50
    sy = top_left_y + play_height/2 - 100
    format = shape.shape[shape.rotation % len(shape.shape)]

    for i, line in enumerate(format):
        row = list(line)
        for j, column in enumerate(row):
            if column == '0':
                pygame.draw.rect(surface, shape.color, (sx + j*30, sy + i*30, 30, 30), 0)

    surface.blit(label, (sx + 10, sy- 30))

Now to actually see this on the screen we need to call the function from main().

# This should go inside the while loop right BELOW draw_window()
# Near the end of the loop
draw_next_shape(next_piece, win)

Clearing the Rows

As we all know in Tetris when all of the positions in a row are filled that row is cleared and every row about it is shifted down. The function clear_rows() will be where we do this. Essentially what we will do is check if a row is full. If it is we will delete that row. This will shift each row down one but leave us with one less row then before. To compensate for this we will add one row to the top of our grid.

For a detailed explanation please watch the video starting at 10:00.

def clear_rows(grid, locked):
    # need to see if row is clear the shift every other row above down one

    inc = 0
    for i in range(len(grid)-1,-1,-1):
        row = grid[i]
        if (0, 0, 0) not in row:
            inc += 1
            # add positions to remove from locked
            ind = i
            for j in range(len(row)):
                    del locked[(j, i)]
    if inc > 0:
        for key in sorted(list(locked), key=lambda x: x[1])[::-1]:
            x, y = key
            if y < ind:
                newKey = (x, y + inc)
                locked[newKey] = locked.pop(key)

Now we need to call clear_rows() from within the main() function.

Inside the while loop it will go in the following position.

def main():
    while run:
        if change_piece:
            for pos in shape_pos:
                p = (pos[0], pos[1])
                locked_positions[p] = current_piece.color
            current_piece = next_piece
            next_piece = get_shape()
            change_piece = False

            # call four times to check for multiple clear rows
            clear_rows(grid, locked_positions) # < ---------- GOES HERE