Menu
CoddyTech

Finish Your Game

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

Now steps 3 to 5: a challenge, an ending and text. Rock Dodge uses one idea you have not seen yet, a list of Rects: a new rock every 400 ms, many on the screen at once.

rocks = []

# on a NEW_ROCK timer event:
rocks.append(pygame.Rect(random.randint(0, 450), -30, 30, 30))

# every frame:
for rock in rocks:
    rock.y += 5
    if rock.colliderect(player):
        state = "lost"
rocks = [rock for rock in rocks if rock.top < 360]

The last line is a list comprehension: a new list with only the rocks still on screen, so the list does not grow forever.

A state string, "playing", "lost" or "won", replaces several flags. And pygame.time.get_ticks() gives the milliseconds since the game started, which makes a timer: survive 20 seconds to win.

Make your game your own: change the colours, the speeds, the rules. Then play it. If it is too hard to win or too quick to lose, change the numbers until it is fun.

challenge icon

Challenge

Easy

Finish your game so that it has:

  1. Something that moves by itself.
  2. Text on the screen, such as a score or a timer.
  3. An ending: a way to win, a way to lose, or both.

The checks look for text, something moving with no key held, a game that runs for 30 seconds without an error, and a window that closes. Everything else is up to you.

Try it yourself

import pygame

pygame.init()
screen = pygame.display.set_mode((480, 360))
pygame.display.set_caption("Rock Dodge")
clock = pygame.time.Clock()

player = pygame.Rect(220, 320, 40, 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]:
        player.x -= 7
    if keys[pygame.K_RIGHT]:
        player.x += 7
    player.clamp_ip(screen.get_rect())

    screen.fill((30, 30, 46))
    pygame.draw.rect(screen, (80, 160, 255), player)
    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