Browse Source

Move `__str__` to `pprint_grid` and add test for it (#394)

Mark Towers 1 năm trước cách đây
mục cha
commit
55beb586d6
2 tập tin đã thay đổi với 27 bổ sung1 xóa
  1. 5 1
      minigrid/minigrid_env.py
  2. 22 0
      tests/test_envs.py

+ 5 - 1
minigrid/minigrid_env.py

@@ -172,12 +172,16 @@ class MiniGridEnv(gym.Env):
     def steps_remaining(self):
         return self.max_steps - self.step_count
 
-    def __str__(self):
+    def pprint_grid(self):
         """
         Produce a pretty string of the environment's grid along with the agent.
         A grid cell is represented by 2-character string, the first one for
         the object and the second one for the color.
         """
+        if self.agent_pos is None or self.agent_dir is None or self.grid is None:
+            raise ValueError(
+                "The environment hasn't been `reset` therefore the `agent_pos`, `agent_dir` or `grid` are unknown."
+            )
 
         # Map of object types to short string
         OBJECT_TO_STR = {

+ 22 - 0
tests/test_envs.py

@@ -1,6 +1,7 @@
 from __future__ import annotations
 
 import pickle
+import re
 import warnings
 
 import gymnasium as gym
@@ -327,3 +328,24 @@ def test_env_sync_vectorization(env_id):
     env.reset()
     env.step(env.action_space.sample())
     env.close()
+
+
+def test_pprint_grid(env_id="MiniGrid-Empty-8x8-v0"):
+    env = gym.make(env_id)
+
+    env_repr = str(env)
+    assert (
+        env_repr
+        == "<OrderEnforcing<PassiveEnvChecker<EmptyEnv<MiniGrid-Empty-8x8-v0>>>>"
+    )
+
+    with pytest.raises(
+        ValueError,
+        match=re.escape(
+            "The environment hasn't been `reset` therefore the `agent_pos`, `agent_dir` or `grid` are unknown."
+        ),
+    ):
+        env.unwrapped.pprint_grid()
+
+    env.reset()
+    assert isinstance(env.unwrapped.pprint_grid(), str)