Example #1
0
def _should_check_if_action_is_safe(
        state: State, action: ResourceNode,
        dangerous_resources: FrozenSet[ResourceInfo],
        all_nodes: Tuple[Node, ...]) -> bool:
    """
    Determines if we should _check_ if the given action is safe that state
    :param state:
    :param action:
    :return:
    """
    if any(resource in dangerous_resources for resource in
           action.resource_gain_on_collect(state.node_context())):
        return False

    if isinstance(action, EventNode):
        return True

    if isinstance(action, EventPickupNode):
        pickup_node = action.pickup_node
    else:
        pickup_node = action

    if isinstance(pickup_node, PickupNode):
        target = state.patches.pickup_assignment.get(pickup_node.pickup_index)
        if target is not None and (target.pickup.item_category.is_major
                                   or target.pickup.item_category.is_key):
            return True

    return False
Example #2
0
 def collectable_resource_nodes(self,
                                state: State) -> Iterator[ResourceNode]:
     for node in self.nodes:
         if not node.is_resource_node:
             continue
         node = typing.cast(ResourceNode, node)
         if node.can_collect(state.node_context()):
             yield node
Example #3
0
 def is_resource_node_present(node: Node, state: State):
     if node.is_resource_node:
         assert isinstance(node, ResourceNode)
         is_resource_set = self._initial_state.resources.is_resource_set
         return all(
             is_resource_set(resource) for resource, _ in
             node.resource_gain_on_collect(state.node_context()))
     return False
Example #4
0
    def update_for(self, world: World, state: State,
                   nodes_in_reach: set[Node]):
        g = networkx.DiGraph()

        for area in world.areas:
            g.add_node(area)

        context = state.node_context()
        for area in world.areas:
            nearby_areas = set()
            for node in area.nodes:
                if node not in nodes_in_reach:
                    continue

                for other_node, requirement in node.connections_from(context):
                    if requirement.satisfied(state.resources, state.energy,
                                             state.resource_database):
                        other_area = self.world_list.nodes_to_area(other_node)
                        if other_area in world.areas:
                            nearby_areas.add(other_area)

            for other_area in nearby_areas:
                g.add_edge(area, other_area)

        self.ax.clear()

        cf = self.ax.get_figure()
        cf.set_facecolor("w")

        if world.name not in self._world_to_node_positions:
            self._world_to_node_positions[
                world.name] = self._positions_for_world(world, state)
        pos = self._world_to_node_positions[world.name]

        networkx.draw_networkx_nodes(g, pos, ax=self.ax)
        networkx.draw_networkx_edges(g, pos, arrows=True, ax=self.ax)
        networkx.draw_networkx_labels(
            g,
            pos,
            ax=self.ax,
            labels={area: area.name
                    for area in world.areas},
            verticalalignment='top')

        self.ax.set_axis_off()

        plt.draw_if_interactive()
        self.canvas.draw()
Example #5
0
    def satisfiable_actions(self,
                            state: State,
                            victory_condition: Requirement,
                            ) -> Iterator[Tuple[ResourceNode, int]]:

        interesting_resources = calculate_interesting_resources(
            self._satisfiable_requirements.union(victory_condition.as_set(state.resource_database).alternatives),
            state.resources,
            state.energy,
            state.resource_database)

        # print(" > satisfiable actions, with {} interesting resources".format(len(interesting_resources)))
        for action, energy in self.possible_actions(state):
            for resource, amount in action.resource_gain_on_collect(state.node_context()):
                if resource in interesting_resources:
                    yield action, energy
                    break
Example #6
0
    def calculate_reach(cls, logic: Logic,
                        initial_state: State) -> "ResolverReach":

        checked_nodes: Dict[Node, int] = {}
        database = initial_state.resource_database
        context = initial_state.node_context()

        # Keys: nodes to check
        # Value: how much energy was available when visiting that node
        nodes_to_check: Dict[Node, int] = {
            initial_state.node: initial_state.energy
        }

        reach_nodes: Dict[Node, int] = {}
        requirements_by_node: Dict[Node,
                                   Set[RequirementList]] = defaultdict(set)

        path_to_node: Dict[Node, Tuple[Node, ...]] = {}
        path_to_node[initial_state.node] = tuple()

        while nodes_to_check:
            node = next(iter(nodes_to_check))
            energy = nodes_to_check.pop(node)

            if node.heal:
                energy = initial_state.maximum_energy

            checked_nodes[node] = energy
            if node != initial_state.node:
                reach_nodes[node] = energy

            requirement_to_leave = node.requirement_to_leave(context)

            for target_node, requirement in logic.game.world_list.potential_nodes_from(
                    node, context):
                if target_node is None:
                    continue

                if checked_nodes.get(target_node,
                                     math.inf) <= energy or nodes_to_check.get(
                                         target_node, math.inf) <= energy:
                    continue

                if requirement_to_leave != Requirement.trivial():
                    requirement = RequirementAnd(
                        [requirement, requirement_to_leave])

                # Check if the normal requirements to reach that node is satisfied
                satisfied = requirement.satisfied(initial_state.resources,
                                                  energy, database)
                if satisfied:
                    # If it is, check if we additional requirements figured out by backtracking is satisfied
                    satisfied = logic.get_additional_requirements(
                        node).satisfied(initial_state.resources, energy,
                                        initial_state.resource_database)

                if satisfied:
                    nodes_to_check[target_node] = energy - requirement.damage(
                        initial_state.resources, database)
                    path_to_node[target_node] = path_to_node[node] + (node, )

                elif target_node:
                    # If we can't go to this node, store the reason in order to build the satisfiable requirements.
                    # Note we ignore the 'additional requirements' here because it'll be added on the end.
                    requirements_by_node[target_node].update(
                        requirement.as_set(
                            initial_state.resource_database).alternatives)

        # Discard satisfiable requirements of nodes reachable by other means
        for node in set(reach_nodes.keys()).intersection(
                requirements_by_node.keys()):
            requirements_by_node.pop(node)

        if requirements_by_node:
            satisfiable_requirements = frozenset.union(*[
                RequirementSet(requirements).union(
                    logic.get_additional_requirements(node)).alternatives
                for node, requirements in requirements_by_node.items()
            ])
        else:
            satisfiable_requirements = frozenset()

        return ResolverReach(reach_nodes, path_to_node,
                             satisfiable_requirements, logic)
Example #7
0
 def is_resource_node_present(node: Node, state: State):
     if node.is_resource_node:
         assert isinstance(node, ResourceNode)
         return node.resource(
             state.node_context()) in self._initial_state.resources
     return False