acousticewe
acousticewe

Reputation: 3

Indefinitely move Python turtle while allowing input

I've just started working on a version of Snake using Turtle, and I've encountered an issue. I want the snake to move indefinitely, but also to allow the user to move the snake with the keyboard. I got the snake to move from user input, but I can't figure out how to get the snake to keep moving in the same direction while there is no input, whilst preventing it from ignoring user input:

while True:
  win.onkey(up,"Up")
  win.onkey(right,"Right")
  win.onkey(down,"Down")
  win.onkey(left,"Left")
  win.listen()
#moves the snake one unit in the same direction it is currently facing
  movesnake()

I'm new to Turtle, and this is my guess at how to solve this issue - which obviously doesn't work. Any help would be appreciated. I'm conscious Pygame might make this easier but since I've already started with Turtle, I would prefer to get a Turtle solution, if possible.

Upvotes: 0

Views: 753

Answers (1)

cdlane
cdlane

Reputation: 41925

An event-driven environment like turtle should never have while True: as it potentially blocks out events (e.g. keyboard). Use an ontimer() event instead.

Generally, onkey() and listen() don't belong in a loop -- for most programs they only need to be called once.

Here's a skeletal example of an autonomous turtle being redirected by user input:

from turtle import Screen, Turtle

def right():
    snake.setheading(0)

def up():
    snake.setheading(90)

def left():
    snake.setheading(180)

def down():
    snake.setheading(270)

def movesnake():

    snake.forward(1)

    screen.ontimer(movesnake, 100)

snake = Turtle("turtle")

screen = Screen()

screen.onkey(right, "Right")
screen.onkey(up, "Up")
screen.onkey(left, "Left")
screen.onkey(down, "Down")

screen.listen()

movesnake()

screen.mainloop()

Upvotes: 1

Related Questions