Пример #1
0
    def test_second_intermediate_turn(self):
        player_color = "white"
        game_state = GameState()
        strategy = strategy_factory("second")
        first_turn = [9, 15, 3]
        first_int_turn = [11, 10]
        second_int_turn = [12, 20]
        third_int_turn = [2, 34]

        turn_1 = strategy.first_turn(game_state, first_turn)
        game_state.player_first_turn(player_color, turn_1[0], turn_1[1],
                                     turn_1[2], turn_1[3])

        turn_2 = strategy.intermediate_turn(game_state, first_int_turn,
                                            player_color)
        self.assertAlmostEqual(turn_2, [10, 0, 'a2'])
        game_state.player_take_turn(player_color, turn_2[0], turn_2[1],
                                    turn_2[2], first_int_turn)

        turn_3 = strategy.intermediate_turn(game_state, second_int_turn,
                                            player_color)
        self.assertAlmostEqual(turn_3, [20, 0, 'a3'])
        game_state.player_take_turn(player_color, turn_3[0], turn_3[1],
                                    turn_3[2], second_int_turn)

        turn_4 = strategy.intermediate_turn(game_state, third_int_turn,
                                            player_color)
        self.assertAlmostEqual(turn_4, [2, 0, 'b3'])
Пример #2
0
    def test_dumb_second_turn(self):
        game_state = GameState()
        strategy = strategy_factory("second")
        first_turn = [0, 1, 2]
        next_legal_turn = [3, 15, 11]
        illegal_turn = [2, 2, 34]

        turn_1 = strategy.first_turn(game_state, first_turn)

        game_state.player_first_turn("white", turn_1[0], turn_1[1], turn_1[2],
                                     turn_1[3])
        turn_2 = strategy.first_turn(game_state, next_legal_turn)
        turn_3 = strategy.first_turn(game_state, illegal_turn)

        self.assertAlmostEqual(turn_1, [2, 0, 'a1', 'n1'])
        self.assertAlmostEqual(turn_2, [11, 0, 'a3', 'w1'])
        self.assertAlmostEqual(turn_3, [34, 0, 'a1', 'n1'])
    def search(self, initial_state, goal_test_str='standard'):
        self.initial_state = initial_state
        strategy = strategy_factory(name=self.strategy_str,
                                    initial_state=initial_state,
                                    weight_value=5,
                                    heuristic_function=self.heuristic_function)
        self.strategy = strategy

        if goal_test_str == "dl_conflict_solved":

            def goal_test(state):
                for pos, goal in state.boxes.items():
                    goal = state.goals.get(pos)
                    box = state.boxes.get(pos)
                    if box is not None and (goal is None
                                            or goal != box.lower()):
                        return False
                agent_goal = state.goals.get(
                    (state.agent_row, state.agent_col))
                #print(agent_goal)
                if agent_goal is None:  # or agent_goal not in "abcdefghijklmnopqrstuvwxyz":  or agent_goal is 'agent':
                    return False

                return True

        else:

            def goal_test(state):
                return state.is_subgoal_state()

        print('Starting search with strategy {}.'.format(strategy),
              file=sys.stderr,
              flush=True)
        strategy.add_to_frontier(initial_state)
        self.solution = None
        iterations = 0
        while True:
            if iterations == 1000:
                print(strategy.search_status(), file=sys.stderr, flush=True)
                iterations = 0

            if memory.get_usage() > memory.max_usage:
                print('Maximum memory usage exceeded.',
                      file=sys.stderr,
                      flush=True)
                self.solution = []
                return None

            if strategy.frontier_empty():
                self.solution = []
                return None

            leaf = strategy.get_and_remove_leaf()
            if goal_test(leaf):
                self.solution = deque(leaf.extract_plan())
                return

            strategy.add_to_explored(leaf)
            for child_state in leaf.get_children():
                if not strategy.is_explored(
                        child_state) and not strategy.in_frontier(child_state):
                    strategy.add_to_frontier(child_state)

            iterations += 1
Пример #4
0
def main(strategy, subgoals, debug, **extras):
    # Read server messages from stdin.
    server_messages = sys.stdin

    # Use stderr to print to console through server.
    print(
        'SearchClient initializing. I am sending this using the error output stream.',
        file=sys.stderr,
        flush=True)

    # Choose if the level is multi or single agent
    is_multi, first_line = is_multi_agent(server_messages)
    if not is_multi:
        client = SearchClient(server_messages, first_line, debug)

        initial_state = client.initial_state
        w_map = WallMap(initial_state.walls)
        w_map.trim_map(initial_state.boxes,
                       (initial_state.agent_row, initial_state.agent_col))
        #print(w_map.str_nodes(), file=sys.stderr, flush=True)
        #print(w_map.str_map(), file=sys.stderr, flush=True)
        g_map = GoalMap(initial_state.goals)
        planner = Planner()
        planner.floyd_warshall(initial_state.walls)
        strategy_ = strategy_factory(name=strategy,
                                     subgoals=subgoals,
                                     wall_map=w_map,
                                     goal_map=g_map,
                                     initial_state=initial_state,
                                     priority_function=goals_sets,
                                     planner=planner,
                                     heuristic_function=h_constant_reward,
                                     dist_function=planner.dist,
                                     weight_value=5)

        solution = client.search(strategy_)

        # Read level and create the initial state of the problem.
        if solution is None:
            print(strategy_.search_status(), file=sys.stderr, flush=True)
            print('Unable to solve level.', file=sys.stderr, flush=True)
            sys.exit(0)
        else:
            print('\nSummary for {}.'.format(strategy_),
                  file=sys.stderr,
                  flush=True)
            print('Found solution of length {}.'.format(len(solution)),
                  file=sys.stderr,
                  flush=True)
            print('{}.'.format(strategy_.search_status()),
                  file=sys.stderr,
                  flush=True)

            for state in solution:
                print("[" + str(state.action) + "]", flush=True)
                response = server_messages.readline().rstrip()
                if response == 'false':
                    print(
                        'Server responsed with "{}" to the action "{}" applied in:\n{}\n'
                        .format(response, state.action, state),
                        file=sys.stderr,
                        flush=True)
                    break
    else:
        # Read level and create the initial state of the problem.
        client = MultiAgentSearchClient(server_messages, first_line)

        # Add a strategy for each agent
        agents = []
        solution_length = 0
        agent_init_states = client.global_state.split_state()

        for agent_id in sorted(client.agents_map.keys()):
            agent = StatespaceSearchAgent(id=agent_id)
            agents.append(agent)
            agent.initial_state = agent_init_states[agent.id]['initial_state']
        for agent in agents:
            agent.set_search_strategy(
                strategy_str=strategy,
                heuristic_function=h_multiagent_generator(agent, agents))

        # Find and resolve Conflicts with the ConflictManager
        conflict_manager = ConflictManager(agents)

        while True:
            joint_action = []
            joint_action_ids = []
            agent_init_states = None
            for agent in agents:
                # note: plan/replan
                if not agent.solution or len(agent.solution) is 0:
                    # note: lazy instatiate
                    if not agent_init_states:
                        agent_init_states = client.global_state.split_state()
                    initial_state = agent_init_states[
                        agent.id]['initial_state']
                    agent.search(initial_state)
                    # TODO: this is very inefficient. Consider when to do better
                    conflict_manager.solve_conflicts(
                        conflict_manager.getconflicts())
            if max(agents, key=lambda agent: len(agent.solution)) is 0:
                print(agent.strategy.search_status(),
                      file=sys.stderr,
                      flush=True)
                print('Unable to solve level.', file=sys.stderr, flush=True)
                sys.exit(0)

            for agent in agents:
                action = agent.act()
                joint_action.append(str(action))
                joint_action_ids.append((agent.id, action))
            action_str = '[' + ','.join(joint_action) + ']'
            print(action_str, flush=True)
            response = server_messages.readline().rstrip()
            if response == 'false':
                # TODO state does not exist.
                print(
                    'Server responsed with "{}" to the action "{}" applied in:\n{}\n'
                    .format(response, state.action, state),
                    file=sys.stderr,
                    flush=True)
                break

            client.global_state = client.global_state.get_child(
                joint_action_ids)
            solution_length = solution_length + 1
            if client.global_state.is_subgoal_state():
                print('\nSummary for {}.'.format(agent.strategy),
                      file=sys.stderr,
                      flush=True)
                print('Found solution of length {}.'.format(solution_length),
                      file=sys.stderr,
                      flush=True)
                print('{}.'.format(agent.strategy.search_status()),
                      file=sys.stderr,
                      flush=True)
                return  # TODO ???