Exemplo n.º 1
0
def resolver(metodo_busqueda, posiciones_personas):
    """ Devuelve un nodo resultado, a partir de una búqueda especificada.

    Argumentos:
    metodo_busqueda -- nombre de método a usar (string);
    posiciones_personas -- lista de tuplas. Cada tupla representa la posicion 
    de una persona en la grilla (aún por rescatar).

    """
    """
    Estado inicial: Lista compuesta de 4 posiciones:
    1era posicion: Tupla. Posicion del robot en la grilla.
    2da posicion: Lista de tuplas. Posiciones de la grilla que el robot va 
    hundiendo (inutilizando).
    3era posicion: Lista de tuplas. Posiciones de la grilla donde se ubican 
    las personas aún no rescatadas.
    4ta posicion: Booleano. Es True si el robot esta 'ocupado' (esta cargando 
    personas), caso contrario False.
    """
    ESTADO_INICIAL = ((0, 0), (), posiciones_personas, False)
    problema = RescatePersonas(ESTADO_INICIAL)

    if metodo_busqueda == 'astar':
        return astar(problema, graph_search=True)
    elif metodo_busqueda == 'depth_first':
        return depth_first(problema, graph_search=True)
    elif metodo_busqueda == 'breadth_first':
        return breadth_first(problema, graph_search=True)
    elif metodo_busqueda == 'greedy':
        return greedy(problema, graph_search=True)
Exemplo n.º 2
0
def play_move_ai(game, current_player, memory, user_args):
    my_viewer = ConsoleViewer()
    my_problem = HanabiProblem(game)
    result = breadth_first(my_problem, viewer=my_viewer)
    #result = breadth_first(my_problem)
    print result.state
    print print_game(result.game_states[result.state], -1, True)
    print result.path()
Exemplo n.º 3
0
def find_path(source: List[List[str]], dest: List[List[str]]) -> TaskExec:

    tp = TaskProblem(goal=dest, initial_vars=source)

    result = breadth_first(tp, graph_search=True)
    if result:
        return result.path()
    return []
Exemplo n.º 4
0
def BFS(SearchingProblem):
    print("---Breadth First Search---")
    before = datetime.now()
    search = breadth_first(SearchingProblem)
    #search = breadth_first(SearchingProblem,viewer=my_viewer)
    after = datetime.now()
    print("Path -->",search.path())
    print("Time -->", (after - before).total_seconds())
    print("Path cost-->",search.cost)
    print("-" * 40)
Exemplo n.º 5
0
def main():
    start_board = Board.board_from_file(sys.argv[1])
    duplication_checks = sys.argv[2]
    method = sys.argv[3]
    heuristic = ''
    check_duplicates = 'graph' in duplication_checks

    if 'star' in method:
        heuristic = sys.argv[4]

        if heuristic == 'max_moves':
            start_board.heuristic = heuristics.max_moves
        elif heuristic == 'min_moves':
            start_board.heuristic = heuristics.min_moves
        elif heuristic == 'max_movable_pegs':
            start_board.heuristic = heuristics.max_movable_pegs
        elif heuristic == 'man':
            start_board.heuristic = heuristics.manhattan_distance
        else:
            print('You did not pick a viable heuristic. Exiting...')
            return

    start = time.time()
    if method == 'dfs':
        result = depth_first(start_board, check_duplicates)
    elif method == 'bfs':
        result = breadth_first(start_board, check_duplicates)

    elif method == 'astar':
        result = astar(start_board, check_duplicates)

    elif method == 'ildf':
        result = iterative_limited_depth_first(start_board, check_duplicates)

    else:
        print('You must choose a valid search method. Exiting...')
        return

    end = time.time()

    print("-" * 30)
    print('Search:', sys.argv[2], 'on', sys.argv[3], sys.argv[4] if len(sys.argv) > 4 else '')
    print('Input File:', sys.argv[1])
    if result:
        path = result.path()
        for step in path:
            print(step[0], '-->', Board.board_from_state(step[1]))
        print('Duration: {0:.4f} seconds'.format(end - start))
        print('Nodes Visited:', len(path))

    else:
        print("No solution found!")


    print("-" * 30)
Exemplo n.º 6
0
def resolver(metodo_busqueda, posiciones_aparatos):
	Inicial = [(3,3)]
	for ap in posiciones_aparatos:
		Inicial.append((ap[0], ap[1], 300))
	if metodo_busqueda == "breadth_first":
		return breadth_first(Problem(tuple(Inicial)), graph_search=True)
	if metodo_busqueda == "astar":
		return astar(Problem(tuple(Inicial)), graph_search=True)
	if metodo_busqueda == "greedy":
		return greedy(Problem(tuple(Inicial)), graph_search=True)
	if metodo_busqueda == "depth_first":
		return depth_first(Problem(tuple(Inicial)), graph_search=True)
def resolver(metodo_busqueda, posicion_rey, controlar_estados_repetidos):
    problema = HnefataflProblem(posicion_rey)
    visor = BaseViewer()
    if metodo_busqueda == "breadth_first":
        resultado = breadth_first(problema, graph_search=controlar_estados_repetidos)
        return resultado
    if metodo_busqueda == "depth_first":
        return depth_first(problema, graph_search=controlar_estados_repetidos)
    if metodo_busqueda == "greedy":
        return greedy(problema, graph_search=controlar_estados_repetidos)
    if metodo_busqueda == "astar":
        return astar(problema, graph_search=controlar_estados_repetidos)
Exemplo n.º 8
0
def createProblem(vx, vy, x_comida, y_comida):
    problem = MarioGame((vx, vy), (x_comida, y_comida))
    result = breadth_first(problem, graph_search=True)
    path = [x[1] for x in result.path()]
    moves = result.path()
    moves = moves[1:]
    lm = []

    for i in moves:
        lm.append(i[0])

    lm.reverse()
    return lm
def resolver(metodo_busqueda):
    visor = BaseViewer()
    if metodo_busqueda == 'breadth_first':
        result = breadth_first(entrega1tradicional(INITIAL), graph_search=True, viewer=visor)
    if metodo_busqueda == 'depth_first':
        result = depth_first(entrega1tradicional(INITIAL), graph_search=True, viewer=visor)
    if metodo_busqueda == 'limited_depth_first':
        result = iterative_limited_depth_first(entrega1tradicional(INITIAL),10, viewer=visor)
    if metodo_busqueda == 'greedy':
        result = greedy(entrega1tradicional(INITIAL), graph_search=True, viewer=visor)
    if metodo_busqueda == 'astar':
        result = astar(entrega1tradicional(INITIAL), graph_search=True, viewer=visor)

    return result
Exemplo n.º 10
0
def main():

    # to record running time
    import time
    start = time.time()
    #### Uncomment an algorithm to use ####
    # result = depth_first(FifteenPuzzleProblem(INITIAL), 1)
    result = breadth_first(FifteenPuzzleProblem(INITIAL), 1)
    # result = limited_depth_first(FifteenPuzzleProblem(INITIAL), depth_limit=8)
    # result = iterative_limited_depth_first(FifteenPuzzleProblem(INITIAL),1)
    end = time.time()

    def report_result(result):
        count = 1
        for action, state in result.path():
            print("**** STEP NUMBER: {} ****".format(count))
            count += 1
            print('Move number', action)
            print(state)

        # Running time
        print("\ntime taken: ", end - start)

    report_result(result)

    # visualize the solution using pygraph module, to use pygraph see: http://github.com/iamaziz/pygraph

    try:
        from pygraph.dgraph import PyGraph
    except ImportError:
        pass

    name = 'easy-BFS'

    def vizit(name):

        g = PyGraph()
        for i in range(len(result.path())):
            try:
                a1, s1 = result.path()[i]
                a2, s2 = result.path()[i + 1]
                r = [s1, a2, s2]
                relation = ' '.join(r)
                g.add_relation(relation)
            except IndexError:
                pass

        g.draw_graph("15-puzzle-{}".format(name), orientation="LR")
Exemplo n.º 11
0
def resolver(metodo_busqueda, posicion_rey, controlar_estados_repetidos):

    INITIAL = posicion_rey
    problema = HnefataflProblema(posicion_rey)
    visor = BaseViewer()

    #Busqueda en amplitud
    if (metodo_busqueda == 'breadth_first'):
        resultado = breadth_first(problema,
                                  graph_search=controlar_estados_repetidos,
                                  viewer=visor)
        return resultado

    #Busqueda en profundidad
    if (metodo_busqueda == 'depth_first'):
        resultado = depth_first(problema,
                                graph_search=controlar_estados_repetidos,
                                viewer=visor)
        return resultado

    #Busqueda avara
    if (metodo_busqueda == 'greedy'):
        resultado = greedy(problema,
                           graph_search=controlar_estados_repetidos,
                           viewer=visor)
        return resultado

    #Busqueda A Estrella
    if (metodo_busqueda == 'astar'):
        resultado = astar(problema,
                          graph_search=controlar_estados_repetidos,
                          viewer=visor)
        return resultado


#   for action, state in resultado.path():
#        print action

#    print resultado.path()
#   print 'produndidad: ' + str(resultado.depth)

#    print state
#    print 'El costo es: ' + str(resultado.cost)
#    print visor.stats

#if __name__ == '__main__':
#    resolver('breadth_first', (5,3),True)
Exemplo n.º 12
0
def resolver(metodo_busqueda, posiciones_personas):
    inicial = GenerarEstado(posiciones_personas)
    problema = RescateHieloProblem(inicial)

    if metodo_busqueda == "breadth_first":
        return breadth_first(problema,
                             graph_search=True,
                             viewer=ConsoleViewer())

    if metodo_busqueda == "greedy":
        return greedy(problema, graph_search=True, viewer=ConsoleViewer())

    if metodo_busqueda == "depth_first":
        return depth_first(problema, graph_search=True, viewer=ConsoleViewer())

    if metodo_busqueda == "astar":
        return astar(problema, graph_search=True, viewer=ConsoleViewer())
Exemplo n.º 13
0
def resolver(metodo_busqueda, posiciones_personas):
    state = ((0, 0), (posiciones_personas), ())

    my_viewer = BaseViewer()
    if 'astar':
        result = astar(TpProblem(state), graph_search=True, viewer=my_viewer)
    elif 'breadth_first':
        result = breadth_first(TpProblem(state),
                               graph_search=True,
                               viewer=my_viewer)
    elif 'depth_first':
        result = depth_first(TpProblem(state),
                             graph_search=True,
                             viewer=my_viewer)
    elif 'greedy':
        result = greedy(TpProblem(state), graph_search=True, viewer=my_viewer)

    return result
Exemplo n.º 14
0
def resolver(metodo_busqueda, franceses, piratas):
    viewer = None
    letra = 0
    franceses = list(franceses)
    piratas = list(piratas)
    for barcos in piratas:
        if letra == 0:
            piratas[0] = list(piratas[0])
            piratas[0].insert(0, 'A')
            piratas[0].append(0)
            piratas[0].append(0)
            piratas[0] = tuple(piratas[0])

        if letra == 1:
            piratas[1] = list(piratas[1])
            piratas[1].insert(0, 'B')
            piratas[1].append(0)
            piratas[1].append(0)
            piratas[1] = tuple(piratas[1])

        if letra == 2:
            piratas[2] = list(piratas[2])
            piratas[2].insert(0, 'C')
            piratas[2].append(0)
            piratas[2].append(0)
            piratas[2] = tuple(piratas[2])
        letra = letra + 1
    
    estado = ((tuple(piratas), tuple(franceses)))
    
    problem = Barcos_Piratas(estado)

    if metodo_busqueda == "breadth_first":    
        resultado = breadth_first(problem, graph_search=True, viewer = viewer)
    elif metodo_busqueda == "greedy":    
        resultado = greedy(problem, graph_search=True, viewer = viewer)
    elif metodo_busqueda == "depth_first":    
        resultado = depth_first(problem, graph_search=True, viewer = viewer)
    elif metodo_busqueda == "astar":
        resultado = astar(problem, graph_search=True, viewer = viewer)
    elif metodo_busqueda == "uniform_cost":
        resultado = uniform_cost(problem, graph_search=True, viewer = viewer)

    return resultado
Exemplo n.º 15
0
def createProblem(listaSnake, food, method, direction):
    problem = SnakeGame((listaSnake[0].rect.x, listaSnake[0].rect.y), (food.rect.x, food.rect.y), listaSnake, direction)
    if method == "astar":
        result = astar(problem, graph_search=True)
    elif method == "dfs":
        result = depth_first(problem, graph_search=True)
    else:
        result = breadth_first(problem, graph_search=True)

    if result == None:
        return False
    moves = result.path()
    moves = moves[1:]
    lm = []

    for i in moves:
        lm.append(i[0])

    lm.reverse()
    return lm
def resolver(metodo_busqueda, posicion_rey, controlar_estados_repetidos):
    problema = HnefataflProblema(posicion_rey)
    visor = BaseViewer()
    #Busquedas, Grafo -> graph_search=True
    if (metodo_busqueda == 'breadth_first'):  # En amplitud
        resultado = breadth_first(problema,
                                  graph_search=controlar_estados_repetidos,
                                  viewer=visor)
    elif (metodo_busqueda == 'depth_first'):  # Profundidad
        resultado = depth_first(problema,
                                graph_search=controlar_estados_repetidos,
                                viewer=visor)
    elif (metodo_busqueda == 'greedy'):  # Avara
        resultado = greedy(problema,
                           graph_search=controlar_estados_repetidos,
                           viewer=visor)
    elif (metodo_busqueda == 'astar'):  # Estrella
        resultado = astar(problema,
                          graph_search=controlar_estados_repetidos,
                          viewer=visor)
    print(visor.stats)
    return resultado
def resolver(metodo_busqueda, posiciones_aparatos):
    estado = [
        (3, 3, 0),
    ]
    nuevo_estado = ((), )
    lista_aparatos = []

    posiciones_aparatos = list(posiciones_aparatos)
    for artefacto in posiciones_aparatos:
        lista_artefacto = list(artefacto)
        lista_aparatos.append(lista_artefacto)

    posiciones_aparatos = tuple(posiciones_aparatos)

    for aparato in lista_aparatos:
        aparato.append(300)

    for aparato in lista_aparatos:
        tupla_aparato = tuple(aparato)
        estado.append(tupla_aparato)

    nuevo_estado = tuple(estado)
    problema = BomerobotProblem(nuevo_estado)

    if metodo_busqueda == 'breadth_first':
        resultado = breadth_first(problema, graph_search=True)
        return resultado
    if metodo_busqueda == 'depth_first':
        resultado = depth_first(problema, graph_search=True)
        return resultado
    if metodo_busqueda == 'greedy':
        resultado = greedy(problema, graph_search=True)
        return resultado
    if metodo_busqueda == 'astar':
        resultado = astar(problema, graph_search=True)
        return resultado
    def is_goal(self, state):
        """ 
            This method evaluates whether the specified state is the goal state.

            state : The game state to test.
        """
        return state == self.goal


#------------------------------------------------------------------------------------------------------------------
#   Program
#------------------------------------------------------------------------------------------------------------------

# Create solver object
result = breadth_first(MissionariesAndCannibals(), graph_search=True)

# Print results
for i, (action, state) in enumerate(result.path()):
    print()
    if action == None:
        print('Initial configuration')
    elif i == len(result.path()) - 1:
        print('After moving', action, 'Goal achieved!')
    else:
        print('After moving', action)

    print(state)

#------------------------------------------------------------------------------------------------------------------
#   End of file
Exemplo n.º 19
0
            available_actions.append(state[row_zero - 1][col_zero])
        if row_zero < 2:
            available_actions.append(state[row_zero + 1][col_zero])

        if col_zero > 0:
            available_actions.append(state[row_zero][col_zero - 1])
        if col_zero < 2:
            available_actions.append(state[row_zero][col_zero + 1])

        return available_actions

    def result(self, state, action):
        row_zero, col_zero = find(0, state)
        row_piece, col_piece = find(action, state)

        #convert tuples to list
        state_modifiable = list(list(row) for row in state)
        state_modifiable[row_zero][col_zero] = action
        state_modifiable[row_piece][col_piece] = 0

        #convert list to tuples
        state_modifiable = tuple(tuple(row) for row in state_modifiable)
        return state_modifiable

    def cost(self, state1, action, state2):
        return 1


problem = EightPuzzle(INITIAL_STATE)
result = breadth_first(problem, viewer=WebViewer())
Exemplo n.º 20
0
    def is_goal(self, state):
        return GOAL_STATE == state
    
    def actions(self, state):
        available_actions = []
        print(ROOMS.get(state))
        for room in ROOMS.get(state):
            available_actions.append((room))

        return available_actions

    def result(self, state, action):
        
        room = action

        #convert tuples to list
        state_modifiable = state
        state_modifiable = (room)
        #convert list to tuples
        return state_modifiable


    def cost(self, state1,action, state2):
        return 1

problem = Labyrinth(INITIAL_STATE)
result = breadth_first(problem, graph_search=True, viewer=WebViewer())

for element in result.path():
    print(element)
print(result)
                state.insert(1 + i, "wa")
                state.remove("wb")

            for i in range(sheeps):
                state.insert(len(state), "sa")
                state.remove("sb")

        else:
            state[0] = "b"
            for i in range(wolfs):
                state.insert(1 + i, "wb")
                state.remove("wa")

            for i in range(sheeps):
                state.insert(len(state), "sb")
                state.remove("sa")
        return "-".join(state)

    def is_goal(self, state):
        if state == "b-wb-wb-wb-sb-sb-sb":
            return True
        else:
            return False


test = IbrahimProblem(initial_state="a-wa-wa-wa-sa-sa-sa")
result = breadth_first(test)

print(result.state)  # the goal state
print(result.path())
        elif action == 'MD':
            p = t[pos[0]][pos[1] + 1]
            t[pos[0]][pos[1]] = p
            t[pos[0]][pos[1] + 1] = 0

        return self.convertStateintoTuple(t)

    def is_goal(self, state):
        return state == GOAL


size = width, height = [800, 600]
pygame.init()
pantalla = pygame.display.set_mode(size)
p = Puzzle()
result = breadth_first(Puzzle(INITIAL))
resultado = result.path()
print(resultado)
done = False
interactive = False
while not done:
    font = pygame.font.Font('freesansbold.ttf', 20)
    if not interactive:
        for action, state in resultado:
            y = 1
            if action == 'MB':
                render = font.render("Movio el espacio hacia abajo", True,
                                     [255, 255, 255])
                pos = [100, 50]
                pantalla.blit(render, pos)
            elif action == 'MA':
Exemplo n.º 23
0
            return list(' ABCDEFGHIJKLMNOPQRSTUVWXYZ')
        return []

    def result(self, state, action):
        return state + action

    def is_goal(self, state):
        return state == GOAL

    def heuristic(self, state):
        wrong = sum(
            [1 if state[i] != GOAL[i] else 0 for i in range(len(state))])
        missing = len(GOAL) - len(state)
        return wrong + missing


# Using Breadth-First Search
t1 = time.time()
problem = HelloProblem(initial_state='')
result = breadth_first(problem)
print('Time: {:.5f}s'.format(time.time() - t1))
print(result.state)
print(result.path())

# Using Greedy Search
t1 = time.time()
problem = HelloProblem(initial_state='')
result = greedy(problem)
print('Time: {:.5f}s'.format(time.time() - t1))
print(result.state)
print(result.path())
Exemplo n.º 24
0
        '''Returns true if a state is the goal state.'''
        return state == GOAL

    def cost(self, state1, action, state2):
        '''Returns the cost of performing an action. No useful on this problem, i
           but needed.
        '''
        return 1

    def heuristic(self, state):
        '''Returns an *estimation* of the distance from a state to the goal.
           We are using the manhattan distance.
        '''
        rows = string_to_list(state)

        distance = 0

        row_c, col_c = find_location(rows, 'c')
        row_c_goal, col_c_goal = goal_positions['c']

        distance += abs(row_c - row_c_goal) + abs(col_c - col_c_goal)

        return distance


result = breadth_first(SnakeProblem(INITIAL), graph_search=True)

for action, state in result.path():
    print('Move ', action)
print(state)
Exemplo n.º 25
0
 def test_breadth_first(self):
     result = breadth_first(self.problem)
     self.assertEquals(result.state, GOAL)
Exemplo n.º 26
0
    def actions(self, state):
        if len(state) < len(GOAL):
            return list(' ABCDEFGHIJKLMNOPQRSTUVWXYZ')
        return []

    def result(self, state, action):
        return state + action

    def is_goal(self, state):
        return state == GOAL
    
    def heuristic(self, state):
        wrong = sum([1 if state[i] != GOAL[i] else 0 for i in range(len(state))])
        missing = len(GOAL) - len(state)
        return wrong + missing

# Using Breadth-First Search
t1 = time.time()
problem = HelloProblem(initial_state='')
result = breadth_first(problem)
print('Time: {:.5f}s'.format(time.time() - t1))
print(result.state)
print(result.path())

# Using Greedy Search
t1 = time.time()
problem = HelloProblem(initial_state='')
result = greedy(problem)
print('Time: {:.5f}s'.format(time.time() - t1))
print(result.state)
print(result.path())
Exemplo n.º 27
0
def doBreadthFirst(NEWMAP, problem, myviewer):
    result = breadth_first(problem, graph_search=True, viewer=myviewer)
    path = [x[1] for x in result.path()]
    print("Ruta realizada Anchura:")
    print(result.path())
    print(printMap(NEWMAP, problem, path))
Exemplo n.º 28
0
def resolver(metodo_busqueda, posiciones_personas):
    state = ((0, 0), (posiciones_personas), ())

    my_viewer = BaseViewer()
    if 'astar':
        result = astar(TpProblem(state), graph_search=True, viewer=my_viewer)
    elif 'breadth_first':
        result = breadth_first(TpProblem(state),
                               graph_search=True,
                               viewer=my_viewer)
    elif 'depth_first':
        result = depth_first(TpProblem(state),
                             graph_search=True,
                             viewer=my_viewer)
    elif 'greedy':
        result = greedy(TpProblem(state), graph_search=True, viewer=my_viewer)

    return result


if __name__ == "__main__":
    my_viewer = BaseViewer()
    state = ((0, 0), ((2, 1), (3, 4), (4, 2)), ())
    result = breadth_first(TpProblem(state),
                           graph_search=True,
                           viewer=my_viewer)
    print("Stats: ", my_viewer.stats)
    print("Solucion: ", result.state)
    print("profundidad_solucion: ", len(result.path()))
    print("costo_solucion:", result.cost)