unlockpickup.py 2.9 KB

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