按下箭头键后设置Python乌龟的位置

Set Python turtle's position after arrow key press

我在玩 Python 乌龟。到目前为止,我可以用箭头键控制它,但是方向几乎是随机的,我想在每次按下箭头键时重置它所面对的方向。但是我不知道该怎么做。有帮助吗?

import turtle
turtle.color("Red")
turtle.title("Test")
turtle.pensize(5)


def tLeft():         #Edit everything later, most likely to be inaccurate.                                   
    turtle.right(180)
    turtle.forward(10)

def tRight():
    turtle.left(180)
    turtle.forward(10)

def tUp():
    turtle.right(90)
    turtle.forward(10)

def tDown():
    turtle.left(270)
    turtle.forward(10)

turtle.onkeypress(tUp, "Up")
turtle.onkeypress(tDown, "Down")
turtle.onkeypress(tRight, "Right")
turtle.onkeypress(tLeft, "Left")    #First test: When started the code did nothing, nothing showed up and no errors was shown. Edit:only needed "listen()"
turtle.listen()

抱歉,如果代码看起来有点奇怪:P

这里有两种方法可以解决这个问题,使用 相对 转向或 绝对 转向。相对转动,我们让海龟向左或向右转动一定量,向前或向后移动一定量:

import turtle

def tLeft():
    turtle.left(90)

def tRight():
    turtle.right(90)

def tForward():
    turtle.forward(10)

def tBackward():
    turtle.backward(10)

turtle.shape('turtle')
turtle.pensize(5)

turtle.onkeypress(tRight, 'Right')
turtle.onkeypress(tLeft, 'Left')
turtle.onkeypress(tForward, 'Up')
turtle.onkeypress(tBackward, 'Down')

turtle.listen()
turtle.mainloop()

对于绝对转向,我们使用使箭头键对应于罗盘位置并将海龟移动到那些绝对方向:

import turtle

def tEast():
    turtle.setheading(0)

def tNorth():
    turtle.setheading(90)

def tWest():
    turtle.setheading(180)

def tSouth():
    turtle.setheading(270)

def tForward():
    turtle.forward(10)

turtle.shape('turtle')
turtle.pensize(5)

turtle.onkeypress(tEast, 'Right')
turtle.onkeypress(tWest, 'Left')
turtle.onkeypress(tNorth, 'Up')
turtle.onkeypress(tSouth, 'Down')

turtle.onkeypress(tForward, 'space')

turtle.listen()
turtle.mainloop()

我在这里添加了 space 条用于向前移动。请注意,转弯不一定是最佳的,我相信这部分是@R.Sharp 在他的答案中使用附加代码解决的问题。

您使用上述哪种方法,或者完全不同的方法,取决于您移动海龟的最终目标。