Third part of this game made with Python. In previous post we’ve added a second ball. Now we add a sound when the balls collides.
import pygame
# Initialize Pygame and set up the display
pygame.init()
screen = pygame.display.set_mode((640, 480))
# Initialize the mixer and load a sound file
pygame.mixer.init()
collision_sound = pygame.mixer.Sound('ball.ogg')
clock = pygame.time.Clock()
# Set up the first ball's initial position and velocity
x1 = 320
y1 = 240
vx1 = 1
vy1 = 1
# Set up the second ball's initial position and velocity
x2 = 100
y2 = 100
vx2 = 2
vy2 = 2
# Set the balls' radius
radius = 20
# Run the game loop
running = True
while running:
# Handle user input
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
vx1 = -2
elif event.key == pygame.K_RIGHT:
vx1 = 2
elif event.key == pygame.K_UP:
vy1 = -2
elif event.key == pygame.K_DOWN:
vy1 = 2
elif event.type == pygame.KEYUP:
vx1 = 0
vy1 = 0
# Update the balls' positions
x1 += vx1
y1 += vy1
x2 += vx2
y2 += vy2
# Check if the balls are out of bounds and reverse their velocities if necessary
if x1 - radius < 0 or x1 + radius > 640:
vx1 = -vx1
if y1 - radius < 0 or y1 + radius > 480:
vy1 = -vy1
if x2 - radius < 0 or x2 + radius > 640:
vx2 = -vx2
if y2 - radius < 0 or y2 + radius > 480:
vy2 = -vy2
# Check if the balls collide and reverse their velocities if necessary
dx = x1 - x2
dy = y1 - y2
distance = (dx ** 2 + dy ** 2) ** 0.5
if distance < 2 * radius:
vx1, vx2 = vx2, vx1
vy1, vy2 = vy2, vy1
collision_sound.play() # Play the collision sound
# Draw the balls and update the display
screen.fill((0, 0, 0))
pygame.draw.circle(screen, (255, 255, 255), (x1, y1), radius)
pygame.draw.circle(screen, (255, 255, 0), (x2, y2), radius)
pygame.display.flip()
clock.tick(60)