我创建了一个随机行走场景,在这个场景中,它在一个随机的方向上走一步,走特定的次数。我遇到的一件事是,有时它会离开我设置的图形窗口,我再也看不到它在哪里了。 代码如下:
from random import *
from graphics import *
from math import *
def walker():
win = GraphWin('Random Walk', 800, 800)
win.setCoords(-50, -50, 50, 50)
center = Point(0, 0)
x = center.getX()
y = center.getY()
while True:
try:
steps = int(input('How many steps do you want to take? (Positive integer only) '))
if steps > 0:
break
else:
print('Please enter a positive number')
except ValueError:
print('ERROR... Try again')
for i in range(steps):
angle = random() * 2 * pi
newX = x + cos(angle)
newY = y + sin(angle)
newpoint = Point(newX, newY).draw(win)
Line(Point(x, y), newpoint).draw(win)
x = newX
y = newY
walker()
我的问题是,有没有一种方法,我可以设置参数的图形窗口,使步行者不能走出窗外?如果它试着,它会掉头尝试另一个方向?你知道吗
尝试定义x和y的上下界。然后使用while循环,不断尝试随机点,直到下一个点在边界内。你知道吗
相关问题 更多 >
编程相关推荐