I am very new at programming as it was only just introduced into my school as a subject and I need some help. I have been given the task to have an animation of three balls (rectangle images) bouncing around the screen and off each other. I have the three balls and the bouncing of the walls all down good, but I don't know how to have them bounce off each other. Any help would be greatly appreciated, my current code is as follows:
import pygame
import random
import sys
if __name__ =='__main__':
ball_image1 = 'beachball1.jpg'
ball_image2 = 'beachball2.jpg'
ball_image3 = 'beachball3.jpg'
bounce_sound = 'thump.wav'
width = 800
top = 600
x = 0
y = 0
background_colour = 0,0,0
caption= 'Bouncing Ball animation'
velocity1 = [-1,-1]
velocity2 = [-1,1]
velocity3 = [1,-1]
pygame.init ()
frame = pygame.display.set_mode ((width, top))
pygame.display.set_caption (caption)
ball1= pygame.image.load (ball_image1). convert()
ball2= pygame.image.load (ball_image2). convert()
ball3= pygame.image.load (ball_image3). convert()
ball_boundary_1 = ball2.get_rect (center=(random.randint(50, 750),random.randint(50, 550)))
ball_boundary_2 = ball2.get_rect (center=(random.randint(50, 750),random.randint(50, 550)))
ball_boundary_3 = ball2.get_rect (center=(random.randint(50, 750),random.randint(50, 550)))
sound = pygame.mixer.Sound (bounce_sound)
while True:
for event in pygame.event.get():
print event
if event.type == pygame.QUIT: sys.exit(0)
if ball_boundary_1.left < 0 or ball_boundary_1.right > width:
sound.play()
velocity1[0] = -velocity1[0]
if ball_boundary_1.top < 0 or ball_boundary_1.bottom > top:
sound.play()
velocity1[1] = -velocity1[1]
if ball_boundary_2.left < 0 or ball_boundary_2.right > width:
sound.play()
velocity2[0] = -velocity2[0]
if ball_boundary_2.top < 0 or ball_boundary_2.bottom > top:
sound.play()
velocity2[1] = -velocity2[1]
if ball_boundary_3.left < 0 or ball_boundary_3.right > width:
sound.play()
velocity3[0] = -velocity3[0]
if ball_boundary_3.top < 0 or ball_boundary_3.bottom > top:
sound.play()
velocity3[1] = -velocity3[1]
ball_boundary_1 = ball_boundary_1.move (velocity1)
ball_boundary_2 = ball_boundary_2.move (velocity2)
ball_boundary_3 = ball_boundary_3.move (velocity3)
frame.fill (background_colour)
frame.blit (ball1, ball_boundary_1)
frame.blit (ball2, ball_boundary_2)
frame.blit (ball3, ball_boundary_3)
pygame.display.flip()