unlockpickup.py 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. from gym_minigrid.minigrid import COLOR_NAMES, MissionSpace
  2. from gym_minigrid.roomgrid import RoomGrid
  3. class UnlockPickupEnv(RoomGrid):
  4. """
  5. ### Description
  6. The agent has to pick up a box which is placed in another room, behind a
  7. locked door. This environment can be solved without relying on language.
  8. ### Mission Space
  9. "pick up the {color} box"
  10. {color} is the color of the box. Can be "red", "green", "blue", "purple",
  11. "yellow" or "grey".
  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 | Pick up an object |
  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. [gym_minigrid/minigrid.py](gym_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 picks up the correct box.
  33. 2. Timeout (see `max_steps`).
  34. ### Registered Configurations
  35. - `MiniGrid-Unlock-v0`
  36. """
  37. def __init__(self, **kwargs):
  38. room_size = 6
  39. mission_space = MissionSpace(
  40. mission_func=lambda color: f"pick up the {color} box",
  41. ordered_placeholders=[COLOR_NAMES],
  42. )
  43. super().__init__(
  44. mission_space=mission_space,
  45. num_rows=1,
  46. num_cols=2,
  47. room_size=room_size,
  48. max_steps=8 * room_size**2,
  49. **kwargs,
  50. )
  51. def _gen_grid(self, width, height):
  52. super()._gen_grid(width, height)
  53. # Add a box to the room on the right
  54. obj, _ = self.add_object(1, 0, kind="box")
  55. # Make sure the two rooms are directly connected by a locked door
  56. door, _ = self.add_door(0, 0, 0, locked=True)
  57. # Add a key to unlock the door
  58. self.add_object(0, 0, "key", door.color)
  59. self.place_agent(0, 0)
  60. self.obj = obj
  61. self.mission = f"pick up the {obj.color} {obj.type}"
  62. def step(self, action):
  63. obs, reward, terminated, truncated, info = super().step(action)
  64. if action == self.actions.pickup:
  65. if self.carrying and self.carrying == self.obj:
  66. reward = self._reward()
  67. terminated = True
  68. return obs, reward, terminated, truncated, info