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.
keepGameRunning=true
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.
Python3
import pygame
pygame.init()
pygame.display.set_mode(( 400 , 500 ))
pygame.display.set_caption( 'GeeksforGeeks' )
running = True
while running:
for event in pygame.event.get():
if event. type = = pygame.QUIT:
running = False
|
Output:
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.
Python3
import pygame
pygame.init()
window = pygame.display.set_mode(( 400 , 500 ))
running = True
color = "red"
while running:
for event in pygame.event.get():
if event. type = = pygame.QUIT:
running = False
window.fill(color)
pygame.display.flip()
if (color = = "red" ):
color = "green"
else :
color = "red"
|
Output:
Last Updated :
01 Oct, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...