def hillClimbing(self, puzzle):
     '''
     This method take an puzzle and generate a harder puzzle (the steps required to solve should be greater than the already generated puzzle)
     by applying hill climbing technique
     :param puzzle: the puzzle that will be used to generate a harder puzzle
     :return: Same puzzle if there is no harder puzzle otherwise a new puzzle which is harder than already known puzzle
     '''
     h = ZeroHeuristic()
     aStar = AStar(h)
     currentPuzzle = puzzle
     sol = aStar.aStar(currentPuzzle)
     currentEval = sol['Steps']
     print( 'Input Steps',currentEval, end="")
     while True:
         nextPuzzle = None
         nextPuzzleEval = -1000
         for neighbor in currentPuzzle.getNextPossibleMoves():
             sol = aStar.aStar(neighbor)
             if sol['Steps'] > nextPuzzleEval:
                 nextPuzzleEval = sol['Steps']
                 nextPuzzle = RushHour(set(neighbor.vehicles))
         if nextPuzzleEval <= currentEval:
             print(' Out Steps',currentEval)
             return currentPuzzle
         currentPuzzle = RushHour(set(nextPuzzle.vehicles))
         currentEval = nextPuzzleEval
예제 #2
0
class a_gac(object):
    def __init__(self, agac_node_class_pointer, astar_renderer=None):
        self.initial_gac = None
        self.agac_node_class_pointer = agac_node_class_pointer
        self.astar = AStar(astar_renderer)

    def init(self, gac):
        self.initial_gac = gac
        gac.init()
        gac.run()

    def run(self):
        if self.initial_gac.constraints == None or self.initial_gac.variables == None:
            print("Not properly initialized. Run init() before run()")
            return

        current_csp = self.initial_gac
        node = self.generate_anode(current_csp)

        self.astar.init(node)

        end = self.astar.run()

        return end

    def generate_anode(self, gac):
        print("generating S0 from {}".format(self.agac_node_class_pointer))
        return self.agac_node_class_pointer(gac)
예제 #3
0
파일: Car.py 프로젝트: kunz36/car-sim
 def onScanner(self, dots):
     self.world = astar.buildMap(self.world, self.car.getPos(), dots)
     if astar.checkCollision(self.inst, self.world) == True:
         self.path, self.lastNode = astar.run(self.world, self.car.getPos(),
                                              self.car.getAngle())
         self.inst = getDrivePath(self.lastNode)
         self.cnt = astar.ITERATIONS
예제 #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()
예제 #5
0
파일: a_gac.py 프로젝트: OlavOlseng/Assig
class a_gac(object):
	def __init__(self, agac_node_class_pointer, astar_renderer = None):
		self.initial_gac = None
		self.agac_node_class_pointer = agac_node_class_pointer
		self.astar = AStar(astar_renderer)
	
	def init(self, gac):
		self.initial_gac = gac
		gac.init()
		gac.run()
		
	def run(self):
		if self.initial_gac.constraints == None or self.initial_gac.variables == None:
			print("Not properly initialized. Run init() before run()")
			return
		
		current_csp = self.initial_gac
		node = self.generate_anode(current_csp) 
		
		self.astar.init(node)
		
		end = self.astar.run()
		
		return end
	
	def generate_anode(self, gac):
		print("generating S0 from {}".format(self.agac_node_class_pointer))
		return self.agac_node_class_pointer(gac)
		
예제 #6
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)
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()
예제 #8
0
def makeZombie(destination, count):
    global zombiePath, zombieLife, zombiePos, explode, chiliList, mapChanged, chiliNum, shovelNum, brickNum, loseGame
    if mapChanged:  #calculate shortestPath again if walls# change
        mapChanged = False
        Asearch = AStar.Astar(End, destination, blockList, mazeSize)
        print('*zombie is finding a new path')
        while Asearch.nextStep() == None:
            print('*there is no path from entrance to exit, try to create one')
            pygame.time.delay(2000)
            Asearch = AStar.Astar(End, destination, blockList, mazeSize)
        else:
            print('*a path is found')
        zombiePath = Asearch.shortestPath
    moveSpeed = 700
    eatSpeed = 1900
    zombieLife = 3
    zombiePos = End[:]
    print('zombie ' + str(count))
    for nextStp in zombiePath:
        if zombieLife < 1:
            break  #zombie is killed
        elif nextStp in [p[0:2] for p in chiliList]:  #chili blocks,eat it
            pygame.time.delay(eatSpeed)
            if zombieLife < 1:
                break  #zombie is killed
            else:
                for p in chiliList:
                    if nextStp == p[0:2]:
                        p[4] = 'die'
        while nextStp in blockList and zombieLife > 0:  #wall blocks
            pygame.time.delay(moveSpeed)
        zombiePos = nextStp  #move
        pygame.time.delay(moveSpeed)
    if explode:  #explode
        pygame.time.delay(200)  #explode animation time
        explode = False
        for x in range(-1, 2):
            for y in range(-1, 2):
                if 0 < x + zombiePos[0] < mazeSize[0] - 1 and 0 < y + zombiePos[
                        1] < mazeSize[1] - 1:  #wall cannot be removed
                    if [x + zombiePos[0],
                            y + zombiePos[1]] in blockList:  #remove walls
                        blockList.remove([x + zombiePos[0], y + zombiePos[1]])
                        mapChanged = True
                    elif [x + zombiePos[0], y + zombiePos[1]
                          ] in [p[0:2] for p in chiliList]:  #remove chilies
                        for p in chiliList:
                            if [x + zombiePos[0], y + zombiePos[1]] == p[0:2]:
                                p[4] = 'die'
    if zombieLife > 0:
        if chiliNum > 0: chiliNum -= 1
        if shovelNum > 0: shovelNum -= 1
        if brickNum > 0: brickNum -= 1
        if chiliNum == 0 and shovelNum == 0 and brickNum == 0:
            print('lose game')
            loseGame = True
            exit()
    makeZombie(destination, count + 1)  #new zombie
예제 #9
0
    def showCalculatedWay(self):

        AStar.solve(self)
        path_array = AStar.solve(self)

        for each in path_array[1:-1:]:
            self.canvas.create_image(each[1] * 60 + 30,
                                     each[0] * 60 + 30,
                                     image=self.path_img)
예제 #10
0
파일: Car.py 프로젝트: jitrc/car-sim
 def onPaint(self, g):
     astar.drawMap(self.world, g)
     if self.path != None:
         pos = self.car.getPos()
         g.setColor(Color.orange)
         drawTree(g, self.path)
     
     if self.lastNode != None:
         g.setColor(Color.green)
         g.setStroke(BasicStroke(2))
         drawPath(g, self.lastNode)
         g.setStroke(BasicStroke(1))
예제 #11
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)
예제 #12
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)
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)
예제 #14
0
파일: cli.py 프로젝트: niyonx/COMP472-AI
def run(algo, h, path):
    if (h not in [0, 1, 2]):
        click.echo('Invalid number of heuristic function. See --help')
        return
    if (algo == 'ucs'):
        UniformCostSearch.run(path)
    elif (algo == 'gbfs'):
        GreedyBestFirstSearch.run(path, h)
    elif (algo == 'astar'):
        AStar.run(path, h)
    else:
        click.echo('Invalid syntax. See --help')
        return
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)
예제 #16
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
예제 #17
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)
예제 #18
0
def main():
    """Main function"""

    # Dictionary that stores all the nodes of the graph
    # in which the keys are the nodes' IDs
    dataNodes = {}

    # Readin data
    readInput(dataNodes)

    # Using Greedy algorithm
    Greedy.greedySearch(dataNodes, INITIAL_NODE, FINAL_NODE)

    # Using A* algorithm
    AStar.aStarSearch(dataNodes, INITIAL_NODE, FINAL_NODE)
예제 #19
0
 def quickMove(self, desRow, desCol):
     self.qCount = 1
     self.qStack = astar.astar_search(self.gs.board,
                                      (self.seekerRowPos,self.seekerColPos),
                                      (desRow,desCol) )
     self.qStack.insert(0,(self.seekerRowPos,self.seekerColPos))
     return
예제 #20
0
    def getFastestRoute(self):

        # update map status, this ensure new obstacles are detected
        self.updateMap()

        logger.debug("Path from: " + str(self.robotPosition) + " to " + str(self.goalPosition) + " Initial Orientation: " + str(self.robotOrientation))
        # get fastest route from AStar giving map, start position and goal position
        route = AStar.findPath(self.map, self.robotPosition.getPositionArray(), self.goalPosition.getPositionArray())

        # if no route was found, return UNKNOWN path
        if route == None:
            return UNKNOWN

        # get only intersection nodes from AStar route
        intersections = self.getIntersectionNodesFromRoute(route)

        # get cardinal points directions based on intersection nodes
        directions = self.getDirectionsFromIntersections(intersections)
        
        logger.debug(directions)

        # get turns based on robot directions and robot orientation
        turns = self.getTurnsFromDirections(directions)

        logger.debug(turns)

        # remove curve turns
        turns = self.removeCurves(turns, intersections)

        # return the turns
        return turns
예제 #21
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
    def generatePath(self):
        print("LOOKING FOR SHORTER PATH")
        map_grid = self.grid.getMap()
        dest = self.grid.getDestiny()
        source = self.grid.getPose()

        # Note: The grid coordinates are inverted

        if map_grid[dest[1]][dest[0]] < 125:
            print("Clicked point not an empty space!")
            return 0
        else:
            print("Point selected has colour")
            map_copy = np.array(map_grid)
            dest_transpose = (dest[1], dest[0])
            source_transpose = (source[1], source[0])

            # Is value < 125 -> True ->  int -> 1
            map_copy = (map_copy < 125).astype(int)

            a = time.time()
            a_star = AStar.Astar(map_copy, source_transpose, dest_transpose)
            path = a_star.get_path()
            t = time.time() - a

            print("Shortest Path found in: %f Seconds" % t)

            self.grid.setPathFinded()
            for node in path:
                self.grid.setPathVal(node[1], node[0], 1)
        pass
def recordHillClimbing():
    data = []
    h0 = ZeroHeuristic()
    aStarWithH0 = AStar(h0)
    for i in range(0, 15):
        for j in range(0, 25):
            filename = '{0}_{1}.txt'.format(i, j)
            r = load_file(boardConfigsFolder + '/{0}'.format(filename))
            sol1 = aStarWithH0.aStar(r)
            rr = load_file(harderPuzzlesFolder + '/{0}'.format(filename))
            sol2 = aStarWithH0.aStar(rr)
            data.append([filename, sol1['Steps'], sol2['Steps']])
            print(filename,sol1['Steps'], sol2['Steps'])
    with open('hillClimbing.csv', 'w', newline='') as f:
        wr = csv.writer(f, delimiter=',')
        wr.writerows(data)
예제 #24
0
파일: Main.py 프로젝트: Azuki-Azusa/A-Star
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')
예제 #25
0
def Load(iWidth,iHeight):
	#//\==== Load From Application
	print "Loading main"
	#//\==== ReLoad Modules (to make sure they are current when reloading)
	reload(KEYDEFS)
	reload(Level)
	reload(AStar)
	reload(Dijkstras)
	#//\==== Set BG colour and Grid Information
	LMF.FrameworkBGColour(0.1,0.6,0.09,1.)
	global GridDimens
	GridDimens = [40,24,64]
	#//\==== Dijkstras
	global DijkstrasPathing
	DijkstrasPathing = Dijkstras.cDijkstras()
	global AStarPathing
	AStarPathing = AStar.cAStar()
	#//\==== Setup ScreenSize
	global ScreenSize
	ScreenSize[0] = iWidth
	ScreenSize[1] = iHeight
	global Boids
	Boids = []
	Boids.append(boid.cBoid(CameraPos[0]+iWidth *0.5,CameraPos[1]+iHeight *0.5))
	#//\==== Setup the Tile able Level
	global LevelGrid
	LevelGrid = Level.cLevelGrid({'width':GridDimens[0], 'height':GridDimens[1] , 'size':GridDimens[2] })
	#//\==== center the view on the middle of the Grid and update the AIE camera
	CameraPos[0] = -(iWidth *0.5) + ((GridDimens[0]*GridDimens[2])*0.5 ) - (GridDimens[2]*0.5)
	CameraPos[1] =  (iHeight*0.5) + ((GridDimens[1]*GridDimens[2])*0.5 ) - (GridDimens[2]*0.5)
	LMF.CameraMove(-CameraPos[0],-CameraPos[1])
	print "Loaded main"
예제 #26
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
def GenerateAStar():
    temp = AStar.astar()[::-1]
    res = np.zeros((len(temp), 2), dtype=int)
    for i in range(len(temp)):
        res[i, 0] = temp[i][0]
        res[i, 1] = temp[i][1]
    return res
예제 #28
0
    def replan(self, node):
        """ Replan an internal CBS tree node """
        # Get the unit to replan
        agent_to_replan = self.tree[node].agent

        # Find the conflicts that need to be avoided
        num_conflicts = 0
        conflicts = []
        temp_location = node
        while temp_location != 0:
            if self.tree[temp_location].agent == agent_to_replan:
                conflicts.append(self.tree[temp_location].conflict)
                num_conflicts += 1
            temp_location = self.tree[temp_location].parent

        # Plan the agent
        path = AStar.astar(self.environments[self.agents[agent_to_replan]],
                           agent_to_replan.start, agent_to_replan.goal,
                           conflicts)
        if path is None:
            return False

        # Add the path to the tree
        self.tree[node].paths[agent_to_replan] = path
        return True
예제 #29
0
def InitFromFile(targetFile, heuType):
    initialMap = []
    goalMap = []

    f = open(targetFile)
    fLines = f.readlines()
    f.close()

    # Getting initial state (line 0-2) and appending to initialMap by row.
    for i in range(0, 3):
        curLine = fLines[i]
        nums = curLine.split()
        initialMap.append([int(nums[0]),
                           int(nums[1]),
                           int(nums[2])])

    # Getting goal state (line 4-6) by row.
    for i in range(4, 7):
        curLine = fLines[i]
        nums = curLine.split()
        goalMap.append([int(nums[0]), int(nums[1]),
                        int(nums[2])])

    # Generates a root node where search can begin.
    rootNode = AStar.StateNode(initialMap, goalMap, 0, heuType, None, None)

    return rootNode, goalMap
예제 #30
0
def main():

    # Usability
    fname = input("File Name -> ")
    heurT = input("Heuristic Type (A or B) -> ")

    # Initialize from file and create a search manager object.
    rootNode, goalMap = InitFromFile(fname, heurT)
    search = AStar.AStarSearch(rootNode, goalMap)
    print("Initial Heuristic:", rootNode.heu)

    # Some terminal output for verbose operation
    print("--- GOAL ---")
    print(goalMap)
    print()
    print(rootNode)

    result = search.doSearch()
    output = GenerateOutput(rootNode, search, result)
    print("\n", "********************************", "\n")
    print(output)
    print("\n", "********************************", "\n")

    #Write results to file if output name is specified.
    fname = ""
    fname = input("Output File Name (or ENTER to skip) -> ")
    if (fname != ""):
        writeout = open(fname, "w+")
        writeout.write(output)
        writeout.close()
        print("Saved.")
    else:
        print("Not saved.")
예제 #31
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)
예제 #32
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)
예제 #33
0
def travel(startState, endState):

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

    return AStar.AStar(startNode, [endNode])
def MainRuntime(start,goal):
    n = math.sqrt(len(start))
    if(not checkGamePossibility(start,goal,n)):
        print("NOT REACHABLE")
        return 
    
    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,2,i)
예제 #35
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)
예제 #36
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])
예제 #37
0
파일: Car.py 프로젝트: jitrc/car-sim
 def init(self, ctrl, background):
     self.dots = [[0,0]]
     self.scanPos = [0,0]
     self.cnt = 0
     self.car = ctrl
     self.world = astar.initWorld()        
     self.inst = None
     self.path = None
     self.lastNode = None
예제 #38
0
    def showCalculatedWay(self):

        AStar.solve(self)
        path_array = AStar.solve(self)

        # MIGHT NOT WORK PROPERLY
        for each in AStar.CHILDREN_MOVE:  #[:-1:]
            if each != AStar.END_COORDINATE and each != AStar.START_COORDINATE and self.chess_board_arr[
                    each[1]][each[0]] != 1:
                self.canvas.create_image(each[1] * 60 + 30,
                                         each[0] * 60 + 30,
                                         image=self.children_img)

        # SHOW THE WAY OF ALGORITHM
        for each in path_array[1:-1:]:
            self.canvas.create_image(each[1] * 60 + 30,
                                     each[0] * 60 + 30,
                                     image=self.path_img)
예제 #39
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()
예제 #40
0
    def start_map(self, tilemap):
        self.map = tilemap

        # Set up blitting surface
        mapSurfWidth = max(self.map.width * GC.TILEWIDTH, GC.WINWIDTH)
        mapSurfHeight = max(self.map.height * GC.TILEHEIGHT, GC.WINHEIGHT)
        self.mapSurf = Engine.create_surface((mapSurfWidth, mapSurfHeight))

        self.grid_manager = AStar.Grid_Manager(self.map)
        self.boundary_manager = CustomObjects.BoundaryManager(self.map)
 def get_neighbour(self, node, direction):
     x, y = node.get_pos()
     dx, dy = AStar.get_directions_array()
     x += dx[direction]
     y += dy[direction]
     try:
         self._check_coords(x, y)
     except AssertionError:
         return None
     return self.get_item_at(x, y)
    def _show_route(self, scribble_map, src, tgt, route):
        if len(route) > 0:
            print("showing route: %s" % route)
        else:
            print("no route to show")
            return

        from matplotlib import pyplot
        dirs = AStar.get_directions_array()

        x = src.x
        y = src.y
        scribble_map[y][x] = 2
        for i in range(len(route)):
            j = int(route[i])
            x += dirs[0][j]
            y += dirs[1][j]
            scribble_map[y][x] = 3
        scribble_map[y][x] = 4

        pyplot.pcolor(scribble_map)
        pyplot.show()
from AStar import *
from LoadRushHourFile import load_file
from main import breadth_first_search
import csv

boardConfigsFolder = "C:/Users/Abbas/PycharmProjects/Rush Hour Puzzle Game/New folder"
def saveResultIntoCSV(data, fileName):
    with open(fileName, 'w', newline='') as f:
        wr = csv.writer(f, delimiter=',')
        wr.writerows(data)
print('File#','Num of Vehicles','Heuristic','Time', 'Expanded Nodes', 'Steps', 'Solveable or not')
h0 = ZeroHeuristic()
h1 = DistanceFromTargetToExit()
h2 = BlockingExitHeuristic()
h3 = BlockingLowerBoundEstimation()
aStarWithH0 = AStar(h0)
aStarWithH1 = AStar(h1)
aStarWithH2 = AStar(h2)
aStarWithH3 = AStar(h3)
data = []
for i in range(3,15):
    for j in range(25):
        puzzleFile = boardConfigsFolder+"/" +"{0}_{1}.txt".format(i,j)
        rushHour = load_file(puzzleFile)
        elapsedTime = time.time()
        sol0 = aStarWithH0.aStar(rushHour)
        t0 = round((time.time()-elapsedTime)*1000)
        numVehicles = len(rushHour.vehicles)

        # data.append([i,numVehicles,'h0',t,sol['Expanded Nodes'],sol['Steps'],s])
        # print(i,numVehicles,'h0',t,sol['Expanded Nodes'],sol['Steps'],s)
예제 #44
0
    def update(self):
        # output = self.handle_events()
        path1 = []

        self.display()

        if self.player.cleaned >= self.numTrashTotal and [self.player.y, self.player.x] == self.trashbin:
            return "finished"

        go_to_trash = True

        if self.player.sumEquipment() < self.player.capacity:
            # klasyfikacja i podjecie decyzji
            decisions = self.classification.classify(self.trash_list, self)

            any_decision = False

            decisions_sorted = []
            for i in range(len(decisions)):
                distance = self.distance(self.trash_list[i])
                decisions_sorted.append([distance, i])
                if decisions[i] == 'True':
                    any_decision = True

            decisions_sorted.sort()

            if any_decision == False and self.player.sumEquipment() == 0:
                if len(self.trash_list) > 0:
                    decisions[decisions_sorted[0][1]] = 'True'

            for j in range(len(decisions)):
                i = decisions_sorted[j][1]
                if decisions[i] == 'True':
                    # utworz instancje AStar
                    a = AStar.AStar()
                    a.init_grid(self.map)
                    # wezel poczatowy
                    start = (self.player.y, self.player.x)
                    # droga od wezla poczatkowego do docelowego
                    path = a.process(start, self.trash_list[i][0], self.trash_list[i][1])
                    # ciag akcji agenta od stanu poczatkowego do docelowego
                    path1 = AStar.get_actions(path, start, self.trash_list[i][0], self.trash_list[i][1])
                    # kolejne wykonanie akcji
                    for j in range(len(path1)):
                        self.player.move(path1[j])
                        self.display()
                        # time.sleep(0.1)
                    self.cleaning()
                    self.trash_list.pop(i)
                    go_to_trash = False
                    break

        if go_to_trash:
            # utworz instancje AStar
            a = AStar.AStar()
            a.init_grid(self.map)
            start = (self.player.y, self.player.x)
            # najkrotsza droga do smietnika
            path = a.process(start, self.trashbin[0], self.trashbin[1])
            # ciag akcji agenta od stanu poczatkowego do docelowego (pole obok smietnika)
            path1 = AStar.get_actions(path, start, self.trashbin[0], self.trashbin[1])

            # kolejne wykonanie akcji
            for i in range(len(path1)):
                self.player.move(path1[i])
                self.display()
                # time.sleep(0.1)

            # oproznianie ekwipunku
            for key in self.player.equipment.keys():
                self.player.equipment[key] = 0
                self.display()
                # time.sleep(0.1)

        return "working"
예제 #45
0
파일: example.py 프로젝트: MoyTW/AStar
# This code is just to generate an empty start and end point for our algorithm to plot a path between.
def find_empty_coordinates(m):
    x = random.randint(0, m.MAP_SIZE)
    y = random.randint(0, m.MAP_SIZE)
    while not m.node_is_passable((x, y)):
        x = random.randint(0, m.MAP_SIZE)
        y = random.randint(0, m.MAP_SIZE)
    return x, y
origin = find_empty_coordinates(em)
destination = find_empty_coordinates(em)

# Here, we use the four functions defined back up in ExampleMap and generate a path.
path = AStar.find_path(origin, destination,
                       func_list_adjacent_nodes=em.list_adjacent_nodes,
                       func_calculate_move_cost=em.calculate_move_cost,
                       func_node_is_passable=em.node_is_passable,
                       func_estimate_cost=em.estimate_cost)
print "The path provided by the A* algorithm from", origin, "to", destination, "is:", path
print ''


def print_map_with_path(example, origin, destination, path):
    print_str = ''
    col = example.MAP_SIZE - 1
    while col >= 0:
        for row in range(example.MAP_SIZE):
            if (row, col) == origin:
                print_str += 'O'
            elif (row, col) == destination:
                print_str += 'D'
예제 #46
0
    def enforceConnectivity(self):
        # Set up AStar algo
        import AStar
        
        wallGlyph = self.tileset.wallGlyph
        mapdata = []

        for y in range(self.mapHeight):
            for x in range(self.mapWidth):
                square = self.levelMap[y][x]
                if square == wallGlyph:
                    mapdata.append(-1)
                else:
                    mapdata.append(1)
        
        self.astar = AStar.setUpMap(mapdata, self.mapWidth, self.mapHeight)
        
        # Find connected components
        connectedComponents = []
        
        # Start with first room
        connectedComponents.append([self.rooms[0]])
        
        # Look at all the others
        for room in self.rooms[1:]:
            connected = False
            fromx, fromy = room[0] # All rooms are simply connected, so choose the first square in each room
            
            for comp in connectedComponents:
                roomToFind = comp[0]
                tox, toy = roomToFind[0]
                
                path = AStar.findPath((fromx, fromy), (tox, toy), self.astar)
                
                if path is not None:
                    comp.append(room)
                    connected = True
                    break
            
            if connected == False:
                connectedComponents.append([room])
                
        if len(connectedComponents) == 1:
            # Nothing left to do
            return
        
        # Find the largest component by # of squares
        largestComp = None
        largestSize = 0
        
        for comp in connectedComponents:
            size = 0
            for room in comp:
                size += len(room)
            
            if size > largestSize:
                largestSize = size
                largestComp = comp
                
        # Connect each component to the largest one
        for comp in connectedComponents:
            if comp is largestComp:
                continue
            
            # Find the closest pairs of points in comp and largestComp
            closestPoints = []
            minDist = maxint
            
            # Loop over points in largestComp
            for p1 in [point for room in largestComp for point in room]:
                # Loop over points in comp
                for p2 in [point for room in comp for point in room]:
                    x1, y1 = p1
                    x2, y2 = p2
                    distance = ManhattanDistance(x1, x2, y1, y2)
                    
                    if distance < minDist:
                        closestPoints = [[p1, p2]]
                        minDist = distance
                    elif distance == minDist:
                        closestPoints.append([p1, p2])
            
            toPoint, fromPoint = random.choice(closestPoints)
            tox, toy = toPoint
            
            currentx, currenty = fromPoint
            tunnelGlyph = self.tileset.tunnelGlyph
            # Random-walk toward toPoint
            while True:
                dx = 0
                dy = 0
                
                if currentx < tox:
                    dx = 1
                elif currentx > tox:
                    dx = -1
                
                if currenty < toy:
                    dy = 1
                elif currenty > toy:
                    dy = -1
                    
                if dy == 0 or random.random() > 0.5:
                    # Step horizontally
                    nextx, nexty = currentx + dx, currenty
                else:
                    # Step vertically
                    nextx, nexty = currentx, currenty + dy
                
                # End if we're next to the goal square
                if (nextx, nexty) == (tox, toy):
                    break
                
                # Place a tunnel square
#                 self.levelMap[nexty][nextx] = tunnelGlyph
                # Silly stuff we have to do because strings are immutable
                row = self.levelMap[nexty]
                
                # Only replace wall squares
                if row[nextx] == wallGlyph:
                    rowl = list(row)
                    rowl[nextx] = tunnelGlyph
                    self.levelMap[nexty] = ''.join(rowl)
                
                currentx, currenty = nextx, nexty
예제 #47
0
파일: a_gac.py 프로젝트: OlavOlseng/Assig
	def __init__(self, agac_node_class_pointer, astar_renderer = None):
		self.initial_gac = None
		self.agac_node_class_pointer = agac_node_class_pointer
		self.astar = AStar(astar_renderer)