How to use the textworld.generator.game.Quest function in textworld

To help you get started, we’ve selected a few textworld examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github microsoft / TextWorld / textworld / testing.py View on Github external
carrot_in_chest = M.new_event_using_commands(quest1_cmds)
    eating_carrot = Event(conditions={M.new_fact("eaten", carrot)})
    quest1 = Quest(win_events=[carrot_in_chest],
                   fail_events=[eating_carrot],
                   reward=2)

    quest2_cmds = quest1_cmds + ["close chest"]
    quest2_actions = M.new_event_using_commands(quest2_cmds).actions
    chest_closed_with_carrot = Event(
        conditions={
            M.new_fact("in", carrot, chest),
            M.new_fact("closed", chest)
        },
        actions=quest2_actions)

    quest2 = Quest(win_events=[chest_closed_with_carrot],
                   fail_events=[eating_carrot])

    M.quests = [quest1, quest2]
    game = M.build()
    game.main_quest = M.new_quest_using_commands(quest2_cmds)
    game_file = _compile_test_game(game, options)
    return game, game_file
github microsoft / TextWorld / textworld / challenges / simple.py View on Github external
])
            )

    if settings["rewards"] == "dense":
        # Moving through places.
        for room in rooms_to_visit:
            quests.append(
                Quest(win_events=[
                    Event(conditions={M.new_fact("at", M.player, room)})
                ])
            )

    if settings["rewards"] in ["dense", "balanced"]:
        # Retrieving the food item.
        quests.append(
            Quest(win_events=[
                Event(conditions={M.new_fact("in", food, M.inventory)})
            ])
        )

    if settings["rewards"] in ["dense", "balanced"]:
        # Retrieving the food item.
        quests.append(
            Quest(win_events=[
                Event(conditions={M.new_fact("in", food, M.inventory)})
            ])
        )

    if settings["rewards"] in ["dense", "balanced", "sparse"]:
        # Putting the food on the stove.
        quests.append(
            Quest(win_events=[
github microsoft / TextWorld / textworld / challenges / treasure_hunter.py View on Github external
# Place it anywhere in the world.
    world.populate_with([wrong_obj], rng=rng_objects)

    # Generate a quest that finishes by taking something (i.e. the right
    #  object since it's the only one in the inventory).
    options.chaining.rules_per_depth = [kb.rules.get_matching("take.*")]
    options.chaining.backward = True
    options.chaining.rng = rng_quest
    # options.chaining.restricted_types = exceptions
    # exceptions = ["r", "c", "s", "d"] if mode == "easy" else ["r"]
    chain = textworld.generator.sample_quest(world.state, options.chaining)

    # Add objects needed for the quest.
    world.state = chain.initial_state
    event = Event(chain.actions)
    quest = Quest(win_events=[event],
                  fail_events=[Event(conditions={Proposition("in", [wrong_obj, world.inventory])})])

    grammar = textworld.generator.make_grammar(options.grammar, rng=rng_grammar)
    game = textworld.generator.make_game_with(world, [quest], grammar)
    game.metadata = metadata
    mode_choice = modes.index(mode)
    uuid = "tw-treasure_hunter-{specs}-{grammar}-{seeds}"
    uuid = uuid.format(specs=encode_seeds((mode_choice, options.nb_rooms, options.quest_length)),
                       grammar=options.grammar.uuid,
                       seeds=encode_seeds([options.seeds[k] for k in sorted(options.seeds)]))
    game.metadata["uuid"] = uuid
    return game
github microsoft / TextWorld / textworld / generator / game.py View on Github external
def __eq__(self, other: Any) -> bool:
        return (isinstance(other, Quest)
                and self.win_events == other.win_events
                and self.fail_events == other.fail_events
                and self.reward == other.reward
                and self.desc == other.desc
                and self.commands == other.commands)
github microsoft / TextWorld / textworld / generator / game.py View on Github external
grammar: The grammar to control the text generation.
        """
        self.world = world
        self.quests = tuple(quests)
        self.metadata = {}
        self._objective = None
        self._infos = self._build_infos()
        self.kb = world.kb
        self.extras = {}

        # Check if we can derive a global winning policy from the quests.
        self.main_quest = None
        policy = GameProgression(self).winning_policy
        if policy:
            win_event = Event(actions=policy)
            self.main_quest = Quest(win_events=[win_event])

        self.change_grammar(grammar)
github microsoft / TextWorld / textworld / generator / game.py View on Github external
Args:
            data: Serialized data with the needed information to build a
                  `Game` object.
        """

        version = data.get("version", cls._SERIAL_VERSION)
        if version != cls._SERIAL_VERSION:
            msg = "Cannot deserialize a TextWorld version {} game, expected version {}"
            raise ValueError(msg.format(version, cls._SERIAL_VERSION))

        kb = KnowledgeBase.deserialize(data["KB"])
        world = World.deserialize(data["world"], kb=kb)
        game = cls(world)
        game.grammar_options = GrammarOptions(data["grammar"])
        game.quests = tuple([Quest.deserialize(d) for d in data["quests"]])
        game._infos = {k: EntityInfo.deserialize(v) for k, v in data["infos"]}
        game.metadata = data.get("metadata", {})
        game._objective = data.get("objective", None)
        game.extras = data.get("extras", {})
        if "main_quest" in data:
            game.main_quest = Quest.deserialize(data["main_quest"])

        return game
github microsoft / TextWorld / textworld / challenges / simple.py View on Github external
Quest(win_events=[
                Event(conditions={M.new_fact("in", food, M.inventory)})
            ])
        )

    if settings["rewards"] in ["dense", "balanced", "sparse"]:
        # Putting the food on the stove.
        quests.append(
            Quest(win_events=[
                Event(conditions={M.new_fact("on", food, stove)})
            ])
        )

    # 3. Determine the losing condition(s) of the game.
    quests.append(
        Quest(fail_events=[
            Event(conditions={M.new_fact("eaten", food)})
        ])
    )

    # Set the subquest(s).
    M.quests = quests

    # - Add a hint of what needs to be done in this game.
    objective = "The dinner is almost ready! It's only missing a grilled {}."
    objective = objective.format(food.name)
    note = M.new(type='o', name='note', desc=objective)
    kitchen_island.add(note)

    game = M.build()
    game.main_quest = M.new_quest_using_commands(walkthrough)
    game.change_grammar(game.grammar)
github microsoft / TextWorld / textworld / generator / maker.py View on Github external
def new_quest_using_commands(self, commands: List[str]) -> Quest:
        """ Creates a new quest using predefined text commands.

        This launches a `textworld.play` session to execute provided commands.

        Args:
            commands: Text commands.

        Returns:
            The resulting quest.
        """
        event = self.new_event_using_commands(commands)
        return Quest(win_events=[event], commands=event.commands)
github microsoft / TextWorld / textworld / generator / maker.py View on Github external
# Skip "None" actions.
        actions = [action for action in recorder.actions if action is not None]

        # Ask the user which quests have important state, if this is set
        # (if not, we assume the last action contains all the relevant facts)
        winning_facts = None
        if ask_for_state and recorder.last_game_state is not None:
            winning_facts = [user_query.query_for_important_facts(actions=recorder.actions,
                                                                  facts=recorder.last_game_state.state.facts,
                                                                  varinfos=self._working_game.infos)]
        if len(commands) != len(actions):
            unrecognized_commands = [c for c, a in zip(commands, recorder.actions) if a is None]
            raise QuestError("Some of the actions were unrecognized: {}".format(unrecognized_commands))

        event = Event(actions=actions, conditions=winning_facts)
        self.quests = [Quest(win_events=[event])]

        # Calling build will generate the description for the quest.
        self.build()
        return self.quests[-1]
github microsoft / TextWorld / textworld / generator / __init__.py View on Github external
raise NoSuchQuestExistError(msg)

        chains.append(chain)
        state = chain.initial_state  # State might have changed, i.e. options.create_variable is True.

    if options.chaining.backward and hasattr(world, "state"):
        world.state = state

    quests = []
    actions = []
    for chain in reversed(chains):
        for i in range(1, len(chain.nodes)):
            actions.append(chain.actions[i - 1])
            if chain.nodes[i].breadth != chain.nodes[i - 1].breadth:
                event = Event(actions)
                quests.append(Quest(win_events=[event]))

        actions.append(chain.actions[-1])
        event = Event(actions)
        quests.append(Quest(win_events=[event]))

    return quests