From 55beb586d65328702c6d9f29d8ad9cdba2db6a69 Mon Sep 17 00:00:00 2001 From: Mark Towers Date: Mon, 14 Aug 2023 16:26:47 +0200 Subject: [PATCH] Move `__str__` to `pprint_grid` and add test for it (#394) --- minigrid/minigrid_env.py | 6 +++++- tests/test_envs.py | 22 ++++++++++++++++++++++ 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/minigrid/minigrid_env.py b/minigrid/minigrid_env.py index 910435fc1..23ae5e18b 100755 --- a/minigrid/minigrid_env.py +++ b/minigrid/minigrid_env.py @@ -172,12 +172,16 @@ def hash(self, size=16): 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 = { diff --git a/tests/test_envs.py b/tests/test_envs.py index 6a88a3486..1027676cb 100644 --- a/tests/test_envs.py +++ b/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 env_func(): 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 + == ">>>" + ) + + 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)