0

This is my code:

from turtle import Turtle, Screen

wn = Screen()
wn.bgcolor('lightblue')

spaceship = Turtle()
spaceship.color('red')
spaceship.penup()

speed = 1

def travel():
    spaceship.forward(speed)
    wn.ontimer(travel, 10)

wn.onkey(lambda: spaceship.setheading(90), 'Up')
wn.onkey(lambda: spaceship.setheading(180), 'Left')
wn.onkey(lambda: spaceship.setheading(0), 'Right')
wn.onkey(lambda: spaceship.setheading(270), 'Down')

while True:
    spaceship.forward(speed)
    if spaceship.xcor() > 500:
        spaceship.goto (-500,0)
    elif spaceship.ycor() > 500:
        spaceship.goto(0,-500)
wn.listen()

travel()

wn.mainloop()

I'm trying to get my keyboard movement to work but after i put the while true codes in they stopped working and in try to get them to work to have the turtle move.

  • 1
    You started an infinite loop that prevented the actual listener and mainloop from running. You should put that logic you have in the `while` loop inside the `travel` function instead. – metatoaster Nov 17 '22 at 00:35
  • travel(): while True: spaceship.forward(speed) if spaceship.xcor() > 500: spaceship.goto (-500,0) elif spaceship.ycor() > 500: spaceship.goto(0,-500) like this? – Ian Rowell Nov 17 '22 at 00:40
  • Also, if the `travel()` method calls the `while True`, it will loop infinitely inside there which isn't what you want. What you really want is the conditions for wrap. The goal is to have the main loop advance your ship through the `ontimer` hook. – metatoaster Nov 17 '22 at 01:33
  • You may wish to refer to [this thread](https://stackoverflow.com/questions/74019827/how-to-add-parameters-to-python-turtle-screen-ontimer-function) as a reference for what you might be trying to do. – metatoaster Nov 17 '22 at 23:59

0 Answers0