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:
- Processes user input
- Updates the state of all game objects
- Updates the display and audio output
- 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
28running = True
29
30# Main loop
31while 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:
realneutron on Dec. 20, 2020
HI! Using Python 3.7.9 on Windows 10 in the Thonny IDE. Detection of the close window button, or the ESCAPE key press is not happening.
My IDE throws out warnings similar to:
Module ‘pygame.locals’ has no attribute ‘K_ESCAPE’
I’m currently googling and not finding anything immediately helpful. I’m curious what your solution is. I’m thinking it has something to do with how the Pygame packaged was installed through Thonny, but I’m not certain. It appears to be installed correctly. I was able to verify through PIP that pygame is installed.