The Wayback Machine - https://web.archive.org/web/20240621125016/https://www.geeksforgeeks.org/introduction-to-pygame/
Open In App

Introduction to pygame

Last Updated : 08 Oct, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

Game programming is very rewarding nowadays and it can also be used in advertising and as a teaching tool too. Game development includes mathematics, logic, physics, AI, and much more and it can be amazingly fun. In python, game programming is done in pygame and it is one of the best modules for doing so.
 

Installing pygame: 
Pygame requires Python; if you don’t already have it, you can download it from python.org. Use python 3.6.1 or greater, because it is much friendlier to newbies, and additionally runs faster.
The best way to install pygame is with the pip tool (which python uses to install packages). Note, this comes with python in recent versions. We use the –user flag to tell it to install into the home directory, rather than globally. 
 

python3 -m pip install -U pygame --user


To see if it works, run one of the included examples: 
 

python3 -m pygame.examples.aliens


If it works, we are ready to go!
Once you have installed pygame, you’re ready to create your very first pygame instance. 
 

Python3




# import the pygame module
import pygame
 
# import pygame.locals for easier
# access to key coordinates
from pygame.locals import *
 
# Define our square object and call super to
# give it all the properties and methods of pygame.sprite.Sprite
# Define the class for our square objects
class Square(pygame.sprite.Sprite):
    def __init__(self):
        super(Square, self).__init__()
         
        # Define the dimension of the surface
        # Here we are making squares of side 25px
        self.surf = pygame.Surface((25, 25))
         
        # Define the color of the surface using RGB color coding.
        self.surf.fill((0, 200, 255))
        self.rect = self.surf.get_rect()
 
# initialize pygame
pygame.init()
 
# Define the dimensions of screen object
screen = pygame.display.set_mode((800, 600))
 
# instantiate all square objects
square1 = Square()
square2 = Square()
square3 = Square()
square4 = Square()
 
# Variable to keep our game loop running
gameOn = True
 
# Our game loop
while gameOn:
    # for loop through the event queue
    for event in pygame.event.get():
         
        # Check for KEYDOWN event
        if event.type == KEYDOWN:
             
            # If the Backspace key has been pressed set
            # running to false to exit the main loop
            if event.key == K_BACKSPACE:
                gameOn = False
                 
        # Check for QUIT event
        elif event.type == QUIT:
            gameOn = False
 
    # Define where the squares will appear on the screen
    # Use blit to draw them on the screen surface
    screen.blit(square1.surf, (40, 40))
    screen.blit(square2.surf, (40, 530))
    screen.blit(square3.surf, (730, 40))
    screen.blit(square4.surf, (730, 530))
 
    # Update the display using flip
    pygame.display.flip()


The above Python code is a simple pygame script to draw four cyan color squares.

Output:

Don’t worry! We will learn a lot more about how to make an object move, how to add animation effects, buttons, music and much more in the next few articles but for now let’s understand this basic code which contains all the necessary pygame elements. 
 

import pygame

from pygame.locals import *

In the first few lines, we import pygame and pygame.locals which is necessary to do before using any module in python.
 

Sprite, Surf, and Rect:

Sprite: Sprite is just a 2d object that we draw on the screen. We can use them by extending the sprite class. 
Surf: Surfaces are like blank sheets of paper on which we draw. Our screen object is also a Surface. They can hold images as well. 
Rects: Rectangular area that we define on a surface. 
 

Python3




class Square(pygame.sprite.Sprite):
 
    def __init__(self):
        super(Square, self).__init__()
        self.surf = pygame.Surface((25, 25))
        self.surf.fill((0, 200, 255))
        self.rect = self.surf.get_rect()


Note: We are using RGB format of color coding in which we can form different colors by giving Red, Blue, and Green color values in the range of 0-255. A tuple of (0, 0, 0) is the color black as there is no color present and a tuple of (255, 255, 255) is the color white.
In our code, we are extending the sprite class so that we can use surfs and rects to draw our squares. We have made a surface of dimension 25x25px and filled it will a color: (0, 200, 255) 
 

pygame.init() :

Python3




pygame.init()
 
screen = pygame.display.set_mode((800, 600))
 
square1 = Square()
square2 = Square()
square3 = Square()
square4 = Square()


The above lines of code initialize pygame using the command pygame.init() which is necessary to use the pygame module commands. After that, we define our screen object and its dimensions in pixels. Then in the next lines, we initialize our four squares.
 

Game Loop 

Python3




while running:
    for event in pygame.event.get():
        if event.type == KEYDOWN:
            if event.key == K_BACKSPACE:
                running = False
        elif event.type == QUIT:
            running = False


The most important part of the game development code is the game loop. This loop continuously runs in the background until the user ends the game or the game is over. Right now our game loop is not much to look forward to. It only tracks two basic events. We can add more events according to the game state, user inputs, and much more but the point to remember here is that the game loop must end after some condition else the user will be stuck in the game loop forever. 
 

Blit and Flip –

Blit: Blit keyword is used to draw a surface on another surface. In simple words when we draw a surface we just blit it onto some other surface.
Flip: It is used to update the entire screen after everything is drawn. Remember that the flip only works after drawing all the necessary surfaces otherwise, it will update nothing. 
 

Python3




screen.blit(square1.surf, (40, 40))
screen.blit(square2.surf, (40, 530))
screen.blit(square3.surf, (730, 40))
screen.blit(square4.surf, (730, 530))
 
pygame.display.flip()


In the above lines of code first, we blit four squares on the screen, and then we flip to make them appear. 
 



Previous Article
Next Article

Similar Reads

Adding Collisions Using pygame.Rect.colliderect in Pygame
Prerequisite: Drawing shapes in Pygame, Introduction to pygame In this article, we are going to use pygame.Rect.colliderect for adding collision in a shape using Pygame in Python. We can easily add collisions in Pygame shapes using the colliderect( ). For this, we are going to draw two rectangles then we will check if the rectangles are colliding o
3 min read
How to add color breezing effect using pygame?
Pygame is a python library that can be used specifically to design and build games. Pygame supports only 2d games that are built using different sprites. Pygame is not particularly best for designing games as it is very complex to use and doesn’t have a proper GUI like unity but it definitely builds logic for further complex projects. Installation:
2 min read
How to create a text input box with Pygame?
In this article, we will discuss how to create a text input box using PyGame. Installation Before initializing pygame library we need to install it. This library can be installed into the system by using pip tool that is provided by Python for its library installation. Pygame can be installed by writing these lines into the terminal. We can install
3 min read
How to add moving platforms in PyGame
Prerequisite: Drawing in Pygame In this article, we will learn how we can add moving platforms to our game using PyGame in Python. Creating a Platform We can easily create any type of platform in pygame using the draw( ) method. For this, we will create react with specific width and height using the draw.rect() function. Syntax: pygame.draw.rect(su
5 min read
How to get keyboard input in PyGame ?
While using pygame module of Python, we sometimes need to use the keyboard input for various operations such as moving a character in a certain direction. To achieve this, we have to see all the events happening. Pygame keeps track of events that occur, which we can see with the events.get() function. In this article, we are going to discuss how we
3 min read
Pygame - Surface
When using Pygame, surfaces are generally used to represent the appearance of the object and its position on the screen. All the objects, text, images that we create in Pygame are created using surfaces. Creating a surface Creating surfaces in pygame is quite easy. We just have to pass the height and the width with a tuple to pygame.Surface() metho
6 min read
Python | Display images with PyGame
Pygame is a cross-platform set of Python modules designed for writing video games. It includes computer graphics and sound libraries designed to be used with the Python programming language. Now, it’s up to the imagination or necessity of the developer, what type of game he/she wants to develop using this toolkit. Command to install pygame : pip in
2 min read
Python | Display text to PyGame window
Pygame is a cross-platform set of Python modules designed for writing video games. It includes computer graphics and sound libraries designed to be used with the Python programming language. Now, it’s up to the imagination or necessity of the developer, what type of game he/she wants to develop using this toolkit.. Command to install pygame on wind
6 min read
Python | Drawing different shapes on PyGame window
Pygame is a cross-platform set of Python modules designed for writing video games. It includes computer graphics and sound libraries designed to be used with the Python programming language. Now, it’s up to the imagination or necessity of developer, what type of game he/she wants to develop using this toolkit. Command to install pygame : pip instal
3 min read
PyGame Set Mouse Cursor from Bitmap
In this article, we are going to see how to set the mouse cursor from bitmap using the PyGame module in Python. What is PyGame?It is a cross-platform set of Python modules designed for writing video games.It includes computer graphics and sound libraries designed to be used with the Python programming language.It can handle time, video, music, font
5 min read
Article Tags :
Practice Tags :