Python is well known as one of the most beginner-friendly and flexible programming languages. But while Python has a fantastic onboarding experience for even the least experienced new programmers, it is actually more confusing to get to grips with in some other ways. Python is so flexible, that it isn’t immediately apparent what you can do with it.
You can read a ton of tutorials, for example, and still not understand how to make a game in Python, or how to build a web app. In this post, we’re going to discuss how to make a very simple game in Python using Pygame, the popular selection of modules designed to facilitate simple game creation.
What is Pygame?
Something that can be tricky for new developers to understand is that programming languages seldom exist in a vacuum. When making an Android app for example, you will not only have to use Java or Kotlin (the two primary programming languages supported by Google) but also the Android SDK. This is the “software development kit” and it contains a host of different libraries, classes, and tools that make Java code work on Android and give it access to the features that are exclusive to mobile platforms.
So it is with Python. Learning Python is not enough to start building things for the most part: you need additional code supplied by other developers in order to make those programs work. In Python, these external tools usually take the form of “modules.” These are small Python programs that perform useful functions that can support your production.
Pygame is one such collection of modules. And as the name suggests, Pygame supplies lots of functions that are useful for game development. That means things like drawing graphics onto the screen and playing sounds. By providing ready-made functions like this, Pygame can save a developer a huge amount of work and streamline the process. Thus, when you ask how to make a game in Python, most people will tell you to use Pygame!
That said, those used to more comprehensive game engines and IDEs like Unity may find Pygame to be somewhat barebones. You won’t find built-in physics or a fancy drag-and-drop interface here! But while this might increase the amount of work for you as a developer, it also liberates you to use your imagination and to approach your game project entirely from scratch.
(This is a good thing, honest!)
Pygame was written by Pete Shinners and was released in 2000. It has been a community project since then and is currently released under the open source free software GNU Lesser General Public License.
How to make a game in Python – A simple first project
I’m going to turn my approach a little on its head for this tutorial. Instead of talking you through a game step-by-step, I’m instead going to give you the code and then we’re going to break down how it all works.
First, make sure you’ve read our basic introduction to Python code:
This will familiarize you with the basics so that you’ll be able to follow along.
You will also need a Python IDE or code editor, which you can learn about here:
Next, you’re going to past the following code. Here’s one I made earlier:
import pygame pygame.init() win = pygame.display.set_mode((1280, 720)) pygame.display.set_caption("Squarey") x = 100 y = 100 baddyX = 300 baddyY = 300 vel = 6 baddyVel = 4 run = True def drawGame(): win.fill((0, 0, 0)) pygame.draw.rect(win, (0, 0, 255), (x, y, 20, 20)) pygame.draw.rect(win, (255, 0, 0), (baddyX, baddyY, 40, 40)) pygame.display.update() while run: pygame.time.delay(100) if baddyX < x - 10: baddyX = baddyX + baddyVel drawGame() elif baddyX > x + 10: drawGame() baddyX = baddyX - baddyVel elif baddyY < y - 10: baddyY = baddyY + baddyVel elif baddyY > y + 10: baddyY = baddyY - baddyVel else: run = False for event in pygame.event.get(): if event.type == pygame.QUIT: run = False keys = pygame.key.get_pressed() if keys[pygame.K_LEFT]: x -= vel if keys[pygame.K_RIGHT]: x += vel if keys[pygame.K_UP]: y -= vel if keys[pygame.K_DOWN]: y += vel drawGame() pygame.quit()
Hit play and you should be greeted with a game that lets you control a little green square around the screen trying to evade a red square. It’s thrilling stuff!
What does all this do?
Congratulations! You just learned how to make a game in Python! Except you probably don’t know what any of this does or why we’ve done it the way we have. So let’s go through it, shall we?
First, we import the Pygame module with the line import pygame. This will likely already be on your machine and probably came as default with your installation. If it didn’t, then you can install it with pip. We also need to initialize Pygame with pygame.init(). Next, we create a window for our game to display in. “Set_caption” lets us give our game a title, displayed at the top of said window.
import pygame pygame.init() win = pygame.display.set_mode((1280, 720)) pygame.display.set_caption("Squarey")
In the next section, we’re defining a bunch of variables: coordinates for ourselves and the bad guy, a speed for ourselves and the bad guy, and a boolean (true or false value) that tells us whether the game is running or not.
x = 100 y = 100 baddyX = 300 baddyY = 300 vel = 6 baddyVel = 4 run = True
There’s a little function next called drawGame().In here, we are first filling the screen with a blank color (black). Doing this means we can move the position of our characters without leaving behind a trail. Another option would be to draw the characters on top of themselves in black.
This is followed by drawing the two squares. We are placing them inside the window, we are giving them RGB color codes, and then we are setting the X and Y coordinates before adding in width and height. Remember: along the corridor and down the stairs! I thought it made sense to make our bad guy a little bit bigger than the good guy, and to make him scary red!
Finally, we call pygame.display.update(), so that these elements actually get drawn on the screen.
def drawGame(): win.fill((0, 0, 0)) pygame.draw.rect(win, (0, 0, 255), (x, y, 20, 20)) pygame.draw.rect(win, (255, 0, 0), (baddyX, baddyY, 40, 40)) pygame.display.update()
If you aren’t sure what a function is, then check out this nifty little tutorial:
How to create a game loop in Python
The next part of the code is where the real fun happens. This is the “boilerplate” that you’ll likely see in a lot of Pygame creations. Essentially, this is a loop that is going to keep repeating as long as the value of run is set to True.
The first line of this loop adds a short delay. In effect, this is what will set our “framerate” and prevent everything from happening too fast for us to even see!
while run: pygame.time.delay(100)
Basically, everything that we want to happen repeatedly is going to go into loop. The first thing we’re putting here is a bit of code that defines the behavior of our bad guy. This uses if and elif (else, if) statements in order to control the flow of the code. If the value of the player’s coordinates are larger than the bad guy’s coordinates, then the bad guy will move to change this: closing in on our position. Because our characters move a few pixels at a time (as defined by the vel and baddyVel variables), I have added a little room for error.
if baddyX < x - 10: baddyX = baddyX + baddyVel drawGame() elif baddyX > x + 10: drawGame() baddyX = baddyX - baddyVel elif baddyY < y - 10: baddyY = baddyY + baddyVel elif baddyY > y + 10: baddyY = baddyY - baddyVel else: run = False
However, if the coordinates fall within the 10 pixels of our player, then it’s game over! run is set to False, and the program exits the loop. The final statement following the loop quits the game.
It’s still a little ugly though, seeing as the coordinates set the top left corner of the square, not the center. This means the collision detection is extremely wonky, and if you were really making a game, you would do some maths to make sure the game ended if the characters touched at all.
Notice how each time the baddy changes position, we call drawGame() and refresh the canvas.
Finally, we need to get the input from the player and move the player character in accordance with this. Thankfully, Pygame makes this very easy:
for event in pygame.event.get(): if event.type == pygame.QUIT: run = False keys = pygame.key.get_pressed() if keys[pygame.K_LEFT]: x -= vel if keys[pygame.K_RIGHT]: x += vel if keys[pygame.K_UP]: y -= vel if keys[pygame.K_DOWN]: y += vel drawGame()
As you may have gathered, the first part of this code also allows the player to exit by clicking the cross button.
Finally, we quit the game once the loop has ended!
This is what we are left with:
It’s not exactly Cyberpunk 2077, but hey at least it’s finished! #burn
Where to go from here
Now you know how to make a game in Python! At least you know how to make moving squares on a screen… But hopefully, this is enough to give you an idea of how Pygame can extend the capabilities of vanilla Python. The rest is just a matter of learning the skills you need to add additional features, until you have something you’re happy with! Check out the official documentation here.
Or, if you want to accelerate your development and learn marketable skills, why not take an online course? This is the fastest way to learn Python properly, and we even have a handy guide to the best online Python courses. Try Coding with Python: Training for Aspiring Developers for just $49.99. Hurry though, as the course is valued around $700.