#This is a simple first pygame example program #I've taken the example from the book, annotated it with comments (which the book #would explain on the following pages) and then broken it into functions import pygame #I need to use screen in more than one function till we see classes #I'll use this 'global' variable to allow the same variable in more than one method screen = None background = None box = None box_x=0 box_y =0 def initAndDisplay(): """initialize pygame and setup the display screen""" global screen pygame.init() # set mode is a method to create a window or full screen display # it takes a single parameter a 'tuple' with the desired window width and #height in pixals. screen = pygame.display.set_mode((800,600)) pygame.display.set_caption("hello world!") #puts a window title on def setupEntities(): global background global box global box_x global box_y """just one entity for now - the background""" #get the drawable part of the window - create a surface for that whole thing background = pygame.Surface(screen.get_size()) #change the background from python standard to colors for this system #saves time when displaying background = background.convert() #set the background color background.fill((255,0,0)) box = pygame.Surface((25,25)) box = box.convert() box.fill((0,200,0)) box_x=0 box_y=300 def action(): #create a clock object to set the framerate global box_x clock = pygame.time.Clock() stillWorking = True while stillWorking: clock.tick(30) #update 30 times/sec (framerate) #handle events - only quit for now for event in pygame.event.get(): if event.type == pygame.QUIT: stillWorking = False box_x = box_x + 5 if box_x > screen.get_width(): box_x =0 #now actually draw something screen.blit(background, (0,0)) screen.blit(box, (box_x,box_y)) pygame.display.flip() #one some systems we need to free pygame resources before the program can end pygame.quit() #now actually invoke the functions to run the program initAndDisplay() setupEntities() action()