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