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 ballon picture global balloon balloon = pygame.image.load("red_balloon.gif") balloon = balloon.convert() def move_and_bounce_object(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 # Here you see that in Python we can return more than one value. # This is a specialy of Python. return x, y, speed_x, speed_y def run_game(): # initialize the balloon's position and speed b_x = 100 b_y = 100 b_speed_x = 0.2 b_speed_y = 0.2 # start clock clock = pygame.time.Clock() keepGoing = True while (keepGoing): dt = clock.tick() for event in pygame.event.get(): if event.type == pygame.QUIT: keepGoing = False # calculate the new position and speed of the balloon # Since the function move_and_bounce_object returns several values # we need an assignment statement that gives a name to each of these # return values. b_x, b_y, b_speed_x, b_speed_y = move_and_bounce_object(dt, b_x, b_y, b_speed_x, b_speed_y, balloon.get_width(),balloon.get_height()) # set background color screen.fill(pygame.color.Color("darkblue")) # draw balloon image screen.blit(balloon,(b_x,b_y)) # update display pygame.display.update() def done(): pygame.quit() def main(): initialize() run_game() done() main()