如何防止随机游走场景外流

2024-10-06 06:46:48 发布

您现在位置: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()

我的问题是,有没有一种方法,我可以设置参数的图形窗口,使步行者不能走出窗外?如果它试着,它会掉头尝试另一个方向?你知道吗


Tags: fromimport图形场景randomsteps方向win
1条回答
网友
1楼 · 发布于 2024-10-06 06:46:48

尝试定义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()

相关问题 更多 >