Table of contents
1.
Introduction
2.
Pygame Library
2.1.
Installation of PyGame
2.2.
Example code
2.3.
PyGame Concepts
2.3.1.
Introduction and Modules
2.3.2.
Shows and Surfaces
2.3.3.
Pictures and Rects
3.
FAQs
4.
Key Takeaways
Last Updated: Mar 27, 2024
Easy

PyGame Library in Python

Author Adya Tiwari
2 upvotes
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Pygame is a cross-stage set of Python modules intended for composing computer games. It incorporates PC illustrations and sound libraries designed to be utilized with the Python programming language.

Pygame Library

Pygame is a cross-stage set of Python modules intended for composing computer games. It incorporates PC illustrations and sound libraries designed to be utilized with the Python programming language.

Pygame is a cross-stage set of Python modules utilized to make computer games.

  • It comprises PC illustrations and sound libraries intended to be utilized with the Python programming language.
  • Pygame was authoritatively composed by Pete Shinners to supplant PySDL.
  • Pygame is reasonable to make client-side applications that can be enveloped by an independent executable.
  • Before finding out about pygame, we want to get what sort of game we need to create.

To learn pygame, it is expected to have essential information on Python.

Before introducing Pygame, Python should be introduced in the framework, and it is excellent to have 3.6.1 or above since it is a lot more amicable to novices and runs quicker.

Installation of PyGame

First, we need to install the pip package to help install Python Libraries like Pygame. Now open your command prompt window and type 

pip - -version
You can also try this code with Online Python Compiler
Run Code

Then to install pygame, type 

pip install pygame
You can also try this code with Online Python Compiler
Run Code

now press enter, and the library will install successfully.

To check if Pygame has been installed successfully, type import pygame on the command prompt window, and if there is no error, then the library has been installed successfully. 

To involve the strategies in the Pygame library, the module should initially be imported:

import pygame
You can also try this code with Online Python Compiler
Run Code

The import explanation composes the pygame adaptation and a connection to the Pygame site to the console:
 

pygame 1.9.6
Hi from the pygame local area.
https://www.pygame.org/contribute.html
You can also try this code with Online Python Compiler
Run Code

The Pygame import explanation is generally positioned toward the start of the program. It imports the pygame classes, strategies, and properties into the current namespace. Presently these new techniques can be called employing pygame.method().

For example, we can now introduce or stop pygame with the accompanying order:

pygame.init()
pygame.quit()
You can also try this code with Online Python Compiler
Run Code

The capacity display.set_mode() sets the screen size. It returns a Surface item which we dole out to the variable screen. This variable will be quite possibly the most utilized. It addresses the window we see:

screen = pygame.display.set_mode((640, 240))
You can also try this code with Online Python Compiler
Run Code

You can now run this program and test it. Right now, it does very little. It opens a window and closes it right away.

Following is the event loop.

The most fundamental piece of any intelligent application is the occasion circle. Responding to occasions permits the client to associate with the application. Occasions are the things that can occur in a program, for example, a

  • mouse click,
  • mouse development,
  • console press,
  • joystick activity.

Coming up next is a boundless circle which prints all occasions to the console:


while True:
    for occasion in pygame.event.get():
        print(event)
You can also try this code with Online Python Compiler
Run Code

Attempt to move the mouse, click a mouse button, or type something on the console. Each activity you do produces an occasion which will be imprinted on the control centre. This will look something like this:

<Event(4-MouseMotion {'pos': (173, 192), 'rel': (173, 192), 'buttons': (0, 0, 0), 'window': None})>
<Event(2-KeyDown {'unicode': 'a', 'key': 97, 'mod': 0, 'scancode': 0, 'window': None})>
<Event(3-KeyUp {'key': 97, 'mod': 0, 'scancode': 0, 'window': None})>
<Event(12-Quit {})>
You can also try this code with Online Python Compiler
Run Code

As we are in an infinite circle, it is difficult to stop this program from inside the application. Make the console the dynamic window and type ctrl-C to prevent the program. This will compose the accompanying message to the console:

^CTraceback (most recent call last):
File "/Users/raphael/GitHub/pygame-tutorial/docs/tutorial1/intro1.py", line 7, in <module>
    for event in pygame.event.get():
KeyboardInterrupt
You can also try this code with Online Python Compiler
Run Code

Now let's take a look at a basic python program. To begin with

Example code

import pygame
pygame.init()


# Set up the drawing window
screen = pygame.display.set_mode([500, 500])


# Run until the user asks to quit
running = True
while running:


    # click the window close button
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False


    # Fill the background with white
    screen.fill((255, 255, 255))


    # Draw a solid blue circle in the center
    pygame.draw.circle(screen, (0, 0, 255), (250, 250), 75)


    pygame.display.flip()


pygame.quit()
You can also try this code with Online Python Compiler
Run Code

 

Using this code, we will be able to create a blue circle on a white background which should look somewhat like this:



Also see, How to Check Python Version in CMD 

Check out Escape Sequence in Python

PyGame Concepts

As pygame and the SDL library are versatile across various stages and gadgets, they need to characterize and work with deliberations for different equipment fundamental factors. Understanding those ideas and reflections will help you plan and foster your games.

Introduction and Modules

The pygame library is made out of various Python developments, incorporating a few unique modules. These modules give conceptual admittance to explicit equipment on your framework and uniform strategies to work with that equipment. For instance, show permits uniform admittance to your video show, while joystick allows conceptual control of your joystick.
In the wake of bringing the pygame library in the model over, the principal thing you did was initialize PyGame utilizing pygame.init(). This capacity calls the different init() elements of all the included pygame modules. Since these modules are reflections for explicit equipment, this introduction step is required so you can work with similar code on Linux, Windows, and Mac.

Shows and Surfaces

Notwithstanding the modules, pygame incorporates a few Python classes, typifying non-equipment subordinate ideas. One of these is the Surface which, at its generally fundamental, characterizes a rectangular region on which you can draw. Surface articles are utilized in numerous settings in pygame. Later you'll perceive how to stack a picture into a Surface and show it on the screen.
In pygame, everything is seen on a solitary client-made show, which can be a window or a full screen. The showcase is made utilizing .set_mode(), which returns a Surface addressing the noticeable piece of the window. This Surface that you pass into drawing capacities like pygame.draw.circle(), and the substance of that Surface is pushed to the showcase when you call pygame.display.flip()

Pictures and Rects

Your essential pygame program draws a shape straightforwardly onto the showcase's Surface; however, you can likewise work with pictures on the circle. The picture module permits you to load and save pictures in many well-known designs. Images are stacked into Surface articles, which can then be controlled and shown in various ways.
As referenced above, Surface items are addressed by square shapes, as are numerous different articles in pygame, like pictures and windows. Square shapes are so intensely utilized that there is an exceptional Rect class just to deal with them. You'll use Rect articles and pictures in your game to draw players and foes and oversee crashes between them.

One similar library like Pyglet is Pygame in Python itself. So let's compare them to let us help decide which one is better for what purpose. 

Pyglet

  • It is firmly woven with OpenGL.
  • Pyglet expects you to subclass to do anything.
  • It has 3D support
  • Code you composed for more established variants of pyglet won't work without changes.
  • Speed savvy, pyglet is quicker than pygame
  • Fewer people group support and less popularity

Pygame

  • Pygame utilizes SDL libraries and doesn't need OpenGL.
  • Pygame is easier to learn since it doesn't expect you to skill to make classes or capacities.
  • It doesn't have 3D help as it utilizes the simple python language structure, so the Pygame system has essentially all you want to make a straightforward 2D game.
  • Pygame is substantially more compact, has more individuals utilizing it, more designers, and a steady API. So the code you composed some time in the past will probably work.
  • Pygame is slower than pyglet.
  • Since it has been there for a long time, there is more excellent local area support and greater fame.

    By this comparison, we can say PyGame is a decent arrangement of libraries for the game turn of events. Additionally, python as a language is entirely agreeable recorded as a hard copy game, particularly for amateurs. Additionally, the article arranged approach is exceptionally convenient in-game turn of events.
     

Read more about, Fibonacci Series in Python

FAQs

1. Is pygame a performant?

While Pygame might be inadequate regarding highlights and improvement when contrasted with simple game advancement structures, low execution in its rare its shortcoming.

2. Could pygame make 3D games?

Pygame isn't strictly intended for 3D designs, so to make a game with 3D illustrations, you'd be in an ideal situation utilizing something different where every one of the essentials, like overshadowing, are done consequently.

3. Does Pygame uphold OpenGL?

The pygame people are fixing it by adding the fitting capacities to get at the OpenGL credits.

4. What does Pygame stop () do?

The pygame. stop() work is somewhat something contrary to the pygame. init() work: it runs code that deactivates the Pygame library.

5. what are a few remarkable rounds of Pygame?

  • Prominent games utilizing Pygame
  • Worries on Fire.
  • Save the Date, IndieCade 2013 Finalist.
  • Drawn Down Abyss.

Key Takeaways

We have discussed what Pygame is and how it is used. We understand that it is a library in Python which can be used in creating games and other applications. Then we understood how to install Pygame using Python, and the code for the same is also available above. After this, we know the uses of Pygame in detail and compared it with Pyglet, which is a similar library. Afterward, we saw some functions in Pygame and how they are used. 

Hey Ninjas! Don’t stop here; check out Coding Ninjas for Python, more unique courses, and guided paths. Also, try Coding Ninjas Studio for more exciting articles, interview experiences, and excellent Machine Learning and Python problems. 

Happy Learning!

 

Live masterclass