Last Updated:

Writing a game in Python | Pygame

game in Python

Python is well known as one of the most beginner-friendly and flexible programming languages. Python has fantastic capabilities for writing a variety of programs even for the least experienced new programmers. Python is so flexible that you can't immediately see what you can do with it.

You can read a ton of tutorials and still don't understand how to make a Python game or how to create a web app. In this post, we'll discuss how to make a very simple Python game with Pygame, a popular set of modules designed to make it easier to create games easily.

What is Pygame?

 

This is something that can be difficult for new developers to understand, so that programming languages rarely exist in a vacuum. For example, when creating an android app, you'll have to use not only Java or Kotlin (the two main programming languages supported by Google), but also the Android SDK.

It's a "software development kit," and it contains many different libraries, classes, and tools that make Java code work on Android and give it access to features that are exclusive to mobile platforms.

It's the same with Python. Learning Python isn't 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 support your production.

Pygame is one such collection of modules. And as the name suggests, Pygame provides many features useful for game development. This includes things like drawing graphics on the screen and playing sounds. By providing out-of-the-box features like this, Pygame can save the developer a huge amount of work and simplify the process. So, when you ask how to make a python game, most people will tell you to use Pygame!

However, those accustomed to more comprehensive game engines and IDEs like Unity may find Pygame somewhat bare bones. You won't find built-in physics or a fancy drag-and-drop interface here! But while this can increase the amount of work for you as a developer, it also frees you from having to use your imagination and approach your game project entirely from scratch.

Pygame was written by Pete Shinners and released in 2000. It has been a community project ever since, and it is currently released under the GNU Opensourcefreesoftware LesserGeneralPublicLicense license.

How to Make a Python Game – A Simple First Project

 

Instead of telling you a step-by-step game, I'll give you the code, and then we'll break down how it all works. Next, you'll walk past the following code.

importpygame
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
defdraw_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)

ifbaddyX< x — 10: baddyX = baddyX + baddyVeldrawGame() elifbaddyX> x + 10:
drawGame()
baddyX = baddyX — baddyVel
elifbaddyY< y — 10: baddyY = baddyY + baddyVelelifbaddyY> y + 10:
baddyY = baddyY — baddyVel
else:
run = False

for event in pygame.event.get():
ifevent.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()

And if that doesn't mean anything to you, don't worry!

Press the play button and you'll be greeted by a game that will allow you to control a small green square around the screen while trying to dodge the red square.

What does all this do?

 

Congratulations! You've just learned how to make a python game! Also, you probably don't know what it all does or why we did it the way we did. So let's get through that, okay?
First, we import the module with which Pygame is imported according to which Pygame. This will most likely already be on your computer and probably came by default with your installation.

If this is not the case, then you can install it using pip. We also need to initialize Pygame with pygame.init(). Next, we create a window to display our game. "Set_caption" allows us to give our game a name displayed at the top of a specified window.

importpygame
pygame.init()
win = pygame.display.set_mode((1280, 720))
pygame.display.set_caption(«Squarey»)

In this section, we define a set of variables: coordinates for ourselves and the bad guy, speed for ourselves and the bad guy, and a logical value (true or false) that tells us whether the game works or not.

PHPSELECT ALL
x = 100
y = 100
baddyX = 300 baddyY
= 300
vel = 6 baddyVel
= 4
run = True

Then there's the small drawGame() function.Here we first fill the screen with a blank color (black). This means that we can move the position of our characters without leaving a trace behind. Another option is to draw symbols on top of themselves in black.

This is followed by drawing two squares. We put them inside the window, give them RGB color codes, and then set the X and Y coordinates before adding width and height. Remember: down the hallway and down the stairs! I thought it made sense to make our bad guy a little bigger than the good guy and make him terribly red!

Finally, we call pygame.display.update(), so these elements are actually drawn on the screen:

defdraw_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()

The next part of the code is where the real fun happens. This is a "template pattern" that you will probably see in many of Pygame's creations. Essentially, this is a loop that will repeat as long as the run value is set to True.

The first line of this loop adds a short delay. Essentially, it's what will set our "frame rate" and prevent everything from happening too quickly for us to even be able to see!

whilerun:
pygame.time.delay(100)

Basically, everything we want to repeat will go in circles. The first thing we put here is a bit of code that determines the behavior of our bad guy. This uses if and elif (else, if) statements to control the flow of code.

If the value of the player's coordinates is greater than the bad guy's coordinates, then the bad guy will move to change that — to get closer to our position. As our characters move a few pixels at a time (as defined by the variables vel and baddyVel), I've added a bit of room for error.

ifbaddyX< x — 10: baddyX = baddyX + baddyVeldrawGame() elifbaddyX> x + 10:
drawGame()
baddyX = baddyX — baddyVel
elifbaddyY< y — 10: baddyY = baddyY + baddyVelelifbaddyY> y + 10:
baddyY = baddyY — baddyVel
else:
run = False

However, if the coordinates fall within 10 pixels of our player, then the game is over! run is set to False, and the program exits the loop. The last statement, following the loop, ends the game.

It's still a bit ugly though, given that the coordinates set the top left corner of the square, not the center. This means that collision detection is extremely shaky, and if you were actually making a game, you'd do some math calculations to make sure the game is over if the characters touched each other at all.

Note that every time the villain changes position, we call drawGame() and update the canvas. Finally, we need to get input from the player and move the player's character accordingly. Fortunately, Pygame does this very easily:

for event in pygame.event.get():
ifevent.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 realized, the first part of this code also allows the player to exit by clicking on the cross.

Now you know how to make a game in Python! At least you know how to make moving squares on the screen... But hopefully that's enough to give you an idea of how Pygame can expand vanillaPython's capabilities. Everything else is just a matter of learning the skills needed to add extra features until you have something that suits you!