繁体   English   中英

按下箭头键后设置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()

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM