Python Pygame

Welcome to my introduction to using Pygame with the Python programming language.

To proceed with this section, you will need Python running on your own computer with a proper editing program such as Jetbrains Pycharm or Microsoft VS Code.

Coordinate system

Pygame is a graphics system for Python. The screen is divided into pixels. You use sets of pixel coordinates to tell Python where to draw shapes, place text or images etc.

Pygame coordinates start with the top-left of the screen being (x=0,y=0).

The x-axis increases as you move to the right.

The y-axis increases as you move down – this is different to the way you do it in Maths so be aware of that!


Hello Pygame!

The basic Pygame program will be structured like this. Code it up and get it to run. It won’t do anything too exciting. It will just be a black screen, though the console area will let you know when you move your mouse or press a key. Press ESCAPE or click the exit icon to close the program.

import pygame, time, random
from pygame.locals import *

window = pygame.display.set_mode((500,500))
fps = pygame.time.Clock()

# Declare colors, images, sounds, fonts, variables
BLACK = (0,0,0)
quit = False

# Main game loop
while not quit:

    # Process events
    for event in pygame.event.get():
        if event.type == QUIT:
            quit = True
        elif event.type == KEYDOWN:
            if event.key == K_ESCAPE:
                quit = True

    # Perform calculations

    # Draw graphics
    pygame.display.update() # Actually does the screen update
    fps.tick(25) # Run the game at 25 frames per second

# Loop over, game over

The comments in the above program are important. They are recommendations on where you want to place the code for each part of your game. It’s a good idea to follow the above as your “master template”. Copy and paste it as the starting point each time you want to begin a new Pygame project.

To briefly explain a few commands: