fps = 30 screenWidth = 640 screenHeight = 480 #global alienImage # check to see if the pygame module is in the namespace try: pygame except NameError: # pygame doesn't exsist, so import it. # this only happens once. import pygame from pygame.locals import * # initialize the pygame display pygame.init() pygame.display.set_mode((screenWidth,screenHeight),0,32) display = pygame.display.get_surface() # initialize the pygame clock clk = pygame.time.Clock() def getMotion(framecount, shapeSize, screenSize, velocity): """ Calculates a linear position using a step number, a velocity, and a derived range of motion. Returns the position. """ # calculate the range of motion: workingSize = (screenSize - shapeSize) / velocity # use mod to find position in the range of motion. # *2 is used to bounce back and forth inside the range pos = framecount % (workingSize * 2) # if we are greater than the initial size, we are moving # in the opposite direction. if pos > workingSize: pos = 2*workingSize - pos return pos * velocity def play(framecount): """ Main game logic, called once per frame.""" # fill the display with black. Clears the screen. pygame.draw.rect(display, (0,0,0,255),(0,0,screenWidth,screenHeight)) shapeColor = (10,80,10,255) shapeWidth = 30 shapeHeight = 30 xVel = 10.0 # velocity in pixels per frame yVel = 10.0 x = getMotion(framecount, shapeWidth, screenWidth, xVel) y = getMotion(framecount, shapeHeight, screenHeight, yVel) # draw a shape. pygame.draw.ellipse(display, shapeColor,(x,y,shapeWidth,shapeHeight)) # update the display. pygame.display.flip() # check for events, and return true if we get an exit signal. events = pygame.event.get() for event in events: if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE): return True # try to maintain a set frame rate. clk.tick(fps) # No exit signal was recived, so return false. return False