import pygame import random 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)) def move_and_bounce_circle(dt, x, y, speed_x, speed_y, radius): """ This function calculates a circle'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 + radius): x = 0 + radius speed_x = - speed_x elif (x > width - radius): x = width - radius speed_x = - speed_x y = y + dt * speed_y if (y < 0 + radius): y = 0 + radius speed_y = - speed_y elif (y > height - radius): y = height - radius 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 balls' position and speed with random numbers; the radius is set to 20 # the variable ball is used to refer to a 4-tuple representing the ball's x-, and y-coordinates # and its x- and y-speed radius = 20 x = random.randint(0+radius,width-radius) y = random.randint(0+radius,height-radius) x_speed = float(random.randint(-30,30))/100 y_speed = float(random.randint(-30,30))/100 ball = (x, y, x_speed, y_speed) # start clock clock = pygame.time.Clock() keepGoing = True while (keepGoing): dt = clock.tick() # go through all events that happened and check ... for event in pygame.event.get(): # ... whether the event was a quit event if event.type == pygame.QUIT: keepGoing = False # update ball's position and speed; notice that ball refers to a 4-tuple ball = move_and_bounce_circle(dt, ball[0], ball[1], ball[2], ball[3], radius) # set background color screen.fill(pygame.color.Color("green")) # draw all ball pygame.draw.circle(screen,(255,0,0),(ball[0],ball[1]),radius) # update display pygame.display.update() def done(): pygame.quit() def main(): initialize() run_game() done() main()