如何在窗口中添加第二个弹跳球?

1 投票
2 回答
3405 浏览
提问于 2025-04-15 11:11

我用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()

2 个回答

3

你可能需要创建一个类来表示你的沙滩球。然后你可以根据需要创建多个沙滩球的实例,并把这些实例放在一个Python列表里。

接着,你可以在每一帧中遍历这个列表,更新每个沙滩球的位置并绘制出来。

你还需要添加一个方法来检测沙滩球之间是否发生碰撞(对于圆形来说,这个检测很简单)。如果检测到碰撞,两个沙滩球就应该模拟一下彼此弹开的效果。

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()

撰写回答