obstructedmaze.py 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  1. from __future__ import annotations
  2. from minigrid.core.constants import COLOR_NAMES, DIR_TO_VEC
  3. from minigrid.core.mission import MissionSpace
  4. from minigrid.core.roomgrid import RoomGrid
  5. from minigrid.core.world_object import Ball, Box, Key
  6. class ObstructedMazeEnv(RoomGrid):
  7. """
  8. ## Description
  9. The agent has to pick up a box which is placed in a corner of a 3x3 maze.
  10. The doors are locked, the keys are hidden in boxes and doors are obstructed
  11. by balls. This environment can be solved without relying on language.
  12. ## Mission Space
  13. "pick up the {COLOR_NAMES[0]} ball"
  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 | Pick up an object |
  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 picks up the blue ball.
  35. 2. Timeout (see `max_steps`).
  36. ## Registered Configurations
  37. "NDl" are the number of doors locked.
  38. "h" if the key is hidden in a box.
  39. "b" if the door is obstructed by a ball.
  40. "Q" number of quarters that will have doors and keys out of the 9 that the
  41. map already has.
  42. "Full" 3x3 maze with "h" and "b" options.
  43. - `MiniGrid-ObstructedMaze-1Dl-v0`
  44. - `MiniGrid-ObstructedMaze-1Dlh-v0`
  45. - `MiniGrid-ObstructedMaze-1Dlhb-v0`
  46. - `MiniGrid-ObstructedMaze-2Dl-v0`
  47. - `MiniGrid-ObstructedMaze-2Dlh-v0`
  48. - `MiniGrid-ObstructedMaze-2Dlhb-v0`
  49. - `MiniGrid-ObstructedMaze-1Q-v0`
  50. - `MiniGrid-ObstructedMaze-2Q-v0`
  51. - `MiniGrid-ObstructedMaze-Full-v0`
  52. """
  53. def __init__(
  54. self,
  55. num_rows,
  56. num_cols,
  57. num_rooms_visited,
  58. max_steps: int | None = None,
  59. **kwargs,
  60. ):
  61. room_size = 6
  62. if max_steps is None:
  63. max_steps = 4 * num_rooms_visited * room_size**2
  64. mission_space = MissionSpace(
  65. mission_func=self._gen_mission,
  66. ordered_placeholders=[[COLOR_NAMES[0]]],
  67. )
  68. super().__init__(
  69. mission_space=mission_space,
  70. room_size=room_size,
  71. num_rows=num_rows,
  72. num_cols=num_cols,
  73. max_steps=max_steps,
  74. **kwargs,
  75. )
  76. self.obj = Ball() # initialize the obj attribute, that will be changed later on
  77. @staticmethod
  78. def _gen_mission(color: str):
  79. return f"pick up the {color} ball"
  80. def _gen_grid(self, width, height):
  81. super()._gen_grid(width, height)
  82. # Define all possible colors for doors
  83. self.door_colors = self._rand_subset(COLOR_NAMES, len(COLOR_NAMES))
  84. # Define the color of the ball to pick up
  85. self.ball_to_find_color = COLOR_NAMES[0]
  86. # Define the color of the balls that obstruct doors
  87. self.blocking_ball_color = COLOR_NAMES[1]
  88. # Define the color of boxes in which keys are hidden
  89. self.box_color = COLOR_NAMES[2]
  90. self.mission = "pick up the %s ball" % self.ball_to_find_color
  91. def step(self, action):
  92. obs, reward, terminated, truncated, info = super().step(action)
  93. if action == self.actions.pickup:
  94. if self.carrying and self.carrying == self.obj:
  95. reward = self._reward()
  96. terminated = True
  97. return obs, reward, terminated, truncated, info
  98. def add_door(
  99. self,
  100. i,
  101. j,
  102. door_idx=0,
  103. color=None,
  104. locked=False,
  105. key_in_box=False,
  106. blocked=False,
  107. ):
  108. """
  109. Add a door. If the door must be locked, it also adds the key.
  110. If the key must be hidden, it is put in a box. If the door must
  111. be obstructed, it adds a ball in front of the door.
  112. """
  113. door, door_pos = super().add_door(i, j, door_idx, color, locked=locked)
  114. if blocked:
  115. vec = DIR_TO_VEC[door_idx]
  116. blocking_ball = Ball(self.blocking_ball_color) if blocked else None
  117. self.grid.set(door_pos[0] - vec[0], door_pos[1] - vec[1], blocking_ball)
  118. if locked:
  119. obj = Key(door.color)
  120. if key_in_box:
  121. box = Box(self.box_color)
  122. box.contains = obj
  123. obj = box
  124. self.place_in_room(i, j, obj)
  125. return door, door_pos
  126. class ObstructedMaze_1Dlhb(ObstructedMazeEnv):
  127. """
  128. A blue ball is hidden in a 2x1 maze. A locked door separates
  129. rooms. Doors are obstructed by a ball and keys are hidden in boxes.
  130. """
  131. def __init__(self, key_in_box=True, blocked=True, **kwargs):
  132. self.key_in_box = key_in_box
  133. self.blocked = blocked
  134. super().__init__(num_rows=1, num_cols=2, num_rooms_visited=2, **kwargs)
  135. def _gen_grid(self, width, height):
  136. super()._gen_grid(width, height)
  137. self.add_door(
  138. 0,
  139. 0,
  140. door_idx=0,
  141. color=self.door_colors[0],
  142. locked=True,
  143. key_in_box=self.key_in_box,
  144. blocked=self.blocked,
  145. )
  146. self.obj, _ = self.add_object(1, 0, "ball", color=self.ball_to_find_color)
  147. self.place_agent(0, 0)
  148. class ObstructedMaze_Full(ObstructedMazeEnv):
  149. """
  150. A blue ball is hidden in one of the 4 corners of a 3x3 maze. Doors
  151. are locked, doors are obstructed by a ball and keys are hidden in
  152. boxes.
  153. """
  154. def __init__(
  155. self,
  156. agent_room=(1, 1),
  157. key_in_box=True,
  158. blocked=True,
  159. num_quarters=4,
  160. num_rooms_visited=25,
  161. **kwargs,
  162. ):
  163. self.agent_room = agent_room
  164. self.key_in_box = key_in_box
  165. self.blocked = blocked
  166. self.num_quarters = num_quarters
  167. super().__init__(
  168. num_rows=3, num_cols=3, num_rooms_visited=num_rooms_visited, **kwargs
  169. )
  170. def _gen_grid(self, width, height):
  171. super()._gen_grid(width, height)
  172. middle_room = (1, 1)
  173. # Define positions of "side rooms" i.e. rooms that are neither
  174. # corners nor the center.
  175. side_rooms = [(2, 1), (1, 2), (0, 1), (1, 0)][: self.num_quarters]
  176. for i in range(len(side_rooms)):
  177. side_room = side_rooms[i]
  178. # Add a door between the center room and the side room
  179. self.add_door(
  180. *middle_room, door_idx=i, color=self.door_colors[i], locked=False
  181. )
  182. for k in [-1, 1]:
  183. # Add a door to each side of the side room
  184. self.add_door(
  185. *side_room,
  186. locked=True,
  187. door_idx=(i + k) % 4,
  188. color=self.door_colors[(i + k) % len(self.door_colors)],
  189. key_in_box=self.key_in_box,
  190. blocked=self.blocked,
  191. )
  192. corners = [(2, 0), (2, 2), (0, 2), (0, 0)][: self.num_quarters]
  193. ball_room = self._rand_elem(corners)
  194. self.obj, _ = self.add_object(
  195. ball_room[0], ball_room[1], "ball", color=self.ball_to_find_color
  196. )
  197. self.place_agent(*self.agent_room)
  198. class ObstructedMaze_2Dl(ObstructedMaze_Full):
  199. def __init__(self, **kwargs):
  200. super().__init__((2, 1), False, False, 1, 4, **kwargs)
  201. class ObstructedMaze_2Dlh(ObstructedMaze_Full):
  202. def __init__(self, **kwargs):
  203. super().__init__((2, 1), True, False, 1, 4, **kwargs)
  204. class ObstructedMaze_2Dlhb(ObstructedMaze_Full):
  205. def __init__(self, **kwargs):
  206. super().__init__((2, 1), True, True, 1, 4, **kwargs)