def test_bfs(): g1 = nx.complete_graph(10) print('with goal: [', end='') for v in a.bfs(g1, 0, 4): print(v, end=' ') print(']') print('no goal: [', end='') for v in a.bfs(g1, 0): print(v, end=' ') print(']') nx.draw(g1, with_labels=True) plt.show() g2 = nx.Graph() g2.add_nodes_from([i for i in range(10)]) g2.add_edges_from([(0, 1), (1, 3), (1, 4), (1, 5), (0, 2), (2, 5), (2, 6), (2, 7), (2, 8), (2, 9)]) print('with goal: [', end='') for v in a.bfs(g2, 0, 6): print(v, end=' ') print(']') print('no goal: [', end='') for v in a.bfs(g2, 0): print(v, end=' ') print(']') nx.draw(g2, with_labels=True) plt.show() plt.close()
def bfs_demo(): # pos = nx.kamada_kawai_layout(graph1) # plt.subplot(221) # nx.draw(graph1, with_labels=True, pos=pos) # plt.subplot(222) # res_graph = algorithms.path_to_graph(graph1, # algorithms.bfs(graph1, 0)) # edge_labels = {(v, u): res_graph.get_edge_data(v, u).get('weight') # for (v, u) in res_graph.edges # if res_graph.get_edge_data(v, u).get('weight') is not None} # nx.draw_networkx_edge_labels(res_graph, pos, edge_labels=edge_labels) # nx.draw(res_graph, with_labels=True, pos=pos) pos = nx.spring_layout(graph2) plt.subplot(121) nx.draw(graph2, pos=pos, with_labels=True) plt.subplot(122) res_G = algorithms.path_to_graph(graph2, algorithms.bfs(graph2, 0)) edge_labels = {(v, w): res_G.get_edge_data(v, w).get('weight') for (v, w) in res_G.edges if res_G.get_edge_data(v, w).get('weight') is not None} nx.draw_networkx_edge_labels(res_G, pos, edge_labels=edge_labels) nx.draw(res_G, with_labels=True, pos=pos) plt.show()
def main(win, width): grid = make_grid(ROWS, width) start = None end = None run = True algo = 'astar' astar_button = Button((10, WIDTH+30, 110, 20), 'Astar Algorithm') astar_button.selected = True dijkstra_button = Button((10, WIDTH+50, 110, 20), 'Dijkstras Algorithm') best_first_button = Button((10, WIDTH+70, 110, 20), 'Best-First-Search') buttons = [astar_button, dijkstra_button, best_first_button] while run: for event in pygame.event.get(): if event.type == pygame.QUIT: run = False if pygame.mouse.get_pressed()[0]: # LEFT pos = pygame.mouse.get_pos() if pos[1]<=width: row, col = get_clicked_pos(pos, ROWS, width) spot = grid[row][col] if not start and spot != end: start = spot start.make_start() elif not end and spot != start: end = spot end.make_end() elif spot != end and spot != start: spot.make_barrier() else: algo = update_buttons(buttons, pos) elif pygame.mouse.get_pressed()[2]: # RIGHT pos = pygame.mouse.get_pos() row, col = get_clicked_pos(pos, ROWS, width) spot = grid[row][col] spot.reset() if spot == start: start = None elif spot == end: end = None if event.type == pygame.KEYDOWN: if event.key == pygame.K_SPACE and start and end: if algo == 'astar': for row in grid: for spot in row: spot.update_neighbors(grid) astar_algorithm(lambda: draw(win, grid, ROWS, width, buttons), grid, start, end) elif algo == 'dijkstras': for row in grid: for spot in row: spot.update_neighbors(grid) bfs(lambda: draw(win, grid, ROWS, width, buttons), grid, start, end) elif algo == 'best_first': for row in grid: for spot in row: spot.update_neighbors(grid) best_first_search(lambda: draw(win, grid, ROWS, width, buttons), grid, start, end) if event.key == pygame.K_m: start = None end = None grid = make_grid(ROWS, width, True) if event.key == pygame.K_c: start = None end = None grid = make_grid(ROWS, width) draw(win, grid, ROWS, width, buttons) pygame.display.update() pygame.quit()
(10, 10)) #设置形态学结构处理的核 矩形:MORPH_RECT; 交叉形:MORPH_CORSS; 椭圆形: MORPH_ELLIPSE dst = cv.dilate(org1, kernel) # 原始道路地图 & 形态学膨胀后的道路地图 fig1 = plt.figure() plt.subplot(311), plt.imshow(255 - org, 'gray'), plt.title('ORIGIN') plt.subplot(312), plt.imshow( 255 - dst, 'gray' ) #,plt.plot(path_x,path_y,'--r'),plt.title('RESULT (%d,%d)->(%d,%d)'%(start[0],start[1],goal[0],goal[1])) # 设置起点和目标点 (height, width) = (dst.shape[0], dst.shape[1]) start = (height // 2, 0) goal = (height // 2, width - 1) # 使用路径规划算法寻找路径 time_0 = time.perf_counter() (path1, mask1) = alg.bfs(dst, start, goal) elapsed = (time.perf_counter() - time_0) print("BFS Time used:", elapsed) print('path length: %d' % (len(path1) - 1)) print('orgi_', np.sum(org == 0)) print('mask_', np.sum(mask1 != 0)) time_0 = time.perf_counter() (path2, mask2) = alg.astar(dst, start, goal) elapsed = (time.perf_counter() - time_0) print("A* Time used:", elapsed) print('path length: %d' % (len(path2) - 1)) print('orgi_', np.sum(org == 0)) print('mask_', np.sum(mask2 != 0)) ''' plt.subplot(313),plt.imshow(mask,'gray')
def main(): bs = int(input("Board size: ")) board = Board(bs) set_goal(bs) start_node = get_start_node(bs) vb = input("Do you want to print intermediate steps? (y/n): ") if vb == 'y' or vb == 'Y': verbose = True elif vb == 'n' or vb == 'N': verbose = False running = True choice = 0 dls_limit = None while running: print("\n---------------------------------------------------") print("Choose and algorithm (1-6) or press 0 to quit:") print("1. Breadth-First Search (BFS)") print("2. Uninformed Cost Search (UCS)") print("3. Depth Limited Search (DLS)") print("4. Iterativee Deepening Depth-First Search (IDS)") print("5. Greedy Best-First Search (GBFS)") print("6. A* Search") print("7. Generate Graphs on 8-Puzzle (time, nodes generated, cost)") try: choice = int(input("Choice: ")) except: print("Only interger input allowed") continue if choice == 0: break elif choice == 1: print(f"Running BFS on: {start_state}") print(f"Goal: {goal_state}\n...") result = bfs(start_node, board, verbose) dls_limit = result.max_depth if result.verdict == 'success': print("Goal State Found!") show_statistics(result) path(result.node) path_to_goal() elif result.verdict == 'failed': print("Goal Not Found") elif choice == 2: print(f"Running UCS on: {start_state}") print(f"Goal: {goal_state}\n...") start_node_ucs = NodeGCost(start_state, goal_state, None, None, 0, 0) result = ucs(start_node_ucs, board, verbose) dls_limit = result.max_depth if result.verdict == 'success': print("Goal State Found!") show_statistics(result) path(result.node) path_to_goal() elif result.verdict == 'failed': print("Goal Not Found") elif choice == 3: if dls_limit is None: print("DLS limit not set by BFS yet") dls_limit = int(input("Limit: ")) else: print(f"BFS set limit to {dls_limit}") print(f"Running DLS on: {start_state}") print(f"Goal: {goal_state}") print(f"limit: {dls_limit}\n...") result = dls(start_node, board, dls_limit, verbose) if result.verdict == 'success': print("Goal State Found!") show_statistics(result) path(result.node) path_to_goal() elif result.verdict == 'failed': print("Goal Not Found") elif choice == 4: print(f"Running IDS on: {start_state}") print(f"Goal: {goal_state}") result = ids(start_node, board, 0 ,verbose) if result.verdict == 'success': print("Goal State Found!") show_statistics(result) path(result.node) path_to_goal() elif result.verdict == 'failed': print("Goal Not Found") elif choice == 5: print(f"Running GBFS on: {start_state}") print(f"Goal: {goal_state}\n...") result = gbfs(start_node, board, verbose) if result.verdict == 'success': print("Goal State Found!") show_statistics(result) path(result.node) path_to_goal() elif result.verdict == 'failed': print("Goal Not Found") elif choice == 6: print(f"Running A* on: {start_state}") print(f"Goal: {goal_state}\n...") start_node_a = NodeFCost(start_state, goal_state, None, None, 0, 0) result = a_star(start_node_a, board, verbose) if result.verdict == 'success': print("Goal State Found!") show_statistics(result) path(result.node) path_to_goal() elif result.verdict == 'failed': print("Goal Not Found") elif choice == 7: unleash_chaos(goal_state)
from utility import read_input_file from problem import Problem from algorithms import ucs, bfs, a_star if __name__ == '__main__': input_dict = read_input_file() for key, value in input_dict.items(): print(key, value, sep=':') for target in input_dict['targets']: problem = Problem( init_state=input_dict['state_grid'][input_dict['landing_site'][1]][ input_dict['landing_site'][0]], state_space=input_dict['state_grid'], goal_state=input_dict['state_grid'][target[1]][target[0]], actions=['E', 'W', 'N', 'S', 'NE', 'SE', 'SW', 'NW'], max_elev_diff=input_dict['max_elevation_diff']) # print(problem) if input_dict['algorithm'].lower() == 'bfs': print(bfs(problem)) elif input_dict['algorithm'].lower() == 'ucs': print(ucs(problem)) else: print(a_star(problem))
def main(): parser = argparse.ArgumentParser() parser.add_argument('-width', type=int, default=121, help='width of the maze') parser.add_argument('-height', type=int, default=97, help='height of the maze') parser.add_argument('-margin', type=int, default=2, help='border of the maze') parser.add_argument('-scale', type=int, default=5, help='size of a cell in pixels') parser.add_argument( '-loop', type=int, default=0, help='number of loops of the animation, default to 0 (loop infinitely)' ) parser.add_argument( '-bits', metavar='b', type=int, default=8, help='an interger beteween 2-8 represents the color depth of the image,\ this parameter determines the size of the global color table.' ) parser.add_argument('-filename', type=str, default='wilson.gif', help='output file name') args = parser.parse_args() # define your favorite global color table here. mypalette = [0, 0, 0, 200, 200, 200, 255, 0, 255] # GIF files allows at most 256 colors in the global color table, # redundant colors will be discarded when the encoder is initialized. for i in range(256): rgb = hls_to_rgb((i / 360.0) % 1, 0.5, 1.0) mypalette += map(lambda x: int(round(255 * x)), rgb) # you may use a binary image instance of PIL's Image class here as the mask image, # this image must preserve the connectivity of the grid graph. from gentext import generate_text_mask mask = generate_text_mask(args.width, args.height, 'UST', '../resources/ubuntu.ttf', 60) maze = Maze(args.width, args.height, args.margin, mask=mask) canvas = maze.add_canvas(scale=args.scale, min_bits=args.bits, palette=mypalette, loop=args.loop, filename=args.filename) # here we need to paint the blank background because the region that has not been # covered by any frame will be set to transparent by decoders. # Comment out this line and watch the result if you don't understand this. canvas.paint_background(wall_color=0) # pad one second delay, get ready! canvas.pad_delay_frame(delay=100) # you may adjust the `speed` parameter for different algorithms. canvas.set_control_params(delay=2, speed=50, trans_index=3, wall_color=0, tree_color=1, path_color=2) start = (args.margin, args.margin) end = (args.width - args.margin - 1, args.height - args.margin - 1) # the maze generation animation. # try prim(maze, start) or kruskal(maze) or random_dfs(maze) here! wilson(maze, start) # pad three seconds delay to help to see the resulting maze clearly. canvas.pad_delay_frame(delay=300) # in the path finding animation the walls are unchanged throughout, # hence it's safe to use color 0 as the transparent color. canvas.set_control_params(delay=5, speed=30, trans_index=0, wall_color=0, tree_color=0, path_color=2, fill_color=3) # the maze solving animation. # try dfs(maze, start, end) or astar(maze, start, end) here! bfs(maze, start, end) # pad five seconds delay to help to see the resulting path clearly. canvas.pad_delay_frame(delay=500) # finally finish the animation and close the file. canvas.save()
try: forbiddenString = inputFile.readline().split(",") except: pass if forbiddenString != ['']: for i in range(len(forbiddenString)): forbidden.append([char for char in forbiddenString[i]]) root = tree.Tree(data=startState, isGoal=(startState == goalState)) fringe = [] expanded = [] pathFound = [] # Call algorithms if algo == 'B': pathFound = algorithms.bfs(root, goalState, forbidden, fringe, expanded) elif algo == 'D': pathFound = algorithms.dfs(root, goalState, forbidden, fringe, expanded) elif algo == 'I': pathFound = algorithms.ids(root, goalState, forbidden, fringe, expanded) elif algo == 'G': pathFound = algorithms.greedy(root, goalState, forbidden, fringe, expanded) elif algo == 'A': pathFound = algorithms.aStar(root, goalState, forbidden, fringe, expanded) elif algo == 'H': pathFound = algorithms.hillClimbing(root, goalState, forbidden, fringe, expanded) else: sys.exit(0) # Format output
plt.subplot(121) pos = nx.spring_layout(g1) nx.draw(g1, pos=pos, with_labels=True) plt.subplot(122) nx.draw(a.prim(g1, 0), pos=pos, with_labels=True) plt.show() def test_dijkstra(): g1 = nx.Graph() g1.add_nodes_from([i for i in range(6)]) g1.add_weighted_edges_from([(0, 2, 4), (0, 4, 8), (1, 2, 3), (1, 4, 5), (1, 3, 6), (2, 5, 12), (3, 5, 9), (4, 5, 1)]) min_paths_dict = a.dijkstra(g1, 0) new_nodes = {i: (i, j) for i, j in min_paths_dict.items()} nx.relabel_nodes(g1, new_nodes, copy=False) pos = nx.spring_layout(g1) nx.draw(g1, pos=pos, with_labels=True) labels = {(u, v): g1.get_edge_data(u, v).get('weight') for (u, v) in g1.edges} nx.draw_networkx_edge_labels(g1, pos=pos, edge_labels=labels) plt.show() time1 = time.time() for i in a.bfs(G, 1): pass time2 = time.time() print(f'time = {time2 - time1}')
import problem import algorithms import sys from copy import deepcopy print("Initialization Phase") state = [] for i in range(3): state.append([]) a, b, c = input().split() state[i].append(int(a)) state[i].append(int(b)) state[i].append(int(c)) puzzle = problem.Problem(state) if sys.argv[1] == "dfs": algorithms.dfs(puzzle) elif sys.argv[1] == "bfs": algorithms.bfs(puzzle) elif sys.argv[1] == "bi": algorithms.bidirectional(puzzle) elif sys.argv[1] == "uni": algorithms.uniform_cost(puzzle) elif sys.argv[1] == "as": algorithms.a_star(puzzle) elif sys.argv[1] == "log": parents = [[deepcopy(puzzle.state), "NOP", "NOA", 5]] parent = deepcopy(puzzle.state) x = algorithms.parent_distance(parent, parents) x += 1 print(x)
def route_between_nodes(source, target): bfs(source) return target.visited
def get_root(self): return self.root def set_goals(self, username): """ Get the friends of the target """ children = self.client.get_friends(username) self.goals = [child.username for child in children] print 'goals: ', self.goals def is_goal(self, username): """ Check if the new user is in the goals set """ return username in self.goals def get_children(self, username): return self.client.get_friends(username) if __name__ == '__main__': tree = FBTree() tree.set_goals(TARGET) results = bfs(tree) print '------------------------------------------' print "RESULT PATHS: %s\n" % '\n'.join(results) print '------------------------------------------'
def run_algos(state_dict, goal, board): entry = {} clear_dict(entry) #BFS sys.stdout.write("Generating stats for BFS..") for x in range(1, 21): result = bfs(Node(state_dict[x], goal, None, None, 0, 0), board, verbose=False) if result.verdict == "success": entry[x]["time"] = result.elapsed_time entry[x]["nodes"] = result.gen_nodes entry[x]["cost"] = result.node.path_cost sys.stdout.write(f" #{x},") else: entry[x]["time"] = 0.0 entry[x]["nodes"] = 0 entry[x]["cost"] = 0 sys.stdout.write(f" #{x}(F),") print("") write_file(entry, "bfs") clear_dict(entry) #DLS sys.stdout.write("Generating stats for DLS..") for x in range(1, 21): result = dls(Node(state_dict[x], goal, None, None, 0, 0), board, x+1, verbose=False) if result.verdict == "success": entry[x]["time"] = result.elapsed_time entry[x]["nodes"] = result.gen_nodes entry[x]["cost"] = result.node.path_cost sys.stdout.write(f" #{x},") else: entry[x]["time"] = 0.0 entry[x]["nodes"] = 0 entry[x]["cost"] = 0 sys.stdout.write(f" #{x}(F),") print("") write_file(entry, "dls") clear_dict(entry) #IDS sys.stdout.write("Generating stats for IDS..") for x in range(1, 21): result = ids(Node(state_dict[x], goal, None, None, 0, 0), board, 0, verbose=False) if result.verdict == "success": entry[x]["time"] = result.elapsed_time entry[x]["nodes"] = result.gen_nodes entry[x]["cost"] = result.node.path_cost sys.stdout.write(f" #{x},") else: entry[x]["time"] = 0.0 entry[x]["nodes"] = 0 entry[x]["cost"] = 0 sys.stdout.write(f" #{x}(F),") print("") write_file(entry, "ids") clear_dict(entry) #UCS sys.stdout.write("Generating stats for UCS..") for x in range(1, 21): result = ucs(NodeGCost(state_dict[x], goal, None, None, 0, 0), board, verbose=False) if result.verdict == "success": entry[x]["time"] = result.elapsed_time entry[x]["nodes"] = result.gen_nodes entry[x]["cost"] = result.node.path_cost sys.stdout.write(f" #{x},") else: entry[x]["time"] = 0.0 entry[x]["nodes"] = 0 entry[x]["cost"] = 0 sys.stdout.write(f" #{x}(F),") print("") write_file(entry, "ucs") clear_dict(entry) #GBFS sys.stdout.write("Generating stats for GBFS..") for x in range(1, 21): result = gbfs(Node(state_dict[x], goal, None, None, 0, 0), board, verbose=False) if result.verdict == "success": entry[x]["time"] = result.elapsed_time entry[x]["nodes"] = result.gen_nodes entry[x]["cost"] = result.node.path_cost sys.stdout.write(f" #{x},") else: entry[x]["time"] = 0.0 entry[x]["nodes"] = 0 entry[x]["cost"] = 0 sys.stdout.write(f" #{x}(F),") print("") write_file(entry, "gbfs") clear_dict(entry) #ASTAR sys.stdout.write("Generating stats for A*..") for x in range(1, 21): result = a_star(NodeFCost(state_dict[x], goal, None, None, 0, 0), board, verbose=False) if result.verdict == "success": entry[x]["time"] = result.elapsed_time entry[x]["nodes"] = result.gen_nodes entry[x]["cost"] = result.node.path_cost sys.stdout.write(f" #{x},") else: entry[x]["time"] = 0.0 entry[x]["nodes"] = 0 entry[x]["cost"] = 0 sys.stdout.write(f" #{x}(F),") print("") write_file(entry, "astar") clear_dict(entry)
# plt.close() plt.imshow(255-dst,'gray'),plt.plot(path_x,path_y,'--r') #,plt.title('RESULT (%d,%d)->(%d,%d)'%(start[0],start[1],goal[0],goal[1])) #plt.show() plt.savefig('output/m2_dst_p') ''' # 设置起点和目标点 (height,width)=(dst.shape[0],dst.shape[1]) start = (height//2, 0) goal = (height//2, width-1) # 使用路径规划算法寻找路径 time_0 = time.perf_counter() (path1,lps1) = alg.bfs(dst, start, goal) elapsed = (time.perf_counter() - time_0) print("BFS Time used:",elapsed) print('path length: %d'%(len(path1)-1)) print('orgi_',np.sum(org==0)) #print('mask_',np.sum(mask1!=0)) # mutils.save_video(filename='output/video%d_bfs.mp4'%i,roadmap=org, path=path1, start=start, goal=goal, show_ani=not flags['save_video'],alg='BFS') # mutils.save_video(filename='output/fig%d_bfs.png'%i,roadmap=org, path=path1, start=start, goal=goal, show_ani=flags['save_video'],alg='BFS') time_0 = time.perf_counter() (path2,lps2) = alg.astar(dst, start, goal) elapsed = (time.perf_counter() - time_0) print("A* Time used:",elapsed) print('path length: %d'%(len(path2)-1)) print('orgi_',np.sum(org==0)) #print('mask_',np.sum(mask2!=0))
def main(): parser = argparse.ArgumentParser() parser.add_argument('-size', type=str, default='121x97', help='size of the maze, e.g. 101x81.') parser.add_argument('-margin', type=int, default=2, help='border of the maze') parser.add_argument('-scale', type=int, default=5, help='size of a cell in pixels') parser.add_argument( '-loop', type=int, default=0, help='number of loops of the animation, default to 0 (loop infinitely)' ) parser.add_argument( '-depth', type=int, default=8, help='an interger beteween 2-8 represents the color depth of the image,\ this parameter determines the size of the global color table.' ) parser.add_argument('-filename', type=str, default='wilson.gif', help='output file name') args = parser.parse_args() width, height = [int(i) for i in args.size.split('x')] # define your favorite global color table here. mypalette = [0, 0, 0, 200, 200, 200, 255, 0, 255] # GIF files allows at most 256 colors in the global color table, # redundant colors will be discarded when the encoder is initialized. for i in range(256): rgb = hls_to_rgb((i / 360.0) % 1, 0.5, 1.0) mypalette += [int(round(255 * x)) for x in rgb] # ---------- enable mask image here ---------- # you may use a binary image instance of PIL's Image class here as the mask image, # this image must preserve the connectivity of the grid graph. # uncommnt the following two lines and use this mask in the `init` functon of `maze` below. #from gentext import generate_text_mask #mask = generate_text_mask(width, height, 'UST', '../../resources/ubuntu.ttf', 60) # -------------------------------------------- maze = Maze(width, height, args.margin, mask=None) canvas = maze.add_canvas( scale=args.scale, #offsets=(65, 112, 45, 107), offsets=(0, 0, 0, 0), depth=args.depth, palette=mypalette, loop=args.loop, filename=args.filename) # ---- insert a specified background image here ---- # How to insert the gif animation into another image: # 1. uncommnt the following two lines. # 2. in calling `maze.add_canvas` above, set the offsets # to put the animation at a suitable place. #canvas.insert_background_image('teacher.png') #canvas.pad_delay_frame(delay=100) # -------------------------------------------------- # If there is no background image then we need to paint the blank background # because the region that has not been covered by any frame will be set to # transparent by decoders. Comment out this line and watch the result if you # don't understand this. canvas.paint_background(wall_color=0) # pad one second delay, get ready! canvas.pad_delay_frame(delay=100) # you may adjust the `speed` parameter for different algorithms. canvas.set_control_params(delay=2, speed=50, trans_index=3, wall_color=0, tree_color=1, path_color=2) start = (args.margin, args.margin) end = (width - args.margin - 1, height - args.margin - 1) # the maze generation animation. # try prim(maze, start) or kruskal(maze) or random_dfs(maze) here! wilson(maze, start) # pad three seconds delay to help to see the resulting maze clearly. canvas.pad_delay_frame(delay=300) # in the path finding animation the walls are unchanged throughout, # hence it's safe to use color 0 as the transparent color. canvas.set_control_params(delay=5, speed=30, trans_index=0, wall_color=0, tree_color=0, path_color=2, fill_color=3) # the maze solving animation. # try dfs(maze, start, end) or astar(maze, start, end) here! bfs(maze, start, end) # pad five seconds delay to help to see the resulting path clearly. canvas.pad_delay_frame(delay=500) # finally finish the animation and close the file. canvas.save()
def move(): data = {} time_remaining = [150] # leave 50ms for network position = None path = None next_move = list() thread_pool = list() potential_snake_positions = list() direction = None with timing("bottle", time_remaining): data = bottle.request.json try: with timing("data parsing", time_remaining): board = Board(**data) snake = board.get_snake(data['you']) direction = general_direction(board, snake.head, snake.attributes['health_points']) move = direction # fallback for enemy_snake in board.snakes: if enemy_snake.attributes['id'] != snake.attributes[ 'id']: # and enemy_snake.attributes['health_points'] >= snake.attributes['health_points']: potential_snake_positions.extend([ position for position in enemy_snake.potential_positions() if board.inside(position) ]) number_of_squares = list() # find number of empty squares in every direction. for cell in neighbours(snake.head): if board.inside(cell): count = len(flood_fill(board, cell, False)) number_of_squares.append((cell, count)) if count <= 10: potential_snake_positions.append(cell) if number_of_squares[0][1] <= 10 and number_of_squares[1][ 1] <= 10 and number_of_squares[2][ 1] <= 10 and number_of_squares[3][1] <= 10: largest = reduce( lambda carry, direction: carry if carry[1] > direction[1] else direction, number_of_squares, number_of_squares[0]) potential_snake_positions.remove(largest[0]) print potential_snake_positions with timing("need_food", time_remaining): food = need_food(board, snake.head, snake.attributes['health_points']) if food: #if snake.attributes['health_points'] < 30: #potential_snake_positions = [] with timing("find_food", time_remaining): food_positions = find_food(snake.head, snake.attributes['health_points'], board, food) positions = [position[0] for position in food_positions] # positions = list(set([ position[0] for position in food_positions ]) - set(potential_snake_positions)) print positions print[board.get_cell(position) for position in positions] for position in positions: t = Thread( target=bfs(snake.head, position, board, potential_snake_positions, next_move)) t = Thread( target=bfs(snake.head, position, board, [], next_move)) thread_pool.append(t) for thread in thread_pool: thread.start() thread.join() next_move = filter(lambda path: not len(path) == 0, next_move) path = min(next_move, key=len) move = get_direction(snake.head, path[0]) else: #with timing("flood_fill", time_remaining): # flood_fill(board.vacant, snake.head, True) with timing("find_safest_position", time_remaining): positions = find_safest_position(snake.head, direction, board) positions = [position[0] for position in positions] # positions = list(set([position[0] for position in positions]) - set(potential_snake_positions)) print positions print[board.get_cell(position) for position in positions] for position in positions: t = Thread( target=bfs(snake.head, position, board, potential_snake_positions, next_move)) t = Thread( target=bfs(snake.head, position, board, [], next_move)) thread_pool.append(t) for thread in thread_pool: thread.start() thread.join() path = max(next_move, key=len) move = get_direction(snake.head, path[0]) except Exception as e: print "WTF", e.message print next_move print path print move if len(next_move) == 0: print "CHANGING MOVE" with timing("floodfill", time_remaining): floods = { "up": len(flood_fill(board, (snake.head[0], snake.head[1] - 1))), "down": len(flood_fill(board, (snake.head[0], snake.head[1] + 1))), "right": len(flood_fill(board, (snake.head[0] + 1, snake.head[1]))), "left": len(flood_fill(board, (snake.head[0] - 1, snake.head[1]))) } move = max(floods.iterkeys(), key=(lambda key: floods[key])) # don't be stupid m_move = add(snake.head, DIR_VECTORS[DIR_NAMES.index(move)]) if board.inside(m_move) and board.get_cell(m_move) == 1: print "CHANGING MOVE" for direction in DIR_NAMES: m_move = add(snake.head, DIR_VECTORS[DIR_NAMES.index(direction)]) if board.inside(m_move) and board.get_cell(m_move) != 1: move = direction print "moving", move return {'move': move, 'taunt': random.choice(TAUNTS)}