我对编程很陌生,因为它只是作为一门学科引入我的学校,我需要一些帮助。我的任务是制作三个球(矩形图像)在屏幕周围弹跳并相互弹开的动画。我的三个球和墙壁的反弹都很好,但我不知道如何让它们相互反弹。任何帮助将不胜感激,我当前的代码如下:
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()