如何使随机游走场景远离图形窗口

时间:2017-11-11 18:22:35

标签: python graphics

我创建了一个随机游走场景,它在一个随机方向上走了一段特定的次数。我遇到的一件事是,有时它会脱离我设置的图形窗口,我再也看不到它在哪里了。 这是代码:

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()

我的问题是,有没有办法可以在图形窗口上设置参数,以便助行器不能走出窗外?如果它试图,它只会转身并尝试另一个方向?

1 个答案:

答案 0 :(得分:0)

尝试定义x和y的上限和下限。然后使用while循环继续尝试随机点,直到下一个在边界内。

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')

# set upper and lower bounds for next point
upper_X_bound = 50.0
lower_X_bound = -50.0
upper_Y_bound = 50.0
lower_Y_bound = -50.0
for i in range(steps):
    point_drawn = 0 # initialize point not drawn yet
    while point_drawn == 0: # do until point is drawn
        drawpoint = 1 # assume in bounds
        angle = random() * 2 * pi
        newX = x + cos(angle)
        newY = y + sin(angle)
        if newX > upper_X_bound or newX < lower_X_bound:
            drawpoint = 0 # do not draw, x out of bounds
        if newY > upper_Y_bound or newY < lower_Y_bound:
            drawpoint = 0 # do not draw, y out of bounds
        if drawpoint == 1: # only draw points that are in bounds
            newpoint = Point(newX, newY).draw(win)
            Line(Point(x, y), newpoint).draw(win)
            x = newX
            y = newY
            point_drawn = 1 # set this to exit while loop

walker()