如何在向该方向移动之前使用箭头键将乌龟转向特定方向
How to turn the turtle to a specific direction with arrow keys before moving in that direction
我想要一个程序,当我按下键盘上的箭头键时,乌龟会先朝那个方向旋转,然后在每次连续按同一方向时朝那个方向移动。
现在我有:
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。我怎样才能把它分开,所以在第一个方向按下乌龟只转动,下一个按下前进?
您只需要检查标题即可。如果乌龟不面向那个方向,转身,否则移动。
同样,您可以使用 functools.partial
and a dict to DRY 代码。
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()
我想要一个程序,当我按下键盘上的箭头键时,乌龟会先朝那个方向旋转,然后在每次连续按同一方向时朝那个方向移动。
现在我有:
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。我怎样才能把它分开,所以在第一个方向按下乌龟只转动,下一个按下前进?
您只需要检查标题即可。如果乌龟不面向那个方向,转身,否则移动。
同样,您可以使用 functools.partial
and a dict to DRY 代码。
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()