擅长:python、mysql、java
<p>您可以添加条件<code>if (t.heading() + 180) % 360 != num:</code>,这意味着如果海龟当前航向的相反方向不是数字传递到函数中的方向,则继续:</p>
<pre><code>import turtle
import random
import time
s = turtle.getscreen()
turtle.screensize(canvwidth=400, canvheight=400)
t = turtle.Turtle()
t.pensize(0)
t.shape('square')
t.color("black")
t.speed(0)
t.penup()
def moveu(num):
if (t.heading() + 180) % 360 != num:
t.setheading(num)
t.forward(20)
s.onkey(lambda : moveu(90), 'w')
s.onkey(lambda : moveu(270), 's')
s.onkey(lambda : moveu(180), 'a')
s.onkey(lambda : moveu(0), 'd')
s.listen()
turtle.mainloop()
</code></pre>