Pygame

The Pygame is a library of Python language. It is an open-source library to download and use every user. It is making graphical multimedia programs like Games, Video, Audio, etc. and it runs all platforms very easily.

  1. What is Pygame
  2. History of Pygame
  3. Requirement
  4. Installation of Pygame
  5. Concepts of Pygame
  6. Simple Pygame application
  7. Interactivity
  8. Adding Functionality
  9. Pygame Text and Font
  10. Draw Modules in Pygame

What is Pygame?

Pygame is a library of python programming language. It is an open-source library for making multimedia applications like games that are built on the top of the SDL library. Pygame requires Python language to be installed in the system. Pygame is highly portable and runs nearly on all platforms and operating systems. Millions of peoples have downloaded Pygame itself, which is a whole lot of bits flying across interwebs. Pygame.org website welcomes all game, video, image, audio, and multimedia applications. Once you have finished getting the start, you could add a fresh project or learn Pygame by reading the docs.

History of Pygame

In the summer of 2000, the Pygame began. Being a multi-year C programmer, I learned about the same time both Python and SDL. You are already familiar with the version 1.5.2 of Python. An introduction to SDL, the Simple Direct Media Layer, may be required. SDL, developed by Sam Lantinga, is a multimedia-controlled cross-platform C library comparable to DirectX.

Requirements

  • Latest version of Python language.
  • Make sure your python language path is set correctly.
  • Download the Pygame setup file if we are installing  Pygame tar.gz file through.
  • Make sure your command prompt works fine.

Pygame Installing on windows 

Installing the Pygame is pretty simple and easy. But the first prerequisite is to Install python 3.7 Installing python on both windows is very easy and straightforward. 

After installing Python, you need to set the path of Python in the system. As follows in the image:

First, we are opening a control panel and click the environment variables:

we are opening a control panel

After open the Environment variables, select the path and click the edit button:

open the Environment variables

Now we click a new button:

we click a new button

After click new button we copy to the path of Python from c: drive and paste it here:

After click new button we copy to the path of Python

Finally, the path of python has been successfully done.

After setting the way, we need to open a cmd prompt.

 we need to open a cmd prompt.

And then type pip command in the cmd prompt.

pip command in the cmd prompt

Now type the pip install pygame command here:

the pip install pygame command

Installation Pygame in Mac:

These are the following steps to install Pygame on Mac OS:

Hit the official site of Pygame pygame.org and, it will display the following window, download pygame-1.9.1release-python.org-32bit-py2.7-macosx10.3.dmg:

to install Pygame on Mac OS

1).Doubleclick and unpack the downloaded file. Now double click the unpacked mpkg.zip file that the installer appears to run. Follow pygame installation instructions.

2). Start the terminal (Cmd+Space, then in the search box enter ‘ terminal ‘). Type ‘ python2.7 ‘ into the terminal and click Enter key.

3). Python should start up, showing the version as 3.7.4 (3.7.4 is fine too), and give you a popup. At the Python popup, type import pygame’. If you don’t get any errors, all is good.

As you can see, the Pygame is installed successfully in the system now, and we are creating a simple pygame application.

PyGame Concepts

As Pygame and SDL library is universal across different platforms and devices, they both need to establish abstractions for different hardware realities and work with them. Learning these principles and ideas will help you create your games and improve them.

Initialization and Modules

The Pygame library consists of a variety of constructs from Python, including several different modules. Such modules provide theoretical links to your system’s specific hardware, as well as standardized methods for operating with that hardware. For example, the display enables improved access to your video display, while joystick enables abstract control of your joystick.

After importing the Pygame library in the above case, initializing PyGame using pygame.init() was the first thing you did. This function calls all including pygame modules to the different init() functions. Since these modules are abstractions for specific hardware, this initialization step is required to allow you to operate on Linux, Windows, and Mac with the same code.

Displays and Surfaces

Pygame also includes several Python classes in addition to the modules, which encapsulate the concepts dependent on non-hardware. One of these is the Surface, which determines a rectangular area that you can draw on, at it is purest. In many contexts, surface objects are used in Pygame. You will see later how an object can be loaded into a surface and displayed on the screen.

On a single user-created monitor, which can be a window or a full screen, everything is represented in pygame. The display is developed using the.set mode() function, which returns the visible part of the window to a layer. It is the Surface that you move through drawing functions such as pygame.draw.circle(), and when you call pygame.display.flip(), the contents of that Surface are moved to the display.

Images and Rects

Your basic pygame program has sculpted a shape directly to the surface of the display, but you can also work with the disk images. You can load and save images in a variety of standard formats using the image module. Frames are loaded into items on the surface, which can be manipulated and viewed in many ways.

As mentioned above, rectangles reflect surface objects, as many other pygame objects, such as images and windows. Squares are used so extensively that only to address them is a unique Rect category. In your game, you’re going to use Rect objects and pictures to draw players and enemies and handle collisions. Okay, the idea is enough. Let’s model a game and write it down!

Basic Game Design

It is always a good idea to have some structure in place before you start writing some code. Since this is a tutorial of a game, let’s also model some basic gameplay.:

  • The goal of the game is to avoid incoming obstacles:
  • The player has to start from the left side of the screen.
  • The obstacles enter randomly in the right and move to the left side in a point to point or straight-line manner.
  • The player can move from left to right, up to down, and vice versa for avoiding the obstacles.
  • The player is not allowed to jump off the screen.
  • The game comes to ends when either the player is hit by an obstacle or when the user closes that particular window.

Simple Pygame Application

Simple Pygame Application

Write code of blank screen :

code of blank screen

Here you can clearly show syntax :

Import Pygame- This is, of course, needed to allow the Pygame framework.

pygame.init()- This works to Initialize all the modules required for Pygame.

pygame.display.set_mode(width,height)- This will launch a window of the desired sizes. The return value is a surface object you will perform graphical operations on.

pygame.event.get()- This Function empties the event queue if you do not call this the windows message will start to pile up, and your game will become unresponsive in the operating system.

pygame.display.flip()- pygame is double buffered so this swaps the buffers all you need to know is that this call is required for the game to become visible.

So, what is the result like when we execute the above code? It looks something like this:

when we execute the above code
  1. It looks quite plain. Let’s start adding some stuff to our screen. We can begin by drawing a rectangle. It’s simple, and for this reason, we use pygame.draw.rect.
  2. As you can imagine, a rectangle will be drawn. This brings in a few points, including the drawing surface, the hue, and the rectangle coordinates/dimensions.#Add this somewhere after the event pumping and before the display.flip()
  3. Pygame.draw.rect(screen,(0, 128,255), pygame.Rect(30,30,60,60))

You can see there are three arguments:

  • The 1st argument is the surface instance to draw the rectangular.
  • The 2nd argument is the (red, green, blue) tuple that represents the color to draw with.
  • The 3rd argument is pygame.Rect instance. The arguments for this constructor are x and y coordinates of the top left corner, the width, and height. 

So what is it that we can watch after adding that small piece of code?

Well, here is the output:

after adding that small piece of code

It seems to be nothing fancy just yet. But we can always start somewhere, right?

So next up on this Pygame Tutorial, let us look at how we can make the game more interactive.

Interactivity

A game’s point is being interactive. The close key is the only thing you can play with right now. What’s not a funny game, right? Both events in the user input come through the queue of events. Add more if loop statements add more interactivity to that.

Add the following code before the loop:

  • is_blue = True

Modify your rectangular code to pick a color conditionally:

  •     if is_blue: color = (0, 128, 255)
  • else: color =(255, 100, 0)]])
  • pygame.draw.rect(screen,color,pygame.Rect(30,30,50,50)) Finally , the very important bit. Add this if statement to your for loop in the same sequence as the other if statement in there.
  • if event.type == pygame.KEYDOWN or event.key ==  pygame.K_SPACE:
  • is_blue = not is_blue

So by pressing the space key, it will change the color of the box. Check the following output:

So by pressing the space key

Is it pretty simple right? We need to find out next on this PyGame tutorial how we can add some features to the game.

Adding Functionality

So, our code looks something like this for now. Check it out below:

Check to output when we try to move the rectangle to the right:

we try to move the rectangle to the right

So, was not that what we were expecting, right?

Two things are wrong.

The rectangle from the previous frame remains on the screen each time you draw a rectangle.

It moves really, very fast.

Firstly, you simply need to reset the screen to the black before you draw the rectangle again. There is a much simpler method to do that on Surface called fill that does this. It takes in an RGB tuple.

Second, each frame’s length is as short as it can be as your super fancy machine. A rational amount such as 60 frames per second needs to reduce the framerate. Thankfully, in pygame.time there’s a simple class called Clock, which will do the same for us. It has a tick method that takes a desired fps frequency.

Put it all together and you get:

Let’s see what is the output of this code:

what is the output of this code

Next up on this PyGame tutorial we will see how we can work with images and how we can integrate them into our game.

Pygame Surface

The surface of the pygame is used to display any picture. The Surface has a predefined resolution and format of pixels. The color of the surface is black, by definition. By passing the size statement, its size is specified.

Surfaces can have the No. of extra attributes like Color keys, Alpha Planes Rectangle, Clipping, Source, etc. The blit routines will attempt to use the hardware acceleration when possible; otherwise, they will use very improved software blitting methods.

Pygame Clock

Times are displayed in the pygame in milliseconds (1/1000 seconds). Pygame clock is used to find the time. The time is essential to create movement, play a sound, or react to any events. Normally, we don’t count time in seconds. We count it in milliseconds. The clock also provides many functions to help in controlling the game’s fps. The few functions are the following:

tick()

This function is used to refresh the clock. The syntax is the following:

tick(framerate=0)

This method must be called once per frame. It will calculate how much milliseconds have passed since the previous call. The framerate’s argument is optional to pass in the function, and if it is passed as an argument, then the function will get delayed keeping the game to perform slower than the given ticks per second.

tick_busy_loop()

The tick_busy_loop( ) is similar to the tick. (The code will never run more than 20 frames per second by calling the clock.tick_busy_loop(20) Once per frame. The following is the syntax:

tick_busy_loop( )

get_time( )

This function is used to get the previous tick. The no. of a millisecond that isdra is passed in the middle of the last two calls in Clock.tick().

get_time()

Pygame Blit

The process used to render the game object onto the surface is termed as blitting. When someone creates the game object, he needs to render it. If we don’t render the game objects, then it will return the black screen as an output. Blitting is the slowest operation in any game. That’s why we need to be very careful not to blit much onto the screen in every possible frame. The function used in blitting is:

blit()

blit (source,dest,area=None special_flags=0)

This function is used to draw one image into another. The draw can be placed with the dest argument. The dest argument can either be a pair of coordinates as shown in the upper left corner of the source blit()

blit(source,dest,area=None special_flags=0)

This function is used to draw one image into another. The draw can be placed with the dest argument. The dest argument can either be a pair of coordinates representing the upper left corner of the source.

Adding Images

Simply calling the Surface Constructor with a tuple width and height, you can create a blank surface.

  • Surface = pygame.Surface((120,120))

This function will create a blank 24-bit RGB image that’s 120 x 120 pixels. The default color will be black. Blitting such an image on a white background will result in this output:

Blitting such an image on a white background

However, you can also include an optional argument in the Surface constructor if you want a 32-bit RGBA photo. Just add the following line in the code: Surface= pygame. Surface((120, 120), pygame. SRCALPHA). This will create a 100x 100 image that’s initialized to transparent.

Rendering such an image on a white background will result in this:

you can also include an optional argument in the Surface constructor

check it out the output of the code:

Draw Circle in Pygame

On Python shell the above code will look like below image:

Python shell the above code will look like below image

Let us check the output of this code :

Let us check the output

    Pygame Text and Font

Pygame also offers font and text rendering facilities. By using the pygame.font.SysFont) (feature, we can load fonts from the framework. Pygame comes with the default font built-in that can be accessed by passing the font name or None. There are a number of functions to support the font work.

Pygame.font.Font() generates the font objects. The real font items do most of the fonts job. Normally, font objects are used to render the text in new surface objects. The following are just a few important font functions:

render()

Render function is used to draw text on a new Surface. Pygame has no facility to draw text on the existing Surface. This builds a new Surface with the specified text render on it. The syntax is the following:

size()

This function is used to determine the number of space or positioning needed to render text. It can also be used for word-wrapping and other layout effects. The syntax is the following:

set_bold()

The following function is used for bold rending of text. The syntax is following:

Now it is the time to build the code of Text in the below:

Let’s see the output of this code as following:

Pygame Lib

Draw an modules

Parameters:

  • surface – Screen to draw on.
  • color- This argument is used to color the given shape. The alpha value is optional if we are using a tuple.
  • rect(Rect)- Draw rectangular, position, and dimensions.
  • start_angle- Start angle of the arc in radians.
  • stop_angle- Stop angle of the arc inside the radians.

There are three conditions for start_angle and stop_angle parameter:

  1. If start_angle < stop_angle, then the arc will be drawn in a counter-clock direction from the start_angle to the end_angle.
  1. If start_angle>stop_angle then tau(tau=2*pi) will be added to stop angle.
  2. If start_angle==stop_angle, nothing will be drawn.

Let’s consider an example:

Let’s see the output of the code given below:

Pygame Tutorial for Beginners

Pin It on Pinterest

Share This