Requirements: Python & pip installed from python.org
The easiest way to install pygame is through the command prompt terminal:
Open up the command prompt and type: pip install pygame to begin installation.
Once installed, type pip show pygame to see information about pygame and to ensure it has been installed properly.
Python comes installed with its own editor (IDLE) but there are many other editors and IDEs to choose from so if you like more functionality then experiment with them and pick whichever suits. A few examples are:
- Sublime Text (I use this one most of the time)
- VS Code (I use this one sometimes)
Now you can begin creating the basic structure of a pygame project. This part consists of three key elements:
- Game Window
- Game Loop
- Event Handler
Begin by importing and initialising the pygame module:
import pygame pygame.init()
Next create the game window by using the
display.set_mode() function. Width and height variables are defined and passed into the
display.set_mode() function to create a game window, which is stored in variable
SCREEN_WIDTH = 800 SCREEN_HEIGHT = 600 screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
Run the code and you’ll notice a window pops up for a split second and closes down again. So why does it do that?
Python is executing each line of code in your program one by one. It initialises the pygame module, then creates a game window and since there is no more code after that, it successfully finishes and the window closes down.
To keep the game window running and active, a game loop is required. This loop will continue running until the user chooses to stop it by closing the game.
Python has different loop types, but for this we will use the
while loop. This loop requires a condition and will continue running as long as that condition is met. This condition will be a variable called
run, which is set to
run = True while run:
With the game loop created, the last component to add is the event handler. The event handler is covered in detail in the next section, so for now only a basic event handler is needed to add the
QUIT functionality so the program can be exited.
This section of code will check for a
QUIT event and change the variable
False. Since the
while loop only continues running when the
run variable is
True, this action ends the
while loop and ends the program.
Once the game is complete, pygame should be un-initialised by running
The final code then becomes:
import pygame pygame.init() SCREEN_WIDTH = 800 SCREEN_HEIGHT = 600 screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT)) run = True while run: for event in pygame.event.get(): if event.type == pygame.QUIT: run = False pygame.quit()