I would like a game that I am coding to play a random ‘success’ noise when the user gets the correct answer. I cannot get pygame zero to do this elegantly (my code at the moment is long-winded)
It feels like this should be possible by calling a random list element, or randomising the string for the sound file. I have tried creating a list of the sound files and selecting a random element but pygame zero doesn’t like this. I have also tried the simple solution at the bottom of this question, below.
The following does work, but I would like a more elegant way of coding this:
if index == question[5]:
print("You got it right!")
score += 1
print("Questions answered: " + str(question_count+1))
rand_sound = randint(1,12)
if rand_sound == 1:
sounds.yes1.play()
elif rand_sound == 2:
sounds.yes2.play()
elif rand_sound == 3:
sounds.yes3.play()
elif rand_sound == 4:
sounds.yes4.play()
elif rand_sound == 5:
sounds.yes5.play()
elif rand_sound == 6:
sounds.yes6.play()
elif rand_sound == 7:
sounds.yes7.play()
elif rand_sound == 8:
sounds.yes8.play()
elif rand_sound == 9:
sounds.yes9.play()
elif rand_sound == 10:
sounds.yes10.play()
elif rand_sound == 11:
sounds.yes11.play()
elif rand_sound == 12:
sounds.yes12.play()
Whereas the following does not work (I get the error message “AttributeError: No sound found like ‘rand_sound’. Are you sure the sound exists?”)
rand_sound = "yes" + str(randint(1,12))
sounds.rand_sound.play()