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

2024-09-29 01:19:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我在和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


Tags: rightdef方向lefteditlistenforwardturtle
1条回答
网友
1楼 · 发布于 2024-09-29 01:19:49

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

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()

在绝对转向时,我们使用使箭头键与指南针位置相对应,并将海龟移动到这些绝对方向:

^{pr2}$

在这里,我添加了空格键用于向前运动。注意,转弯并不一定是最佳的,我相信这就是@R.Sharp在回答中附加代码的部分原因。

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

相关问题 更多 >