0
我對python語言和編程一般都很陌生,對我一無所知。我創建了一個隨機行走場景,它在隨機方向上進行一次特定次數的步驟。我遇到的一件事情是,有時它會離開我設置的圖形窗口,我不能再看到它在哪裏。 下面是代碼:如何保持走出圖形窗口的隨機行走場景
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()
我的問題是,有沒有辦法,我可以設置圖形窗口的參數,使步行者不能窗外去了?如果它試圖,它會轉過身來嘗試另一個方向?
謝謝!