In this tutorial, we will be creating the game loop of our PyGame game. By adding the game loop, we can keep our game window from disappearing. If by chance you don’t have a game window yet, you can check out this part of our PyGame Basics series.

To create our game loop, we need a clock to set the FPS, or frames-per-second of our game. Under the last line of our game window code, add the following line:

clock = pygame.time.Clock()

We will also need a variable to determine whether or not the game is running. Under the line where we instantiate a clock, add the following variable declaration:

running = True

Now we need to add the actual game loop. Our PyGame game loop will be made up of a while loop. Let’s start by adding a while loop checking if running is true.

while running:

Inside our while loop, we need to check if any internal game events have been triggered. For example, if we click the close button, we want our game window to close. To add this mechanic, append the following bit inside our while loop.

for event in pygame.event.get():
    if event.type == pygame.QUIT:
        running = False

After the for loop, but still inside the while loop, we need to render anything that needs to be drawn, as well as ensure the game FPS is set at 60. Add the following two lines after the for loop.

pygame.display.update()
clock.tick(60)

Additionally, we will also want the game to quit properly if the game loop breaks. Add these two lines after the while loop.

pygame.quit()
quit()

When we run the game at this point, we should see that our game window no longer disappears. We are now ready to add some content to our game!

If you found this guide helpful, you may consider taking a look at the rest of this tutorial series. To receive news about our latest tutorials and courses, be sure to subscribe to our newsletter.

Sharing this tutorial on your favorite social media platform would be much appreciated, only if you found this guide valuable.

Subscribe To Our Newsletter

Subscribe To Our Newsletter

Join our mailing list to receive the latest news regarding tutorials and courses we publish!

Please check your inbox to confirm your subscription.

Share This