我怎样才能让一个随机移动的乌龟被限制在一个半径为 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)
此代码适用于屏幕中的海龟,但不适用于圆形。