def dijkstra_shortest_path(self, start, end):
     pre_grids = PQ()
     grid_dist = PQ()
     grid_dist[start] = 0
     pre_grids[start] = -1
     while grid_dist:
         cur = grid_dist.smallest()
         for g in [-81,81,-1,1]:
             g+=cur
             if 0>g or g>=len(self.grid):
                 continue
             if g in pre_grids:
                 continue
             if self.grid[g] == "grass":
                 continue
             if self.grid[g] == "soul_sand":
                 if g not in grid_dist or grid_dist[g] > grid_dist[cur]+4:
                     grid_dist[g] = grid_dist[cur]+4
                     pre_grids[g] = cur
             elif self.grid[g] == "stone":
                 if g not in grid_dist or grid_dist[g] > grid_dist[cur]+1:
                     grid_dist[g] = grid_dist[cur]+1
                     pre_grids[g] = cur
             else:
                 if g not in grid_dist or grid_dist[g] > grid_dist[cur]:
                     grid_dist[g] = grid_dist[cur]
                     pre_grids[g] = cur
         del grid_dist[cur]
     result = []
     cur = end
     while pre_grids[cur] != -1:
         result.insert(0,cur)
         cur = pre_grids[cur]
     result.insert(0,start)
     return result
Beispiel #2
0
def dijkstra_shortest_path(grid_obs, source, dest, danger_blocks=[]):
    """
    Finds the shortest path from source to destination on the map. It used the grid observation as the graph.
    See example on the Tutorial.pdf file for knowing which index should be north, south, west and east.

    Args
        grid_obs:   <list>  list of block types string representing the blocks on the map.
        source:     <int>   source block index.
        dest:       <int>   destination block index.

    Returns
        path_list:  <list>  block indexes representing a path from source (first element) to destination (last)
    """

    action_trans = {'north': -21, 'south': 21, 'west': -1, 'east': 1}

    path_set = set()  # indexes
    priority_dict = PQ()  # key = index, value = distance value
    parent = [-1] * len(grid_obs)
    for i in range(0, len(grid_obs)):
        if (grid_obs[i] in danger_blocks):
            continue
        priority_dict[i] = math.inf
    priority_dict[source] = 0

    while (len(priority_dict) != 0):
        # picking vertex with minimum distance (smallest() from priority queue) and is not in the path set
        # priority dict should not contain vertices added to path_list
        smallest_vertex = priority_dict.smallest()
        smallest_vertex_distance = priority_dict[smallest_vertex]

        # adding u to the path set
        path_set.add(smallest_vertex)
        # removing from priority dict
        priority_dict.pop(smallest_vertex)

        for adj_index in [
                smallest_vertex + modifier
                for modifier in action_trans.values()
        ]:
            if adj_index in priority_dict:
                # sum of distance value u (in priority queue) and edge u-v (always 1)
                new_distance_value = smallest_vertex_distance + 1
                v_distance_value = priority_dict[adj_index]
                if (new_distance_value < v_distance_value):
                    # update if new distance value is less than value saved in data structure
                    priority_dict[adj_index] = new_distance_value
                    # update parent
                    parent[adj_index] = smallest_vertex

    # generating shortest path utilizing parents (in reverse order)
    path_list = [dest]
    while (True):
        current_parent = parent[path_list[-1]]
        if (current_parent == -1):
            break
        path_list.append(current_parent)

    return list(reversed(path_list))
Beispiel #3
0
    def get_shortest_path(self, grid_obs, source, dest):
        q = PQ()
        self.init_pq(grid_obs, q)
        q[source] = 0
        prev = dict()
        dist = q.copy()
        [prev.update({key: None}) for key in q.keys()]
        for node in q:
            neighbors = []
            if node not in range(0, 21) and grid_obs[node - 21] in [
                    'air', 'wooden_door', 'tallgrass', 'double_plant'
            ]:
                neighbors.append(node - 21)
            if (node + 1) % 21 != 0 and grid_obs[node + 1] in [
                    'air', 'wooden_door', 'tallgrass', 'double_plant'
            ]:
                neighbors.append(node + 1)
            if node % 21 != 0 and grid_obs[node - 1] in [
                    'air', 'wooden_door', 'tallgrass', 'double_plant'
            ]:
                neighbors.append(node - 1)
            if node not in range(420, 441) and grid_obs[node + 21] in [
                    'air', 'wooden_door', 'tallgrass', 'double_plant'
            ]:
                neighbors.append(node + 21)
            for n in neighbors:
                alt = 0
                if n in dist:
                    alt = dist[node] + 1
                    if alt < dist[n]:
                        dist[n] = alt
                        prev[n] = node
                        q[n] = alt

        path_list = [dest]
        last = dest
        while last != source:
            path_list = [prev[last]] + path_list
            last = prev[last]

        return path_list
 def dijkstra_shortest_path(self):
     pre_grids = PQ()
     grid_dist = PQ()
     grid_dist[self.start] = 0
     pre_grids[self.start] = -1
     while grid_dist:
         cur = grid_dist.smallest()
         for g in [-self.up_down_dist,self.up_down_dist,-1,1]:
             g+=cur
             if g not in pre_grids and self.grid[g] != "air":
                 if g not in grid_dist or grid_dist[g] > grid_dist[cur]+1:
                     grid_dist[g] = grid_dist[cur]+1
                     pre_grids[g] = cur
         del grid_dist[cur]
     result = []
     cur = self.end
     while pre_grids[cur] != -1:
         result.insert(0,cur)
         cur = pre_grids[cur]
     result.insert(0,self.start)
     return result
def dijkstra_shortest_path(grid_obs, source, dest):
    """
    Finds the shortest path from source to destination on the map. It used the grid observation as the graph.
    See example on the Tutorial.pdf file for knowing which index should be north, south, west and east.

    Args
        grid_obs:   <list>  list of block types string representing the blocks on the map.
        source:     <int>   source block index.
        dest:       <int>   destination block index.

    Returns
        path_list:  <list>  block indexes representing a path from source (first element) to destination (last)
    """
    #------------------------------------
    #
    #   Fill and submit this code
    #
    predecessors = {source: float('inf')}
    visited_blocks = {source: 0}
    queue = PQ()
    queue.__setitem__(source, 0)
    goodIndices = []

    print len(grid_obs)

    for index in range(len(grid_obs)):
        if grid_obs[index] != "air":
            goodIndices.append(index)

    for index in goodIndices:
        if index != source:
            visited_blocks[index] = float('inf')

    while queue:
        blocks_to_go = []
        current_position = queue.smallest()
        del queue[current_position]

        for difference in [-81, -1, 1, 81]:
            if (current_position + difference) in goodIndices:
                blocks_to_go.append(current_position + difference)

        for block_Index in blocks_to_go:
            gap = visited_blocks[current_position] + 1
            if gap < visited_blocks[block_Index]:
                visited_blocks[block_Index] = gap
                predecessors[block_Index] = current_position
                queue.__setitem__(block_Index, gap)

    shortest_paths = []
    while dest != source:
        shortest_paths.append(dest)
        dest = predecessors[dest]
    shortest_paths.append(source)
    shortest_paths.reverse()

    return shortest_paths
Beispiel #6
0
	def dijkstra(self, start, dest):
		start_dist = 0
		priorityQ = PQ()
		priorityQ.setdefault(start, start_dist)

		trace = dict()
		visited = set()

		trace[start] = [None, start_dist]

		while(True):
			#print("AIHSHDAHDHSIHIDDSDASHDSADSIAHSDAH")
			current = priorityQ.smallest()
			#print(current)
			del priorityQ[current]
			if (current == dest):
				break;
			visited.add(current)

			n, e, s, w = self.getAdjacents(current)


			if (n[1] < self.northMax and self.wumpusMap[n[0]][n[1]] == 0 and self.pitMap[n[0]][n[1]] == 0 and n not in visited):   
				priorityQ.setdefault(n, trace[current][1] + 1)
				trace[n] = [current, trace[current][1] + 1]
			if (s[1] >= 0 and self.wumpusMap[s[0]][s[1]] == 0 and self.pitMap[s[0]][s[1]] == 0 and s not in visited):
				priorityQ.setdefault(s, trace[current][1] + 1)
				trace[s] = [current, trace[current][1] + 1]
			if (e[0] < self.eastMax and self.wumpusMap[e[0]][e[1]] == 0 and self.pitMap[e[0]][e[1]] == 0 and e not in visited):
				priorityQ.setdefault(e, trace[current][1] + 1)
				trace[e] = [current, trace[current][1] + 1]
			if (w[0] >= 0 and self.wumpusMap[w[0]][w[1]] == 0 and self.pitMap[w[0]][w[1]] == 0 and w not in visited):
				priorityQ.setdefault(w, trace[current][1] + 1)
				trace[w] = [current, trace[current][1] + 1]

		path = [dest]
		last = dest
		while(True):
			if (trace[last][0] is None):
				break;
			path.insert(0, trace[last][0])
			last = trace[last][0]

		return path
Beispiel #7
0
def GetMissionXML(seed, gp, size=10):
    return '''<?xml version="1.0" encoding="UTF-8" standalone="no" ?>
            <Mission xmlns="http://ProjectMalmo.microsoft.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

              <About>
                <Summary>Hello world!</Summary>
              </About>

            <ServerSection>
              <ServerInitialConditions>
                <Time>
                    <StartTime>1000</StartTime>
                    <AllowPassageOfTime>false</AllowPassageOfTime>
                </Time>
                <Weather>clear</Weather>
              </ServerInitialConditions>
              <ServerHandlers>
                  <FlatWorldGenerator generatorString="3;7,44*49,73,35:1,159:4,95:13,35:13,159:11,95:10,159:14,159:6,35:6,95:6;12;"/>
                  <DrawingDecorator>
                    <DrawSphere x="-27" y="70" z="0" radius="30" type="air"/>
                  </DrawingDecorator>
                  <MazeDecorator>
                    <Seed>''' + str(seed) + '''</Seed>
                    <SizeAndPosition width="''' + str(
        size) + '''" length="''' + str(
            size) + '''" height="10" xOrigin="-32" yOrigin="69" zOrigin="-5"/>
                    <StartBlock type="emerald_block" fixedToEdge="true"/>
                    <EndBlock type="redstone_block" fixedToEdge="true"/>
                    <PathBlock type="diamond_block"/>
                    <FloorBlock type="air"/>
                    <GapBlock type="air"/>
                    <GapProbability>''' + str(gp) + '''</GapProbability>
                    <AllowDiagonalMovement>false</AllowDiagonalMovement>
                  </MazeDecorator>
                  <ServerQuitFromTimeUp timeLimitMs="100000"/>
                  <ServerQuitWhenAnyAgentFinishes/>
                </ServerHandlers>
              </ServerSection>

              <AgentSection mode="Survival">
                <Name>CS175AwesomeMazeBot</Name>
                <AgentStart>
                    <Placement x="0.5" y="56.0" z="0.5" yaw="0"/>
                </AgentStart>
                <AgentHandlers>
                    <DiscreteMovementCommands/>
                    <AgentQuitFromTouchingBlockType>
                        <Block type="redstone_block"/>
                    </AgentQuitFromTouchingBlockType>
                    <ObservationFromGrid>
                      <Grid name="floorAll">
                        <min x="-10" y="-1" z="-10"/>
                        <max x="10" y="-1" z="10"/>
                      </Grid>
                  </ObservationFromGrid>
                </AgentHandlers>
              </AgentSection>
            </Mission>'''
    """
    Used the agent observation API to get a 21 X 21 grid box around the agent (the agent is in the middle).

    Args
        world_state:    <object>    current agent world state

    Returns
        grid:   <list>  the world grid blocks represented as a list of blocks (see Tutorial.pdf)
    """
    while world_state.is_mission_running:
        #sys.stdout.write(".")
        time.sleep(0.1)
        world_state = agent_host.getWorldState()
        if len(world_state.errors) > 0:
            raise AssertionError('Could not load grid.')

        if world_state.number_of_observations_since_last_state > 0:
            msg = world_state.observations[-1].text
            observations = json.loads(msg)
            grid = observations.get(u'floorAll', 0)
            break
    return grid
    """
    Finds the shortest path from source to destination on the map. It used the grid observation as the graph.
    See example on the Tutorial.pdf file for knowing which index should be north, south, west and east.

    Args
        grid_obs:   <list>  list of block types string representing the blocks on the map.
        source:     <int>   source block index.
        dest:       <int>   destination block index.

    Returns
        path_list:  <list>  block indexes representing a path from source (first element) to destination (last)
    """

    action_trans = {'north': -21, 'south': 21, 'west': -1, 'east': 1}

    path_set = set()  # indexes
    priority_dict = PQ()  # key = index, value = distance value
    parent = [-1] * len(grid_obs)
    for i in range(0, len(grid_obs)):
        if (grid_obs[i] in danger_blocks):
            continue
        priority_dict[i] = math.inf
    priority_dict[source] = 0

    while (len(priority_dict) != 0):
        # picking vertex with minimum distance (smallest() from priority queue) and is not in the path set
        # priority dict should not contain vertices added to path_list
        smallest_vertex = priority_dict.smallest()
        smallest_vertex_distance = priority_dict[smallest_vertex]

        # adding u to the path set
        path_set.add(smallest_vertex)
        # removing from priority dict
        priority_dict.pop(smallest_vertex)

        for adj_index in [
                smallest_vertex + modifier
                for modifier in action_trans.values()
        ]:
            if adj_index in priority_dict:
                # sum of distance value u (in priority queue) and edge u-v (always 1)
                new_distance_value = smallest_vertex_distance + 1
                v_distance_value = priority_dict[adj_index]
                if (new_distance_value < v_distance_value):
                    # update if new distance value is less than value saved in data structure
                    priority_dict[adj_index] = new_distance_value
                    # update parent
                    parent[adj_index] = smallest_vertex

    # generating shortest path utilizing parents (in reverse order)
    path_list = [dest]
    while (True):
        current_parent = parent[path_list[-1]]
        if (current_parent == -1):
            break
        path_list.append(current_parent)

    return list(reversed(path_list))