def main():
    arrows, end_img, home_img = loadFiles()
    running = True
    g = grid(WIDTH, HEIGHT)
    # g.walls.append(vec(5, 5))
    start = vec(3, 20)
    end = vec(30, 2)

    path = AStar(g, start, end)
    astar = True
    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_SPACE:
                    if astar:
                        astar = False
                    else:
                        astar = True

            if event.type == pygame.MOUSEBUTTONDOWN:
                pos = vec(pygame.mouse.get_pos()) // GRIDHEIGHT
                if event.button == 1:
                    if pos not in g.walls:
                        g.walls.append(pos)
                    else:
                        g.walls.remove(pos)
                elif event.button == 3:
                    end = pos
                elif event.button == 2:
                    start = pos
            if astar:
                path = AStar(g, start, end)
            else:
                path = Dijkstra(g, start, end)

        screen.fill((0, 0, 0))
        g.drawGrid(screen)
        g.drawWalls(screen)
        for node in path:
            x, y = node
            rect = pygame.Rect(x * GRIDWIDTH, y * GRIDHEIGHT, GRIDWIDTH,
                               GRIDHEIGHT)
            pygame.draw.rect(screen, (30, 30, 30), rect)
        if vec2tuple(start) in path:
            current = start + path[vec2tuple(start)]
        while current != end:
            x = current.x * GRIDWIDTH + GRIDWIDTH / 2
            y = current.y * GRIDHEIGHT + GRIDHEIGHT / 2
            a = vec2tuple(path[(current.x, current.y)])
            img = arrows[a]
            screen.blit(img, img.get_rect(center=(x, y)))
            current = current + path[vec2tuple(current)]
        g.drawGrid(screen)
        g.draw_icons(screen, start, end, end_img, home_img)
        pygame.display.flip()
    pygame.quit()
Esempio n. 2
0
def selectMethod(solver):
    print("1 - Backtracking")
    print("2 - Breadth First Search")
    print("3 - Depth First Search (limited)")
    print("4 - Ordered Search")
    print("5 - Greed Search")
    print("6 - A* Search")
    print("7 - IDA* Search")

    o = int(input("> "))
    enterObjective()
    if o == 1:
        solver = Backtracking(start, end)
    if o == 2:
        solver = Solver()  #BreadthFirst(start, end)
    if o == 3:
        solver = DepthFirst(start, end)
    if o == 4:
        solver = OrderedSearch(start, end)
    if o == 5:
        solver = GreedySearch(start, end)
    if o == 6:
        solver = AStar(start, end)
    if o == 7:
        solver = Solver()

    return solver
Esempio n. 3
0
    def initMap(self, w, h):
        self.mapdata = []
        self.mapw = w
        self.maph = h
        self.startpoint = [1, h / 2]
        self.endpoint = [w - 2, h / 2]
        self.current_location = AStar.SQ_Location(
            self.startpoint[0], self.startpoint[1]
        )  #Initializes the current location as the starting point
        self.next_location = deepcopy(self.current_location)
        size = w * h
        for i in range(size):
            #Alternates color, to easily visualize the grid
            if i % 2 == 0:
                self.mapdata.append(1)
            else:
                self.mapdata.append(2)

        self.mapdata[(self.startpoint[1] * w) + self.startpoint[0]] = 5
        self.mapdata[(self.endpoint[1] * w) + self.endpoint[0]] = 6
        """Create a copy of the initial configuration of the map """
        self.initial_mapdata = deepcopy(self.mapdata)
        self.maprect = Rect(0, 0, w * 32,
                            h * 32)  #each small cell is 32 pix size.
        """init astar planner """
        """first the map"""
        self.astar = AStar.AStar(
            AStar.SQ_MapHandler(self.mapdata, self.mapw, self.maph))
        """init the start and end positions"""
        start = AStar.SQ_Location(self.startpoint[0], self.startpoint[1])
        end = AStar.SQ_Location(
            self.endpoint[0],
            self.endpoint[1])  #SQ means "square" map location
        self.astar.start(start, end)
Esempio n. 4
0
    def Run(self):
        f = open("de.txt", "w")
        gridSize = self.gridSize
        mat = [[0 for i in range(gridSize)] for j in range(gridSize)]
        for i in range(gridSize):
            for j in range(gridSize):
                if self.canvas.itemcget(self.grid[i][j], "fill") == 'black':
                    mat[i][j] = 1
                f.write(str(mat[i][j]))
                f.write(" ")
            f.write("\n")

        si = self.startNode.pos.i
        sj = self.startNode.pos.j
        gi = self.goalNode.pos.i
        gj = self.goalNode.pos.j

        if self.str_algo != "ARA*":
            myMap = algo.Map()
            myMap.create(gridSize, mat, si, sj, gi, gj)
            flagFind = algo.AStar(myMap, self)

            if flagFind:
                res = self.tracking(myMap)
                messagebox.showinfo("Message", "Complete finding path")
            else:
                messagebox.showinfo("Message", "No path!")
        else:
            myMap = ara.Map()
            myMap.create(gridSize, mat, si, sj, gi, gj)

            ara.ARA(myMap, 2.5, 0.5, self)
            messagebox.showinfo("Message", "Complete finding path")

        f.close()
Esempio n. 5
0
def h1h2():
    for i in range(10):
        table = Input.Input(1)
        print("h1(n):", end=' ')
        test = AStar.AStar(table, 1)
        time_start = time.time()
        test.run()
        time_end = time.time()
        print('Cost:', time_end - time_start, 's')

        print("h2(n):", end=' ')
        test = AStar.AStar(table, 2)
        time_start = time.time()
        test.run()
        time_end = time.time()
        print('Cost:', time_end - time_start, 's')
Esempio n. 6
0
def main():

    if len(sys.argv) == 2:
        configFileName = sys.argv[1]
    else:
        configFileName = "freeworld.config"

    cfgReader = ConfigFileReader.ConfigFileReader(configFileName)

    ret, height, width, numRobots, R, baseX, baseY, initLocs, obstacles = cfgReader.readCfg(
    )
    if ret == -1:
        print 'readCfg() Unsuccessful!'
        sys.exit(-1)
    else:
        print 'Read the config file', configFileName

    k = 2
    T = 100000

    algo = CommExplore.CommExplore(height, width, obstacles, numRobots,
                                   initLocs, T)

    astar = AStar.AStar()

    path, cost = astar.aStarSearch(algo.gridworld, (0, 0), (6, 6))
    cost = cost[(6, 6)]
    print 'cost:', cost
Esempio n. 7
0
 def __init__(self, spieler, spiel):
     self.debug = False
     self.spiel = spiel
     self.spieler = spieler
     spieler.ki = self
     self.spielfeld = spiel.spielfeld
     self.searchalgorithm = AStar.AStar(self.spieler, self.spielfeld,
                                        spiel.wetter)
Esempio n. 8
0
def openHere(startState):

    goal = (startState[0], startState[1], startState[2], 1)

    startNode = CSpace.CSpaceNode(*CSpace.stateToCspace(*startState), [])
    endNode = CSpace.CSpaceNode(*CSpace.stateToCspace(*goal), [])

    return AStar.AStar(startNode, [endNode])
Esempio n. 9
0
def travel(startState, endState):

    startNode = CSpace.CSpaceNode(*CSpace.stateToCspace(*startState),
                                  [checkNoCollision])
    endNode = CSpace.CSpaceNode(*CSpace.stateToCspace(*endState),
                                [checkNoCollision])

    return AStar.AStar(startNode, [endNode])
Esempio n. 10
0
    def __init__(self,
                 height,
                 width,
                 obstacles,
                 numRobots,
                 initLocs,
                 R=10,
                 k=10,
                 T=10,
                 base=[0, 0]):

        # Initialize the grid world
        self.gridworld = GridWorld.GridWorld(height, width, obstacles)

        # Initialize a list of robots
        self.robots = [Robot.Robot(j + 1, -1, -1) for j in range(numRobots)]
        # Initialize the starting location of each robot
        i = 0
        for initLoc in initLocs:
            # If any robot is placed out of bounds or on an obstacle, print an error message and exit
            currentPoint = (initLoc[0], initLoc[1])
            if not self.gridworld.inBounds(
                    currentPoint) or not self.gridworld.passable(currentPoint):
                print 'Initial location', currentPoint, 'is not possible'
                sys.exit(-1)
            # Otherwise, modify the current location of the robot to currentPoint
            self.robots[i].setLocation(initLoc[0], initLoc[1])
            # Update that particular grid cell's occupied status
            self.gridworld.cells[initLoc[0]][initLoc[1]].occupied = True
            self.gridworld.cells[initLoc[0]][initLoc[1]].visited = True
            i += 1

        # Initialize other parameters of the algorithm
        self.height = height
        self.width = width
        self.numRobots = numRobots
        self.R = R
        self.k = k
        self.T = T
        self.base = base

        # keeps track of the number of time steps elapsed
        self.t = 0
        # keeps track of the time taken to exhaust the frontier
        self.completionTime = 0
        self.completedFlag = False
        # froniter
        self.frontier = []
        # new positions of each of the robots
        self.newPos = []
        # population of configurations
        self.cfgc = []
        # keeps track of the number of stalls
        self.stalls = 0

        # We also initialize an instance of AStar, which helps us in computing Manhattan distance
        self.astar = AStar.AStar()
Esempio n. 11
0
    def Execute(self):
        #Tell the agent to calculate the path
        print('executing pathfinding state')

        #TODO: Take the maze from the parent agent class and calculate a map
        self.agent.path = AStar(self.agent.world, (self.agent.x, self.agent.y),
                                self.agent.target)

        #End current state and transition to moving state
        self.fsm.transitionTo('toMoving')
Esempio n. 12
0
def travelAndOpen(startState, endXYZ):
    goals = inverseKinematics(*endXYZ)

    startNode = CSpace.CSpaceNode(*CSpace.stateToCspace(*startState),
                                  [checkNoCollision])
    endNodes = [
        CSpace.CSpaceNode(*CSpace.stateToCspace(*g, 1), [checkNoCollision])
        for g in goals
    ]

    return AStar.AStar(startNode, endNodes)
Esempio n. 13
0
def travelKeepClosed(startState, endXYZ):
    goals = inverseKinematics(*endXYZ)

    startNode = CSpace.CSpaceNode(*CSpace.stateToCspace(*startState),
                                  [checkNoCollision, checkStillClosed])
    endNodes = [
        CSpace.CSpaceNode(*CSpace.stateToCspace(*g, 0),
                          [checkNoCollision, checkStillClosed]) for g in goals
    ]

    return AStar.AStar(startNode, endNodes)
Esempio n. 14
0
    def getAlgo(type, Matrix, startX, startY, n, grid, size):
        if type == "DFS":
            print("DFS")
            result = DFS(Matrix, startX, startY, n - 1, n - 1, grid, n, size)

            return result
        if type == "BFS":
            return BFS(Matrix, startX, startY, n - 1, n - 1, grid, n, size)
        if type == "AStar":
            return AStar(Matrix, startX, startY, n - 1, n - 1, grid, n, size,
                         "Manhattan")
Esempio n. 15
0
def run():
    global flag, p, cost

    gui.redraw(height, width, cellSize, initializer.gridworld)

    if algoflag == 1:
        path = BFS().search(initializer.gridworld, start, goal)
    elif algoflag == 2:
        path = Dijkstra().search(initializer.gridworld, start, goal)
    else:
        path = AStar().search(initializer.gridworld, start, goal)

    if flag == False:
        if path == True and initializer.gridworld.cells[goal[0]][
                goal[1]].visited == False:
            if algoflag == 1:
                BFS().search(initializer.gridworld, start, goal)
            elif algoflag == 2:
                Dijkstra().search(initializer.gridworld, start, goal)
            else:
                AStar().search(initializer.gridworld, start, goal)

        else:
            if algoflag == 1:
                p, explored, cost = BFS().makepath(initializer.gridworld)
            elif algoflag == 2:
                p, explored, cost = Dijkstra().makepath(initializer.gridworld)
            else:
                p, explored, cost = AStar().makepath(initializer.gridworld)
            flag = True
        gui.redraw(height, width, cellSize, initializer.gridworld)

    else:
        print('Path found!')
        print('The path is:', p)
        print('The cost is:', cost[goal])
        print('GUI will exit in:', t, 'seconds')
        time.sleep(t)
        sys.exit()

    root.after(1, run)
Esempio n. 16
0
def MainRuntime(start, goal):
    aStar = AStar(start, goal)

    loop = True
    while (loop):
        res_data = aStar.step()
        loop = res_data[0]
        if (not loop):
            if (res_data[1] == None):
                print("NOT REACHED FROM ALGORITHM")
            else:
                print_data(res_data, goal)
Esempio n. 17
0
def crunchData():
    # Get data
    data = request.get_json(force=True)
    adjacencyMatrix = data['adjacency']
    distanceMatrix = data['distance']
    start = int(data['start'])
    end = int(data['end'])

    # Find shortest path
    listOfShortestPath = AS.AStar(adjacencyMatrix, distanceMatrix, start, end)

    return jsonify(listOfShortestPath)
Esempio n. 18
0
    def run(self, prev_cost_reached=None, is_rnd=False):
        done = False
        while (not done):
            for agent in self.agents:
                if not agent.pickup:
                    continue
                agent.one_step_in_path()
                self.cost += 1
                # if prev_cost_reached:
                #     if self.cost > prev_cost_reached:
                #         return None, 10**5, done
                if agent.done_with_target():
                    if not agent.pickup.advance_pickup_state(
                            self.workers, agent.is_copy):
                        x, y = agent.pickup.target_list[0].coordinates
                        self.graph[x][y].booked = False
                        #Delivered back shelf
                        if not assign_item_to_agent(agent, self.workers):
                            agent.pickup = None
                            agent.is_carrying_shelf = False
                    if agent.pickup:
                        x, y = agent.pickup.target_list[0].coordinates
                        self.graph[x][y].booked = True
                        agent.is_carrying_shelf = agent.pickup.is_carrying_shelf(
                        )
                        agent.path = AStar(self.graph, agent)
                    else:
                        agent.path = []

            agent1, agent2 = self.agents_will_collide_next_step()
            if agent1:
                state = State(agent1, agent2, self.agents)
                if is_rnd:
                    self.crash_count += 1
                    rules = [0, 1, 2, 3, 4]
                    for j in range(0, 5):
                        i = random.randint(0, len(rules) - 1)
                        rules.pop(i)
                        ok, new_path1, new_path2 = self.can_apply_rule(
                            state, i)
                        if ok:
                            self.apply_rule(state, i, new_path1, new_path2)
                            break
                elif not self.dec_tree:
                    return state, self.cost, done
                else:
                    self.crash_count += 1
                    self.apply_tree_rule(state)

            done = not one_agent_has_pickup(self.agents)

        return None, self.cost, done
def MainRuntime(start, goal):
    for i in range(1, 30):
        loop = True
        aStar = AStar(start, goal, i)
        while (loop):

            res_data = aStar.step()
            loop = res_data[0]
            if (not loop):
                if (res_data[1] == None):
                    print("NOT REACHED FROM ALGORITHM")
                else:
                    print_data(res_data, goal, 2, i)
Esempio n. 20
0
 def __init__(self, graph, agents, workers, dec_tree=None):
     self.graph = graph
     self.agents = agents
     self.workers = workers
     self.cost = 0
     self.dec_tree = dec_tree
     self.fail_tree_rule_count = 0
     self.crash_count = 0
     for agent in self.agents:
         if agent.pickup:
             agent.path = AStar(self.graph, agent)
             agent.walking_path = [agent.pos]
     self.solve_first()
Esempio n. 21
0
def createPaths(y, x, dungeon):
    """
    Create paths
    DONE from door to door or
    TODO from path to door or
    from door to path or
    from door to dead end or
    from path to dead end
    """
    #TODO from path to door
    #TODO from door to path
    #TODO from door to dead end
    #TODO from path to dead end
    #TODO make sure every room is accessible!

    mapDataForAstar = []
    doors = []

    for rowId in range(len(dungeon)):
        for charId in range(len(dungeon[rowId])):
            if dungeon[rowId][charId] in "#RFS":  # Check that given spot is free for building
                mapDataForAstar.append(-1)
            elif dungeon[rowId][charId] == "D":  # Check if given spot is door
                if x != charId and y != rowId:
                    doors.append([charId, rowId])  # Add door to door list
                mapDataForAstar.append(1)
            else:
                mapDataForAstar.append(1)

    # ---- Begin path finding -----
    astar = AStar.AStar(AStar.SQ_MapHandler(mapDataForAstar, len(dungeon[0]), len(dungeon)))  # Init A*
    start = AStar.SQ_Location(x, y)  # Give start point
    door = choice(doors)  # Pick door as endpoint
    end = AStar.SQ_Location(door[0], door[1])  # Make the endpoint
    p = astar.findPath(start, end)  # Find the path

    if not p:
        print "No path found!"
        return 0

    else:
        pathlines = []

        for n in p.nodes:
            pathlines.append((n.location.x, n.location.y))  # Add path points to list variable

    for point in pathlines:
        if dungeon[point[1]][point[0]] != "D":  # Make sure that no doors are overwritten
            dungeon[point[1]][point[0]] = "P"  # Write paths to map

    return 1
Esempio n. 22
0
def walk(start, sorted_nodes, walls):
    for end_i in sorted_nodes:
        # if end_i not in full_path:
        # if full_path.count(end_i) == 0:
        a = AStar.AStar()
        a.init_grid(25, 25, walls, start, end_i)
        path = a.solve()
        # print path
        for i in path:
            if path.index(i) < len(path) - 1 or sorted_nodes.index(
                    end_i) == len(sorted_nodes) - 1:
                full_path.append(i)
        start = end_i
    ch.get_char_from_path(full_path)
Esempio n. 23
0
def FindDistances():
	# find distances from one key to another

	for subset in itertools.combinations(keynames, 2):

		l1 = subset[0]
		l2 = subset[1]

		# print(f"L1 {l1}  L2 {l2}")

		x1 = keys[l1][0]
		y1 = keys[l1][1]

		x2 = keys[l2][0]
		y2 = keys[l2][1]

		maze = []
		for y in range(0, gridsizey):
			mline = []
			row = grid[y]
			for pos in row:
				if pos == WALL:
					mline.append(10000)
				else:
					mline.append(0)
			maze.append(mline)

		astar = AStar(maze)
		path = astar.run([x1, y1], [x2, y2])

		# print("path:")
		# print(path)

		hasontherkey = 0
		doorsinpath = []
		for p in path:
			pp = (p[0], p[1])
			# print(pp)
			if pp in doorcoords:
				doorsinpath.append(doorcoords[pp])
			# elif pp in keycoords:
			# 	ok = keycoords[pp]
			# 	# print(ok)
			# 	if ok != l1 and ok != l2 and ok != STARTKEY:
			# 		print("true")
			# 		hasontherkey += 1
			# input("press...")

		if hasontherkey < 2:
			distances[subset] = (len(path) - 1, doorsinpath)
Esempio n. 24
0
 def SetDestination(self):
     if (len(self.WalkPath[0]) == 0):
         NewDestination = BreadthFirst(self.CurrentNode,
                                       self.Player.ExploredTiles,
                                       "Exploring").Run()
         if (NewDestination[0] == self.CurrentNode[0]
                 and NewDestination[1] == self.CurrentNode[1]):
             self.State = State()
             if (self.Player.TreeListPerfectlySorted == False):
                 self.Player.SortTrees()
             return
         self.WalkPath = AStar(self.CurrentNode, NewDestination,
                               self.Player.ExploredTiles, False).Run()
         self.SetDirection()
    def __init__ (self, algorithm, startingNode, endNode, heuristic) :
        if algorithm.upper() == 'A*' :
            self.solver = AStar.AStar(heuristic)
        elif algorithm.upper() == 'FLOODFILL' :
            self.solver = Floodfill.Floodfill()
        else :
            print('Invalid solver.')

        self.startingNode    = startingNode
        self.finalNode       = endNode
        self.onPathFound     = None
        self.paths           = []
        self.nodeIndexer     = None
        self.getNodeNeighbor = None
        self.isGoal          = None
Esempio n. 26
0
def MainRuntime(start, goal):
    n = math.sqrt(len(start))
    if (not checkGamePossibility(start, goal, n)):
        print("NOT REACHABLE")
        return
    aStar = AStar(start, goal)

    loop = True
    while (loop):
        res_data = aStar.step()
        loop = res_data[0]
        if (not loop):
            if (res_data[1] == None):
                print("NOT REACHED FROM ALGORITHM")
            else:
                print_data(res_data, goal)
Esempio n. 27
0
    def __init__(self, available_targets, unit, view_range, gameStateObj):
        self.all_targets = available_targets

        self.unit = unit
        self.range = view_range
        self.double_move = self.unit.stats['MOV']*2 + self.unit.getMaxRange()

        self.grid = gameStateObj.grid_manager.get_grid(self.unit)
        self.pathfinder = AStar.AStar(self.unit.position, None, self.grid, gameStateObj.map.width, gameStateObj.map.height,
                                      self.unit.team, 'pass_through' in self.unit.status_bundle)

        # Flags so we don't do things twice
        self.widen_flag = False # Determines if we've already widened our search
        self.ally_flag = False # Determines if we've already taken into account our allies' positions when determining reachable squares

        self.reset()
Esempio n. 28
0
def PartA():

    print("Part A")

    BuildMap()

    start = (int(gridsizex / 2), int(gridsizey / 2))
    end = (osystemx, osystemy)

    maze = []
    for y in range(0, gridsizey):
        mline = []
        row = grid[y]
        for pos in row:
            if pos == WALL:
                mline.append(10000)
            else:
                mline.append(0)
        maze.append(mline)

    astar = AStar(maze)
    path = astar.run([start[0], start[1]], [end[0], end[1]])

    for s in path:
        xx = s[0]
        yy = s[1]
        cur = maze[yy][xx]
        if cur == 0:
            maze[yy][xx] = "P"
        else:
            maze[yy][xx] = "W"

    for y, mrow in enumerate(maze):
        for x, mcol in enumerate(mrow):
            if x == start[0] and y == start[1]:
                print("S", end="")
            elif x == end[0] and y == end[1]:
                print("E", end="")
            elif mcol == "P":
                print("O", end="")
            else:
                print("." if mcol > 0 else " ", end="")
        print("")

    # print(path)

    print("Answer:", len(path) - 1)
Esempio n. 29
0
    def sorted_a_star(self, start_point, _positions, wales):
        if len(_positions) < 1:
            return self.sorted_moves
        else:
            dist = []
            for position in _positions:
                a = AStar.AStar()
                a.init_grid(25, 25, wales, start_point, position)
                path = a.solve()
                dist.append(len(path))

            min_dist_idx = 0
            for distance in range(1, len(dist)):
                if dist[distance] < dist[min_dist_idx]:
                    min_dist_idx = distance
            start_point = _positions[min_dist_idx]
            self.sorted_moves.append(_positions[min_dist_idx])
            del _positions[min_dist_idx]
            return self.sorted_a_star(start_point, _positions, wales)
Esempio n. 30
0
 def sorted_pos(self, start_point, _positions, wales):
     edges = []
     _positions.insert(0, start_point)
     new_list = list(_positions)
     for i in range(0, len(_positions)):
         for j in range(0, len(_positions)):
             if i == j:
                 continue
             a = AStar.AStar()
             a.init_grid(25, 25, wales, _positions[i], _positions[j])
             path = a.solve()
             edges.append((i, j, len(path)-1))
             # print 'graph.addEdge(' + str(i) + ',' + str(j) + ',' + str(len(path) - 1) + ')'
     pso_indecies = pso.get_pso(edges, _positions)
     print pso_indecies
     for i in range(len(pso_indecies)):
         new_list[pso_indecies[i]] = _positions[pso_indecies[i]]
     del new_list[0]
     return new_list