Menu
CoddyTech

Random Drops

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

When the block falls past the bottom, put it back above the top so it falls again. Its top is past the bottom when block.top > 360.

To make the game less predictable, drop it at a random place. Python's random module picks numbers: random.randint(0, 460) is a whole number from 0 to 460, both included.

import random

if block.top > 360:
    block.y = -20
    block.x = random.randint(0, 460)

Why 460? The block is 20 wide, so an x of 460 puts its right side at the window's edge. And y = -20 puts it right above the window, so it slides in from the top.

challenge icon

Challenge

Easy
  1. Add import random at the top.
  2. After the block falls, when block.top > 360, set block.y = -20 and block.x to random.randint(0, 460).

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)
block = pygame.Rect(220, 0, 20, 20)

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

    block.y += 3

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

pygame.quit()

All lessons in The Game Loop

Practice on your own: Pygame playground