【问题标题】:How to turn the turtle to a specific direction with arrow keys before moving in that direction [closed]在朝该方向移动之前如何使用箭头键将乌龟转向特定方向[关闭]
【发布时间】:2023-07-01 03:36:01
【问题描述】:

我想要一个程序,当我按下键盘上的箭头键时,Turtle 将首先朝那个方向旋转,然后随着每次连续按下同一方向而朝那个方向移动。

现在我有:

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

但这会使乌龟在每次按下时转动AND。我怎样才能将它分开,所以在第一个方向按下乌龟只转动,然后下一个按下前进?

【问题讨论】:

  • 请从intro tour 重复on topichow to ask。 “告诉我如何解决这个编码问题?”与 Stack Overflow 无关。您必须诚实地尝试解决方案,然后就您的实施提出具体问题。 Stack Overflow 并不打算取代现有的教程和文档。有许多网站提供有关如何根据键采取行动的介绍性材料。我们希望您在此处发布之前使用这些内容。
  • 我只需要在最后添加mainloop(),它就完美运行了。
  • 不工作 :(((
  • @DAB 请edit 解释究竟是什么不工作的问题。在我的机器上,问题是龟屏没有保持打开状态。见minimal reproducible example

标签: python python-3.x python-turtle


【解决方案1】:

您只需要检查标题。如果海龟没有面向那个方向,则转身,否则移动。

同样,您可以在代码中使用functools.partialDRY 的字典。

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

【讨论】: