Pygame Template
Pygame has a bit of required start-up code that is unreasonable to memorize. Here is the starter code you can copy and paste for every Pygame program you create. It’s good to save this template on your hard drive so you don’t have to go looking for it.
Warning
Do not save this or any file as pygame.py
or you will get import errors.
When running this file, you should be presented with a white screen with a blue circle.
# pygame template
import pygame
pygame.init()
WIDTH = 640
HEIGHT = 480
SIZE = (WIDTH, HEIGHT)
screen = pygame.display.set_mode(SIZE)
clock = pygame.time.Clock()
# ---------------------------
# Initialize global variables
circle_x = 200
circle_y = 200
# ---------------------------
running = True
while running:
# EVENT HANDLING
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# GAME STATE UPDATES
# All game math and comparisons happen here
# DRAWING
screen.fill((255, 255, 255)) # always the first drawing command
pygame.draw.circle(screen, (0, 0, 255), (circle_x, circle_y), 30)
# Must be the last two lines
# of the game loop
pygame.display.flip()
clock.tick(30)
#---------------------------
pygame.quit()
The parts of a game
When working with Pygame, or any other game library for that matter, there are distinct places in your code that it is good practice to keep well organized. There are specific sections for initializing variables, event handling (mouse clicks and button presses), game state updates (the math and the logic for moving objects, for example), and drawing. It is easy to mix these concepts up into each other, but try to keep them separate as best you can.