Python is known as one of the most beginner-friendly and flexible programming languages. But while Python offers a fantastic onboarding experience for even the least experienced new programmer, it actually is More confusing to deal with it any other way. Python is so flexible that it is not immediately apparent what you can do with it.
For example, you can read a ton of tutorials and still don’t know how to make a game in Python or create 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 game creation easy.
What is pygame?
Something that can be difficult for new developers to understand is that programming languages rarely exist in a vacuum. For example, when building an Android app, in addition to using Java or Kotlin (the two main programming languages supported by Google), you also need to use the Android SDK. This is the “Software Development Kit” and it contains a variety of different libraries, classes, and tools that run Java code on Android and give it access to features that are unique to mobile platforms.
So it is with Python. For the most part, learning Python is not enough to start building: 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 one, 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 something of a barebones. You won’t find any built-in physics or a fancy drag-and-drop interface here! While this increases the workload for you as a developer, it also frees you from giving free rein to 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 collaborative venture since then and is currently released under the open source free software GNU Lesser General Public License.
How to Create a Game in Python – A Simple First Project
I’m going to turn my approach a little on the head for this tutorial. Instead of walking you through a game step by step, I’ll instead give you the code and then we’ll 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 will be able to get involved.
You’ll also need a Python IDE or a code editor like PyCharm or even Visual Studio.
See also: Install Python and start coding on Windows, Mac, or Linux
Next, paste in the following code. Here’s one that I did 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 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 honestly I find that way faster and clearer. And if that doesn’t mean anything to you, don’t worry!)
Hit play and you should be greeted with a game where you can control a small green square on the screen to dodge a red square. It is an exciting thing!
What does it all do?
Congratulations! You just learned how to make a game in Python! Unless you probably don’t know what all this does or why we did it that way. 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 probably came standard with your installation. If it doesn’t, you can install it using pip. We also have 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 the 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 going or not.
x = 100 y = 100 baddyX = 300 baddyY = 300 vel = 6 baddyVel = 4 run = True
Next up is a little function 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 black on top of each other.
Then the two squares are drawn. We place them in the window, give them RGB color codes, and then we set the X and Y coordinates before adding the width and height. Remember: down the hall and down the stairs! I thought it would make sense to make our bad guy a little bigger than the good guy and make him 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 real fun happens in the next part of the code. 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 will set our “frame rate” and keep everything from happening too fast for us to even see!
while run: pygame.time.delay(100)
Basically whatever we want to repeat will get into a loop. The first thing we put in here is a bit of code that defines our villain’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 villain’s coordinates, the villain will move to change this: it is approaching our position. Since our characters move a few pixels at a time (like through the vel and baddyVel Variables), I’ve added a little space 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 set to false and the program exits the loop. The last statement after the loop ends the game.
It’s still a little ugly though, as the coordinates set the top left corner of the square, not the center. This means that the collision detection is extremely shaky, and if you were really developing a game you’d do some math to make sure that if the characters even touch, the game will end.
Notice how we call every time the villain 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 noticed, the first part of this code also allows the player to exit 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 to 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 expand Vanilla Python’s abilities. 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! 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 hands-on guide to the best Python courses online. To attempt Programming with Python: Training for budding developers for only $ 49.99. Hurry up though, the course is valued at around $ 700.