【发布时间】:2017-11-08 17:45:15
【问题描述】:
我在玩 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
【问题讨论】:
-
*.com/questions/36019509/… 看看这个 - 看看你的进展情况
-
假设 'turtle.right(90)' 将你的乌龟向右旋转 90 度,连续按向上键 4 次应该绘制一个边长为 10 的正方形。您需要存储海龟所面对的方向并计算如何在每个转向命令中转向新方向。或者,要将乌龟的方向重置为“向上”,然后在每次向前后向相反的方向转向之前转向的方向。然后将转角调整为上=0,左,右=90,下=180。