简体   繁体   中英

Problems with os “afplay” - Turtle, Python

I'm writing a snake game in python using turtle and 'os'. I'm trying to create a game over screen and play a sound when lives = 0. It's all working out, except for the sound, which glitches and keeps playing over and over again on top of itself.

This is the code for that part:

while True: wn.update()

if lives == 0:
    os.system("afplay game_over.wav&")
    head.hideturtle()
    food.hideturtle()
    over.write("GAME\nOVER", align="center", font=("Retro Gaming", 70, "normal"))

I've just started learning how to code and can't figure out what is wrong. The other sounds on my game such as when the snake hits the border or eats an apple works just fine.

My guess is that the moment your lives are equal to zero, every time your update loop runs the condition is met and the sound is played.It's fine for the hiding of the head and food because once they are hidden you can run the hide method over and over and nothing looks different. Same with the text.

For example, this is a similar scenario to what you have:

turtle = {'lives': 10, 'show': True}

while True:
    if turtle['lives'] == 0:
        print('Turtle died')
        turtle['show'] = False

    if turtle['lives'] > 0:
        turtle['lives'] -= 1

This will decrease the turtle's lives each turn as long as they are greater than 0. The moment they go down to 0, the first if statement will kick in and you will see 'Turtle died' printed over and over again each time the loop runs. In the same way that you keep on hiding the head, it doesn't matter how often you set turtle['show'] to False , it effectively does nothing.

To fix this, you need to make sure you run your death routine only once. This is an example way of doing it:

turtle = {'lives': 10, 'show': True, 'state': 'alive'}

while True:
    if turtle['lives'] == 0 and turtle['state'] == 'alive':
        turtle['state'] = 'dead'
        print('Turtle died')
        turtle['show'] = False

    if turtle['lives'] > 0:
        turtle['lives'] -= 1

This way you ensure that the death routine only runs once.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM