Ich bin sehr neu im Programmieren, da es erst als Thema in meine Schule eingeführt wurde und ich Hilfe brauche. Mir wurde die Aufgabe gestellt, eine Animation von drei Bällen (Rechteckbildern) zu haben, die um den Bildschirm und voneinander abprallen. Ich habe die drei Bälle und das Aufprallen der Wände alle gut, aber ich weiß nicht, wie sie sich gegenseitig abprallen lassen. Jede Hilfe wäre sehr dankbar, mein aktueller Code ist wie folgt:Wie ändere ich die Richtung, in der sich meine Rechtecke bewegen?
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()