Lectures‎ > ‎

Week08

Introduction to Pygame

  • Pygame is a Python library for programming graphics, animation, and games.
  • We can use what we know about variables, values, statements, functions, and lists to write games.
  • Learn more at: http://www.pygame.org

Basics

  • Coordinates
  • Event loop
  • User input

Pygame Code Template

# rect.py - Draw a simple rectangle

import pygame
 
# Define some colors
black    = (   0,   0,   0)
white    = ( 255, 255, 255)
green    = (   0, 255,   0)
red      = ( 255,   0,   0)
 
pygame.init()
  
# Set the height and width of the screen
size = [500,500]
screen = pygame.display.set_mode(size)
 
pygame.display.set_caption("Simple Rectangle")
 
# Loop until the user clicks the close button.
done = False
 
# Used to manage how fast the screen updates
clock = pygame.time.Clock()
 
# Main event loop
while not done:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True
        if event.type == pygame.KEYUP and event.key == pygame.K_ESCAPE:
            done = True
 
    # Set the screen background
    screen.fill(black)
 
    # Draw the rectangle
    pygame.draw.rect(screen,white,[100,100,300,300])
  
    # Limit to 20 frames per second
    clock.tick(20)
 
    # Go ahead and update the screen with what we've drawn.
    pygame.display.flip()
     
# Exit cleanly
pygame.quit()


Comments