unlock.py 2.8 KB

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