How to add a def function with a while true loop
I added a function definition to tell my turtle to jump when you press the spacebar. I also have a while True loop in my code where the while True
loop gets stuck temporarily whenever the spacebar is pressed until the jump completes and then continues.
I’ve tried adding function definitions in the while true
loop and outside. I can only put the function definition before the while True loop, because if I put it after while True
, the code will never reach it.
#making the player jump
def jump():
player.fd(100)
player.rt(180)
player.fd(100)
player.lt(180)
turtle.listen()
turtle.onkey(jump, "space")
I
hope the while True
loop doesn’t get stuck, but it doesn’t seem to work no matter where I try to put def
.
I also saw another answer similar to this but didn’t understand how to apply it to my code.
Any other suggestion would be fine.
Solution
Before you let the async stuff work, here’s a minimalist implementation that uses turtle’s own timer events to keep obstacles moving, even when jumping:
from turtle import Screen, Turtle
def jump():
screen.onkey(None, 'space') # disable handler inside handler
if jumper.ycor() == 0: # if jumper isn't in the air
jumper.forward(150)
jumper.backward(150)
screen.onkey(jump, 'space')
def move():
hurdle.forward(6)
if hurdle.xcor() > -400:
screen.ontimer(move, 100)
jumper = Turtle('turtle')
jumper.speed('slowest')
jumper.penup()
jumper.setheading(90)
hurdle = Turtle('turtle')
hurdle.speed('fastest')
hurdle.penup()
hurdle.setheading(180)
hurdle.setx(400)
screen = Screen()
screen.onkey(jump, 'space')
screen.listen()
move()
screen.mainloop()
You can find several fleshed out versions on SO by searching for “[turtle-graphics] jump”
Avoid using the while true:
loop in Turtle’s event-based environment.