Join us and get access to hundreds of tutorials and a community of expert Pythonistas.

Unlock This Lesson

This lesson is for members only. Join us and get access to hundreds of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Hint: You can adjust the default video playback speed in your account settings.

Setting up the Game Loop

In this lesson, you’ll add the game loop to your code. Every game uses a game loop to control gameplay. The game loop does four very important things:

  1. Processes user input
  2. Updates the state of all game objects
  3. Updates the display and audio output
  4. Maintains the speed of the game

You will create the event loop just below your current code, starting from line 27:

27 # Variable to keep the main loop running
28 running = True
29 
30 # Main loop
31 while running:
32     # Look at every event in the queue
33     for event in pygame.event.get():
34         # Did the user hit a key?
35         if event.type == KEYDOWN:
36             # Was it the Escape key? If so, stop the loop.
37             if event.key == K_ESCAPE:
38                 running = False
39 
40         # Did the user click the window close button? If so, stop the loop.
41         elif event.type == QUIT:
42             running = False

For more information about the pygame event loop, check out the following resources from the pygame documentation:

Comments & Discussion

Become a Member to join the conversation.