BlogsDope image BlogsDope

Introduction to Pygames

Feb. 28, 2021 PYTHON LIBRARY 287

Python is a very popular and versatile programming language having a vast number of applications. Some of them are Web Development, Machine Learning, Data Analysis, Scripting, Game Development, Desktop Applications, and a lot more. Here, we are going to discuss how Python language helps in Game Development.

Pygame in Python

With the help of the Python module that is, Pygame we can easily create many easy yet amazing fun games. To put it into simple words, the Pygame module enables us to write rich multimedia programs and games in Python. Pygame uses the Simple DirectMedia Layer (SDL) library which allows real-time computer game development. A good game logic makes the game engine run faster which results in good efficiency of the game. Pygame is fairly low-level when it comes to writing games. Let's see in this section how Pygame works.

Prerequisites to play with Pygame

  • You should have Python installed in your system. If not already, then, download it from here. Download the latest version to avoid any issues further.
  • Have a Python IDE where you can write programs and execute them. Some of them are PyCharm, Visual Studio Cose, Jupyter Notebook,etc
  • You should have basic knowledge about how Python programming works.

Installation of Pygame

Installation may vary for different operating systems. However, it is recommended to use pip to install modules in Python. We are going to use pip to install the Pygame module:
pip install pygame

Now, get ready for some programming using the Pygame module in Python. Here, I am using PyCharm as IDE.

Pygame Window

We will first need a gaming window in which we can build any game. Let's see how to create one using Pygame:

import pygame
pygame.init()
screen = pygame.display.set_mode((400, 400))
done = False
while not done:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                done = True
        pygame.display.flip()

If we run the above code, a Pygame window will appear on the screen. It will look like this:

Let's quickly go through the code above and understand what each command means:

1. import pygame - This will import the Pygame module which we installed using pip into your current program.

2. init() - This is required to initialize all the modules required for PyGame

3. pygame.display.set_mode((width, height)) - The window which will appear would be of the size of given width and height here. 

4. pygame.event.get() - We know that the game is a series of different events so this command will help us to clear/empty the events queue before adding a new one.

5. pygame.QUIT -  This command is used to quit/exit the program. 

6. pygame.display.flip() -  if we make any updates in the program, this command will help us to make them visible on the window screen.

7. A game will always require a loop to control when the program ends. The while loop will do this work.

Naming the Pygame Window

We use the command pygame.display.set_caption("Any Name") to give a name to the window screen. In the below example we are naming the window as CodesDope. Let's see how it looks:
import pygame
pygame.init()
pygame.display.set_caption("CodesDope")
screen = pygame.display.set_mode((500, 500))
done = False
while not done:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True
    pygame.display.flip()

Image Adding with Pygame

The function pygame.image.load(“anyimage.jpg”) — function will load the image from the path which will be given as the argument to it. Let's see how it appears:
import pygame
pygame.init()
pygame.display.set_caption("CodesDope")

screen = pygame.display.set_mode((500, 500))
white = [255, 255, 255]
screen.fill(white)

done = False

image = pygame.image.load('dinasaur.jpg')
image_t = pygame.transform.scale(image, (400, 400))
screen.blit(image_t, (10, 100))

while not done:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True

    pygame.display.flip()

In the above code, we are first making the window screen color white which is default black with the help of the function screen.fill(). The color scheme [255, 255, 255]  appears as white color.

1. By the command pygame.image.load('dinasaur.jpg'), we are loading the image of a dinosaur. Please carefully give the entire file path of the image where it is saved and to avoid any file path complications, it is suggested to keep the image in the same path where your program code is.

2. We are using pygame.transform.scale(image, (400, 400)) to resize the image.

3. screen.blit() is used to render the game object onto the surface. If we do not render the game objects and simply run the program, then it will give the empty window as an output. The first argument is the source that is the image and the second argument is the coordinates to decide the position of the object.

Drawing a Rectangle with Pygame

Now, let's put something on this blank black screen. Let's see how to draw a rectangle on this screen:

import pygame
pygame.init()
screen = pygame.display.set_mode((500, 500))
done = False
x = 100
y = 50
while not done:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True
    pygame.draw.rect(screen, (128, 128, 128), pygame.Rect(x, y, 150, 180))
    pygame.display.flip()

1. So, we use pygame.draw.rect() to draw a rectangle.

2. It takes three arguments:

a. screen - The window screen on which the rectangle will appear

b. (128, 128, 128) - A tuple of RGB color scheme to give a color to the rectangle.

c. pygame.Rect(x, y, 150, 180) - This is used to indicate the position of the rectangle on the screen and the dimensions of the rectangle. x and y are the distance from the left of the window screen and     the distance from the top of the window screen respectively. The third argument is the width that is 150 and the fourth argument is the height of the rectangle that is 180.

Play with the above arguments in your program with different colors and dimensions and see the results. Below are some we are some basic color schemes to try with:

Color
Red
Green
Blue
Black
0
0
0
White
255
255
255
Medium Gray
128
128
128
Aqua
0
128
128
Navy Blue
0
0
128
Green
0
255
0
Orange
255
165
0
Yellow
255
255
0

Now, let's do a little trick. We will use our above rectangle code and make it a little lively. We will press the SPACEBAR button on our keyboard to change its color. Let's see how it is implemented:

import pygame

pygame.init()
screen = pygame.display.set_mode((500, 500))
done = False
grey = True
x = 100
y = 50

while not done:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True
        if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
            grey = not grey

    screen.fill((0, 0, 0))
    if grey:
        color = (128, 128, 128)
    else:
        color = (255, 255, 0)
    pygame.draw.rect(screen, color, pygame.Rect(x, y, 150, 180))

    pygame.display.flip()

Look through the above code

1. First we will take any variable, for the above code, the variable name is grey and is assigned False. You can assign it True also and the code will work accordingly

2. Then we check event.type == pygame.KEYDOWN which says that pygame.KEYDOWN and pygame.KEYUP are used to detect if a key is physically pressed down or released respectively.

3. We also check event.key == pygame.K_SPACE which recognizes that the user has pressed the SPACEBAR button.

4. If the above two conditions are True, which means the color needs to be changed, then the variable grey is assigned as not grey grey = not grey, which will simply assign the opposite value of the previously assigned value. That is it will become True if it was initially False and vice-versa.

5. The next if condition will accordingly check if the value of grey is True or False and hence the color will be changed. 

Using Arrow Keys for Movement with Pygame

Look at this carefully. We are slowly diving deep into this. Now, let's make our program a bit interactive with the user. We will use the four arrow keys on our keyword to move the box to different positions on the window screen. Let's see how we can do this:

import pygame

pygame.init()
screen = pygame.display.set_mode((500, 500))
done = False
grey = False
x = 100
y = 50

clock = pygame.time.Clock()

while not done:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True
        if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
            grey = not grey

    pressed = pygame.key.get_pressed()
    if pressed[pygame.K_UP]: y -= 5
    if pressed[pygame.K_DOWN]: y += 5
    if pressed[pygame.K_LEFT]: x -= 5
    if pressed[pygame.K_RIGHT]: x += 5

    screen.fill((0, 0, 0))
    if grey:
        color = (128, 128, 128)
    else:
        color = (255, 255, 0)
    pygame.draw.rect(screen, color, pygame.Rect(x, y, 150, 180))

    pygame.display.flip()
    clock.tick(60)

In the above code, we are using the arrow keys on the keyboard to move the box with a distance of 5. The commands pygame.K_UPpygame.K_DOWNpygame.K_LEFT, pygame.K_RIGHT help the interpreter to recognize the arrow keys. Also notice that here we are using the class Clock from pygame.time. It provides a method clock.tick() that takes an argument which is time in milliseconds. This function is used to update the clock. This can be used to help limit the runtime speed of a game. By calling clock.tick(60) once per frame, the program will never run at more than 60 frames per second. Try it using without clock.tick(60) and see the difference. 

Adding Music with Pygame

How about adding a music track to the program? Sounds good right? Let's see how we can achieve this:
import pygame
pygame.init()
pygame.display.set_caption("CodesDope")

screen = pygame.display.set_mode((500, 500))
white = [255, 255, 255]
screen.fill(white)

done = False

image = pygame.image.load('dinasaur.jpg')
image_t = pygame.transform.scale(image, (400, 400))
screen.blit(image_t, (10, 100))

pygame.mixer.music.load("Dinosaur-Growl.mp3")
pygame.mixer.music.play(-1)

while not done:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True

    pygame.display.flip()
Here, we have taken the code where we had inserted a dinosaur picture and now we are adding a dinosaur sound effect to it.
  1. The function pygame.mixer.music.load() will load the mp3 audio file which we provide as the argument to it.
  2. The function pygame.mixer.music.play(-1) will play the audio infinite time until we close the window.
  3. Note that the argument to the function pygame.mixer.music.play() is the frequency of playing the audio. -1 will play it infinitely. If we provide any number, the audio will be played that many times. Also, if we write 0  as the argument the soundtrack will play one time.
These were some of the basic features of Pygame. There are several other features of Pygame for game development, which you can explore once you know the basics.

Liked the post?
Rarely seen, always noticed.
Editor's Picks
0 COMMENT

Please login to view or add comment(s).