Game development for beginners using Pygame [Part 1]

Interested in making games but don’t know how to start? This post is for you.

This post assumes that you have at least some familiarity with Python (concepts such as classes, loops, functions, and methods).

What is Pygame?

Pygame is a library for python that allows us to create 2D games. It is actually a wrapper for the SDL(Simple DirectMedia Layer) multimedia library. It can handle event polling, blitting images onto a window, sound, and so on. You can get it here.

What’s in a game?

When making a 2D game, there is a very basic skeleton that is used. The basic most part of a game is its mainloop. As its name suggests, the mainloop is a piece of code that is executed repeatedly during the runtime of the game. The mainloop follows the following structure:

Loop:
    poll for events
    do calculations
    modify objects
    paint images on screen

 

We shall be using this mainloop to create a very simple game.

 

Starting out

Create any working directory, e.g. game. Then, place any image you like in it and call it player.png.

The following image is provided for you:

Player Image

 

Now, type the following in any text editor of your choice and save it as game.py.

#!/usr/bin/env python2

import pygame as pg
import sys

WIDTH = 360
HEIGHT = 480

WHITE = (255, 255 , 255)

class Player(pg.sprite.Sprite):
    
    def __init__(self, imagePath):
        
        # We first set the appropriate object variables
        self.image = pg.image.load(imagePath)

        # These are the coordinates of the player on the screen
        self.x, self.y = (WIDTH/2, HEIGHT/2)

        self.speed = 5

    def move(self, mov_tup):
        
        # mov_up contains changes made to the x and y positions
        # we simply add those changes to the player's position
        self.x += mov_tup[0]
        self.y += mov_tup[1]


def main():
    pg.init()   # initialise pygame
    pg.display.set_mode((WIDTH, HEIGHT)) # setting the window's dimensions
    mainS = pg.display.get_surface()
    FPS = 60 # Frames per second
    
    # the main window can now be accessed through mainS

    player = Player("player.png")

    # The clock is necessary for refreshing the screen
    clock = pg.time.Clock()   
    mov_tup = (0, 0)
    # This is the actual mainloop
    while True:
        
        for event in pg.event.get():
            
            if event.type == pg.QUIT:
                pg.quit()
                sys.exit()

            elif event.type == pg.KEYDOWN:
                
                if event.key == pg.K_d:
                    mov_tup = (player.speed, 0)
                if event.key == pg.K_a:
                    mov_tup = (-player.speed, 0)
                if event.key == pg.K_w:
                    mov_tup = (0, -player.speed)
                if event.key == pg.K_s:
                    mov_tup = (0, player.speed)

        player.move(mov_tup)
        mainS.fill(WHITE)       # Fill the screen with the colour white
        mainS.blit(player.image, (player.x, player.y))  # Paint the player in the correct pos
        pg.display.update()

        # re-paint FPS times a second
        clock.tick(FPS)


main()

 

The game looks something like this:

Game background

How it all comes together

First of all, you need to understand the coordinate system used. In pygame, the coordinates start at the top-left of the screen and they increase on going to the right or on going downwards.

Second, colours are understood by pygame to be tuples of RGB(Red, Green, Blue) values. For white, all the values are maxed out to 255.

 

The code itself is easy to understand. First, we created a Player class, which inherits from the Sprite class of pygame (This will be explained later). The player object is an instance of this class. We gave it an image attribute and two position attributes. Then, we added a move method that takes a tuple of two-values and adds them to the positions. So, changes in positions are added to the respective positions of the player so that it can move to the new position.

In the main function, we initialise pygame. Then, we tell pygame to create a screen of our desired size, and we ‘store’ it in mainS. We create a clock object and initialise the value of mov_tup.

 

Then comes the intereseting part. Within the mainloop is a for loop that iterates over all the events recorded by pygame. It checks to see if the user has pressed any of W, A, S, or D. According to the key pressed, the value of mov_tuple changes.

The move method of the player object is called during every iteration of the loop. It simply shifts the x and y attributes of the object. The blit method paints the player according to the given coordinates. Therefore, our ball is in perpetual motion until we deliberately change its direction.

 

After handling all that, we simply update the display. This is the part that causes the images to be actually painted onto the screen. Finally, clock.tick simply tells pygame to repaint the screen 60 times in a second.

That’s it. This is how the game runs. The loop keeps running until the player quits. Essentially, all we are doing is painting different colors on the screen in response to the player’s commands very, very quickly.

And Now for Something Completely Different

The above was a simple demo to illustrate basic ideas about pygame and game creation. Next time, we’re going to learn how to create a complete game. I hope you learned something useful from this post.

The next part shall come soon.

 

Leave a Reply