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
- 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
- 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:
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
- Select the Project Interpreter and click on the + icon.
Pygame Project Interpreter
- It will display the search box. Search the pygame and click on the install package button.
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
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
- 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
Sample Code
Output
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
- 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
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
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
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.
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
Sample Code
Output
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
Output
Rect
Pygame Keydown
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
Output
Sample Code
Output
When we press the Down key, the rectangle is reshaped in the downwards. The output is the following:
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
- These functions are used to draw a rectangle on the given surface
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.
Draw a polygon
Polygon
The following functions are used to draw a polygon on the given surface.
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
These are the function of ellipse.
Parameters
- 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
These are the methods of straight line
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.
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.
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
Output
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
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
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
Read Also
Set_bold()
- It is used for bold rending of text.
Syntax
Sample Code
Output
Text Example
Pygame has the following function to list all the fonts available on the machine:
Another function
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
Sample Code
Read Also
Output
Sprite
- After pressing the arrow keys, one rectangle will collide with another rectangle then output is:
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
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.
Read Also
Installing pyglet is very simple. By using the below command to install pyglet.
Sample Code
Output
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. |