Ejemplo n.º 1
0
    def test_win_action(self):
        g_rng.set_seed(2018)
        map_ = make_small_map(n_rooms=5, possible_door_states=["open"])
        world = World.from_map(map_)

        for max_depth in range(1, 3):
            for rule in data.get_rules().values():
                chain = sample_quest(world.state, rng=None, max_depth=max_depth,
                                     nb_retry=30, allow_partial_match=True, backward=True,
                                     rules_per_depth={0: [rule]}, exceptions=["r"])
                assert len(chain) == max_depth, rule.name

                # Build the quest by providing the actions.
                actions = [c.action for c in chain]
                quest = Quest(actions)
                tmp_world = World.from_facts(chain[0].state.facts)

                state = tmp_world.state
                for action in actions:
                    assert not state.is_applicable(quest.win_action)
                    state.apply(action)

                assert state.is_applicable(quest.win_action)

                # Build the quest by only providing the winning conditions.
                quest = Quest(actions=None, winning_conditions=actions[-1].postconditions)
                tmp_world = World.from_facts(chain[0].state.facts)

                state = tmp_world.state
                for action in actions:
                    assert not state.is_applicable(quest.win_action)
                    state.apply(action)

                assert state.is_applicable(quest.win_action)
Ejemplo n.º 2
0
 def setUpClass(cls):
     g_rng.set_seed(201809)
     cls.tmpdir = tempfile.mkdtemp()
     cls.options = textworld.GameOptions()
     cls.options.path = cls.tmpdir
     cls.options.file_ext = ".ulx"
     cls.game, cls.game_file = testing.build_and_compile_game(cls.options)
Ejemplo n.º 3
0
def test_blend_instructions(verbose=False):
    # Make generation throughout the framework reproducible.
    g_rng.set_seed(1234)

    M = textworld.GameMaker()
    r1 = M.new_room()
    r2 = M.new_room()
    M.set_player(r1)

    path = M.connect(r1.north, r2.south)
    path.door = M.new(type="d", name="door")
    M.add_fact("locked", path.door)
    key = M.new(type="k", name="key")
    M.add_fact("match", key, path.door)
    r1.add(key)

    quest = M.set_quest_from_commands(["take key", "unlock door with key", "open door", "go north",
                                       "close door", "lock door with key", "drop key"])

    game = M.build()

    grammar1 = textworld.generator.make_grammar(flags={"blend_instructions": False},
                                                rng=np.random.RandomState(42))

    grammar2 = textworld.generator.make_grammar(flags={"blend_instructions": True},
                                                rng=np.random.RandomState(42))

    quest.desc = None
    game.change_grammar(grammar1)
    quest1 = quest.copy()
    quest.desc = None
    game.change_grammar(grammar2)
    quest2 = quest.copy()
    assert len(quest1.desc) > len(quest2.desc)
def generate_never_ending_game(args):
    g_rng.set_seed(args.seed)

    msg = "--max-steps {} --nb-objects {} --nb-rooms {} --quest-length {} --quest-breadth {} --seed {}"
    print(
        msg.format(args.max_steps, args.nb_objects, args.nb_rooms,
                   args.quest_length, args.quest_breadth, g_rng.seed))
    print("Generating game...")

    options = GameOptions()
    options.seeds = g_rng.seed
    options.nb_rooms = args.nb_rooms
    options.nb_objects = args.nb_objects
    options.quest_length = args.quest_length
    options.quest_breadth = args.quest_breadth

    game = textworld.generator.make_game(options)
    if args.no_quest:
        game.quests = []

    game_name = "neverending"
    path = pjoin(args.output, game_name + ".ulx")
    options = textworld.GameOptions()
    options.path = path
    options.force_recompile = True
    game_file = textworld.generator.compile_game(game, options)
    return game_file
Ejemplo n.º 5
0
def test_html_viewer():
    # Integration test for visualization service
    num_nodes = 3
    num_items = 10
    g_rng.set_seed(1234)
    grammar_flags = {"theme": "house", "include_adj": True}
    game = textworld.generator.make_game(world_size=num_nodes,
                                         nb_objects=num_items,
                                         quest_length=3,
                                         grammar_flags=grammar_flags)

    game_name = "test_html_viewer_wrapper"
    with make_temp_directory(prefix=game_name) as tmpdir:
        game_file = compile_game(game, game_name, games_folder=tmpdir)

        env = textworld.start(game_file)
        env = HtmlViewer(env, open_automatically=False, port=8080)
        env.reset()  # Cause rendering to occur.

    # options.binary_location = "/bin/chromium"
    driver = get_webdriver()

    driver.get("http://127.0.0.1:8080")
    nodes = driver.find_elements_by_class_name("node")
    assert len(nodes) == num_nodes
    items = driver.find_elements_by_class_name("item")

    objects = [obj for obj in game.world.objects if obj.type != "I"]
    assert len(items) == len(objects)

    env.close()
    driver.close()
Ejemplo n.º 6
0
def test_used_names_is_updated(verbose=False):
    # Make generation throughout the framework reproducible.
    g_rng.set_seed(1234)

    # Generate a map that's shape in a cross with room0 in the middle.
    P = Variable('P')
    r = Variable('r_0', 'r')
    k1 = Variable('k_1', 'k')
    k2 = Variable('k_2', 'k')
    c1 = Variable('c_1', 'c')
    c2 = Variable('c_2', 'c')
    facts = [
        Proposition('at', [P, r]),
        Proposition('at', [k1, r]),
        Proposition('at', [k2, r]),
        Proposition('at', [c1, r]),
        Proposition('at', [c2, r]),
        Proposition('match', [k1, c1]),
        Proposition('match', [k2, c2])
    ]
    world = World.from_facts(facts)
    world.set_player_room()  # Set start room to the middle one.
    world.populate_room(10,
                        world.player_room)  # Add objects to the starting room.

    # Generate the world representation.
    grammar = textworld.generator.make_grammar({},
                                               rng=np.random.RandomState(42))

    game = textworld.generator.make_game_with(world, [], grammar)
    for entity_infos in game.infos.values():
        if entity_infos.name is None:
            continue

        assert entity_infos.name in grammar.used_names
Ejemplo n.º 7
0
def test_making_game_with_names_to_exclude():
    g_rng.set_seed(42)

    with make_temp_directory(prefix="test_render_wrapper") as tmpdir:
        game_file1, game1 = textworld.make(2,
                                           20,
                                           3,
                                           3, {"names_to_exclude": []},
                                           seed=123,
                                           games_dir=tmpdir)

        game1_objects_names = [
            info.name for info in game1.infos.values() if info.name is not None
        ]
        game_file2, game2 = textworld.make(
            2,
            20,
            3,
            3, {"names_to_exclude": game1_objects_names},
            seed=123,
            games_dir=tmpdir)
        game2_objects_names = [
            info.name for info in game2.infos.values() if info.name is not None
        ]
        assert len(set(game1_objects_names) & set(game2_objects_names)) == 0
Ejemplo n.º 8
0
    def test_generating_quests(self):
        g_rng.set_seed(2018)
        map_ = make_small_map(n_rooms=5, possible_door_states=["open"])
        world = World.from_map(map_)

        def _rule_to_skip(rule):
            # Examine, look and inventory shouldn't be used for chaining.
            if rule.name.startswith("look"):
                return True

            if rule.name.startswith("inventory"):
                return True

            if rule.name.startswith("examine"):
                return True

            return False

        for max_depth in range(1, 3):
            for rule in KnowledgeBase.default().rules.values():
                if _rule_to_skip(rule):
                    continue

                options = ChainingOptions()
                options.backward = True
                options.max_depth = max_depth
                options.max_length = max_depth
                options.create_variables = True
                options.rules_per_depth = [[rule]]
                options.restricted_types = {"r"}
                chain = sample_quest(world.state, options)

                # Build the quest by providing the actions.
                actions = chain.actions
                assert len(actions) == max_depth, rule.name
                quest = Quest(win_events=[Event(actions)])
                tmp_world = World.from_facts(chain.initial_state.facts)

                state = tmp_world.state
                for action in actions:
                    assert not quest.is_winning(state)
                    state.apply(action)

                assert quest.is_winning(state)

                # Build the quest by only providing the winning conditions.
                quest = Quest(
                    win_events=[Event(conditions=actions[-1].postconditions)])
                tmp_world = World.from_facts(chain.initial_state.facts)

                state = tmp_world.state
                for action in actions:
                    assert not quest.is_winning(state)
                    state.apply(action)

                assert quest.is_winning(state)
Ejemplo n.º 9
0
def test_quest_winning_condition():
    g_rng.set_seed(2018)
    map_ = make_small_map(n_rooms=5, possible_door_states=["open"])
    world = World.from_map(map_)

    def _rule_to_skip(rule):
        # Examine, look and inventory shouldn't be used for chaining.
        if rule.name.startswith("look"):
            return True

        if rule.name.startswith("inventory"):
            return True

        if rule.name.startswith("examine"):
            return True

        return False

    for rule in KnowledgeBase.default().rules.values():
        if _rule_to_skip(rule):
            continue

        options = ChainingOptions()
        options.backward = True
        options.max_depth = 1
        options.create_variables = True
        options.rules_per_depth = [[rule]]
        options.restricted_types = {"r"}
        chain = sample_quest(world.state, options)
        assert len(chain.actions) > 0, rule.name
        event = Event(chain.actions)
        quest = Quest(win_events=[event])

        # Set the initial state required for the quest.
        tmp_world = World.from_facts(chain.initial_state.facts)
        game = make_game_with(tmp_world, [quest], make_grammar({}))

        if tmp_world.player_room is None:
            # Randomly place the player in the world since
            # the action doesn't care about where the player is.
            tmp_world.set_player_room()

        game_name = "test_quest_winning_condition_" + rule.name.replace(
            "/", "_")
        with make_temp_directory(prefix=game_name) as tmpdir:
            game_file = _compile_game(game, path=tmpdir)

            env = textworld.start(game_file)
            env.reset()
            game_state, _, done = env.step("look")
            assert not done
            assert not game_state.won

            game_state, _, done = env.step(event.commands[0])
            assert done
            assert game_state.won
Ejemplo n.º 10
0
 def setUpClass(cls):
     g_rng.set_seed(201809)
     cls.tmpdir = tempfile.mkdtemp()
     cls.options = textworld.GameOptions()
     cls.options.path = pjoin(cls.tmpdir, "tw-game.z8")
     cls.game, cls.game_file = testing.build_and_compile_game(cls.options)
     cls.infos = EnvInfos(
         max_score=True,
         score=True,
         won=True,
         lost=True,
     )
Ejemplo n.º 11
0
def make_example_game(args):
    g_rng.set_seed(20201008)

    M = GameMaker()

    # Define rooms
    roomS = M.new_room(name="start", desc="\n")
    roomI = M.new_room(name="if", desc="\n")
    roomV = M.new_room(name="variable", desc="\n")
    roomF = M.new_room(name="for", desc="\n")

    # Define connections
    connectSI = M.connect(roomS.east, roomI.west)
    connectSV = M.connect(roomS.south, roomV.north)
    connectFS = M.connect(roomF.east, roomS.west)

    # Set player
    M.set_player(roomS)

    #Create objects
    i_rand=random.choice(string.ascii_letters)
    f_rand=random.choice(string.ascii_letters)
    v_rand=random.choice(string.ascii_letters)

    objectI = M.new(type='o', name=i_rand, desc="if")
    objectF = M.new(type='o', name=f_rand, desc="for")
    objectV = M.new(type='o', name=v_rand, desc="variable")

    #Add objects to rooms
    roomI.add(objectI)
    roomF.add(objectF)
    roomV.add(objectV)

    #Print object names for testing (will not be in game)
    print(objectI.name)
    print(objectF.name)
    print(objectV.name)

    #Create quests with assigned rewards
    q1 = M.record_quest() #Create quest for including completed if statement
    q1.reward = 1 #Reward for completing if statement (sparse=1, dense=5, balanced=1)
    q2 = M.record_quest() #Create quest for including complete for loop
    q2.reward = 1 #Reward for completing for loop (same distribution as if)
    q3 = M.record_quest() #Create quest for including print statement
    q3.reward = 1 #Reward for completing print statement (sparse=0, dense=1, balanced=1)
    q4 = M.record_quest() #Create quest for including new variable assignment
    q4.reward = 1 #Reward for completing variable assignment (same distribution as print)

    #Create game and associated files
    game_file = M.compile("./carr_dang_shortRL/compiled_game/games.ulx")

    return game_file
Ejemplo n.º 12
0
    def setUpClass(cls):
        g_rng.set_seed(201809)
        cls.tmpdir = tempfile.mkdtemp()
        cls.options = textworld.GameOptions()
        cls.gamefile = pjoin(cls.tmpdir, "tw-game.json")

        cls.game = testing.build_game(cls.options)
        cls.game.save(cls.gamefile)
        cls.infos = EnvInfos(
            facts=True,
            policy_commands=True,
            admissible_commands=True,
            intermediate_reward=True
        )
 def setUpClass(cls):
     g_rng.set_seed(201809)
     cls.tmpdir = tempfile.mkdtemp()
     cls.options = textworld.GameOptions()
     cls.options.path = pjoin(cls.tmpdir, "tw-game.ulx")
     cls.game, cls.gamefile_ulx = testing.build_and_compile_game(
         cls.options)
     cls.options.path = pjoin(cls.tmpdir, "tw-game.z8")
     cls.gamefile_z8 = textworld.generator.compile_game(
         cls.game, cls.options)
     cls.infos = EnvInfos(facts=True,
                          policy_commands=True,
                          admissible_commands=True,
                          intermediate_reward=True)
 def setUpClass(cls):
     g_rng.set_seed(201809)
     cls.tmpdir = tempfile.mkdtemp()
     cls.options = textworld.GameOptions()
     cls.options.path = pjoin(cls.tmpdir, "tw-game.ulx")
     cls.game, cls.gamefile_ulx = testing.build_and_compile_game(
         cls.options)
     cls.options.path = pjoin(cls.tmpdir, "tw-game.z8")
     cls.gamefile_z8 = textworld.generator.compile_game(
         cls.game, cls.options)
     cls.infos = EnvInfos(
         max_score=True,
         objective=True,
     )
Ejemplo n.º 15
0
def test_variable_infos(verbose=False):
    g_rng.set_seed(1234)
    grammar_flags = {"theme": "house", "include_adj": True}
    game = textworld.generator.make_game(world_size=5, nb_objects=10, quest_length=3, grammar_flags=grammar_flags)

    for var_id, var_infos in game.infos.items():
        if var_id not in ["P", "I"]:
            if verbose:
                print(var_infos.serialize())

            assert var_infos.id is not None
            assert var_infos.type is not None
            assert var_infos.name is not None
            assert var_infos.noun is not None
            assert var_infos.adj is not None
            assert var_infos.desc is not None
Ejemplo n.º 16
0
def test_logger():
    rng = np.random.RandomState(1234)
    game_logger = GameLogger()

    for _ in range(10):
        seed = rng.randint(65635)
        g_rng.set_seed(seed)
        game = textworld.generator.make_game(world_size=5, nb_objects=10, quest_length=3, quest_breadth=3)
        game_logger.collect(game)

    with make_temp_directory(prefix="textworld_tests") as tests_folder:
        filename = pjoin(tests_folder, "game_logger.pkl")
        game_logger.save(filename)
        game_logger2 = GameLogger.load(filename)
        assert game_logger is not game_logger2
        assert game_logger.stats() == game_logger2.stats()
Ejemplo n.º 17
0
 def setUpClass(cls):
     g_rng.set_seed(201809)
     cls.tmpdir = tempfile.mkdtemp()
     cls.options = textworld.GameOptions()
     cls.options.path = pjoin(cls.tmpdir, "tw-game.ulx")
     cls.game, cls.gamefile_ulx = testing.build_and_compile_game(cls.options)
     cls.options.path = pjoin(cls.tmpdir, "tw-game.z8")
     cls.gamefile_z8 = textworld.generator.compile_game(cls.game, cls.options)
     cls.infos = EnvInfos(
         inventory=True,
         description=True,
         score=True,
         moves=True,
         won=True,
         lost=True,
     )
Ejemplo n.º 18
0
def test_do_not_overwrite_entity_desc(verbose=False):
    # Make generation throughout the framework reproducible.
    g_rng.set_seed(1234)

    M = textworld.GameMaker()
    r1 = M.new_room()
    M.set_player(r1)

    key = M.new(type="k", name="key", desc="This is a skeleton key.")
    r1.add(key)

    quest = M.set_quest_from_commands(["take key"])
    quest.desc = "Find a valuable object."

    M.build()
    assert key.infos.desc == "This is a skeleton key."
    assert quest.desc == "Find a valuable object."
Ejemplo n.º 19
0
def test_making_game_with_names_to_exclude():
    g_rng.set_seed(42)

    with make_temp_directory(prefix="test_render_wrapper") as tmpdir:
        options = textworld.GameOptions()
        options.path = tmpdir
        options.nb_rooms = 2
        options.nb_objects = 20
        options.quest_length = 3
        options.quest_breadth = 3
        options.seeds = 123
        game_file1, game1 = textworld.make(options)

        options2 = options.copy()
        game1_objects_names = [info.name for info in game1.infos.values() if info.name is not None]
        options2.grammar.names_to_exclude = game1_objects_names
        game_file2, game2 = textworld.make(options2)
        game2_objects_names = [info.name for info in game2.infos.values() if info.name is not None]
        assert len(set(game1_objects_names) & set(game2_objects_names)) == 0
Ejemplo n.º 20
0
def test_quest_losing_condition():
    g_rng.set_seed(2018)
    M = textworld.GameMaker()

    # The goal
    commands = ["go east", "insert carrot into chest"]

    # Create a 'bedroom' room.
    R1 = M.new_room("bedroom")
    R2 = M.new_room("kitchen")
    M.set_player(R1)

    path = M.connect(R1.east, R2.west)
    path.door = M.new(type='d', name='wooden door')
    path.door.add_property("open")

    carrot = M.new(type='f', name='carrot')
    M.inventory.add(carrot)

    # Add a closed chest in R2.
    chest = M.new(type='c', name='chest')
    chest.add_property("open")
    R2.add(chest)

    failing_conditions = (Proposition("eaten", [carrot.var]), )
    quest = M.set_quest_from_commands(commands)
    quest.set_failing_conditions(failing_conditions)
    game = M.build()

    game_name = "test_quest_losing_condition"
    with make_temp_directory(prefix=game_name) as tmpdir:
        game_file = compile_game(game, game_name, games_folder=tmpdir)

        env = textworld.start(game_file)
        env.reset()
        # Make sure we do not rely on the quest progression to
        # determine if the game was lost.
        assert not env._compute_intermediate_reward

        game_state, _, done = env.step("eat carrot")
        assert done
        assert game_state.has_lost
        assert not game_state.has_won
Ejemplo n.º 21
0
def generate_never_ending_game(args):
    g_rng.set_seed(args.seed)
    msg = "--max-steps {} --nb-objects {} --nb-rooms {} --quest-length {} --seed {}"
    print(
        msg.format(args.max_steps, args.nb_objects, args.nb_rooms,
                   args.quest_length, g_rng.seed))
    print("Generating game...")

    grammar_flags = {}
    game = textworld.generator.make_game(args.nb_rooms, args.nb_objects,
                                         args.quest_length, grammar_flags)
    if args.no_quest:
        game.quests = []

    game_name = "neverending"
    game_file = textworld.generator.compile_game(game,
                                                 game_name,
                                                 force_recompile=True,
                                                 games_folder=args.output)
    return game_file
Ejemplo n.º 22
0
    def test_win_action(self):
        g_rng.set_seed(2018)
        map_ = make_small_map(n_rooms=5, possible_door_states=["open"])
        world = World.from_map(map_)

        for max_depth in range(1, 3):
            for rule in data.get_rules().values():
                options = ChainingOptions()
                options.backward = True
                options.max_depth = max_depth
                options.create_variables = True
                options.rules_per_depth = [[rule]]
                options.restricted_types = {"r"}
                chain = sample_quest(world.state, options)

                # Build the quest by providing the actions.
                actions = chain.actions
                if len(actions) != max_depth:
                    print(chain)
                assert len(actions) == max_depth, rule.name
                quest = Quest(actions)
                tmp_world = World.from_facts(chain.initial_state.facts)

                state = tmp_world.state
                for action in actions:
                    assert not state.is_applicable(quest.win_action)
                    state.apply(action)

                assert state.is_applicable(quest.win_action)

                # Build the quest by only providing the winning conditions.
                quest = Quest(actions=None,
                              winning_conditions=actions[-1].postconditions)
                tmp_world = World.from_facts(chain.initial_state.facts)

                state = tmp_world.state
                for action in actions:
                    assert not state.is_applicable(quest.win_action)
                    state.apply(action)

                assert state.is_applicable(quest.win_action)
Ejemplo n.º 23
0
def test_quest_winning_condition():
    g_rng.set_seed(2018)
    map_ = make_small_map(n_rooms=5, possible_door_states=["open"])
    world = World.from_map(map_)

    for rule in data.get_rules().values():
        chain = sample_quest(world.state,
                             rng=None,
                             max_depth=1,
                             nb_retry=20,
                             allow_partial_match=True,
                             backward=True,
                             rules_per_depth={0: [rule]},
                             exceptions=["r"])
        assert len(chain) > 0, rule.name
        quest = Quest([c.action for c in chain])

        # Set the initial state required for the quest.
        tmp_world = World.from_facts(chain[0].state.facts)
        game = make_game_with(tmp_world, [quest], make_grammar({}))

        if tmp_world.player_room is None:
            # Randomly place the player in the world since
            # the action doesn't care about where the player is.
            tmp_world.set_player_room()

        game_name = "test_quest_winning_condition_" + rule.name.replace(
            "/", "_")
        with make_temp_directory(prefix=game_name) as tmpdir:
            game_file = compile_game(game, game_name, games_folder=tmpdir)

            env = textworld.start(game_file)
            env.reset()
            game_state, _, done = env.step("look")
            assert not done
            assert not game_state.has_won

            game_state, _, done = env.step(quest.commands[0])
            assert done
            assert game_state.has_won
Ejemplo n.º 24
0
def test_quest_winning_condition():
    g_rng.set_seed(2018)
    map_ = make_small_map(n_rooms=5, possible_door_states=["open"])
    world = World.from_map(map_)

    for rule in data.get_rules().values():
        options = ChainingOptions()
        options.backward = True
        options.max_depth = 1
        options.create_variables = True
        options.rules_per_depth = [[rule]]
        options.restricted_types = {"r"}
        chain = sample_quest(world.state, options)
        assert len(chain.actions) > 0, rule.name
        quest = Quest(chain.actions)

        # Set the initial state required for the quest.
        tmp_world = World.from_facts(chain.initial_state.facts)
        game = make_game_with(tmp_world, [quest], make_grammar({}))

        if tmp_world.player_room is None:
            # Randomly place the player in the world since
            # the action doesn't care about where the player is.
            tmp_world.set_player_room()

        game_name = "test_quest_winning_condition_" + rule.name.replace(
            "/", "_")
        with make_temp_directory(prefix=game_name) as tmpdir:
            game_file = compile_game(game, game_name, games_folder=tmpdir)

            env = textworld.start(game_file)
            env.reset()
            game_state, _, done = env.step("look")
            assert not done
            assert not game_state.has_won

            game_state, _, done = env.step(quest.commands[0])
            assert done
            assert game_state.has_won
Ejemplo n.º 25
0
def generate_never_ending_game_old(args):
    g_rng.set_seed(args.seed)
    msg = "--max-steps {} --nb-objects {} --nb-rooms {} --seed {}"
    print(
        msg.format(args.max_steps, args.nb_objects, args.nb_rooms, g_rng.seed))
    print("Generating game...")

    map_ = textworld.generator.make_map(n_rooms=args.nb_rooms)
    world = World.from_map(map_)
    world.set_player_room()
    world.populate(nb_objects=args.nb_objects)
    grammar = textworld.generator.make_grammar(flags={"theme": "house"})

    quests = []  # No quest
    game = textworld.generator.make_game_with(world, quests, grammar)

    game_name = "neverending"
    game_file = textworld.generator.compile_game(game,
                                                 game_name,
                                                 force_recompile=True,
                                                 games_folder=args.output)
    return game_file
Ejemplo n.º 26
0
def test_html_viewer():
    # Integration test for visualization service
    # requires geckodriver to be in PATH for selenium to work.
    num_nodes = 3
    num_items = 10
    g_rng.set_seed(1234)
    grammar_flags = {"theme": "house", "include_adj": True}
    game = textworld.generator.make_game(world_size=num_nodes, nb_objects=num_items, quest_length=3, grammar_flags=grammar_flags)

    game_name = "test_html_viewer_wrapper"
    with make_temp_directory(prefix=game_name) as tmpdir:
        game_file = compile_game(game, game_name, games_folder=tmpdir)

        env = textworld.start(game_file)
        env = HtmlViewer(env, open_automatically=False, port=8080)
        env.reset()  # Cause rendering to occur.

    options = Options()
    options.add_argument('headless')
    options.add_argument('ignore-certificate-errors')
    options.add_argument("test-type")
    options.add_argument("no-sandbox")
    options.add_argument("disable-gpu")
    # options.binary_location = "/bin/chromium"

    driver = webdriver.Chrome(chrome_options=options)
    driver.get("http://127.0.0.1:8080")
    nodes = driver.find_elements_by_class_name("node")
    assert len(nodes) == num_nodes
    items = driver.find_elements_by_class_name("item")

    # add one for P
    assert len(items) == num_items + 1

    env.close()
    driver.close()
Ejemplo n.º 27
0
def test_cannot_win_or_lose_a_quest_twice():
    g_rng.set_seed(2018)
    M = textworld.GameMaker()

    # Create a 'bedroom' room.
    R1 = M.new_room("bedroom")
    R2 = M.new_room("kitchen")
    M.set_player(R1)

    path = M.connect(R1.east, R2.west)
    path.door = M.new(type='d', name='wooden door')
    path.door.add_property("open")

    carrot = M.new(type='f', name='carrot')
    lettuce = M.new(type='f', name='lettuce')
    M.inventory.add(carrot)
    M.inventory.add(lettuce)

    # Add a closed chest in R2.
    chest = M.new(type='c', name='chest')
    chest.add_property("open")
    R2.add(chest)

    # The goals
    event_carrot_in_closed_chest = Event(conditions={M.new_fact("in", carrot, chest),
                                                     M.new_fact("closed", chest)})
    event_drop_carrot_R1 = Event(conditions={M.new_fact("at", carrot, R1)})
    event_drop_carrot_R2 = Event(conditions={M.new_fact("at", carrot, R2)})

    quest1 = Quest(win_events=[event_carrot_in_closed_chest],
                   fail_events=[event_drop_carrot_R1, event_drop_carrot_R2])

    event_lettuce_in_closed_chest = Event(conditions={M.new_fact("in", lettuce, chest),
                                                      M.new_fact("closed", chest)})
    event_drop_lettuce_R1 = Event(conditions={M.new_fact("at", lettuce, R1)})
    event_drop_lettuce_R2 = Event(conditions={M.new_fact("at", lettuce, R2)})

    quest2 = Quest(win_events=[event_lettuce_in_closed_chest],
                   fail_events=[event_drop_lettuce_R1, event_drop_lettuce_R2])

    M.quests = [quest1, quest2]
    game = M.build()

    game_name = "test_cannot_win_or_lose_a_quest_twice"
    with make_temp_directory(prefix=game_name) as tmpdir:
        game_file = _compile_game(game, path=tmpdir)

        env = textworld.start(game_file)

        # Complete quest1 then fail it.
        env.reset()
        game_state, score, done = env.step("go east")
        assert score == 0
        game_state, score, done = env.step("insert carrot into chest")
        assert score == 0
        game_state, score, done = env.step("close chest")
        assert score == 1
        assert not done
        game_state, score, done = env.step("open chest")

        # Re-completing quest1 doesn't award more points.
        game_state, score, done = env.step("close chest")
        assert score == 1
        assert not done

        game_state, score, done = env.step("open chest")
        game_state, score, done = env.step("take carrot from chest")
        game_state, score, done = env.step("drop carrot")
        assert score == 1
        assert not done

        # Then fail quest2.
        game_state, score, done = env.step("drop lettuce")
        assert done
        assert game_state.lost
        assert not game_state.won

        env.reset()
        game_state, score, done = env.step("go east")
        game_state, score, done = env.step("insert carrot into chest")
        game_state, score, done = env.step("insert lettuce into chest")
        game_state, score, done = env.step("close chest")
        assert score == 2
        assert done
        assert not game_state.lost
        assert game_state.won
Ejemplo n.º 28
0
import textworld as tw
from textworld import GameMaker

from textworld import g_rng  # global random generator
g_rng.set_seed(1)

M = GameMaker()
roomA = M.new_room("room A")
roomB = M.new_room("room B")
corridor = M.connect(roomA.exits['east'], roomB.exits['west'])
M.render(interactive=True)
Ejemplo n.º 29
0
import textworld
from textworld import GameMaker
from textworld.generator.data import KnowledgeBase
from textworld.generator.game import Event, Quest
from textworld.generator.game import GameOptions

from textworld.generator import compile_game
import io
import sys
import contextlib
import numpy as np

# Make the generation process reproducible.
from textworld import g_rng  # Global random generator.
g_rng.set_seed(20180916)

def _compile_test_game(game):
    grammar_flags = {
        "theme": "house",
        "include_adj": False,
        "only_last_action": True,
        "blend_instructions": True,
        "blend_descriptions": True,
        "refer_by_name_only": True,
        "instruction_extension": []
    }
    rng_grammar = np.random.RandomState(1234)
    grammar = textworld.generator.make_grammar(grammar_flags, rng=rng_grammar)
    game.change_grammar(grammar)

    game_file = textworld.generator.compile_game(game)
Ejemplo n.º 30
0
 def setUpClass(cls):
     g_rng.set_seed(201809)
     cls.game = build_test_game()
     cls.tmpdir = tempfile.mkdtemp()
     cls.game_file = _compile_game(cls.game, folder=cls.tmpdir)