두 번째 튀는 공을 창에 추가하는 방법?
문제
나는 해변 공이 화면 주위에 튀기기 위해 애니메이션 (파이썬)을 코딩했습니다. 나는 이제 창에 두 번째 공을 추가하고 싶고, 두 공이 서로 튀기기 위해 충돌 할 때.
지금까지, 이것에 대한 나의 시도는 실패했습니다. 이 작업을 수행하는 방법이 있습니까? 지금까지 가지고있는 코드는 다음과 같습니다.
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()
해결책
코드의 매우 기본적인 구조 조정이 있습니다. 여전히 많이 정리 될 수 있지만 수업의 인스턴스를 어떻게 사용할 수 있는지 보여 주어야합니다.
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()
다른 팁
당신은 아마도 당신의 비치 볼을 대표하기 위해 수업을 만들어야 할 것입니다. 그런 다음 원하는만큼 인스턴스를 인스턴스하고 인스턴스를 파이썬 목록에 넣습니다.
그런 다음 각 프레임에서 해당 목록을 살펴보고 각 프레임을 업데이트하고 렌더링합니다.
다른 볼에 대한 충돌을 테스트하는 방법을 포함해야합니다 (이것은 원의 경우 간단합니다). 충돌이 감지되면 관련된 공은 서로 바운스를 시뮬레이션해야합니다.
제휴하지 않습니다 StackOverflow