Search code examples
pythonpython-3.xpython-turtle

How to turn the turtle to a specific direction with arrow keys before moving in that direction


I want a program that when I press the arrow keys on the keyboard, the Turtle will first rotate in that direction and then move in that direction with each consecutive press of the same direction.

Right now I have:

from turtle import *

def go_up():
    setheading(90)
    forward(100)

def go_Left():
    setheading(180)
    forward(100)

def go_down():
    setheading(270)
    forward(100)

def go_Right():
    setheading(0)
    forward(100)

shape('turtle')

listen()

onkeypress(go_up , 'Up')
onkeypress(go_Left , 'Left')
onkeypress(go_down , 'Down')
onkeypress(go_Right , 'Right')

But this makes the turtle turn AND move with each press. How can I separate it so on the first direction press the turtle only turns, and the next presses advances?


Solution

  • You just need to check the heading. If the turtle isn't facing that direction, turn, otherwise move.

    As well, you can use functools.partial and a dict to DRY out the code.

    from turtle import *
    from functools import partial
    
    def turn_then_go(angle):
        if heading() != angle:
            setheading(angle)
        else:
            forward(100)
    
    directions = {'Right': 0, 'Up': 90, 'Left': 180, 'Down': 270}
    for direction, angle in directions.items():
        onkeypress(partial(turn_then_go, angle), direction)
    
    shape('turtle')
    listen()
    mainloop()