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.
- Get Pycharm here: https://www.jetbrains.com/pycharm/
- Install PyCharms if you don’t already have it on your computer (my students should have it installed automatically by IT)
- Start Pycharms and create a new project (I recommend creating a new folder for all your Python programs)
- Install the Pygame library following the instructions I provide in class. I won’t include it in this handbook as the instructions might change when Pycharm updates, and are also slightly different for Windows vs Macs.
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!
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 * pygame.init() 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(): print(event) if event.type == QUIT: quit = True elif event.type == KEYDOWN: if event.key == K_ESCAPE: quit = True # Perform calculations # Draw graphics window.fill(BLACK) pygame.display.update() # Actually does the screen update fps.tick(25) # Run the game at 25 frames per second # Loop over, game over pygame.quit()
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:
importlines at the top are telling Python to load other code saved elsewhere (in this case the code that makes pygame exist)
pygame.display.set_mode((500,500))is setting the width and height of your game window.
windowis a variable that we use to draw things onto the screen
- Pygame will only actually draw onto your screen when it hits the
window.fill(BLACK)will erase everything on screen and fill the screen with the specified color, in this case black.
fps.tick(25)is saying we want the game to run at 25 frames per second