obstructedmaze.py 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  1. from gym_minigrid.minigrid import COLOR_NAMES, DIR_TO_VEC, Ball, Box, Key, MissionSpace
  2. from gym_minigrid.roomgrid import RoomGrid
  3. class ObstructedMazeEnv(RoomGrid):
  4. """
  5. ### Description
  6. The agent has to pick up a box which is placed in a corner of a 3x3 maze.
  7. The doors are locked, the keys are hidden in boxes and doors are obstructed
  8. by balls. This environment can be solved without relying on language.
  9. ### Mission Space
  10. "pick up the {COLOR_NAMES[0]} ball"
  11. ### Action Space
  12. | Num | Name | Action |
  13. |-----|--------------|---------------------------|
  14. | 0 | left | Turn left |
  15. | 1 | right | Turn right |
  16. | 2 | forward | Move forward |
  17. | 3 | pickup | Pick up an object |
  18. | 4 | drop | Unused |
  19. | 5 | toggle | Toggle/activate an object |
  20. | 6 | done | Unused |
  21. ### Observation Encoding
  22. - Each tile is encoded as a 3 dimensional tuple:
  23. `(OBJECT_IDX, COLOR_IDX, STATE)`
  24. - `OBJECT_TO_IDX` and `COLOR_TO_IDX` mapping can be found in
  25. [gym_minigrid/minigrid.py](gym_minigrid/minigrid.py)
  26. - `STATE` refers to the door state with 0=open, 1=closed and 2=locked
  27. ### Rewards
  28. A reward of '1' is given for success, and '0' for failure.
  29. ### Termination
  30. The episode ends if any one of the following conditions is met:
  31. 1. The agent picks up the blue ball.
  32. 2. Timeout (see `max_steps`).
  33. ### Registered Configurations
  34. "NDl" are the number of doors locked.
  35. "h" if the key is hidden in a box.
  36. "b" if the door is obstructed by a ball.
  37. "Q" number of quarters that will have doors and keys out of the 9 that the
  38. map already has.
  39. "Full" 3x3 maze with "h" and "b" options.
  40. - `MiniGrid-ObstructedMaze-1Dl-v0`
  41. - `MiniGrid-ObstructedMaze-1Dlh-v0`
  42. - `MiniGrid-ObstructedMaze-1Dlhb-v0`
  43. - `MiniGrid-ObstructedMaze-2Dl-v0`
  44. - `MiniGrid-ObstructedMaze-2Dlh-v0`
  45. - `MiniGrid-ObstructedMaze-2Dlhb-v0`
  46. - `MiniGrid-ObstructedMaze-1Q-v0`
  47. - `MiniGrid-ObstructedMaze-2Q-v0`
  48. - `MiniGrid-ObstructedMaze-Full-v0`
  49. """
  50. def __init__(self, num_rows, num_cols, num_rooms_visited, **kwargs):
  51. room_size = 6
  52. max_steps = 4 * num_rooms_visited * room_size**2
  53. mission_space = MissionSpace(
  54. mission_func=lambda: f"pick up the {COLOR_NAMES[0]} ball",
  55. )
  56. super().__init__(
  57. mission_space=mission_space,
  58. room_size=room_size,
  59. num_rows=num_rows,
  60. num_cols=num_cols,
  61. max_steps=max_steps,
  62. **kwargs,
  63. )
  64. self.obj = Ball() # initialize the obj attribute, that will be changed later on
  65. def _gen_grid(self, width, height):
  66. super()._gen_grid(width, height)
  67. # Define all possible colors for doors
  68. self.door_colors = self._rand_subset(COLOR_NAMES, len(COLOR_NAMES))
  69. # Define the color of the ball to pick up
  70. self.ball_to_find_color = COLOR_NAMES[0]
  71. # Define the color of the balls that obstruct doors
  72. self.blocking_ball_color = COLOR_NAMES[1]
  73. # Define the color of boxes in which keys are hidden
  74. self.box_color = COLOR_NAMES[2]
  75. self.mission = "pick up the %s ball" % self.ball_to_find_color
  76. def step(self, action):
  77. obs, reward, terminated, truncated, info = super().step(action)
  78. if action == self.actions.pickup:
  79. if self.carrying and self.carrying == self.obj:
  80. reward = self._reward()
  81. terminated = True
  82. return obs, reward, terminated, truncated, info
  83. def add_door(
  84. self,
  85. i,
  86. j,
  87. door_idx=0,
  88. color=None,
  89. locked=False,
  90. key_in_box=False,
  91. blocked=False,
  92. ):
  93. """
  94. Add a door. If the door must be locked, it also adds the key.
  95. If the key must be hidden, it is put in a box. If the door must
  96. be obstructed, it adds a ball in front of the door.
  97. """
  98. door, door_pos = super().add_door(i, j, door_idx, color, locked=locked)
  99. if blocked:
  100. vec = DIR_TO_VEC[door_idx]
  101. blocking_ball = Ball(self.blocking_ball_color) if blocked else None
  102. self.grid.set(door_pos[0] - vec[0], door_pos[1] - vec[1], blocking_ball)
  103. if locked:
  104. obj = Key(door.color)
  105. if key_in_box:
  106. box = Box(self.box_color)
  107. box.contains = obj
  108. obj = box
  109. self.place_in_room(i, j, obj)
  110. return door, door_pos
  111. class ObstructedMaze_1Dlhb(ObstructedMazeEnv):
  112. """
  113. A blue ball is hidden in a 2x1 maze. A locked door separates
  114. rooms. Doors are obstructed by a ball and keys are hidden in boxes.
  115. """
  116. def __init__(self, key_in_box=True, blocked=True, **kwargs):
  117. self.key_in_box = key_in_box
  118. self.blocked = blocked
  119. super().__init__(num_rows=1, num_cols=2, num_rooms_visited=2, **kwargs)
  120. def _gen_grid(self, width, height):
  121. super()._gen_grid(width, height)
  122. self.add_door(
  123. 0,
  124. 0,
  125. door_idx=0,
  126. color=self.door_colors[0],
  127. locked=True,
  128. key_in_box=self.key_in_box,
  129. blocked=self.blocked,
  130. )
  131. self.obj, _ = self.add_object(1, 0, "ball", color=self.ball_to_find_color)
  132. self.place_agent(0, 0)
  133. class ObstructedMaze_Full(ObstructedMazeEnv):
  134. """
  135. A blue ball is hidden in one of the 4 corners of a 3x3 maze. Doors
  136. are locked, doors are obstructed by a ball and keys are hidden in
  137. boxes.
  138. """
  139. def __init__(
  140. self,
  141. agent_room=(1, 1),
  142. key_in_box=True,
  143. blocked=True,
  144. num_quarters=4,
  145. num_rooms_visited=25,
  146. **kwargs,
  147. ):
  148. self.agent_room = agent_room
  149. self.key_in_box = key_in_box
  150. self.blocked = blocked
  151. self.num_quarters = num_quarters
  152. super().__init__(
  153. num_rows=3, num_cols=3, num_rooms_visited=num_rooms_visited, **kwargs
  154. )
  155. def _gen_grid(self, width, height):
  156. super()._gen_grid(width, height)
  157. middle_room = (1, 1)
  158. # Define positions of "side rooms" i.e. rooms that are neither
  159. # corners nor the center.
  160. side_rooms = [(2, 1), (1, 2), (0, 1), (1, 0)][: self.num_quarters]
  161. for i in range(len(side_rooms)):
  162. side_room = side_rooms[i]
  163. # Add a door between the center room and the side room
  164. self.add_door(
  165. *middle_room, door_idx=i, color=self.door_colors[i], locked=False
  166. )
  167. for k in [-1, 1]:
  168. # Add a door to each side of the side room
  169. self.add_door(
  170. *side_room,
  171. locked=True,
  172. door_idx=(i + k) % 4,
  173. color=self.door_colors[(i + k) % len(self.door_colors)],
  174. key_in_box=self.key_in_box,
  175. blocked=self.blocked,
  176. )
  177. corners = [(2, 0), (2, 2), (0, 2), (0, 0)][: self.num_quarters]
  178. ball_room = self._rand_elem(corners)
  179. self.obj, _ = self.add_object(
  180. ball_room[0], ball_room[1], "ball", color=self.ball_to_find_color
  181. )
  182. self.place_agent(*self.agent_room)
  183. class ObstructedMaze_2Dl(ObstructedMaze_Full):
  184. def __init__(self, **kwargs):
  185. super().__init__((2, 1), False, False, 1, 4, **kwargs)
  186. class ObstructedMaze_2Dlh(ObstructedMaze_Full):
  187. def __init__(self, **kwargs):
  188. super().__init__((2, 1), True, False, 1, 4, **kwargs)
  189. class ObstructedMaze_2Dlhb(ObstructedMaze_Full):
  190. def __init__(self, **kwargs):
  191. super().__init__((2, 1), True, True, 1, 4, **kwargs)