Home | GitHub | Pygame Docs
In this article, we will go over the structure to open and keep the window running in 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.
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:
Pygame can be installed through pypi by using the pip package manager. This is as simple as,
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 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!
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:
Finally, we get into the actual code! Time to write the most legendary line
at the top of our main.py
file,
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: 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.
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
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. We notice two problems here:
ctrl + c
in your terminal.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 This should make it responsive, and not hang.
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
There we go! Our window is much more fit for our desktop now. Notice the aspect ratio of the window stays the same.
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
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,
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
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()
.
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,
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.
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.
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
Code: