Random Drops
Lesson 11 of 41 in Coddy's Make Games with Pygame course.
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
EasyDrop a new block at a random place after each one.
- Add
import randomat the top. - After the block falls, when
block.top > 360, setblock.y = -20andblock.xtorandom.randint(0, 460).
Press Play: blocks keep dropping at random places. Then Check.
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 Make Games with Pygame
2Events and Collisions
The BasketA Falling BlockPractice on your own: Pygame playground