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,
pip install pygame-ce
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
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
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)
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)
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
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
while True:
events = pygame.event.get()
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)
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
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:
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
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
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()
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:
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()