Python is known as one of the most beginner-friendly and flexible programming languages. While Python offers a fantastic onboarding experience for even the least experienced new programmers, it actually is More confusing to find your way around any other way. Python is so flexible that it isn’t immediately apparent what you can do with it.
For example, you can read a ton of tutorials and still not understand how to make a game in Python or how to make a web app. In this post we are going to discuss how to make a very simple game in Python using Pygame, the popular selection of modules designed to make it easy to create games easily.
What is pygame?
It can be difficult for new developers to understand that programming languages rarely exist in a vacuum. For example, when building an Android app, in addition to using Java or Kotlin (the two primary programming languages supported by Google), you also need to use the Android SDK. This is the “Software Development Kit,” which contains a variety of different libraries, classes, and tools that make Java code work on Android and provide access to features that are only available for mobile platforms.
It is the same with Python. Learning Python is not enough to start building things for the most part: you need additional code provided by other developers to make these programs work. In Python, these external tools usually take the form of “modules”. These are small Python programs that perform useful functions that can aid your production.
Pygame is one such collection of modules. And as the name suggests, Pygame has many features that are useful for game development. That means things like drawing graphics on the screen and playing sounds. By providing pre-built features like this, Pygame can save a developer a lot of work and streamline the process. So if 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 a little barebones. You won’t find any built-in physics or a fancy drag-and-drop interface here! While this can add to the workload for you as a developer, it also frees you from using your imagination and starting your game project from scratch.
(That’s a good thing, honestly!)
Pygame was written by Pete Shinners and published in 2000. It has been a community project since then and is currently released under the open source software GNU Lesser General Public License.
How to Make a Game in Python – An Easy First Project
I’m going to turn my approach a little on the head for this tutorial. Instead of taking you step by step through a game, I’ll instead give you the code and then we’ll break down how it works.
First, make sure you’ve read our basic introduction to Python code. This will familiarize you with the basics so that you can follow along.
You’ll also need a Python IDE or a code editor like PyCharm or even Visual Studio.
See also: Here’s how to install Python and start coding on Windows, Mac, or Linux
Next, paste in the following code. Here is one that I used to do:
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 draw_game(): 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 draw_game() pygame.quit()
(In a perfect world I would use snake case for the coordinates, but in all honesty I find that much quicker and clearer. And if that doesn’t mean anything to you, don’t worry about it!)
When you hit “Play” you should be greeted with a game that lets you control a small green square on the screen to dodge a red square. It’s exciting stuff!
What does it all do?
Congratulations! You just learned how to make a game in Python! Unless you probably don’t know what all of this is doing, or why we did it the way we did. So let’s go through it, shall we?
Using pip to install modules
First we import the pygame module with the line Import pygame. This is likely already present on your computer and was used by default during your installation. If not, you can install it using pip. We also need to initialize pygame pygame.init (). Next, we’ll create a window that our game can be viewed in. With “Set_caption” we can give our game a title that will be displayed at the top of this window.
import pygame pygame.init() win = pygame.display.set_mode((1280, 720)) pygame.display.set_caption("Squarey")
In the next section we define a number of variables: coordinates for us and the bad guy, a speed for us and the bad guy, and a boolean value (true or false) that tells us whether the game is on or not.
x = 100 y = 100 baddyX = 300 baddyY = 300 vel = 6 baddyVel = 4 run = True
Next, a small function is called Character game ()Here we first fill the screen with a blank color (black). This way we can shift the position of our characters without leaving a trace. Another option would be to draw the characters over you in black.
Then the two squares are drawn. We place them in the window, give them RGB color codes, and then set the X and Y coordinates before adding the width and height. Remember: along the corridor and down the stairs! I thought it would make sense to make our bad guys a little bigger than the good guys and make them scary red!
Finally we call pygame.display.update ()so that these elements are actually drawn on the screen.
def draw_game(): 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()
See also: How to call a function in Python
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 are likely to see in many pygame creations. Essentially, this is a loop that repeats for as long as the value of Run is set to True.
The first line of this loop adds a short delay. In fact, this is what sets our “frame rate” and prevents everything from going too fast for us to even see!
while run: pygame.time.delay(100)
Basically anything we try to do repeatedly will get into a loop. The first thing we put in here is a bit of code that defines our evil’s behavior. This used if and elif (else, if) statements to control the flow of code. If the value of the player’s coordinates is greater than the coordinates of the evil one, the evil one will change that: he is approaching our position. Because our characters move a few pixels at a time (like through the vel and baddyVel Variables) I’ve added a little room for errors.
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 are within our player’s 10 pixels, it’s game over! Run is set to False and the program exits the loop. The last statement after the loop ends the game.
It’s still a little ugly as the coordinates set the top left corner of the square rather than the center. This means that the collision detection is extremely shaky. If you were really making a game you would do some math to make sure the game would end if the characters touched at all.
Notice how we call every time the bad guy changes position Character game () and refresh the canvas.
Finally, we need to get the input from the player and move the player character accordingly. Fortunately, 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 draw_game()
As you may have already learned, the player can also exit in the first part of this code by clicking the cross button.
Finally, once the loop is over, we’ll end the game!
That’s left for us:
It is not accurate Cyberpunk 2077but hey at least it’s done! #burn
Where do you 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 will be 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 extra functionality until you have something that you are happy with! Read the official documentation here.
Or take an online course if you want to accelerate your development and learn marketable skills. This is the fastest way to learn Python properly, and we even have a hands-on guide to the best Python courses online. To attempt Coding with Python: training for budding developers for only $ 49.99. Hurry, the course is worth around $ 700.