For our example, let’s go back to the
bouncing_rect.pypractice problem. We now want to add a bouncing sound to this whenever the rectangle hits the corner of the screen. We can do the following:
import pygame import time # not necessary, but used for frame cap pygame.init() # initialize pygame module bounce_sound = pygame.mixer.Sound("./bounce.wav") # load the bounce sound SCREEN_SIZE = (600, 400) RECT_SIZE = (100, 100) RED = (255, 0, 0) BLACK = (0, 0, 0) momentum = [1, 1] # (down and right) window = pygame.display.set_mode(SCREEN_SIZE) running = True # start the rectangle in the middle of the screen x = SCREEN_SIZE // 2 y = SCREEN_SIZE // 2 while running: # if the rectangle collided with the left or right side # of the screen if x + RECT_SIZE >= SCREEN_SIZE or x <= 0: momentum = -momentum bounce_sound.play() # play the bounce sound for collisions # if the rectangle collided with the top or bottom # of the screen if y + RECT_SIZE >= SCREEN_SIZE or y <= 0: momentum = -momentum bounce_sound.play() # play the bounce sound for collisions # add the speed to the current x and y to get the # new x and y x += momentum y += momentum window.fill(BLACK) # 'erase' the previous frame pygame.draw.rect(window, RED, (x, y, RECT_SIZE, RECT_SIZE)) pygame.display.update() # update the display for event in pygame.event.get(): if event.type == pygame.QUIT: running = False time.sleep(0.01) # frame cap to make the rectangle more visible pygame.quit() # deactivate the pygame module
View code and sound file on Github
Copyright © 2021 Code 4 Tomorrow. All rights reserved. The code in this course is licensed under the MIT License. If you would like to use content from any of our courses, you must obtain our explicit written permission and provide credit. Please contact firstname.lastname@example.org for inquiries.