Getting Started with Pygame
Pygame is a free-to-use and open-source set of Python Modules. And as the name suggests, it can be used to build games. You can code the games and then use specific commands to change it into an executable file that you can share with your friends to show them the work you have been doing. It includes computer graphics and sound libraries designed to be used with the Python programming language. PyGame 2.0.1 is the latest version at the time of writing this article.
Setting Up Pygame:
By default, Python doesn’t come with PyGame as an in-built Library. So we have to install it using the command prompt. Open a command prompt and type the following command:
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course
pip install pygame
If you already have PyGame installed, use the following command to check the version:
pip show pygame
If your Pygame is not updated to the latest version, use the following command:
pip install pygame --upgrade
If this command shows a ModuleNotFoundError, then it is clear that pygame is not installed.
Simple PyGame Example:
- pygame.init(): This command is used to initiate the pygame module.
- pygame.display.set_mode((500,500)): This command is used to make a window of desired size, (width, height). The return value is a Surface Object which is the object where we perform different graphical operations.
- pygame.display.set_caption(title = “”): This command is used to set the title of the window/ board.
- pygame.event.get(): This is used to empty the event queue. If we do not call this, the window messages will start to pile up and, the game will become unresponsive in the opinion of the operating system.
- pygame.QUIT: This is used to terminate the event when we click on the close button at the corner of the window.
Add Image to the Pygame WIndow:
Blitting is the process of rendering the game object onto the surface. When we create the game object, we should render it. If we don’t render the game object, it will show the black window. In pygame there is a way to do this blitting process, i,e, blit().
It is one of the slowest operations in any game, so we need to be careful while using it as we shouldn’t blit much onto the screen in every frame.
Syntax: blit(src, dest)
src : It is the source of the image which we want to display on the screen
dest : It is the coordinates where we want our image to be displayed.
Rectangle Box in Pygame Window:
In Pygame we use rect() method to draw rectangle boxes on the window. Pygame uses Rect objects to store and manipulate rectangular areas. It can be formed by the combination of left, top, width, and height values.