Mis*_*ify 4 python turtle-graphics
我想使用海龟创建一个程序,该程序在随机方向上移动 50 次随机距离,在 x 和 y 轴上保持在 -300 到 300 范围内(通过向相反方向转动并在到达边界时向前移动) 。
当 if 语句为 true 时,代码运行良好,但偶尔当执行 else 语句时(由于超出边界),else 语句会一次又一次执行,直到计数达到 50。换句话说,它会沿着同一条线。我不明白为什么,因为当乌龟弹开时,它应该在边界内并再次运行 if 语句,而不是 else 语句。我该如何解决这个问题,以便乌龟在弹跳后继续随机行走?谢谢
我的代码如下所示
import turtle
import random
count = 0
while count <51:
count += 1
if (turtle.xcor() >-300 and turtle.xcor() <300) and\
(turtle.ycor() >-300 and turtle.ycor() <300):
turtle.forward(random.randint(30,100))
turtle.right(random.randint(0,360))
else:
turtle.right(180)
turtle.forward(300)
Run Code Online (Sandbox Code Playgroud)
在if语句中,应该先转向,再前进:
\n\n假设您位于 (0,299),并且乌龟面朝上,您将向前(假设为 100),然后转向(假设为向左)。然后您将位于 (0, 399),面向左。
\n\n然后,您将进入 else 循环,向右/300,因此将处于 300/399,因此仍然超出范围(请注意forward(300)可能也有点太多)。
如果你先转弯,然后向前走,你就真的掉头了。
\n但再一次,300 可能太多了。我宁愿用以下方法保存之前的距离:
if (-300 < turtle.xcor() <300) and (-300 < turtle.ycor() <300):\n turtle.right(random.randint(0,360))\n distance = random.randint(30,100) \n turtle.forward(distance)\nelse:\n turtle.right(180)\n turtle.forward(distance)\nRun Code Online (Sandbox Code Playgroud)\n\n想象一下你在 (299,299) 处,走 135\xc2\xb0 (向上/向左对角),向前 100。然后你会得到y>300,如果你掉头,向前 300,你会得到x>300。然后又开始循环。
| 归档时间: |
|
| 查看次数: |
16865 次 |
| 最近记录: |