Menu
CoddyTech

A Falling Block

Lesson 10 of 40 in Coddy's Make Games with Pygame course.

Something falling is something whose y grows every frame. Make the block a Rect too, and add to its y in each pass of the loop:

block = pygame.Rect(220, 0, 20, 20)

while running:
    # events and keys
    block.y += 3
    # fill, draw

At 60 frames a second, 3 pixels a frame is 180 pixels a second. The window is 360 tall, so the block takes two seconds to reach the bottom.

The block keeps falling after it leaves the window. Nothing stops it yet; the next lesson brings it back.

challenge icon

Challenge

Easy
  1. Below the basket, make block = pygame.Rect(220, 0, 20, 20).
  2. In the loop, after the basket moves, add 3 to block.y.
  3. Draw the block in red (235, 80, 80) after the basket.

Try it yourself

import pygame

pygame.init()
screen = pygame.display.set_mode((480, 360))
pygame.display.set_caption("Catch the Blocks")
clock = pygame.time.Clock()

basket = pygame.Rect(200, 330, 80, 16)

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    keys = pygame.key.get_pressed()
    if keys[pygame.K_LEFT]:
        basket.x -= 8
    if keys[pygame.K_RIGHT]:
        basket.x += 8
    basket.clamp_ip(screen.get_rect())

    screen.fill((30, 30, 46))
    pygame.draw.rect(screen, (80, 160, 255), basket)
    pygame.display.flip()
    clock.tick(60)

pygame.quit()
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Make Games with Pygame

Practice on your own: Pygame playground