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.