TurtleGraphics Python - Constraining random-moving turtle in a circle?(将随机移动的海龟限制在一个圆圈中?)
问题描述
如何才能使随机移动的乌龟被约束在半径为50的圆内,圆的中心位于(0,0)?因此,如果海龟当前位于位置(x,y),则它与中心的距离为math.sqrt(x**2+y**2)。每当乌龟离中心的距离超过50时,让它转过身来继续前进。我已经得到了处理屏幕大小的代码,但是我要把math.sqrt(x**2+y**2)放在哪里才能把它限制在一个圆圈里呢?以下是我到目前为止拥有的代码:
import turtle, random, math
def bounded_random_walk(num_steps, step_size, max_turn):
turtle.reset()
width = turtle.window_width()
height = turtle.window_height()
for step in range(num_steps):
turtle.forward(step_size)
turn = random.randint(-max_turn, max_turn)
turtle.left(turn)
x, y = turtle.position()
if -width/2 <= x <= width/2 and -height/2 <= y <= height/2:
pass
else: # turn around!
turtle.left(180)
turtle.forward(step_size)
此代码适用于屏幕中的乌龟,但不适用于圆圈中的乌龟。
推荐答案
您编写代码的位置:
if -width/2 <= x <= width/2 and -height/2 <= y <= height/2:
你真正的意思是"如果点(x,y)在允许的区域内"。因此,当"允许面积"是"半径为50以原点为中心的圆"时,比较距离和半径的平方(这比取平方根更清楚...!-),你会得到:
if (x*x + y*y) <= 50*50:
保留所有其余代码不变。
编辑:由于操作员评论这对他不起作用,我将if/Else更改为:
x, y = turtle.position()
# if -width/3 <= x <= width/3 and -height/3 <= y <= height/3:
if (x*x + y*y) <= 50*50:
pass
else: # turn around!
print 'Bounce', step, x, y
turtle.left(180)
turtle.forward(step_size)
并将其作为bounded_random_walk(200, 10, 30)
从Mac OS X上的Terminal.App运行,因此将显示print
。结果是我得到了大约50到60张"弹跳"的照片,海龟显然被限制在所需的圆圈内,逻辑和几何也表明它必须如此。
因此,我希望操作员按照这些思路来编辑他们自己的答案(理想情况下是在系统上,并且在一种安排中,他可以看到print
的结果,或者以其他方式提供输出并理想地将结果显示给我们),这样我就可以帮助他调试他的代码。
这篇关于将随机移动的海龟限制在一个圆圈中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将随机移动的海龟限制在一个圆圈中?


基础教程推荐
- 合并具有多索引的两个数据帧 2022-01-01
- 使用 Google App Engine (Python) 将文件上传到 Google Cloud Storage 2022-01-01
- 如何在 Python 中检测文件是否为二进制(非文本)文 2022-01-01
- 将 YAML 文件转换为 python dict 2022-01-01
- Python 的 List 是如何实现的? 2022-01-01
- 哪些 Python 包提供独立的事件系统? 2022-01-01
- 如何在Python中绘制多元函数? 2022-01-01
- 使 Python 脚本在 Windows 上运行而不指定“.py";延期 2022-01-01
- 症状类型错误:无法确定关系的真值 2022-01-01
- 使用Python匹配Stata加权xtil命令的确定方法? 2022-01-01