PyGame For Beginners

Have you ever been enthralled by a video game and have wanted to build your own? I guess that, since our childhood, everyone has had a fantasy to create their own game and design their own set of rules. Many, including me, used to think that it was hard to create a game, but when I started looking at various options, I came across PyGame, which helped me build my dream game, in a very interesting process.

For making a game of your choice, a little bit of python programming is all you need to know. My blog will surely help you create your own game. So let’s get started with this tutorial of PyGame, which will help you understand and implement its basics.

Introduction

What is PyGame?

PyGame is a library of Python language. It is used to develop 2-D games and is a platform where you can use a set of Python modules to develop a game. It is an easy-to-understand and beginner-friendly platform that can help you develop games quickly. You can go through the official website of PyGame to get an idea of what it actually is.

Official Website of PyGame is:- https://www.pygame.org

What basic preparation is needed before starting?

  1. You should have Python IDLE to write the source code. You can download the official IDLE from the website:-www.python.org. This link will redirect you to downloads. According to your operating system, download the latest version of python. While downloading, don’t forget to check the box to add to path. You can even use PyCharm where you can download library pygame and do the programming.
Download Python IDLE

2. Once the IDLE is downloaded, open command prompt and type the below command. This will install the PyGame library.

pip install pygame
Something like this will appear.

Now let’s start programming 😊

The first thing we need is to import PyGame and create a game window. Refer to the below code.

import pygamepygame.init()screen = pygame.display.set_mode((500, 500))done = Falsewhile not done:        for event in pygame.event.get():            if event.type == pygame.QUIT:                done = True        pygame.display.flip()

Knowing the terms

  1. import pygame :- This command is used to access the PyGame framework. It is the first step to start the process of game development.
  2. pygame.init():- This initializes all the modules required for PyGame.
  3. pygame.display.set_mode((width, height)):- This will launch a window of the desired size.
  4. pygame.event.get():- Since the game will be a series of events, this syntax will help you to empty the events’ queue before adding a new one.
  5. pygame.quit:- This syntax is used to exit the program altogether.
  6. pygame.display.flip():- PyGame is double-buffered so this swaps the buffers. All you need to know is that this call is required for any updates that you make to the game screen to become visible.

Output

Once you run the above code, you will get this game window.👇

Looks rather plain, right?🤔 Let us start by adding some content to our screen.

Giving a title and icon to the game window

We can add a title by pygame.display.set_caption(‘Name’) and icon by icon=pygame.image.load(‘game.jpg’) and
pygame.display.set_icon(icon) which will set an icon.

Adding a rectangle to the game window

It is very simple to draw a rectangle. We use pygame.draw.rect to draw one. Now, to make a rectangle, we have to put in its dimensions in the function such as its height,width and coordinates to be displayed on the screen.

# Add this somewhere after the event pumping and before the display.flip()pygame.draw.rect(screen, (0, 128, 255), pygame.Rect(60, 60, 90, 90))

Something like this — >

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

Output of title icon and rectangle

Similarly, many shapes can be created. There are several features of PyGame for game development, which you can explore once you know the basics. It is essential to know that PyGame is used to control the graphics of the game that you are developing. Sometimes, you can control the logic of the game. Keep reading this PyGame tutorial to know the steps to build your own game.

Adding music and images to the game

To make your game more interesting, you can add music and images.

  1. To add images, we use pygame.image,load(‘image.jpg’).
  2. To add music, we use pygame.mixer.music,load(‘music.mp3’). But first, we need to import a mixer and initialize it. Refer the below provided code to get more clarification.
import pygame
pygame.init()
from pygame import mixer
mixer.init()
screen = pygame.display.set_mode((500, 500))
done = False
x=60
y=60
image=pygame.image.load(r'C:\Users\Tanishq\Downloads\wallpaper.jpg')
screen.blit(image, (0, 0))
pygame.mixer.music.load(r'C:\Users\Tanishq\Desktop\song.mp3')
pygame.mixer.music.play(-1)
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
pygame.draw.rect(screen, (255,0,0), pygame.Rect(x, y, 90, 90))

pygame.display.flip()

Some key terms

  1. r:- In the above code, before giving the code we write ‘r’ because the r‘..’ string modifier causes the ‘..’ string to be interpreted literally. That means, r‘My\Path\Without\Escaping’ will evaluate to ‘My\Path\Without\Escaping’ — without causing the backslash to escape characters. The prior is equivalent to ‘My\\Path\\Without\\Escaping’ string, but without the raw modifier.
  2. screen.blit(image, (0,0)):- This will screen the image on the window game.
  3. pygame.mixer.music.play(-1):- The number indicates frequency of the music track. This will play the music infinitely. if we write any number it will play that many time. 0 means it will play one time.
  4. pygame.mixer.music.queue(‘next_song.mp3’):- This will queue the song to be played next.
  5. pygame.mixer.music.stop():- This will stop the music.

Output

Changing the color of the box

Now that the blue box appears a little boring, let’s change the color of the box. To get the RGB color codes go to this website :-https://www.rapidtables.com/web/color/RGB_Color.html

Now if I press the space bar, the color of the box should change to brown. The code for the same is:-

is_red = True
#in infinite while loop:-
if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
is_red = not is_red
if is_red: color = (255, 0, 0)
else: color = (102, 0, 0)

We will get this output once the space key is pressed.

Moving the rectangle

Now let’s move the block around the game window. Have a look at below given code. Here ‘pressed’ gives the key pressed by user. The coordinate system is as follows. So, when UP key is pressed the Y- coordinate is subtracted.

        pressed = pygame.key.get_pressed()
if pressed[pygame.K_UP]: y -= 1
if pressed[pygame.K_DOWN]: y += 1
if pressed[pygame.K_LEFT]: x -= 1
if pressed[pygame.K_RIGHT]: x += 1
if is_red: color = (255, 0, 0)
else: color = (102, 0, 0)

pygame.draw.rect(screen, color, pygame.Rect(x, y, 90, 90))

pygame.key.get_pressed():- This will get a list of booleans that describes the state of each keyboard key.

The duration of each frame is as short as your super fancy computer can make it. The frame rate needs to be throttled at a sane number such as 60 frames per second. Luckily, there is a simple class in pygame.time called Clock that does this for us. It has a method called tick which takes in a desired fps rate.

#Add this before loop.
clock = pygame.time.Clock()
#Add this in loop.
clock.tick(60)

Output

If we use keys, we get something like this.

This isn’t appealing, right? The box should move over the image. so add one code after defining the pressed function. This function resets the screen before you draw your next rectangle.

#screen.blit(image, (0, 0))

This will give the output:-

Now it looks better, but once again, we face the issue of the box getting out of frame once the coordinates exceed the window size. Add the following conditions after defining pressed function and before screen.blit():-

if x<=0:
x=0
elif x>=400:
x=400
if y>=400:
y=400
elif y<=0:
y=0

These will prevent your object to go out of frame. You can even control the speed with the change in x and y axis.

Adding circle and changing thickness

Similar to the rectangle, we can add a circle. pygame.draw.circle(surface, color, (x, y), radius) function is used to draw a circle.

pygame.draw.circle(screen, color, (300,60),50)

You can also change the thickness of shapes using pygame.draw.circle(surface, color, (x, y), radius, thickness), or pygame.draw.rect(surface,color,(x,y,h,w),thickness)

Implementation of both is shown below

#Rectangle thickness
pygame.draw.rect(screen, (255,255,0), pygame.Rect(60, 300, 90, 90),10)
#Circle thikness
pygame.draw.circle(screen, (255,255,0), (300,300),50,10)

You can even draw lines using pygame.draw.line(screen, color, (x_initial, y_initial) , (x_final, y_final), thickness). Amazing 3-D images can be created by drawing lines. You just need basic knowledge of the coordinate system.

Lets look at a shape ‘T’ created by me.

pygame.draw.line(screen, color ,(50,150), (250,150), 10)
pygame.draw.line(screen, color, (150, 150), (150, 250), 10)

Adding Text

You can add text such as GAME OVER. Let us look at how this is done. This code is to be written before infinite loop and last line in loop.

# create a font object.
# 1st parameter is the font file which is present in pygame.
# 2nd parameter is size of the font
font = pygame.font.Font('freesansbold.ttf', 50)# create a text surface object, on which text is drawn on it.
text = font.render('GAME OVER', True, (255,0,0) , (0,128,255))
# create a rectangular object for the text surface object
textRect = text.get_rect()
# set the center of the rectangular object.
textRect.center = (250, 250)
#Add this in infinite loop.
#To clear everything on screen
screen.fill((255,255,255))
screen.blit(text, textRect)

Creating an object that moves randomly on screen

If you want to include an enemy in your game, which moves randomly, you can even do that. Just follow this procedure.

Let’s take a ball which is moving randomly.

  1. Import random
  2. Load ball image and set the position of ball randomly using random.randint(coordinates): -
x_pos=random.randint(0,400)
y_pos=random.randint(50,400)

3. Now define the x_change and y_change coordinates.

x_ch=3
y_ch=40

4. Define the ball function.

def ball(x_cordinate ,y_cordinate):
screen.blit(ballimage, (x_cordinate ,y_cordinate))

5. Give the conditions, according to coordinates, such that the ball does not move out of frame. And move in x direction like pendulum and bounce back in each round. Also call the ball function.

x_pos+=x_ch
if x_pos<=50:
x_ch=3
y_pos+=y_ch
elif x_pos>400:
x_ch=-3
y_pos+=y_ch
if y_pos>400:
y_pos=400

ball(x_pos,y_pos)

It looks something like this:-

Limitations

PyGame, although very interesting and rewarding, has its own set of challenges. You have to be extremely accurate with the commands you are putting in. For example, these commands are case sensitive. Also, PyGame is generally used for 2-D games that are simpler. These mostly include shapes and minimal graphics. In addition to this, you have to use several commands for a single graphic, which can be complicated and tiresome.

Conclusion

PyGame is a great and useful tool that can help you develop your dream game. The biggest perk of using PyGame is its easy access and its huge community support. It is easy to install, learn, and use. Within a few hours of beginning, you can create a game you once thought you’d never be able to with such ease.

Author: Tanishq Gandhi

--

--