unlock.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. from typing import Optional
  2. from minigrid.core.mission import MissionSpace
  3. from minigrid.core.roomgrid import RoomGrid
  4. class UnlockEnv(RoomGrid):
  5. """
  6. ![Unlock](../_static/figures/Unlock.png)
  7. ### Description
  8. The agent has to open a locked door. This environment can be solved without
  9. relying on language.
  10. ### Mission Space
  11. "open the door"
  12. ### Action Space
  13. | Num | Name | Action |
  14. |-----|--------------|---------------------------|
  15. | 0 | left | Turn left |
  16. | 1 | right | Turn right |
  17. | 2 | forward | Move forward |
  18. | 3 | pickup | Unused |
  19. | 4 | drop | Unused |
  20. | 5 | toggle | Toggle/activate an object |
  21. | 6 | done | Unused |
  22. ### Observation Encoding
  23. - Each tile is encoded as a 3 dimensional tuple:
  24. `(OBJECT_IDX, COLOR_IDX, STATE)`
  25. - `OBJECT_TO_IDX` and `COLOR_TO_IDX` mapping can be found in
  26. [minigrid/minigrid.py](minigrid/minigrid.py)
  27. - `STATE` refers to the door state with 0=open, 1=closed and 2=locked
  28. ### Rewards
  29. A reward of '1' is given for success, and '0' for failure.
  30. ### Termination
  31. The episode ends if any one of the following conditions is met:
  32. 1. The agent opens the door.
  33. 2. Timeout (see `max_steps`).
  34. ### Registered Configurations
  35. - `MiniGrid-Unlock-v0`
  36. """
  37. def __init__(self, max_steps: Optional[int] = None, **kwargs):
  38. room_size = 6
  39. mission_space = MissionSpace(mission_func=lambda: "open the door")
  40. if max_steps is None:
  41. max_steps = 8 * room_size**2
  42. super().__init__(
  43. mission_space=mission_space,
  44. num_rows=1,
  45. num_cols=2,
  46. room_size=room_size,
  47. max_steps=max_steps,
  48. **kwargs
  49. )
  50. def _gen_grid(self, width, height):
  51. super()._gen_grid(width, height)
  52. # Make sure the two rooms are directly connected by a locked door
  53. door, _ = self.add_door(0, 0, 0, locked=True)
  54. # Add a key to unlock the door
  55. self.add_object(0, 0, "key", door.color)
  56. self.place_agent(0, 0)
  57. self.door = door
  58. self.mission = "open the door"
  59. def step(self, action):
  60. obs, reward, terminated, truncated, info = super().step(action)
  61. if action == self.actions.toggle:
  62. if self.door.is_open:
  63. reward = self._reward()
  64. terminated = True
  65. return obs, reward, terminated, truncated, info