Finish Your Game
Part of the Projects section of Coddy's Pygame journey. Lesson 31 of 31.
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 the journey: a sprite Group in place of the list, pictures, a sound on a hit, music, a menu before the game, a high score, rooms built from text 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 so that it has:
- Something that moves by itself.
- Text on the screen, such as a score or a timer.
- 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: shapes or pictures, sounds, music, states and maps all work.
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 Projects
Practice on your own: Pygame playground