import pygame def initialize(): """ This function sets some global constants (i.e., the values of these global variables never change). """ pygame.init() # set up the display window global width, height, screen width = 640 height = 480 screen = pygame.display.set_mode((width,height)) # load the picture global guy guy = pygame.image.load("WalkingSquare1.gif") def move_and_bounce_rect(dt, x, y, speed_x, speed_y, obj_width, obj_height): """ This function calculates an object's new position based on its old position, the time that has passed since the last update, and its speed. It also makes sure that the object bounces off the edge of the screen. """ x = x + dt * speed_x if (x < 0): x = 0 speed_x = - speed_x elif (x > width - obj_width): x = width - obj_width speed_x = - speed_x y = y + dt * speed_y if (y < 0): y = 0 speed_y = - speed_y elif (y > height - obj_height): y = height - obj_height speed_y = - speed_y return x, y, speed_x, speed_y def run_game(): # initialize the guy's position and speed g_x = 100 g_y = 100 g_speed_x = 0 g_speed_y = 0 # start clock clock = pygame.time.Clock() keepGoing = True while (keepGoing): dt = clock.tick() # go through all events that happened and ... for event in pygame.event.get(): # ... check whether the event was a quit event if event.type == pygame.QUIT: keepGoing = False # ... check whether the event was of type pygame.KEYDOWN and # if so, check which key was pressed and change the speed of the character accordingly # ... check whether the event was of type pygame.KEYUP # if so, check which key was released and set the correspondind speed to 0 g_x, g_y, g_speed_x, g_speed_y = move_and_bounce_rect(dt, g_x, g_y, g_speed_x, g_speed_y, guy.get_width(), guy.get_height()) # set background color screen.fill(pygame.color.Color("green")) # draw image screen.blit(guy,(g_x,g_y)) # update display pygame.display.update() def done(): pygame.quit() def main(): initialize() run_game() done() main()