Introduction to Game Development in Python (part 1)

Arpit Omprakash
Byte-Sized-Code
Published in
8 min readMay 15, 2020

Game development is a rewarding experience and also an exciting teaching tool. But what can you learn by coding the most boring game? This post serves as an introduction to Pygame by helping you write a simple program.

A game of Chess between the Holmes brothers

Pygame is an excellent tool for developers. It isn’t set up to be compatible with mobile devices. Also, due to Python’s nature, it isn’t great for commercial products in general; yet, its strengths include its ease of use and accessibility. The flow of the Pygame workflow is a fantastic way for beginners to learn game programming at a deeper level. It is straightforward, while also having a fair amount of depth.

Before jumping right into coding, we first need to know some basic stuff. Thus, we take this short diversion to help you better understand the purpose and basics of installing and using Pygame. You can skip this part if you are already familiar with Pygame.

GUI vs. CLI

The “normal” python programs that you write with pythons built-in functions interact with the user by print and input statements. You can output text onto the screen, and the user inputs values using the keyboard. These kinds of programs are said to have a CLI (Command Line Interface, pronounced as See-El-Eye). CLI are interfaces that heavily depend on the keyboard and are generally devoid of graphics.

On the other hand, GUI (Graphical User Interface, pronounced as Gooey) displays graphical stuff, as the name indicates. All of us are most familiar with this interface. In fact, the screen you are using to read this post is a GUI, and the machine you are running it on (Windows, Android, Ubuntu, or iOS) is also a GUI.

A CLI program is somewhat limited in terms of functionality. As some of you may have noticed, a CLI program waits for the user to input an answer using the keyboard and press enter before the application can process the information. This means a program (or game) cannot process input in real-time (as the user presses a button). CLI programs also lack the visual appeal of color and graphics. Thus, it is essential to learn to program in GUI to develop advanced games using graphics (like this game of snake).

Pygame provides functions for creating programs with GUI. Pygame functions easily take care of things like drawing graphics, playing sounds, handling mouse input, and other items necessary to develop GUI applications.

Installing Pygame

I believe it is better to learn by coding rather than just reading random articles or books. Here is the source code for a simple “Hello World” program in Pygame that we will use as a reference to learn more about Pygame. I highly encourage people to write this simple snippet of code and play around with it as we discuss different features of Pygame.

Since you are here, I assume you know at least a bit of python and what pip is. If not google it! It’s never too late to learn. If you haven’t installed Pygame yet, you can do so by running the following commands:

python -m pip install pygame

To check if it is properly installed, you can run an example file included in the package:

python3 -m pygame.examples.aliens

If it works, you are ready to go! Else have a look here.

The World’s Most Boring Game

Type the above code in an empty file and save it with the extension “.py”. Then go on and run the program. A window like this should appear:

The most boring game in pygame!

Yay! You just made the world’s most boring video game! It’s just a blank screen with a “Hello World!” on the top of the window (title bar). Like a standard window, clicking on the X button on the corner of the window will end the game and make the window disappear.

Lets’s take a closer look at the program.

Setting up a Pygame Program

The first few lines of the code will be found in almost any program that uses Pygame.

import pygame, sys
from pygame.locals import *

The first line is a simple import statement that imports the pygame and sys modules. It enables us to use the functions present in the respective modules to develop our game. All of the Pygame functions dealing with graphics, sound, and other features that Pygame provides are in the pygame module.
The second line imports several constant variables stored in the pygame.locals module that we can use in our program.

pygame.init()

The fourth line is the pygame init function call, which always needs to be called after importing the pygame module and before calling any other Pygame function. The init function initializes all the imported modules of Pygame before they can be used. Failure to include this in any program will always lead to errors.

DISPLAYSURF = pygame.display.set_mode((400, 300))

The fifth line calls the set_mode function that returns a pygame.Surface object for the window (Surfaces coming up in the next post). The supplied tuple (400, 300) will return a window with a width of 400 pixels and a height of 300 pixels. Note: The set_mode function takes in a tuple as an argument. A TypeError is thrown when you try to supply two ints instead of a tuple.

pygame.display.set_caption('Hello World!')

Line 6 sets the caption text that will appear on the title bar of the game. It takes a string as an argument and makes the text appear as the caption:

Title bar caption

Game Loops and Game States

while True: # main game loop
for event in pygame.event.get():

The while loop in line number 7 is special. It always evaluates to True and, thus, is an infinite while loop. The loop never exits unless it encounters a break, return, or in our case, the sys.exit() call.

Most of the games developed in pygame or in general have a while loop along with a comment (good programmers always comment!) calling it the “main loop” or “game loop”, even the “main game loop”. A game loop is a loop where the code does three things:

  • Handles events
  • Updates the game state
  • Draws the game state to the screen

The game state simply refers to a set of values for all the variables in a game program. In many games, the game state includes the set of variables that track a players health and position, the health and position of any enemies, any marks/trails made by the player or enemy, the score, whose turn it is and other things that describe a precise moment in the game.

A game state can be thought of as a picture of an instance of the game. Whenever you pause a game, the game state doesn’t change, and saving a game basically saves the game state.

Since players interact with the game using events (such as a mouse click or keyboard presses), the game state is usually updated in response to such events. The game loop constantly checks and re-checks many times a second for any new events that have happened and updates the game state accordingly. In Pygame, this is done by calling the pygame.event.get() function.
The main loop also contains code that updates the game state based on which events have been created. This is termed as event handling.

The game loop

pygame.event.Event Objects

Any time the user does one of the several actions such as pressing a keyboard, or moving/clicking the mouse on the program’s window, a pygame.event.Event object is created to record this “event”. We can get a list of events that have happened by calling the pygame.event.get() function.
This is precisely what we are doing in the first line inside the while loop. The pygame.event.get() function returns a list of events that have happened since the last time the function was called.

while True: # main game loop
for event in pygame.event.get():

The for loop will iterate over the list of events that have happened since the last time the get function was evoked. On each iteration, a variable named event is assigned the value of the next event object in the list. The list is sequential, i.e., the order of events in the list is the order in which they happen. If no events have happened, an empty list is returned.

The QUIT Event

Event objects have an attribute (or property) called type, which tells what kind of event the object represents. Pygame has a constant variable for each of the possible types in the pygame.locals module.

if event.type == QUIT:
pygame.quit()
sys.exit()

The first line of this code block checks if the event type is equal to the constant QUIT. If the event object is a quit event, then the pygame.quit() and sys.exit() lines are run, closing the pygame module and closing the window. The pygame.quit() function is like the opposite of the pygame.init() function and deactivates the pygame library. The sys.exit() closes the window and terminates the program.

One should always call pygame.quit() before calling sys.exit() . In most cases, it works just fine either way, but in some cases, some bugs will crash the native python IDLE (if you are using IDLE). Also, many times I have noticed that one has to manually turn off the instance of pygame from the task manager if you don't call the pygame.quit() function at the end of your program.

Since there are no other ‘if’ statements, the code doesn’t do much of event handling, and our keyboard presses and mouse movements go unnoticed. The program then continues to the final line:

pygame.display.update()

The function in the last line draws the Surface object returned by pygame.display.set_mode to the screen. Since the Surface object hasn’t changed, the same black image is redrawn to the screen each time pygame.display.update() is called. That’s the whole program. The program then returns to executing the while loop from the beginning and repeating the process described again and again till we close the window.

Conclusion

Wait! It’s just this? Probably that’s what all of you are wondering right now. The post serves as a simple and easy to grasp introduction to Pygame. Here is a link to making a game of snake in Pygame for the interested readers.

Things that you learned:

  • The basic structure of a Pygame program
  • Game Loops and game states
  • Events and event handling in Pygame

Soon, I’ll post another article that dives deeper into the objects and graphics parts of the Pygame library. Follow to get notified of the next article on Pygame. If you found this article interesting or helpful, do clap, share, and recommend it!

--

--

Arpit Omprakash
Byte-Sized-Code

I'm a Programming and Statistics enthusiast studying Biology. To find out if we have common interests, have a look at my thoughts: https://aceking007.github.io/