Skip to content

Commit

Permalink
Merge pull request #330 from MarcCote/enh_guess_backend
Browse files Browse the repository at this point in the history
Add helper function to load the right Environment based on file exten…
  • Loading branch information
MarcCote committed Nov 21, 2023
2 parents 08ab525 + c73f7c9 commit df4a201
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 20 deletions.
12 changes: 12 additions & 0 deletions textworld/envs/__init__.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,19 @@
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT license.
import re

from textworld.envs.glulx.git_glulx import GitGlulxEnv
from textworld.envs.zmachine.jericho import JerichoEnv
from textworld.envs.tw import TextWorldEnv
from textworld.envs.wrappers.tw_inform7 import TWInform7


def _guess_backend(path):
# Guess the backend from the extension.
if path.endswith(".ulx"):
return GitGlulxEnv
elif re.search(r"\.z[1-8]", path):
return JerichoEnv

msg = "Unsupported game format: {}".format(path)
raise ValueError(msg)
25 changes: 5 additions & 20 deletions textworld/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,7 @@
from textworld.core import EnvInfos, Environment, Agent
from textworld.generator.game import Game, GameOptions

from textworld.envs import GitGlulxEnv
from textworld.envs import JerichoEnv
from textworld.envs import TextWorldEnv
import textworld.envs
from textworld.envs import TWInform7

from textworld.agents import HumanAgent
Expand Down Expand Up @@ -41,23 +39,10 @@ def start(path: str, request_infos: Optional[EnvInfos] = None,
raise IOError(msg)

# Guess the backend from the extension.
backend = "zmachine"
if path.endswith(".ulx"):
backend = "glulx"
elif path.endswith(".json"):
backend = "json"

if backend == "zmachine":
env = JerichoEnv(request_infos)
elif backend == "glulx":
env = GitGlulxEnv(request_infos)
elif backend == "json":
env = TextWorldEnv(request_infos)
else:
msg = "Unsupported backend: {}".format(backend)
raise ValueError(msg)

if TWInform7.compatible(path) and backend != "json":
Env = textworld.envs._guess_backend(path)
env = Env(request_infos)

if TWInform7.compatible(path):
wrappers = [TWInform7] + list(wrappers)

# Apply all wrappers
Expand Down

0 comments on commit df4a201

Please sign in to comment.