DEV Community

professional writer
professional writer

Posted on

How to Install Pygame and Make a Python 3 Game Development Template

Image description## Intro

You can use the open-source pygame library to create games and other multimedia applications using the Python programming language. pygame, which can run on a variety of platforms and operating systems, is built on top of the highly portable SDL (Simple DirectMedia Layer) development library.

Without having to worry about the complexities involved in working with video and audio on the backend, you can manage the logic and graphics of your games by using the pygame module.

read also : Twitter's Api

This guide will walk you through setting up Pygame in your Python development environment, then it will demonstrate how to create a template for creating games using Pygame and Python 3.

Prerequisites

Make sure Python 3 and a programming environment are set up on your local computer or server before beginning this tutorial.

read also : What is the encrypt library?

Additionally, you should be knowledgeable about the following Python programming concepts:

  • Conditional statements
  • Importing modules
  • Boolean logical operators
  • Variables
  • while loops
  • for loops

Installing pygame

Let's start by turning on the Python 3 development environment:

$. my_env/bin/activate
Enter fullscreen mode Exit fullscreen mode

You can use pip to install pygame once this is enabled:

pip install pygame
Enter fullscreen mode Exit fullscreen mode

Once you run this command, you should see output that looks similar to the following:

Output
Collecting pygame
  Using cached pygame-1.9.3-cp35-cp35m-manylinux1_x86_64.whl
Installing collected packages: pygame
Successfully installed pygame-1.9.3
Enter fullscreen mode Exit fullscreen mode

The following command will launch a mock game showcasing what pygame is capable of in terms of graphics and sound, allowing you to confirm that you have correctly installed pygame on a system with video and audio support:

python -m pygame.examples.aliens
Enter fullscreen mode Exit fullscreen mode

You can also enter the Python interactive console to make sure you can import the pygame module if you'd prefer not to open the sample or if your setup does not include AV. To open the console, first enter the following Python command:

>>> import pygame
Enter fullscreen mode Exit fullscreen mode

When you enter the ENTER key after the command, you'll know that pygame was installed successfully if you don't get any errors. With the quit() command, the Python interactive console can be closed.

Check out the GettingStarted wiki if you are having trouble installing via the command line.

Later on in this tutorial, we'll assume that a monitor will be used to display the graphical user interface so that we can check our code.

nano our_game.py
Enter fullscreen mode Exit fullscreen mode

Starting a project in Pygame requires adding the import statement, which can be found at the top of your file, which is used to import modules:

import pygame
Enter fullscreen mode Exit fullscreen mode

In order to add some of the pygame constants and functions to your file's global namespace, we can also opportunistically add another import statement below the first line:

import pygame
from pygame.locals import *
Enter fullscreen mode Exit fullscreen mode

setting up pygame
From here, we'll use the init() function, which stands for "initialise," to set up pygame's features.

import pygame
from pygame.locals import *


pygame.init()
Enter fullscreen mode Exit fullscreen mode

All the pygame modules that need to be initialised will launch automatically when you use the init() function.

Additionally, you can initialise every module in Pygame separately, as in:

pygame.font.init()
Enter fullscreen mode Exit fullscreen mode

If you request it, the init() function will give you a tuple. Both successful and unsuccessful initialization will be shown in this tuple. Both the general init() call and the initialization of particular modules (which will let us know whether those modules are available) can be done in this way:

i = pygame.init()
print(i)

f = pygame.font.init()
print(f)
Enter fullscreen mode Exit fullscreen mode

If we run the code above, we will receive output similar to the following:

Output
(6, 0)
None
Enter fullscreen mode Exit fullscreen mode

The I variable in this instance returned the tuple (6, 0), indicating that there were 6 successful initializations of PyGame and 0 unsuccessful ones. The None value of the f variable indicates that the module is not accessible in this specific environment.

Setting Up the Display Surface

We need to set up our game display surface from here. We'll set up a window or screen for display using pygame.display.set mode() and pass it to a variable. We will pass a pair of numbers representing width and height in a tuple as the display resolution argument into the function. Let's incorporate this feature into our programme:

import pygame
from pygame.locals import *


pygame.init()

game_display = pygame.display.set_mode((800, 600))
Enter fullscreen mode Exit fullscreen mode

The set mode() function received the tuple (800, 600) as an argument, which represents the resolution of the width (800 px) and the height (600 px) (600 px). There are two sets of parentheses in the function above because the tuple is enclosed within them.

Since you'll probably use the integers for your game's resolution frequently, you should probably assign those numbers to variables rather than using them repeatedly. As a result, it will be simpler to modify your programme because you will only need to change the data passed to the variables.

The variables display width and display height will be used to specify the width and height of the game's display, respectively, and passed to the set mode() function:

import pygame
from pygame.locals import *


pygame.init()

display_width = 800
display_height = 600

game_display = pygame.display.set_mode((display_width, display_height))

Enter fullscreen mode Exit fullscreen mode

At this point the game display surface is set up with a resolution for its width and height.

Updating the Display

After that, we must use one of two available functions to update the game surface's display.

Animations are typically changes made over time between various frames. When you think of animations, you might picture a flip book because they are made up of a series of images that change gradually from one page to the next. These pages simulate movement when quickly turned through because the text and images on each page seem to be moving. Instead of using pages, frames are used in computer games.

One of the functions that can be used to update the display of the game surface is called flip() and can be called in our file above because it is based on the idea of flipping pages or frames.

pygame.display.flip()
Enter fullscreen mode Exit fullscreen mode

The flip() function modifies the entire screen's display surface.

Because it updates only selected areas of the screen rather than the entire area, saving memory, the update() function is more frequently used than the flip() function.

Let's include the update() function at the very end of our game.py:

import pygame
from pygame.locals import *


pygame.init()

display_width = 800
display_height = 600

game_display = pygame.display.set_mode((display_width, display_height))

pygame.display.update()
Enter fullscreen mode Exit fullscreen mode

At this point, the programme can be run without encountering any issues, but the display surface will only briefly open before quickly closing.

Creating the Game Loop

The display has been set, pygame has been imported, and the game surface has been updated. Now we can work on the main game loop.

The game will be run by a while loop that we will build. The loop will invoke the Boolean value True, meaning that it will continue to loop indefinitely unless interrupted.

We will build a for loop to iterate through the user events in the event queue within this main game loop of our programme. This for loop will be called by the pygame.event.get() function.

Although the for loop is currently empty, we can add a print() statement to demonstrate that the code is acting as expected. The events from the iteration will be passed into

import pygame
from pygame.locals import *


pygame.init()

display_width = 800
display_height = 600

game_display = pygame.display.set_mode((display_width, display_height))

pygame.display.update()

while True:
    for event in pygame.event.get():
        print(event)
Enter fullscreen mode Exit fullscreen mode

To make sure that our code is working, let’s run the program:

python our_game.py
Enter fullscreen mode Exit fullscreen mode

The file will open in a 800x600 window when we run it. You can use your mouse to test the events, click inside the window, and key on your keyboard. These events will print to the console window on your computer.

Your output will resemble something like this:

Output
<Event(4-MouseMotion {'rel': (616, 355), 'buttons': (0, 0, 0), 'pos': (616, 355)})>
<Event(5-MouseButtonDown {'button': 1, 'pos': (616, 355)})>
<Event(6-MouseButtonUp {'button': 1, 'pos': (616, 355)})>
<Event(2-KeyDown {'scancode': 3, 'key': 102, 'unicode': 'f', 'mod': 0})>
<Event(3-KeyUp {'scancode': 3, 'key': 102, 'mod': 0})>
...
Enter fullscreen mode Exit fullscreen mode

The user events that are happening are displayed in this output. As they are produced by the user, these events are what will govern the game. Your code will take in these events each time you call the pygame.event.get() function.

In the terminal window, press CTRL + C to halt the program's execution.

As we won't need to see all of this terminal output, you can now delete or comment out the print() statement.
Now that we know how to exit a game, we can work on finishing up our template.

Quitting

We can uninitialize the relevant modules before quitting Python as usual to end a pygame programme.

Both the Python quit() function and the pygame.quit() function will uninitialize all pygame modules.

We should also be aware that pygame.QUIT is sent to the event queue when the user instructs the programme to terminate by clicking the "X" in the top-right corner of the game window because users control game functionality and events.

In the event-handling for loop, let's begin directing the program's flow with a conditional if statement:

import pygame
from pygame.locals import *


pygame.init()

display_width = 800
display_height = 600

game_display = pygame.display.set_mode((display_width, display_height))

pygame.display.update()

while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            quit()
Enter fullscreen mode Exit fullscreen mode

According to the code above, the programme should uninitialize the pygame modules with pygame.quit() and terminate itself with quit if the user has asked it to do so ().

We can invoke event.type and QUIT without adding pygame. because pygame.locals has been imported.

Although users may be aware of the "X" in the game window's upper corner, we may want to have other user actions serve as the basis for the request to end the programme. The KEYDOWN event type and one or more keys can be used to accomplish this.

The user is depressing a key on their keyboard when the KEYDOWN event occurs. For the sake of this discussion, assume that the Q key (as in

import pygame
from pygame.locals import *


pygame.init()

display_width = 800
display_height = 600

game_display = pygame.display.set_mode((display_width, display_height))

pygame.display.update()

while True:
    for event in pygame.event.get():
        if event.type == QUIT or (
             event.type == KEYDOWN and (
              event.key == K_ESCAPE or
              event.key == K_q
             )):
            pygame.quit()
            quit()
Enter fullscreen mode Exit fullscreen mode

Boolean logical operators have been added so that the programme can end if the user clicks the "X" in the top-right corner of the game window or presses one of the escape or Q keys down (note that this is not case sensitive).

At this point, you can test the functionality of the game running and then quitting by either exiting the window with the "X" icon, or by pressing either the Q or ESC key, if you run the programme using the python our game.py command.

Code Improvements and Next Steps

Although the aforementioned programme is fully operational, there are some things we can do to make the code better.

To begin with, we can substitute a function definition for the code that is in the while loop:

def event_handler():
    for event in pygame.event.get():
        if event.type == QUIT or (
             event.type == KEYDOWN and (
              event.key == K_ESCAPE or
              event.key == K_q
             )):
            pygame.quit()
            quit()
Enter fullscreen mode Exit fullscreen mode

This will tidy up and condense the while loop a little bit, especially as we expand the functionality of our game.

Additionally, we can add a caption to the window's title bar (which currently says pygame window) to begin polishing the game. We can accomplish this with the following line:

pygame.display.set_caption('Our Game')
Enter fullscreen mode Exit fullscreen mode

The string "Our Game" above can be changed to whatever name you prefer for the game.

We can also insert the pygame.display.update() procedure into the primary game loop.

Now, our complete code appears as follows:

import pygame
from pygame.locals import *


pygame.init()

display_width = 800
display_height = 600

game_display = pygame.display.set_mode((display_width, display_height))
pygame.display.set_caption('Our Game')


def event_handler():
    for event in pygame.event.get():
        if event.type == QUIT or (
             event.type == KEYDOWN and (
              event.key == K_ESCAPE or
              event.key == K_q
             )):
            pygame.quit()
            quit()

while True:
    event_handler()

    pygame.display.update()
Enter fullscreen mode Exit fullscreen mode

The code above can also be approached in other ways, such as by using a break statement to exit a loop before entering a game exit.

From here, you should continue learning how to animate images and control the frame rate, display images through drawing and sprites, and more. By reading the official pygame documentation, you can learn more about pygame game development.

Conclusion

This tutorial showed you how to set up a template that you can use for managing the main loop of a Python game, as well as how to install the open-source module pygame into your Python 3 programming environment.

Image description
You can learn "How To Create A Twitterbot With The Tweepy Library" or "How To Plot Data Using Matplotlib" to complete other programming tasks that use Python modules.

Top comments (0)