pythonrandompygame-mixer

Random.Choice always the same result


Some pretext that's maybe useful idk. I use mixer and am trying to do a random music choice but the random.choice always take the last one (song 5). This is my code

if Mamp=='1':
vad=input("[1] Bakground music")
#Mixer shit
mixer.init()
pygame.mixer.get_init
if vad=='1':
    commands=[mixer.music.load("song1.mp3"), mixer.music.load("song2.mp3"),mixer.music.load("song3.mp3"),mixer.music.load("song4.mp3"),mixer.music.load("song5.mp3")]
    current_command=random.choice(commands)
    current_command
    mixer.music.play(0)

I looked at many answers for the same problem but all wer're just fixing thier (the uploader's) code and uploaded it so I couldn't use it for my code. And since i'm trying to learn python it would be great if you could also explain what went wrong?


Solution

  • commands=[mixer.music.load("song1.mp3"), ...]
    current_command=random.choice(commands)
    current_command
    

    You're doing this part all wrong.

    It seems like you want to make a list of commands to be executed later, but that's not what you're actually doing. The load() commands are actually executed when the commands list is created. And because song5.mp3 is the last one, it gives the appearance of being "picked" every time.

    Try it this way instead:

    songs = ["song1.mp3", "song2.mp3", "song3.mp3", "song4.mp3", "song5.mp3"]
    song = random.choice(songs)
    mixer.music.load(song)