我编写了一个动画(在python中),用于沙滩球在屏幕上反弹。我现在希望在窗口添加第二个球,当两个球碰撞时它们互相反弹。
到目前为止,我对此的尝试都没有成功。任何想法如何做到这一点?我到目前为止的代码如下。
import pygame
import sys
if __name__ =='__main__':
ball_image = 'Beachball.jpg'
bounce_sound = 'Thump.wav'
width = 800
height = 600
background_colour = 0,0,0
caption= 'Bouncing Ball animation'
velocity = [1,1]
pygame.init ()
frame = pygame.display.set_mode ((width, height))
pygame.display.set_caption (caption)
ball= pygame.image.load (ball_image). convert()
ball_boundary = ball.get_rect (center=(300,300))
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.left < 0 or ball_boundary.right > width:
sound.play()
velocity[0] = -1 * velocity[0]
if ball_boundary.top < 0 or ball_boundary.bottom > height:
sound.play()
velocity[1] = -1 * velocity[1]
ball_boundary = ball_boundary.move (velocity)
frame.fill (background_colour)
frame.blit (ball, ball_boundary)
pygame.display.flip()
答案 0 :(得分:7)
这是您的代码的一个非常基本的重组。它仍然可以整理很多,但它应该告诉你如何使用该类的实例。
import pygame
import random
import sys
class Ball:
def __init__(self,X,Y):
self.velocity = [1,1]
self.ball_image = pygame.image.load ('Beachball.jpg'). convert()
self.ball_boundary = self.ball_image.get_rect (center=(X,Y))
self.sound = pygame.mixer.Sound ('Thump.wav')
if __name__ =='__main__':
width = 800
height = 600
background_colour = 0,0,0
pygame.init()
frame = pygame.display.set_mode((width, height))
pygame.display.set_caption("Bouncing Ball animation")
num_balls = 1000
ball_list = []
for i in range(num_balls):
ball_list.append( Ball(random.randint(0, width),random.randint(0, height)) )
while True:
for event in pygame.event.get():
print event
if event.type == pygame.QUIT:
sys.exit(0)
frame.fill (background_colour)
for ball in ball_list:
if ball.ball_boundary.left < 0 or ball.ball_boundary.right > width:
ball.sound.play()
ball.velocity[0] = -1 * ball.velocity[0]
if ball.ball_boundary.top < 0 or ball.ball_boundary.bottom > height:
ball.sound.play()
ball.velocity[1] = -1 * ball.velocity[1]
ball.ball_boundary = ball.ball_boundary.move (ball.velocity)
frame.blit (ball.ball_image, ball.ball_boundary)
pygame.display.flip()
答案 1 :(得分:3)
你应该创建一个代表你的沙滩球的课程。然后,您可以根据需要添加实例,并将实例放在Python列表中。
然后,您将在每个帧上浏览该列表,更新并呈现每个帧。
您需要包含一种方法来测试与另一个球的碰撞(这对圆圈来说很简单)。如果检测到碰撞,所涉及的球应该模拟彼此反弹。