How to Program a Game in Python with Pygame

Marsh Rod
2 min readNov 29, 2020

--

Step 1

2

Run the installer.

Step 2

3

Verify that the installation worked. Open a Python terminal. Type “import pygame.” If you don’t see any errors then Pygame was successfully installed.

import pygame

Step 3

2

Import Pygame. Pygame is a library that provides access to graphics functions. If you want more information on how these functions work, you can look them up on the Pygame website. https://www.pygame.org/docs/

import pygame

from pygame.locals import *

Step 4

3

Set the window resolution. You’ll be making a global variable for the screen resolution so that can be referenced in several parts of the game. It’s also easy to find at the top of the file so it can be changed later. For advanced projects, putting this information in a separate file would be a better idea.

resolution = (400,300)

Step 5

4

Define some colors. Colors in pygame are (RBGA which range in values between 0 and 255. The alpha value (A) is optional but the other colors (red, blue, and green are mandatory).

white = (255,255,255)

black = (0,0,0)

red = (255,0,0)

Step 6

5

Initialize the screen. Use the resolution variable that was defined earlier.

screen = pygame.display.set_mode(resolution)

Step 7

6

Make a game loop. Repeat certain actions in every frame of our game. Make a loop that will always repeat to cycle through all these actions.

while True:

Step 8

7

Color the screen.

screen.fill(white)

Step 9

8

Display the screen. If you run the program, the screen will turn white and then the program will crash. This is because the operating system is sending events to the game and the game isn’t doing anything with them. Once the game receives too many unhandled events, it will crash.

while True:

pygame.display.flip()

Step 10

9

Handle events. Get a list of all events that have occurred in each frame. You’re only going to care about one event, the quit event. This occurs when the user closes the game window. This will also prevent our program from crashing due to too many events.

while True:

for event in pygame.event.get():

if event.type == QUIT:

pygame.quit()

--

--

Marsh Rod
0 Followers

I say that the most liberating thing about beauty is realizing that you are the beholder.