Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction 
2.
Installation
3.
Getting Started
4.
Some Functions
4.1.
Sprite, Surf, and Rect
4.2.
Pygame.init()
4.3.
Game Loop
5.
Frequently Asked Questions
5.1.
Is pygame good for beginners?
5.2.
What is pygame used for?
5.3.
Is Pygame worth learning?
5.4.
What games are made with Pygame?
5.5.
Is pygame fast?
6.
Conclusion
Last Updated: Mar 27, 2024

Introduction to pygame

Master Python: Predicting weather forecasts
Speaker
Ashwin Goyal
Product Manager @

Introduction 

Game programming is quite lucrative these days, and it may also be used for advertising and education. Math, logic, physics, AI, and much more are all used in game development, and it can be a lot of fun. Game programming in Python is done with pygame, which is one of the best modules for the job.

Installation

Pygame requires Python, which you can get from python.org if you don't already have it. Python 3.6.1 or higher is recommended because it is more user-friendly and runs faster.

The pip tool is the best way to install pygame (which Python uses to install packages). This is included in current versions of Python. We tell it to install within the user's home directory rather than globally using the –user argument.

python3 -m pip install -U pygame --user

to check, run this: 

python3 -m pygame.examples.aliens

If it works we are good to go!!!

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Getting Started

Below is a commented code which you can run and see the output in your system, here you can understand how the basic code is working and then build more things on top of it. 

# now we import the pygame module
import pygame
 
# importing pygame.locals for easy
# access to key coordinates
from pygame.locals import *
 
#Define our square object and call super to give it all of #pygame.sprite.properties Sprite's and functions.
#Define the class that our square objects will belong to.
class Square(pygame.sprite.Sprite):
    def __init__(self):
        super(Square, self).__init__()
        
        #making squares of side 25px
        self.surf = pygame.Surface((25, 25))
        
        # Defining the color of the surface using RGB color coding.
        self.surf.fill((0, 200, 255))
        self.rect = self.surf.get_rect()
 
# initializing pygame
pygame.init()
 
# Defining the dimensions of screen object
screen = pygame.display.set_mode((800, 600))
 
# instantiating the square objects
square1 = Square()
square2 = Square()
square3 = Square()
square4 = Square()
 
# = to keep our game loop running
running = True
 
# this is the game loop
while running:
    # looping through the event queue
    for event in pygame.event.get():
        # Checking for KEYDOWN event
        if event.type == KEYDOWN:
            # If the Backspace key is pressed, 
            if event.key == K_BACKSPACE:
                gameOn = False
        # here we check for QUIT event
        elif event.type == QUIT:
            gameOn = False
 
    # Defining where the squares will appear on the screen
    # Using 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))
 
    # Updating the display using flip
    pygame.display.flip()

Output:

Hence this code was just to draw some rectangles at the corners. Let's learn about more functions which are used in Pygame. 

Some Functions

Sprite, Surf, and Rect

Sprite: A sprite is a two-dimensional object that we draw on the computer screen. By extending the sprite class, we may use them.

Surf: Surfaces are similar to blank sheets of paper that we use to sketch on. Our screen object is a Surface as well. They can also store images.

Rects: On a surface, we define a rectangular region.

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()

Pygame.init()

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

The preceding lines of code use the command pygame.init() to initialise pygame, which is required to use the pygame module commands. Following that, we define our screen object and its pixel dimensions. Then we initialise our four squares in the following lines.

Game Loop

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 game loop is the most crucial portion of the game development code. Until the user exits the game or the game is over, this loop continues in the background. Right now, there isn't much to look forward to in our game loop. It merely keeps track of two main occurrences. We can add more events based on the game state, user inputs, and so on, but keep in mind that the game loop must finish after some condition, or the user would be stuck in the game loop indefinitely.

There are a lot more things which can be learned from the official documentation, practising and making more games. 

Check out this problem - Optimal Strategy For A Game

Frequently Asked Questions

Is pygame good for beginners?

Pygame 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.

What is pygame used for?

The pygame library is an open-source module for the Python programming language that is designed to assist you in the development of games and other multimedia applications. Pygame, which is based on the SDL (Simple DirectMedia Layer) development library, can run on a variety of platforms and operating systems.

Is Pygame worth learning?

Pygame, in my opinion, is an excellent tool for beginners to use to get comfortable with programming and the game production process, as well as to feel successful when creating games. It's also a fantastic tool for quick prototyping.

What games are made with Pygame?

Notable games using Pygame:
Frets on Fire.
Dangerous High School Girls in Trouble.
Save the Date, IndieCade 2013 Finalist.
Drawn Down Abyss.

Is pygame fast?

PyGame is fast enough for a wide range of game styles. There's no use in updating the screen at a higher rate than the monitor refreshes. A basic Pong game in PyGame should always run at full-FPS.

Conclusion

So, in a nutshell, we learnt about Pygame and got introduced to it also learnt how we can draw various shapes in Pygame, and also change how these shapes. More details about various functions can be found in official documentation. 

Check out our Coding Ninjas Studio Guided Path to learn about Data Structures and AlgorithmsCompetitive ProgrammingJavaScriptSystem Design, and more, Take a look at the mock test series and participate in the contests hosted by Coding Ninjas Studio if you want to improve your coding skills. If you are new to preparation and want to work for firms such as Amazon, Microsoft, Uber, and others, you should review the problemsinterview experiences, and interview bundle for placement preparations.

Consider taking one of our paid courses to give yourself and your profession an edge!

Please vote for our blogs if you find them valuable and exciting.

Happy Learning!

Next article
Pygame - blit() function
Live masterclass