2017-11-11 3 views
0

저는 파이썬 언어와 프로그래밍에 대해 처음 보았습니다. 나는 특정 시간 동안 무작위 방향으로 한 단계 씩 걸리는 랜덤 워크 시나리오를 만들었습니다. 내가 한 번 실행 한 것은 내가 설정 한 그래픽 창에서 가끔 사라져서 더 이상 볼 수 없다는 것입니다. 워커는 창 밖으로 갈 수 있도록 내가 그래픽 창에 매개 변수를 설정할 수있는 방법이 있나요,랜덤 워크 시나리오가 그래픽 창 외부로 나가는 것을 방지하는 방법

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

내 질문은 : 여기 코드인가? 그렇게하려고하면 그냥 돌아 서서 다른 방향을 시도할까요?

감사합니다.

답변

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