def main(problem=rhook16b, time_limit=5): """ Call proj2.main and wait for time_limit (default 5) number of seconds, then kill it and read the last velocity it put into choices.txt. If the velocity is (0,0) and the position is on the finish line, the run ends successfully. Otherwise, add an error to the velocity, and draw the move in the graphics window. If the move crashes into a wall, the run ends unsuccessfully. """ print('Problem:', problem) (p0, f_line, walls) = problem turtle.Screen() # open the graphics window tdraw.draw_problem((p0, f_line, walls)) (x, y) = p0 (u, v) = (0, 0) # If proj2 includes an initialization procedure, call it to cache some data if 'initialize' in dir(proj2): print('Calling proj2.initialize.') p = mp.Process(target=proj2.initialize, \ args = (((x,y),(u,v)), f_line, walls, )) p.start() # Wait for 10 seconds (the time limit I specified on Piazza) p.join(10) if p.is_alive(): print('\nWarning: terminating proj2.initialize at 10 seconds.') print('This means its output may be incomplete.') p.terminate() else: print("Note: proj2.py doesn't contain an initialize program.") while True: if goal_test((x, y), (u, v), f_line): print('\nYour program completed a successful run.') break (u, v, ok) = get_proj2_choice((x, y), (u, v), f_line, walls, time_limit) if ok == False: print("\nYour program didn't produce a correct move.") break draw_edge(((x, y), (x + u, y + v)), 'green') error = steering_error(u, v) (xnew, ynew) = (x + u + error[0], y + v + error[1]) print('proj2 chose velocity {}, steering error is {}, result is {}'.format( \ (u,v), error, (xnew,ynew))) edge = ((x, y), (xnew, ynew)) draw_edge(edge, 'red') if crash(edge, walls): print('\nYou have crashed.') break (x, y) = (xnew, ynew)
def make_one(size=48, display=0, title='', density=1, complexity=1): """ Create a random racetrack and print out its definition. The parameters are: size: each racetrack is a square grid of dimensions approximately size x size. Because of some idiosyncracies involving the maze subroutine, the dimensions are rounded to the nearest multiple of 4. title: a string to use as part of each racetrack's name. display: if display > 0, an ASCII drawing of the maze will be printed (in addition to the racetrack's definition). If display > 1, the racetrack will also be displayed in a graphics window. density and complexity: arguments for the maze subroutine. They affect how many obstacles (inner walls) to create, and how long each of them should be. The strategy is as follows. First, use the maze subroutine to create a random maze of dimensions size/4 x size/4. Next, add a starting point and finish line. Then, so the distance between adjacent walls won't be too small, multiply all coordinates by 4, to get a racetrack of dimensions size x size. """ # The maze program requires width and height to be odd, # so round them to the nearest odd integer xmax = ymax = (size // 4) * 2 + 1 M = maze(xmax, ymax, complexity, density) # if display>0: print_maze(M,xmax,ymax,title) # M is a 2-D array of True/False (i.e., blocked/non-blocked) values. # Look for horizontal and vertical strings of blocked points, and # translate them into walls for the racetrack problem. walls = [] for x in range(xmax): walls.extend(make_vertical_walls(xmax,ymax,x,M)) for y in range(ymax): walls.extend(make_horizontal_walls(xmax,ymax,y,M)) (start,x,y) = choose_starting_point(M,xmax,ymax) finish = choose_finish_line(x,y,M,xmax,ymax) print(finish) if display>0: print_racetrack(title,start,finish,M,xmax,ymax) # the racetrack's width and height are 1/2 of what we want, so double them problem = double_prob(start, finish, walls) problem = double_prob(start, finish, walls) if display>1: draw_edges = tdraw.draw_edges turtle.Screen() # open the graphics window turtle.clearscreen() tdraw.draw_problem(problem, title=title) return problem
def main(problem, strategy, h, module, verbose=2, draw=0, title=''): """ Args are as follows: - prob should be a triple [s0, f_line, walls], where s0 is the initial state, f_line is the finish line, walls is a list of walls - strategy should be 'bf' (best first), 'df' (depth first), 'uc' (uniform cost), 'gbf' (greedy best first), 'a*', or 'none' (don't try to solve the problem, just display it). - h should be a heuristic function of three arguments h(s,f_line,walls), where s is the current state, f_line is the finish line, walls is a list of walls - verbose should be one of the following: 0 - silent, just return the answer. 1 - print some statistics at the end of the search. 2 - print brief info at each iteration, and statistics at the end of the search. 3 - print additional info at each iteration, and stats at the end of the search. 4 - print the above, and pause at each iteration. - draw should either be 0 (draw nothing) or 1 (draw everything) - title is a title to put at the top of the drawing. It defaults to the names of the search strategy and heuristic (if there is one) """ s0 = (problem[0], (0,0)) # initial state f_line = problem[1] walls = problem[2] # convert h, next_states, and goal_test to the one-arg functions fsearch wants h_for_fsearch = lambda state: h(state, f_line, walls) next_for_fsearch = lambda state: [(s,1) for s in next_states(state,walls)] goal_for_fsearch = lambda state: goal_test(state,f_line) if draw: draw_edges = tdraw.draw_edges if title == '': if h: title = strategy + ', ' + h.__name__ else: title = strategy turtle.Screen() # open the graphics window tdraw.draw_problem(problem, title=title) else: draw_edges = None if strategy != 'none': importlib.reload(module) solution = fsearch.main(s0, next_for_fsearch, goal_for_fsearch, strategy, \ h_for_fsearch, verbose, draw_edges) else: solution = None if verbose: print('Solution ({} states):\n{}'.format(len(solution), solution)) if draw: print("\n*** Finished running '{}'.".format(title)) print("Type carriage return to continue:") sys.stdin.readline() # turtle.mainloop() return solution
def main(problem=None, draw=1, single_step=0): """ Create a random racetrack problem, or take one as a parameter. Then, repeatedly retrieve next velocity from proj3.main and move there, until either you crash or you reach the finish line and have velocity (0,0). If single_step = 1, then wait for carriage returns between steps. """ if not problem: problem = maketrack.main() (p0, f_line, walls) = problem if draw: turtle.Screen() # open the graphics window turtle.clearscreen() tdraw.draw_problem((p0, f_line, walls), title='foo') (x, y) = p0 (u, v) = (0, 0) i = 0 while True: i += 1 if goal_test((x, y), (u, v), f_line): print('\nYou win.') break state = ((x, y), (u, v)) (u, v) = proj3.main(state, f_line, walls) (xnew, ynew) = (x + u, y + v) print('Move {}: proj3.main chose velocity {}'.format(i, (u, v)), end='') print(', new position is {}'.format((xnew, ynew))) edge = ((x, y), (xnew, ynew)) if draw: draw_edge(edge, 'red') if crash(edge, walls): print('\nYou have crashed, so you lose.') break (x, y) = (xnew, ynew) if single_step: print("\n*** Finished move {}. Hit carriage return to continue.\n". format(i)) sys.stdin.readline()
def main(s, f_line, walls, strategy, h, verbose=2, draw=0, title=''): """ Args are as follows: - s is the initial state, f_line is the finish line, walls is a list of walls - strategy should be 'bf' (best first), 'df' (depth first), 'uc' (uniform cost), 'gbf' (greedy best first), 'a*', or 'none' (don't try to solve the problem, just display it). - h should be a heuristic function of three arguments h(s,f_line,walls), where s is the current state, f_line is the finish line, walls is a list of walls - verbose should be one of the following: 0 - silent, just return the answer. 1 - print some statistics at the end of the search. 2 - print brief info at each iteration, and statistics at the end of the search. 3 - print additional info at each iteration, and stats at the end of the search. 4 - print the above, and pause at each iteration. - draw should either be 0 (draw nothing) or 1 (draw everything) - title is a title to put at the top of the drawing. It defaults to the names of the search strategy and heuristic (if there is one) """ # convert h, next_states, and goal_test to the one-arg functions fsearch wants h_for_fsearch = lambda state: h(state, f_line, walls) next_for_fsearch = lambda state: [(ns, 1) for ns in next_states(state, walls)] goal_for_fsearch = lambda state: goal_test(state, f_line) if draw: draw_edges = tdraw.draw_edges if title == '': if h: title = strategy + ', ' + h.__name__ else: title = strategy turtle.Screen() # open the graphics window tdraw.draw_problem((s[0], f_line, walls), title=title) else: draw_edges = None if strategy != 'none': solution = fsearch.main(s, next_for_fsearch, goal_for_fsearch, strategy, \ h_for_fsearch, verbose, draw_edges) else: solution = None if draw: print("\n*** Finished '{}'. Close the graphics window to continue.\n". format(title)) turtle.mainloop() return solution
def main(problem, strategy, h, verbose=2, draw=0, title=''): """ Args are as follows: - prob should be a triple [s0, f_line, walls], where s0 is the initial state, f_line is the finish line, walls is a list of walls - strategy should be 'bf' (best first), 'df' (depth first), 'uc' (uniform cost), 'gbf' (greedy best first), or 'a*'. - h should be a heuristic function of three arguments h(s,f_line,walls), where s is the current state, f_line is the finish line, walls is a list of walls - verbose should be one of the following: 0 - silent, just return the answer. 1 - print some statistics at the end of the search. 2 - print brief info at each iteration, and statistics at the end of the search. 3 - print additional info at each iteration, and stats at the end of the search. 4 - print the above, and pause at each iteration. - draw should either be 0 (draw nothing) or 1 (draw everything) - title is a title to put at the top of the drawing. It defaults to the names of the search strategy and heuristic (if there is one) """ s0 = (problem[0], (0, 0)) # initial state f_line = problem[1] walls = problem[2] # convert h, next_states, and goal_test to the single-argument functions gsearch wants h_for_gs = lambda state: h(state, f_line, walls) next_for_gs = lambda state: [(s, 1) for s in next_states(state, walls)] goal_for_gs = lambda state: goal_test(state, f_line) if draw: draw_edges = tdraw.draw_edges if title == '': if h: title = strategy + ', ' + h.__name__ else: title = strategy turtle.Screen() # open the graphics window tdraw.draw_problem(problem, title=title) else: draw_edges = None solution = gsr.search(s0, next_for_gs, goal_for_gs, strategy, h_for_gs, \ verbose, draw_edges) if draw: print("\n*** Finished '{}'. Close the graphics window to continue.\n". format(title)) turtle.mainloop() return solution
def main(size=28, doprint=0, draw=0, title='', complexity=.1, density=.1): """ Create a racetrack of dimensions approximately size * size. Because of some idiosyncracies involving the maze subroutine, the dimensions are rounded to the nearest multiple of 4. If doprint = 1, print an ascii version of the problem; if draw = 1, draw it using tdraw. - title is the title to use for printing and/or drawing. - complexity and density are just passed to maze(...) unchanged. """ # Create a random maze of width and height approximately # size/2 x size/2. The maze program requires width and height # to be odd, so we round size/2 to the nearest odd integer. xmax = ymax = (size // 4) * 2 + 1 M = maze(xmax, ymax, complexity, density) if doprint: print_maze(M,xmax,ymax,title) # M is a 2-D array of True/False (i.e., blocked/non-blocked) values. # Look for horizontal and vertical strings of blocked points, and # translate them into walls for the racetrack problem. walls = [] for x in range(xmax): walls.extend(make_vertical_walls(xmax,ymax,x,M)) for y in range(ymax): walls.extend(make_horizontal_walls(xmax,ymax,y,M)) (start,x,y) = choose_starting_point(M,xmax,ymax) finish = choose_finish_line(x,y,M,xmax,ymax) # the racetrack is only half the size we want, so double it problem = double_prob(start, finish, walls) if draw: draw_edges = tdraw.draw_edges turtle.Screen() # open the graphics window turtle.clearscreen() tdraw.draw_problem(problem, title=title) return problem
def main(problem=sample_probs.rhook32b, max_search_time=5, max_init_time=5, \ opponent=op.opponent1, verbose=1, draw=1): """ First call proj2.initialize (if it exists) and wait max_init_time (default 5) seconds. Then repeatedly do the following steps until you win or lose: - Call proj2.main, and wait max_search_time (default 5) number of seconds. - Kill proj2.main, and read the last velocity it put into choices.txt. - If it isn't a legal velocity, exit with 'lose'. - If velocity = (0,0) and distance from finish line <= 1, exit with 'win'. - Call the opponent to add an error to the velocity. - Draw the move in the graphics window. - If the move crashes into a wall, exit with 'lose'. """ if verbose: print(problem) (title, p0, f_line, walls) = problem if draw: turtle.Screen() # open the graphics window tdraw.draw_problem((p0, f_line, walls), title=title) (x,y) = p0 (u,v) = (0,0) # If proj2 includes an initialization procedure, call it to cache some data if 'initialize' in dir(proj2): if verbose: print('Calling proj2.initialize.') proj2.initialize(((x,y),(u,v)), f_line, walls) time.sleep(5) #p = mp.Process(target=proj2.initialize, \ # args = (((x,y),(u,v)), f_line, walls, )) #p.start() # Wait for max_init_time seconds # p.join(max_init_time) # if p.is_alive(): # if verbose: # print('\nWarning: terminating proj2.initialize at {} seconds.'.format(max_init_time)) # print('This means its output may be incomplete.') # p.terminate() # elif verbose: # print("Note: proj2.py doesn't contain an initialize program.") while True: if goal_test((x,y), (u,v), f_line): if verbose: print('\nYou win.') return 'win' (u, v, ok) = get_proj2_choice((x,y), (u,v), f_line, walls, max_search_time) if ok == False: if verbose: print("\nYour program produced an incorrect move, so you lose.") return 'wrong move' if draw: draw_edge(((x,y), (x+u, y+v)), 'green') error = opponent((x,y), (u,v), f_line, walls) (xnew,ynew) = (x+u+error[0], y+v+error[1]) if verbose: print('proj2 velocity {}, opponent error {}, result is {}'.format( \ (u,v), error, (xnew,ynew))) edge = ((x,y), (xnew, ynew)) if draw: draw_edge(edge, 'red') if crash(edge, walls): if verbose: print('\nYou crashed, so you lose.') return 'crash' (x,y) = (xnew, ynew)