def __init__(self, game, ai_information): self.game = game # Capture AI settings that the user specified search_type = ai_information[0] search_strategy = ai_information[1] # Set the strategy to use to search with if search_strategy == "bfs": search_strategy = BFS() elif search_strategy == "dfs": search_strategy = DFS() elif search_strategy == "astar": search_strategy = AStar(ai_information[2]) elif search_strategy == "idastar": self.search_strategy = IDAStar(game.board, ai_information[2]) else: raise Exception('Invalid search stategy') if search_strategy == "idastar": pass elif (search_type == "tree-search"): self.search_strategy = TreeSearch(game.board, search_strategy) elif (search_type == "graph-search"): self.search_strategy = GraphSearch(game.board, search_strategy) else: raise Exception('Invalid search type')
def puzzle(args): start = Puzzle(np.array([4, 3, 6, 8, 2, 7, 5, 1, 0])) goal = Puzzle(np.array([8, 1, 2, 7, 0, 3, 6, 5, 4])) path = BFS(start, goal) for s in path: print(s[1].board.reshape((3, 3))) if s[0]: print("ACTION: ", s[0])
def main(): test_case_1 = ["CDE", "CFG", "EHE", "EIJ", "GHK", "GLC"] test_case_2 = ["CDE", "CFG", "EHI", "GJC", "GKG"] root_node_1 = geography_node(test_case_1, words_added=["ABC"], name="root") print("BFS of Test Case 1:") print("Result of BFS on Test Case 1: %s, nodes visited: %d\n" % (BFS(root_node_1, node_count_max=128))) print("DFS of Test Case 1:") print("Result of DFS on Test Case 1: %s, nodes visited: %d\n" % (DFS(root_node_1, node_count_max=128))) root_node_2 = geography_node(test_case_2, words_added=["ABC"], name="root") print("BFS of Test Case 2:") print("Result of BFS on Test Case 2: %s, nodes visited: %d\n" % (BFS(root_node_2, node_count_max=128))) print("DFS of Test Case 2:") print("Result of DFS on Test Case 2: %s, nodes visited: %d\n" % (DFS(root_node_2, node_count_max=128)))
def means_end(args): start_state = MeansEndState({ ROBOT: { LOCATION: LIVING_ROOM, HOLDS: NONE }, PERSON: { LOCATION: LIVING_ROOM, HOLDS: NONE }, GLASS: { LOCATION: CUPBOARD, HOLDS: NONE }, SODA: { LOCATION: FRIDGE, HOLDS: NONE }, KITCHEN_DOOR: CLOSED, FRIDGE_DOOR: CLOSED, CUPBOARD_DOOR: CLOSED }) goal_state = MeansEndState({ ROBOT: { LOCATION: LIVING_ROOM, HOLDS: NONE }, PERSON: { LOCATION: LIVING_ROOM, HOLDS: GLASS }, GLASS: { LOCATION: LIVING_ROOM, HOLDS: SODA }, SODA: { LOCATION: LIVING_ROOM, HOLDS: NONE }, KITCHEN_DOOR: CLOSED, FRIDGE_DOOR: CLOSED, CUPBOARD_DOOR: CLOSED }) path = BFS(start_state, goal_state) for s in path: if s[0]: print(s[0])
def get_search(self): print "================================" print "Choose a Search Method:" print "================================" print "1. Depth First Search" print "2. Breadth First Search" print "3. A* Heuristic Search" search_input = int(raw_input("Enter search choice: => ")) if search_input is -1: return elif search_input is 1: self.search = DFS() elif search_input is 2: self.search = BFS() elif search_input is 3: self.search = AS()
def BFS1(): pygame.init() screen = Screen() screen.set_start(126, 276) screen.set_obstacle(200, 191) screen.set_obstacle(201, 270) screen.set_obstacle(194, 357) screen.set_obstacle(195, 459) screen.set_obstacle(118, 363) screen.set_obstacle(267, 196) screen.set_obstacle(354, 192) screen.set_obstacle(432, 193) screen.set_obstacle(508, 194) screen.set_obstacle(270, 447) screen.set_end(272, 286) screen.draw() pygame.display.flip() pygame.display.set_caption('BFS:press space to step the search') search = BFS(screen) # BFS while True: for event in pygame.event.get(): if event.type == locals.QUIT or (event.type == locals.KEYUP and event.key == locals.K_ESCAPE): pygame.quit() return 1 elif event.type == locals.KEYUP and event.key == locals.K_SPACE and not search.over: search.step() screen.draw_BFS() pygame.display.flip() elif (event.type == locals.KEYUP and event.key == locals.K_SPACE) and search.over: search.setroad() screen.draw_BFS() pygame.display.flip() search.displaystep()
for n in range(3,nEnd+1,2): print('Size of Puzzle: n =', n) puzzle = nPuzzleGraph(n) puzzleValued = nPuzzleGraphValued(n) for i in range(NumIterations): print('Iteration', i) initState = gen_state(n) initState = State(initState) puzzle.setInitialState(initState) puzzleValued.setInitialState(initState) start = timeit.default_timer() BFS(puzzle, puzzle.initialState) end = timeit.default_timer() sumBFS += end - start start = timeit.default_timer() UCS(puzzleValued, puzzleValued.initialState) end = timeit.default_timer() sumUCS += end - start start = timeit.default_timer() DFS(puzzle, puzzle.initialState) end = timeit.default_timer() sumDFS += end - start start = timeit.default_timer() DLS(puzzle, puzzle.initialState, DEPTHLIMIT)
def main(): """Main method that is run. Main method that takes command line arguments and performs given operation/s. """ from argparse import ArgumentParser from data_loader import get_state_space, get_heuristic from search import BFS, UCS, DFS, lDFS, IDS, GBFS, HCS, AStar from heuristic_check import is_optimistic, is_consistent from puzzle_heuristic import manhattan_distance parser = ArgumentParser( 'run specified search algorithm on a given state space') parser.add_argument('ss', type=str, help='path to a state space to use') parser.add_argument( '-a', '--algorithm', type=str, choices=['bfs', 'ucs', 'dfs', 'ldfs', 'ids', 'gbfs', 'hcs', 'astar'], help='state space search algoritm to use') parser.add_argument('-d', '--depth', type=int, help='maximum depth for the limited DFS') parser.add_argument('-e', '--heuristic', type=str, help='heuristic to use: [path, \'l1\']') parser.add_argument('-c', '--check', action='store_true', help="run checks on heuristic") args = parser.parse_args() s0, transitions, goal = get_state_space(args.ss) heuristic = None if args.heuristic: if args.heuristic == 'l1': heuristic = manhattan_distance(goal) else: heuristic = get_heuristic(args.heuristic) if args.algorithm: if args.algorithm == 'bfs': BFS(s0, transitions, goal) elif args.algorithm == 'ucs': UCS(s0, transitions, goal) elif args.algorithm == 'dfs': DFS(s0, transitions, goal) elif args.algorithm == 'ldfs': if args.depth: lDFS(s0, transitions, goal, args.depth) else: print('Maximum depth not provided.') elif args.algorithm == 'ids': IDS(s0, transitions, goal) elif heuristic: if args.algorithm == 'gbfs': GBFS(s0, transitions, goal, heuristic) elif args.algorithm == 'hcs': HCS(s0, transitions, heuristic) elif args.algorithm == 'astar': AStar(s0, transitions, goal, heuristic) else: print('Invalid algorithm.') else: print('No heuristic provided.') if args.check: if heuristic: print('Checking heuristic') is_optimistic(heuristic, transitions, goal) is_consistent(heuristic, transitions) else: print('No heuristic provided.')
from search import BFS import numpy as np arr = np.array([[1, 2, 3], [4, 5, 0], [7, 8, 6]]) a = BFS(arr) a.search()
from search import BFS import numpy as np from state import * if __name__ == '__main__': print('Witaj') arr = np.array([[1, 2, 3], [4, 5, 0], [7, 8, 6]], dtype=np.uint8) state = State(arr, None, None, None, None) print(hash(state)) A = BFS(arr) A.search() # a = BFS(arr) # a.search()
def rungame(layout, agent, render): game = GameState(layout) print("INITIAL INFORMATION OF MAZE") game.show_information() # LOAD IMAGE PATH backdrop_path, floor_path, wall_path, key_path, gate_path, trap_path, stair_path, explorer_path, \ mummy_white_path, mummy_red_path, scorpion_white_path, scorpion_red_path, white_fight_path, \ red_fight_path = load_image_path(game.maze_size) # LOAD IMAGE backdrop = pygame.image.load(backdrop_path) floor = pygame.image.load(floor_path) stair = graphics.stairs_spritesheet(stair_path) trap = graphics.trap_spritesheet(trap_path) key = graphics.key_spritesheet(key_path) gate = graphics.gate_spritesheet(gate_path) wall = graphics.wall_spritesheet(wall_path, game.maze_size) explorer_sheet = graphics.character_spritesheet(explorer_path) mummy_white_sheet = graphics.character_spritesheet(mummy_white_path) mummy_red_sheet = graphics.character_spritesheet(mummy_red_path) scorpion_white_sheet = graphics.character_spritesheet(scorpion_white_path) scorpion_red_sheet = graphics.character_spritesheet(scorpion_red_path) # GAME explorer = { "sprite_sheet": explorer_sheet, "coordinates": Cal_coordinates(game, game.explorer_position[0], game.explorer_position[1]), "direction": game.explorer_direction, "cellIndex": 0 } list_mummy_white = [] for i in range(len(game.mummy_white_position)): mummy_white = { "sprite_sheet": mummy_white_sheet, "coordinates": Cal_coordinates(game, game.mummy_white_position[i][0], game.mummy_white_position[i][1]), "direction": game.mummy_white_direction[i], "cellIndex": 0 } list_mummy_white.append(mummy_white) list_mummy_red = [] for i in range(len(game.mummy_red_position)): mummy_red = { "sprite_sheet": mummy_red_sheet, "coordinates": Cal_coordinates(game, game.mummy_red_position[i][0], game.mummy_red_position[i][1]), "direction": game.mummy_red_direction[i], "cellIndex": 0 } list_mummy_red.append(mummy_red) list_scorpion_white = [] for i in range(len(game.scorpion_white_position)): scorpion_white = { "sprite_sheet": scorpion_white_sheet, "coordinates": Cal_coordinates(game, game.scorpion_white_position[i][0], game.scorpion_white_position[i][1]), "direction": game.scorpion_white_direction[i], "cellIndex": 0 } list_scorpion_white.append(scorpion_white) list_scorpion_red = [] for i in range(len(game.scorpion_red_position)): scorpion_red = { "sprite_sheet": scorpion_red_sheet, "coordinates": Cal_coordinates(game, game.scorpion_red_position[i][0], game.scorpion_red_position[i][1]), "direction": game.scorpion_red_direction[i], "cellIndex": 0 } list_scorpion_red.append(scorpion_red) if render: # SET SCREEN pygame.init() window = pygame.display.set_mode( (game.screen_size_x, game.screen_size_y)) pygame.display.set_caption("Mummy Maze") # SET FPS FPS = 30 clock = pygame.time.Clock() graphics.draw_screen(window, game.maze, backdrop, floor, game.maze_size, game.cell_rect, stair, game.stair_position, trap, game.trap_position, key, game.key_position, gate, game.gate, wall, explorer, list_mummy_white, list_mummy_red, list_scorpion_white, list_scorpion_red) pygame.display.update() explorer_character = characters.Explorer(game.explorer_position[0], game.explorer_position[1]) mummy_white_character = [] if game.mummy_white_position: for i in range(len(game.mummy_white_position)): mummy_white_character.append( characters.mummy_white(game.mummy_white_position[i][0], game.mummy_white_position[i][1])) mummy_red_character = [] if game.mummy_red_position: for i in range(len(game.mummy_red_position)): mummy_red_character.append( characters.mummy_red(game.mummy_red_position[i][0], game.mummy_red_position[i][1])) scorpion_white_character = [] if game.scorpion_white_position: for i in range(len(game.scorpion_white_position)): scorpion_white_character.append( characters.scorpion_white(game.scorpion_white_position[i][0], game.scorpion_white_position[i][1])) scorpion_red_character = [] if game.scorpion_red_position: for i in range(len(game.scorpion_red_position)): scorpion_red_character.append( characters.scorpion_red(game.scorpion_red_position[i][0], game.scorpion_red_position[i][1])) if agent == "SearchAgent": print("FINDING SOLUTION ...") ans = BFS(explorer_character, mummy_white_character, mummy_red_character, scorpion_white_character, scorpion_red_character, game.gate, game.trap_position, game.key_position, game.maze) for i in range(len(ans) - 2, -1, -1): if ans[i][0] == ans[i + 1][0] - 2 and ans[i][1] == ans[i + 1][1]: explorer["direction"] = "UP" if ans[i][0] == ans[i + 1][0] + 2 and ans[i][1] == ans[i + 1][1]: explorer["direction"] = "DOWN" if ans[i][0] == ans[i + 1][0] and ans[i][1] == ans[i + 1][1] - 2: explorer["direction"] = "LEFT" if ans[i][0] == ans[i + 1][0] and ans[i][1] == ans[i + 1][1] + 2: explorer["direction"] = "RIGHT" if ans[i][0] != ans[i + 1][0] or ans[i][1] != ans[i + 1][1]: explorer_character.move( ans[i][0], ans[i][1], render, window, game, backdrop, floor, stair, game.stair_position, trap, game.trap_position, key, game.key_position, gate, game.gate, wall, explorer, list_mummy_white, list_mummy_red, list_scorpion_white, list_scorpion_red) print("Explorer position: {} {}".format( explorer_character.get_x(), explorer_character.get_y())) isEnd = update_enemy_position( window, render, game, backdrop, floor, stair, trap, key, gate, wall, explorer, explorer_character, mummy_white_character, mummy_red_character, scorpion_white_character, scorpion_red_character, list_mummy_white, list_mummy_red, list_scorpion_white, list_scorpion_red) if isEnd: print("NUMBER STEP: {}".format(len(ans) - 1)) break isEnd = False render = True while agent == "KeyboardAgent" and not isEnd: explorer_x = explorer_character.get_x() explorer_y = explorer_character.get_y() explorer_new_x = explorer_x explorer_new_y = explorer_y for event in pygame.event.get(): if event.type == pygame.QUIT: isEnd = True if event.type == pygame.KEYDOWN: if event.key == pygame.K_UP: if explorer_character.eligible_character_move( game.maze, game.gate, explorer_x, explorer_y, explorer_x - 2, explorer_y): explorer_new_x -= 2 explorer["direction"] = "UP" if event.key == pygame.K_DOWN: if explorer_character.eligible_character_move( game.maze, game.gate, explorer_x, explorer_y, explorer_x + 2, explorer_y): explorer_new_x += 2 explorer["direction"] = "DOWN" if event.key == pygame.K_LEFT: if explorer_character.eligible_character_move( game.maze, game.gate, explorer_x, explorer_y, explorer_x, explorer_y - 2): explorer_new_y -= 2 explorer["direction"] = "LEFT" if event.key == pygame.K_RIGHT: if explorer_character.eligible_character_move( game.maze, game.gate, explorer_x, explorer_y, explorer_x, explorer_y + 2): explorer_new_y += 2 explorer["direction"] = "RIGHT" if event.key == pygame.K_SPACE: pass if explorer_x != explorer_new_x or explorer_y != explorer_new_y: explorer_character.move( explorer_new_x, explorer_new_y, render, window, game, backdrop, floor, stair, game.stair_position, trap, game.trap_position, key, game.key_position, gate, game.gate, wall, explorer, list_mummy_white, list_mummy_red, list_scorpion_white, list_scorpion_red) print("Explorer position: {} {}".format( explorer_character.get_x(), explorer_character.get_y())) isEnd = update_enemy_position( window, render, game, backdrop, floor, stair, trap, key, gate, wall, explorer, explorer_character, mummy_white_character, mummy_red_character, scorpion_white_character, scorpion_red_character, list_mummy_white, list_mummy_red, list_scorpion_white, list_scorpion_red) if isEnd: break
def heuristicGraph(state): if state == 0: return 5 if state == 1: return 4 if state == 2: return 4 if state == 3: return 2 if state == 4: return 2 if state == 5: return 0 graph = SimpleGraph() graphValued = SimpleValuedGraph() print('---------Graph----------') print('BFS:', BFS(graph, 0)) print('DFS:', DFS(graph, 0)) print('IDS:', IDS(graph, 0)) print('DLS:', DLS(graph, 0, 3)) print('UCS:', UCS(graphValued, 0)) print('Astar:', A_star(graphValued, 0, heuristicGraph)) #MCTS(graphValued,0,100) def heuristicPuzzle(state): heuristic = 0 goalState = [1,2,3,4,5,6,7,8,0]
#Not the end of the txt if x[j] is not "\n": #Fill the board map if x[j] == "X": board[(i, j)] = x[j] goalsPos[(i, j)] = x[j] numGoals += 1 j += 1 else: board[(i, j)] = x[j] j += 1 #Next character else: j += 1 #Not the end of the txt else: if x is not "\n" and boxFlg == False: player.append(int(x[0])) player.append(int(x[2])) boxFlg = True elif x is not "\n" and boxFlg == True: boxesPos.append([int(x[0]), int(x[2])]) #next line i += 1 read_level(sys.argv[1]) print(DFS(board, player, goalsPos, boxesPos)) print(BFS(board, player, goalsPos, boxesPos)) print(IDFS(board, player, goalsPos, boxesPos))
from search import DFS, BFS from queueG import Queue from graph import Node root = Node(1) b = Node(3) c = Node(4) d = Node(10) e = Node(11) root.addNeighbor(b) # There's a better way b.addNeighbor(root) b.addNeighbor(e) e.addNeighbor(b) root.addNeighbor(c) c.addNeighbor(root) c.addNeighbor(d) d.addNeighbor(c) #print("DFS: ") #DFS(root) print("BFS: ") BFS(root)