Finish Your Game
Lesson 41 of 41 in Coddy's Make Games with Pygame course.
Now steps 3 to 5: a challenge, an ending and text. Rock Dodge keeps its rocks in 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", decides what each frame does, as in Sky Runner. And pygame.time.get_ticks() gives the milliseconds since the game started, which makes a timer: survive 20 seconds to win.
Your game can use everything from this course, and the Pygame journey shows more: sprites, pictures, sound, menus, high scores and maps.
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
EasyFinish your game.
- Add something that moves by itself.
- Show text on the screen, such as a score or a timer.
- Give it an ending: a way to win, a way to lose, or both.
Press Play: something moves on its own and your text shows. Then Check.
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()
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