How to set up the Game Loop in PygGame ?
In this article, we will see how to set up a game loop in PyGame. Game Loop is the loop that keeps the game running. It keeps running till the user wants to exit. While the game loop is running it mainly does the following tasks:
- Update our game window to show visual changes
- Update our game states based on user inputs
- Handle different types of events
- Keep game window running
Simply game loop is a while loop having only one condition to check whether our boolean condition to keep the game running is true.
Setting up the Game Loop
Step 1: Declare a Boolean variable to true which will be used to check whether our player wants to keep playing our game or not.
Step 2: Create a while loop and check our above Boolean variable that whether it is true or not. If true keep the loop running which suggests keeping our game loop running. In this while loop check for events and if the event is quit then set the above variable too false to exit our game loop and end our pygame window.
while keepGameRunning: for event in pygame.event.get(): if event.type == pygame.QUIT: keepGameRunning = False
Below is the complete implementation.
In the below code, we are creating a simple game loop that creates a pygame window and checks if the event type is quit and, if it is true then quit the game.
In the below code, we added one more task to our game loop i.e. to update our screen in each loop. Here we change the background color for each loop by updating our screen in each loop.
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course