Pygame Guide for Sneks


Home | GitHub | Pygame Docs


Project maintained by pygame-guide-for-sneks Hosted on GitHub Pages — Theme by mattgraham

Basic Window Setup in Pygame


In this article, we will go over the structure to open and keep the window running in pygame.

Table of contents

What is Pygame?

Before we get into the nitty gritty parts of it, let us first understand what pygame is. Pygame is a free and open source library for the Python programming language built on top of SDL2. Pygame allows us to build multimedia applications such as video games.

Pygame provides the very basic utility to draw and manipulate pixels on to the screen, much like SDL2, but with extended utility in various forms that makes it easier to use. Pygame gives you direct control over how you want the code to run, this means you could also easily do things that could drastically cause the drop of performance of your application if you aren't careful. This article guides you through how to avoid such things, while also giving you deeper understanding of pygame and how to use it.

Prerequisites

As pygame is a library for python, it is necessary that you are familiar with Python itself. This goes beyond the scope of this book, but there are some other great resources for learning Python, such as automate the boring stuff. Now, luckily you don't have to be an Anthony Shaw or Tim Peters to be able to use pygame, just some basic Python will do. This includes:

Since in Python everything is an object, that is also how you would interact with the utilities provided through pygame, so knowing how they work is crucial.

Installing Pygame

Pygame can be installed through pypi by using the pip package manager. This is as simple as,

pip install pygame-ce
BUT, how you access your pip depends on your Operating System and what interpreter you plan on using to run the code you will be writing throughout this article. For the sake of this article, we recommend installing pygame globally, and using your global interpreter to run your code. For windows, the way you access pip can be
pip install pygame-ce
# Or

# Accessing pip as a module through your python launcher

# For windows
py -m pip install pygame-ce

# For unix (Mac/Linux)
python3 -m pip install pygame-ce

# Relevant to both 
python -m pip install pygame-ce
py3 -m pip install pygame-ce
If you aren't too confident with where pygame is being installed, use your python launcher as shown in the last few methods to install it, and use the same launcher to run the code accordingly!

Setting Up the Project Directory

Throughout this whole miniseries, you will be required to work with a couple different files, it would be better and recommended if everything required to run your game is within one directory. We will create the required folders as we go, rather than take the generic approach and dump everything into our project folder that we wouldn't need(yet). But, we do still need some basic setup.

First, create a folder wherever you would like, and name it whatever you want. I will be naming it pygame_platformer and I will store it in my D:\dev\projects\ directory. Once you have your project directory created, make a main.py file. This is where the code for our game will be! For now that is enough. If you check the contents of your project folder, it should look like this:

PS D:\dev\projects\pygame_platformer> ls


    Directory: D:\dev\projects\pygame_platformer


Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
-a----        11-08-2022     22:09              0 main.py

Opening a Window With Pygame

Finally, we get into the actual code! Time to write the most legendary line at the top of our main.py file,

import pygame

Alright, now recall the part where I mention you should run all code through the same launcher to which pygame was installed. For this, the safest bet is opening up the same terminal application, and using your respective python launcher to run main.py. For me, this is py as I am on windows.

Your output should look like this:

PS D:\dev\projects\pygame_platformer> py main.py
pygame-ce 2.1.3 (SDL 2.0.22, Python 3.11.1)
If your code runs fine and you get the desired output, congrats 🎉 ! You just installed pygame successfully on your system! The Python version is to be noted, we will be using 3.10.4 in this article, the pygame version will be 2.1.2, but pygame takes backward compatibility seriously, and most older version code would work on newer verions too, and we wouldn't be introducing any of the newer features in this article. As of now 2.1.2 is the latest stable release of pygame.

Next up, after importing pygame, the first thing you do is to always initialize the module. If you don't do this step it can lead to problems later on, this initializes many submodules such as pygame.font, pygame.mixer, etc. which we will cover in detail later.

import pygame

pygame.init()

Now let's actually open up a window, for this, we will look at the pygame.display.set_mode function. This allows us to initialize the window, and it returns a pygame.Surface when called. A pygame.Surface is a data type which allows us to manipulate and draw pixels on it. This special surface is directly linked to what shows up on the window, so everything we want to appear on the window should be drawn on this special surface first. For now, let us look at what we need in order to call pygame.display.set_mode

import pygame

pygame.init()


WIN_SIZE = (420, 250)
screen = pygame.display.set_mode(WIN_SIZE)
Notice that we passed in a tuple containing two integers, the first integer is the width of the window we want to create, and the second is the height of the window. This fills in the size parameter which is the only required argument to call this function.

When you run this code, the window opens up and then closes immediately. Why is that? This is because there is nothing telling pygame that the window is alive, nor is the python program continuing to run. After creating that special surface we were talking about, it just closes. To keep the window alive and running, we need to keep the Python program running. To do this, let us create a while loop. From this point onward, the code presented is assumed to be added at the end of the file unless mentioned otherwise.

while True:
    pass
We notice two problems here:
  1. The window is really laggy, it hangs immediately. To close the application run ctrl + c in your terminal.
  2. The window is small, a bit too small.
We will address both the issues present here.

The window is really laggy.

While the python program is still running, pygame has no way of understanding that the window is still running, it needs some kind of system that checks for these events. For this, we can grab all the window events that are going on

while True:
    events = pygame.event.get()
This should make it responsive, and not hang.

The window is small.

It's all well and good if you want to window to be small, but generally you cant really tell what size of display your user is going to have, a fix-all solution for this is to use the pygame.SCALED flag. This way your application directly adjusts its size to fit the user's display. Not its aspect ratio, its size. The aspect ratio of the window stays the same. Try adding in the flag when calling pygame.display.set_mode

screen = pygame.display.set_mode(WIN_SIZE, flags=pygame.SCALED)
There we go! Our window is much more fit for our desktop now. Notice the aspect ratio of the window stays the same.

Exiting the game

We have an interesting problem, if you tried closing the application with the X button, it won't work. This is because you haven't defined what you want pygame to do when the X button is pressed. The way you exit it as of now is to use ctrl + c in the terminal you are running it from.

Obviously, this isn't ideal, at all. Remember how we grabbed all the events that were going on in the window? That actually includes closing it as well. All we have to do is check if the window is being closed(i.e, the X button is being pressed), and if it is we just need to exit our while loop. For this, we first iterate over the events

for event in events:
    pass
Make sure this is within the while loop. The iterator, i.e, the event object presented to us here is pretty useful. We can access it's type attribute which will be an integer, and check if that is going to be the type of event that corresponds to closing the window. Here's how it is done,
for event in events:
    if event.type == pygame.QUIT:
        pass
pygame.QUIT is the integer constant that represents trying to quit the application. Now, you can guess what to do next, we need to exit the loop. We ran this using a
while True:
So the only way to exit this is to throw an exception, the way one of the lead contributors of the pygame project itself like to do it, and I have adopted as well, is to raise SystemExit. Alternatively you can import sys, and run sys.exit().
while True:
    events = pygame.event.get()

    for event in events:
        if event.type == pygame.QUIT:
            raise SystemExit
And there we have it! Our game should close when we press the X button accordingly.

There are many different styles and ways to close a pygame application, you can raise an exception like shown here or use a variable to determine if the game is still running,

running = True 
while running:
    events = pygame.event.get()

    for event in events:
        if event.type == pygame.QUIT:
            running = False
There are some benefits to this, the application only closes after it completes the last iteration, rather than stopping midway! Another thing you can add to this is quitting pygame after the while loop. This can solve problems like IDLE keeping the window open even after you ended the application.
while running:
    events = pygame.event.get()

    for event in events:
        if event.type == pygame.QUIT:
            running = False

pygame.quit()

As a rule of thumb, you should also fill your screen with a solid color every frame, as to avoid seeing the last frame in the current one, and also updating your display.

screen.fill("black")

pygame.display.flip()
We can pass strings for colors in pygame, as covered in the colors article. pygame.display.flip just updates what is shown on the window, it does the same as pygame.display.update but internally when you call pygame.display.update without any arguments it simply calls pygame.display.flip

Final Result

Code:

import pygame

pygame.init()


WIN_SIZE = (420, 250)
screen = pygame.display.set_mode(WIN_SIZE, flags=pygame.SCALED)

running = True
while running:
    events = pygame.event.get()

    for event in events:
        if event.type == pygame.QUIT:
            running = False

    screen.fill("black")
    pygame.display.flip()

pygame.quit()


Useful Stuffs

You can visit the pygame documentation to find the full list of functions and other information about the Pygame library.

Other Useful Links


Pygame Examples

Want to contribute to this guide or did you find a problem? Visit us here!

Created by the Pygame Guide for Sneks Organization