I'm new to python and programming in general and for my first project, I've created a game inspired by the "Space Invaders" using pygame.
Now that I want to add background music to the game, when I start the game, the background music starts and keeps on playing but the game freezes and I have no choice but to force quit.
Here's the code for the Music class:
import pygame.mixer
class Music():
"""A class to load and play the bg_music."""
def play_background_music(self):
pygame.init()
pygame.mixer.init()
pygame.mixer.music.load('Arcade - Public Memory.wav')
pygame.mixer.music.play(-1)
while pygame.mixer.music.get_busy():
pygame.time.Clock().tick(40)
And here's the code for the main file:
import pygame
from settings import Settings
from ship import Ship
import game_functions as gf
from pygame.sprite import Group
from game_stats import Gamestats
from button import Button
from scoreboard import Scoreboard
from music import Music
def run_game():
"""Initialize game, settings, and screen object."""
pygame.init()
ai_settings = Settings()
screen = pygame.display.set_mode((
ai_settings.screen_width, ai_settings.screen_height))
pygame.display.set_caption("Alien Invasion")
# Make the play button.
play_button = Button(ai_settings, screen, "Play")
# Create an instance to store game statics and create a scoreboard.
stats = Gamestats(ai_settings)
sb = Scoreboard(ai_settings, screen, stats)
# Make a ship, a group of bullets, and a group of aliens
ship = Ship(ai_settings, screen)
bullets = Group()
aliens = Group()
# Make a music instance
music = Music()
# Create a fleet of aliens
gf.create_fleet(ai_settings, screen, ship, aliens)
# Start the main loop of the program
while True:
# Watch for keyboard and mouse events
gf.check_events(ai_settings, screen, stats, sb, play_button, ship,
aliens, bullets)
if stats.game_active:
music.play_background_music()
ship.update()
gf.update_bullets(ai_settings, screen, stats, sb, ship, aliens,
bullets)
gf.update_aliens(ai_settings, screen, stats, sb, ship, aliens,
bullets)
gf.update_screen(ai_settings, screen, stats, sb, ship, aliens, bullets,
play_button)
run_game()
Maybe there is a function that I should be using that I'm not aware of?, maybe I've created a Music instance and called it in the wrong place? Or maybe the music file is too heavy?
I'd appreciate it if someone could help me out.