Menu
CoddyTech

A Falling Block

Part of the The Game Loop section of Coddy's Pygame journey. Lesson 24 of 32.

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.

This game moves by the frame, as Move a Square did, not by dt. A Rect keeps whole numbers only, so a step such as 0.6 pixels would be cut to 0 and the Rect would never move. Games that move Rects by time keep the position in a Vector2 and copy it to the Rect.

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()

All lessons in The Game Loop

Practice on your own: Pygame playground