Pygame Tutorial | Pygame Download | Pygame Install



  • Python is the very easiest programing language. In every emerging field in computing, Python makes its presence actively.
 Pygame

Pygame

  • Python has large libraries for various Language like
    • Machine Learning (Numpy, Pandas, Matplotlib) , AI (Pytorch, TensorFlow)
    • Game development (Pygame, Pyglet).

Pygame

  • Pygame may be a cross-platform set of Python modules. It is used to make video games.
  • It consists of special effects and sound libraries designed to be used with the Python programing language.
  • It was officially written by Pete Shinners to replace PySDL.
  • It is suitable for client-side applications which is potentially wrapped during a standalone executable.
 Pygame Video Game

Pygame Video Game

  • To learn pygame, we must required to have basic knowledge of Python

Pygame Installation

Install pygame in windows

  • Before installing Pygame, Python should be installed within the system, and it's good to have 3.6.1 or above version because it's much friendlier to beginners, and additionally runs faster. There are two ways to install Pygame. They are given below:

Installing through pip

  • The great way to install Pygame is with the pip tool. The command is that the following:
py -m pip install -U pygame --user

Installing through an IDE

  • The second way is to install it through an IDE and here we are using Pycharm IDE. Installation of pygame within the pycharm is simple . we will install it by running the above command within the terminal or use the subsequent steps:
    • Open the File tab and click on on the Settings option.
 Pygame Setting

Pygame Setting

    • Select the Project Interpreter and click on the + icon.
 Pygame Setting

Pygame Project Interpreter

    • It will display the search box. Search the pygame and click on the install package button.
 Pygame Install Package

Pygame Install Package

    • To check whether the pygame is properly installed or not, in the IDLE interpreter. To type the following command and press Enter: import pygame
    • If the command runs successfully without throwing any errors, that means we have successfully installed Pygame. The right version of IDLE to use for pygame programming.
 Python Shell

Python Shell

Install pygame in Mac:

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

Mac

  • Double click on the downloaded file and unzip it. Now double click on the unzipped mpkg file that appears to run the installer. Follow the instructions to install pygame.
    • To Start the terminal (Cmd+Space, then enter 'terminal' within the search box). within the terminal, type 'python2.7'.
    • press enter.
    • Python should begin , display the version as 2.7.2 (2.7.1 is ok too), and provides you a prompt. At the Python prompt, type 'import pygame'. If you do not get any errors, everything is workining fine.

Pygame Example

 Pygame-Example

Pygame Example

Sample Code

import pygame

pygame.init()
screen = pygame.display.set_mode((400,500))  
done = False  

while not done:  
for event in pygame.event.get():  
ifevent.type == pygame.QUIT:  
            done = True  
pygame.display.flip()

Output

 Pygame Window

Pygame Window

Syntax Explanation

import pygame

  • Its provides to access the pygame framework.
  • To imports all functions of pygame.

pygame.init()

  • It is used for initialize all the specified module of the pygame.

pygame.display.set_mode((width, height))

  • Display a window with specified size. The return value may be a Surface object which is that the object where we'll perform graphical operations.

pygame.event.get()

  • This is often used for empty the event queue. If we don't call this, the window messages will start to compile and, the sport will become unresponsive within the opinion of the OS .

pygame.QUIT

  • This is often used to terminate the event once we click on the close button at the corner of the window.

pygame.display.flip()

  • Pygame is double-buffered, so this will shifts the buffers. It's essential to call this function so as to form any updates that you simply make on the game screen to form visible.

Pygame Surface

  • The pygame Surface will display any image. It has a pre-defined resolution and with pixel format. The Surface color is by default black. Its size is defined by passing the dimensions argument.
  • Surfaces can have the amount of additional attributes like alpha planes, color keys, source rectangle clipping, etc.
  • The blit routines will plan to use hardware acceleration when possible; otherwise, they're going to use highly enhanced software blitting methods.

Pygame Clock

  • Times are represented in millisecond (1/1000 seconds) in pygame which is used to trace the time.
  • It is important to make motion, play a sound, or, react to any event. Generally , we do not count time in seconds. We count it in milliseconds.
  • It's also provides various functions to assist in controlling the game's frame rate.

Some functions are the following:

Tick()

  • It is used to update the lock

Syntax

tick(framerate=0)
  • This method should be called once per frame. It will calculate how many milliseconds have passed since the previous call..

tick_busy_loop()

  • tick_busy_loop(): Same as the tick(). By calling the Clock.
  • tick_busy_loop(30): Once per frame, the program will not run at program more than 30 frames per second.

Syntax

tick_busy_loop()

get_time()

  • It is used to get the previous tick.
  • The number of a millisecond that passed between the last two calls in Clock.tick().

Syntax

get_time()

Pygame Blit

  • The pygame blit is the process to render the game object onto the surface, and this process is called blitting.
  • When we create the game object, we need to render it. If we don't render the game objects and run the program, then it will display the black window as an output.
  • It is one of the slowest operations in any game so, we need to be careful to not to blit much onto the screen in every frame. The primary function used in blitting is blit().

blit()

  • It is used to draw one image into another. The draw are often placed with dest argument. The dest argument will be a pair of coordinates representing the upper left corner of the source

Syntax

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

Pygame Adding Image

  • To add an image on pygame window, We need to instantiate a blank surface by calling the Surface constructor with a width and height tuple.
surface = pygame.Surface((100,100))
 Custom Image

Custom Image

  • The above line creates a blank 24-bit RGB image that's 100*100 pixels with the default black color.
  • For the transparent initialization of Surface, pass the SRCALPHA argument
surface = pygame.Surface((100,100), pygame.SRCALPHA) 

Sample Code

import pygame
pygame.init()
white = (255, 255, 255)  
# assigning values to height and width variable   
height = 400  
width = 400  
# creating the display surface object   
# of specific dimension..e(X, Y).   
display_surface = pygame.display.set_mode((height, width))    
# set the pygame window name   
pygame.display.set_caption('Image')  
# creating a surface object, image is drawn on it.   
image = pygame.image.load(r'wikitechy.png')  

# infinite loop   
while True:  
display_surface.fill(white)  
display_surface.blit(image, (0, 0))  

for event in pygame.event.get():  
ifevent.type == pygame.QUIT:  
pygame.quit()
            # quit the program.   
quit()
        # Draws the surface object to the screen.   
pygame.display.update()

Output

 Adding Image

Adding Image

Pygame Rect

  • It is used to draw a rectangle in Pygame.
  • Pygame uses Rect objects to store and manipulate rectangular areas.
  • A Rect are often formed from a mixture of left, top, width, and height values. It also can be created from Python objects that are already a Rect or have an attribute named "rect".
  • rect() function is used to perform changes within the position or size of a rectangle. It returns the new copy of the Rect with the affected changes.

Sample code

import pygame
pygame.init()
screen = pygame.display.set_mode((400, 300))  
done = False  

while not done:  
for event in pygame.event.get():  
ifevent.type == pygame.QUIT:  
            done = True  
pygame.draw.rect(screen, (0, 125, 255), pygame.Rect(30, 30, 60, 60))    

pygame.display.flip()

Output

 Rect

Rect

Pygame Keydown

 Polling

Polling

  • Pygame KEYDOWN and KEYUP are detect the event if a key is pressed and released.
    • KEYDOWN : It detects the key press.
    • KEYUP : It detects the key release.
  • key : Key is an integer id. It represents every key on the keyword.
  • mod : This is a bitmask of all the modifier keys that are in the pressed state when the event occurred.

Sample Code

import pygame
pygame.init()
# sets the window title  
pygame.display.set_caption(u'Keyboard events')  
# sets the window size  
pygame.display.set_mode((400, 400))  
while True:  
    # gets a single event from the event queue  
event = pygame.event.wait()  
    # if the 'close' button of the window is pressed  
ifevent.type == pygame.QUIT:  
        # stops the application  
        break  
# Detects the 'KEYDOWN' and 'KEYUP' events  
ifevent.type in (pygame.KEYDOWN, pygame.KEYUP):  
        # gets the key name  
key_name = pygame.key.name(event.key)  
# converts to uppercase the key name  
key_name = key_name.upper()
        # if any key is pressed  
ifevent.type == pygame.KEYDOWN:  
            # prints on the console the key pressed  
print(u'"{}" key pressed'.format(key_name))  
# if any key is released  
elifevent.type == pygame.KEYUP:  
# prints on the console the released key  
print(u'"{}" key released'.format(key_name))  

Output

"RETURN" Key pressed
"RETURN" Key released
"SPACE" Key pressed
"SPACE" Key released
"DELETE" Key pressed
"DELETE" Key released

Sample Code

import pygame

pygame.init()
screen = pygame.display.set_mode((400, 300))  
done = False  
is_blue = True  
x = 30  
y = 30  

while not done:  
for event in pygame.event.get():  
ifevent.type == pygame.QUIT:  
            done = True  
ifevent.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:  
is_blue = not is_blue

pressed = pygame.key.get_pressed()  
if pressed[pygame.K_UP]: y -= 3  
if pressed[pygame.K_DOWN]: y += 3  
if pressed[pygame.K_LEFT]: x -= 3  
if pressed[pygame.K_RIGHT]: x += 3  

    if is_blue:  
color = (0, 128, 255)  
    else:   
color = (255, 100, 0)  
pygame.draw.rect(screen, color, pygame.Rect(x, y, 60, 60))  

pygame.display.flip()

Output

 Keydown

When we press the Down key, the rectangle is reshaped in the downwards. The output is the following:

 Keydown

Keydown

Pygame Draw

  • Pygame provides geometry functions to draw simple shapes to the surface.
  • This functions accept a width argument to suggest the size of the thickness round the edge of the shape . If the width is passed 0, then the shape are going to be solid(filled).
  • All the drawing function takes the colour argument. It will be one among the following formats:
    • pygame.Color objects
    • An (RGB) triplet(tuple/list)
    • An (RGBA) quadruplet(tuple/list)
    • An integer value that has been mapped to the surface's pixel format

Draw a rectangle

 Draw Rect

Draw Rect

  • These functions are used to draw a rectangle on the given surface
pygame.draw.rect(surface, color, rect)
pygame.draw.rect(surface, color, rect, width=0)

Parameters

  • surface - Screen to draw on.
  • color- It is used to color the given shape.
  • rect(Rect)- Draw rectangle, position, and dimensions.
  • width(int)- (optional) To use the thickness or to point that the rectangle is filled.
if width == 0, (default) fill the rectangle
if width > 0, used for line thickness
if width < 0, nothing will be drawn

Draw a polygon

 Polygon

Polygon

The following functions are used to draw a polygon on the given surface.

pygame.draw.polygon(surface,color,points)
pygame.draw.polygon(surface, color, points, width=0)

Parameters

  • surface - Screen to draw on.
  • color - It is used to color the given shape.
  • points(tuple(coordinate) or list(coordinate)) - A sequence of 3 or more (x,y) coordinates that make up the vertices of the polygon. Each coordinate in the sequence must be tuple/list.

Draw an ellipse

 Ellipse

Ellipse

These are the function of ellipse.

Parameters

pygame.draw.ellipse(surface, color, rect)
pygame.draw.ellipse(surface, color, rect, width=0)
  • surface - Screen to draw on.
  • color - It is used to color the given shape.
  • rect(Rect) - Draw rectangle, position, and dimensions.

Draw a straight line

 Line

Line

These are the methods of straight line

pygame.draw.line(surface,color,start_pos,end_pos,width)
pygame.draw.line(surface,color,start_pos,end_pos,width=1)

Parameters

  • surface - Screen to draw on.
  • color - It is used to color the given shape.
  • start_pos - Start position of the line
  • end_pos - End position of the line

Draw a circle

These are functions of the circle.

circle(surface, color, center, radius)
circle(surface, color, center, radius, width=0)

Parameters

  • surface - Screen to draw on.
  • color - It is used to color the given shape.
  • center - The center point of the circle as a sequence of two int/float.
  • radius(int or float) - Radius of the circle, measured from the center parameter.

Draw an elliptical arc

These are the functions of elliptical arc.

? arc(surface, color, rect, start_angle, stop_angle)
? arc(surface, color, rect, start_angle, stop_angle, width=1)

Parameters

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

There are three conditions for start_angle and stop_angle parameter:

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

Sample Code

import pygame
from math import pi  
pygame.init()
# size variable is using for set screen size  
size = [400, 300]  
screen = pygame.display.set_mode(size)  
pygame.display.set_caption("Shapes")  
# done variable is using as flag   
done = False  
clock = pygame.time.Clock()  
while not done:  
# clock.tick() limits the while loop to a max of 10 times per second.  
clock.tick(10)  
for event in pygame.event.get():  # User did something  
ifevent.type == pygame.QUIT:  # If user clicked on close symbol   
done = True  # done variable that we are complete, so we exit this loop  

# All drawing code occurs after the for loop and but  
    # inside the main while done==False loop.  
    # Clear the default screen background and set the white screen background  
screen.fill((0, 0, 0))  
# Draw on the screen a green line which is 5 pixels wide.  
pygame.draw.line(screen, (0, 255, 0), [0, 0], [50, 30], 5)  
    # Draw on the screen a green line which is 5 pixels wide.  
pygame.draw.lines(screen, (0, 0, 0), False, [[0, 80], [50, 90], [200, 80], [220, 30]], 5)  
    # Draw a rectangle outline  
pygame.draw.rect(screen, (0, 0, 0), [75, 10, 50, 20], 2)  
    # Draw a solid rectangle  
pygame.draw.rect(screen, (0, 0, 0), [150, 10, 50, 20])  
    # This draw an ellipse outline, using a rectangle as the outside boundaries  
pygame.draw.ellipse(screen, (255, 0, 0), [225, 10, 50, 20], 2)  
    # This draw a solid ellipse, using a rectangle as the outside boundaries  
pygame.draw.ellipse(screen, (255, 0, 0), [300, 10, 50, 20])  
    # Draw a triangle using the polygon function  
pygame.draw.polygon(screen, (0, 0, 0), [[100, 100], [0, 200], [200, 200]], 5)  
    # This draw a circle  
pygame.draw.circle(screen, (0, 0, 255), [60, 250], 40)  
    # This draw an arc  
pygame.draw.arc(screen, (0, 0, 0), [210, 75, 150, 125], 0, pi / 2, 2)  
    # This function must write after all the other drawing commands.  
pygame.display.flip()
# Quite the execution when clicking on close  
pygame.quit()

Output

 Draweg

Pygame Draw

Pygame Font & Text

  • Pygame also provides facilities to render the font and text. we will load fonts from the system by using the pygame.font.SysFont() function.
  • Pygame comes with the built-in default font which may be accessed by passing the font name or None. There are many functions to assist to figure with the font.
  • The font objects are created with pygame.font.Font().The actual font objects do most of the works through with fonts.
  • Font objects are used to render the text into new Surface objects.
 font

font

Some important font functions are the following:

render()

  • It is used to draw text on a replacement Surface. Pygame has no facility to draw text on the actual Surface. This creates a replacement Surface with the required text render on it.

Syntax

render(text, antialias, color, background=None)  

size()

  • It 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.

Syntax

Size(bool)

Read Also

Set_bold()

  • It is used for bold rending of text.

Syntax

set_bold(bool)  

Sample Code

import pygame
pygame.init()
screen = pygame.display.set_mode((640, 480))  
done = False  

#load the fonts  
font = pygame.font.SysFont("Times new Roman", 72)  
# Render the text in new surface  
text = font.render("Hello, Wikitechy", True, (158, 16, 16))  
while not done:  
for event in pygame.event.get():  
ifevent.type == pygame.QUIT:  
            done = True  
ifevent.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:  
            done = True  
screen.fill((255, 255, 255))  
    #We will discuss blit() in the next topic  
screen.blit(text,(320 - text.get_width() // 2, 240 - text.get_height() // 2))  
pygame.display.flip()

Output

 Text Example

Text Example

Pygame has the following function to list all the fonts available on the machine:

all_font = pygame.font.get_fonts() 

Another function

font = pygame.font.Font(None,size)

Pygame Sprite and Collision Detection

  • It may be a two-dimensional image that's a part of the large graphical scene. Generally, a sprite are going to be some object within the scene.
  • Pygame provides sprites and sprite groups that help for collision detection. It is that the process when two objects on the screen collide each other.
  • The Sprite module contains the varied simple classes to be used within the games.
  • It's optional to use Sprite classes and different group classes when using pygame.
 Sprite and Collision

Sprite and Collision

Sample Code

import pygame
import sys  
#Sprite class   
class Sprite(pygame.sprite.Sprite):  
def __init__(self, pos):  
        pygame.sprite.Sprite.__init__(self)  
self.image = pygame.Surface([20, 20])  
self.image.fill((255, 0, 255))  
self.rect = self.image.get_rect()
self.rect.center = pos
def main():  
pygame.init()
clock = pygame.time.Clock()  
    fps = 50  
bg = [0, 0, 0]  
size =[300, 300]  
    screen = pygame.display.set_mode(size)  
player = Sprite([40, 50])  
    # Define keys for player movement  
player.move = [pygame.K_LEFT, pygame.K_RIGHT, pygame.K_UP, pygame.K_DOWN]  
player.vx = 5  
player.vy = 5  
wall = Sprite([100, 60])  
wall_group = pygame.sprite.Group()
wall_group.add(wall)  
player_group = pygame.sprite.Group()
player_group.add(player)  
    while True:  
for event in pygame.event.get():  
ifevent.type == pygame.QUIT:  
                return False  
key = pygame.key.get_pressed()  
for i in range(2):  
if key[player.move[i]]:  
player.rect.x += player.vx * [-1, 1][i]  

for i in range(2):  
if key[player.move[2:4][i]]:  
player.rect.y += player.vy * [-1, 1][i]  
screen.fill(bg)  
        # first parameter takes a single sprite  
        # second parameter takes sprite groups  
        # third parameter is a kill command if true  
hit = pygame.sprite.spritecollide(player, wall_group, True)  
        if hit:  
        # if collision is detected call a function to destroy  
            # rect
player.image.fill((255, 255, 255))  
player_group.draw(screen)  
wall_group.draw(screen)  
pygame.display.update()
clock.tick(fps)  
pygame.quit()
sys.exit
if __name__ == '__main__':  

Read Also

Output

 Sprite

Sprite

  • After pressing the arrow keys, one rectangle will collide with another rectangle then output is:
 Collide

Collide

Pyglet

  • Python also has an another game library named pyglet .
  • It is cross-platform windowing and multimedia library for Python.
  • It is used to developing games and other visually rich applications.
  • It supports user interface event handling, windowing, OpenGL graphics, loading images and videos, and playing sounds and music.
 Pyglet

Pyglet

Features of Pyglet

  • No external installation requirements or dependencies.
  • It can load images, sound, music, and video in any format.
  • Pyglet is provided under the BSD open-source license.
  • Take benefit of multiple windows and multi-monitor.
  • It supports both Python 2 and 3.

Installing pyglet is very simple. By using the below command to install pyglet.

pip install pyglet  

Sample Code

import pyglet
window = pyglet.window.Window()  
lable = pyglet.text.Label('Wikitechy', font_name='Times New Roman', font_size=36,  
                          x= window.width//2,y=window.height//2,anchor_x='center', anchor_y='center')  
@window.event  
defon_draw():  
window.clear()
lable.draw()
pyglet.app.run()

Output

 Pygleteg

Pyglet

Difference between Pygame and Pyglet

Pyglet Pygame
Written in pure Python

It can be compiled using the other Python interpreters.
Best canvas system

Pygame provides a drawing system that allows the user to create and draw an unlimited number of the canvas.
Cross-platform

It can work with Window, Linux, and OS X.
Usage API

The API is very straightforward.
3d support

Since pyglet is so firmly merged with OpenGL.
It allows the support of drawing in 3D.
Easy Python syntax

Pygame uses Python as its scripting language. Python is widely treated one of the most natural languages to grasp even for beginners.
Less Popularity

Pyglet is less popular because it has small community support.
More popular

Pygame is more popular than the pyglet.


Related Searches to Pygame Tutorial | Pygame Download | Pygame Install