If you're a coder and have played any sort of video game, I'm sure that you've caught yourself wondering at least once about how creators like Sega, Treyarch or Nintendo actually put together the finished product. Hopefully this article can satisfy that inner curiosity you've had for how to make some of these games. We'll be using python, because firstly, it's a popular language and secondly, it's super easy to use. Some purists may claim that C++ is the best language for making simple games, but as I said, Python is easy to use and pygame was specifically built just for making games.

So, how do we approach making a game using python and pygame? I've divided the tutorial into 4 major steps:

  1. Getting a hang of how to develop game foundations using a text-based game.
  2. Learning how to use pygame.
  3. Adding sprites.
  4. Putting it all together to make a masterpiece.

For the purposes of this tutorial, we'll be simulating a few games overall, but primarily we'll set our goal to be making a Monopoly game. Rather than just throwing in a lot of lines of code here, I prefer giving the outline and some intuition on how to proceed. All the code used for the tutorial bit can be found here. Without further ado, let's start!

Step 0: The prerequisites

Well, the major prerequisite is being comfortable with basic python syntax. I'll be assuming that you already know python as I move along, but if you don't, there are plenty of sources to learn from. I would recommend MIT OCW's 6.0001, Introduction to Computer Science and Programming in Python, as it's a very structured way to learn the language.

There are a handful of libraries that are useful for game making in python like PyOpenGL and pyglet. However, for this tutorial, I'll be using pygame. It's convenient and fairly easy to work with. To get the pygame library, just hit:

pip3 install pygame

in the terminal or command prompt (if you use Windows).

The only other prerequisite remaining is a tool to draw your characters and backgrounds in. How fancy your designs and characters are is up to you. Personally, I'm not much of a designer and hence a tool like GIMP (Gnu Image Manipulation Program) suffices for me. You can also use Photoshop, Illustrator, Blender or even Tux Paint if that's what suits you. How you design the game is your choice, but it helps if you're thoroughly proficient with at least one design tool.

Step 1 : Rules of the Game

Before we can make our own Assassin's Creed, it's imminent that we first get comfortable with the idea of actually writing up code for a video game. You could think of this as just translating the game's principles and rules from English to python. This is where core CS principles come into play. Proficiency in object oriented programming goes a long way, but just knowing how to use objects and classes well suffices. The best way to master the skill of enforcing the game rules in python is to remove the graphics aspect entirely from your approach and learning by making text-based games. The code for this section can be found here.

Let's try making a simple business strategy game in python. I'll be making a game based off of monopoly but you're free to try whatever you want. It'll be a text-based game, so don't expect it to look fancy. Before we start coding anything, it's imperative that we first define our rules in English (or whichever language you speak in). Let's say we want this game to be played by two players on a board. The board consists of a set of "places". Each place costs a certain amount of money and has a certain "rent", which is a payment that a player has to pay when landing on a place owned by another player. The places on the board are arranged in a square loop. Each player has some money and owns a certain number of places. In a given turn, each player has a single position defined on the board. Traversal across the board is done by the roll of a die which determines how many positions on the board the player shifts by. A player starts a turn by rolling the die and moving. After moving, if the player lands on a place that has no owner, they are free to either buy the place or pass. If the player lands on a place owned by another player, they pay the owner the required amount of rent.  A player loses the game when they run out of money.

Whew! It's exhausting to explain the rules of a simplified form of Monopoly in English, so you can imagine that it'd be even more challenging to code these principles into python. This is why teams of people write up the code for more complicated games like Call of Duty and StarCraft.

Let's try working on it in python. The first thing you'd need to do for that is start by defining all the game characters and mechanics. So we can define players and places (the main entities of the game by classes):

class Player:
    def __init__(self):
        self.money = 2000
        self.position = 0
        self.name = "P" + str(len(board))
        self.places = []

Similarly, required functions can be implemented to enforce features of the game. I made only one function to implement a single turn for that player. A single turn consists of 2 choices : one where the player can choose to look at his/her owned places before rolling and the second where the player can choose to buy the place they land on. The same function also checks if the player has landed on a place owned by another player and pays rent accordingly.

For movement, a random number is generated and motions along the board are cyclic, meaning that a roll of 4 on the last position of the board will put the player at the 4th position.

diceno = random.randint(1,4)
print("dice shows " + str(diceno))
if (self.position + diceno < len(board)):
    self.position += diceno

else:
    self.position = self.position + diceno - len(board)

It's left as an exercise to you to try and implement the remaining game concepts such as buying and renting yourself. However, as mentioned before, the code is available on GitHub for reference.


I made a small-scale game with 2 players and 6 places on the board with a four sided die, but you can be as ambitious as you want with the scale of the game. Screenshot-from-2020-05-07-02-39-12-1

Step 2 : Working with Pygame

The next skill you need to master is getting comfy with using pygame. It's fairly simple to learn and there are plenty of things you can do with it once you're familiar with it. The best place to learn the intricacies of any python library is to refer the documentation!

In this part of the tutorial, we'll try to make a simple 2D game, where me make a little block that can move around the screen and collect coins. The best way to cover a breadth of features in pygame is to be free from the restrictions imposed by having to make a game with complicated game mechanics, so we'll be making a simple game so that we can learn how to get familiar with pygame as game mechanics are covered in step 1.

Our game will consist of a red box moving around and collecting coins. Each coin we collect will add to our score. We'll also get some music to play in the background. The code for this section is here.

As you can imagine, the first part of our code involves actually importing the pygame library and initialising it. So for that we do:


import pygame

pygame.init() # This is an initialisation function required for all pygame projects.

Following this, we're free to start setting up the global pygame-related variables. Everything on pygame typically runs on what's known as a Surface. The game screen is a surface and so are all image objects you work with. So the next step is to define a game surface for your current project:


win = pygame.display.set_mode((500,500)) # Set size in tuple as required
pygame.display.set_caption("Coin Collector")

To add some music to the game, we're going to use the pygame mixer. Here I've used an mp3 file for the Rustboro soundtrack from Pokemon Ruby. You can add whichever soundtrack you want or even compose your own. The music.play() function for the mixer class takes an argument for number of plays. If the number is set to 0, then it will play once. The value -1 implies that the track will be played indefinitely.


pygame.mixer.music.load('rustboro.mp3')
pygame.mixer.music.play(-1)

The next step is to define the participants of the game. In this case, it's just our little red box. I'll be using an object of type Player (my own class) to define the parameters of the rectangle. To draw the character, use the pygame.draw class like this:


pygame.draw.rect(win, (r, g, b), (x, y, width, height))

where (r, g, b) should be replaced with the colour of your choice. Similarly (x, y, width, height) should be replaced with the x,y position and the width and height of your rectangle.

Pro Tip : It would help to remember that pygame's coordinate system is a bit weird. The top left corner of the object is set as (0,0) instead of the centre, so when you're setting the position of any object, remember that you're most likely defining the position of the top left corner (this rule doesn't apply to drawing circles).

The most central part of the game is the main loop of the game. Once you've decided the objects that are taking part in the game, it's time to set up the main game loop.

The main game loop interacts with the user conveniently using what are known as pygame events. So when you're making the game loop, it is important that each iteration of the loop checks the pygame event list.


run = True
while (run): # You can set the game ending condition to whatever you want
    for event in pygame.event.get(): #checks all pygame events.
        if event.type == pygame.QUIT: #checks if the game window is closed
            run = False
            break
            

You can utilise other events such as key presses and mouse events. For moving the square around, you can look at all the keys that have been pressed like this:


    pressed = pygame.key.get_pressed()
    if pressed[pygame.K_UP]:
        #perform action for pressing the up key
    if pressed[pygame.K_DOWN]:
        #perform action for down key
    if pressed[pygame.K_LEFT]:
        #perform action for left key
    if pressed[pygame.K_RIGHT]:
        #perform action for right key

Naturally this is also included in the main game loop.

The most important part of the game loop is defining a refresh function, which changes what you want to print on the screen.


def refresh():
    win.fill((0, 0, 0))
    p.draw()  # This draws the player object that I have defined
    for coin in coins:  # Draws all the coins, another object I defined
        if coin.collected == False:
            coin.draw()

    score.updatescore(p.numcollected)
    
    pygame.display.update() # This is the most important portion. It updates the pygame screen


And voila, you're done! You can improve on this to define whatever features you want. But my simple game with a rectangle capturing coins was done with this framework and it turned out fine.

Screenshot-from-2020-05-07-02-24-51

Step 3 : Designing sprites

Since I myself am not a design expert, I shall keep this section short. Sprites can be useful in many ways. Firstly, they make the aesthetic of the game more pleasing. You end up dealing with more than just squares and circles. Secondly, you can convey information to the player using the sprite. For example, you can convey whether the player is facing down or up or in any other direction. I used GIMP (Gnu Image Manipulation Program) to design my sprites, and they turned out alright.

Designing a Rook in GIMP

However, software that allow more sophistication in design do exist. So do software with less intricacy. You could design in sprites in anything from Tux Paint to Adobe Illustrator, it depends on your convenience more than anything. The best place to learn GIMP is from their website.

To add your own sprites into pygame, use:


img = pygame.image.load('img-path')

Now, the image gets treated like a surface. However, you can blit this surface onto your previous surface using win.blit().

win.blit(img, coordinates) # Enter coordinates as a tuple

Conclusion : Putting it all together

Now that you're familiar with the elemental steps of game-making, which are hard-coding the rules, working with the pygame environment and adding your own sprites into the game, you're now ready to go out and make your own. If you remember the monopoly game we made in Step 1, it was actually inspired by my first game devlopment project, which is a full version of monopoly in pygame. You can check it out here.