gotodoor.py 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157
  1. from typing import Optional
  2. from minigrid.core.constants import COLOR_NAMES
  3. from minigrid.core.grid import Grid
  4. from minigrid.core.mission import MissionSpace
  5. from minigrid.core.world_object import Door
  6. from minigrid.minigrid_env import MiniGridEnv
  7. class GoToDoorEnv(MiniGridEnv):
  8. """
  9. <p>
  10. <img src="https://raw.githubusercontent.com/Farama-Foundation/Minigrid/master/figures/gotodoor-6x6.png" alt="gotodoor-6x6" width="200px"/>
  11. <video width="200px">
  12. <source src="https://raw.githubusercontent.com/Farama-Foundation/Minigrid/master/figures/gotodoor-6x6.mp4" type="video/mp4" />
  13. </video>
  14. </p>
  15. ### Description
  16. This environment is a room with four doors, one on each wall. The agent
  17. receives a textual (mission) string as input, telling it which door to go
  18. to, (eg: "go to the red door"). It receives a positive reward for performing
  19. the `done` action next to the correct door, as indicated in the mission
  20. string.
  21. ### Mission Space
  22. "go to the {color} door"
  23. {color} is the color of the door. Can be "red", "green", "blue", "purple",
  24. "yellow" or "grey".
  25. ### Action Space
  26. | Num | Name | Action |
  27. |-----|--------------|----------------------|
  28. | 0 | left | Turn left |
  29. | 1 | right | Turn right |
  30. | 2 | forward | Move forward |
  31. | 3 | pickup | Unused |
  32. | 4 | drop | Unused |
  33. | 5 | toggle | Unused |
  34. | 6 | done | Done completing task |
  35. ### Observation Encoding
  36. - Each tile is encoded as a 3 dimensional tuple:
  37. `(OBJECT_IDX, COLOR_IDX, STATE)`
  38. - `OBJECT_TO_IDX` and `COLOR_TO_IDX` mapping can be found in
  39. [minigrid/minigrid.py](minigrid/minigrid.py)
  40. - `STATE` refers to the door state with 0=open, 1=closed and 2=locked
  41. ### Rewards
  42. A reward of '1' is given for success, and '0' for failure.
  43. ### Termination
  44. The episode ends if any one of the following conditions is met:
  45. 1. The agent stands next the correct door performing the `done` action.
  46. 2. Timeout (see `max_steps`).
  47. ### Registered Configurations
  48. - `MiniGrid-GoToDoor-5x5-v0`
  49. - `MiniGrid-GoToDoor-6x6-v0`
  50. - `MiniGrid-GoToDoor-8x8-v0`
  51. """
  52. def __init__(self, size=5, max_steps: Optional[int] = None, **kwargs):
  53. assert size >= 5
  54. self.size = size
  55. mission_space = MissionSpace(
  56. mission_func=self._gen_mission,
  57. ordered_placeholders=[COLOR_NAMES],
  58. )
  59. if max_steps is None:
  60. max_steps = 4 * size**2
  61. super().__init__(
  62. mission_space=mission_space,
  63. width=size,
  64. height=size,
  65. # Set this to True for maximum speed
  66. see_through_walls=True,
  67. max_steps=max_steps,
  68. **kwargs,
  69. )
  70. @staticmethod
  71. def _gen_mission(color: str):
  72. return f"go to the {color} door"
  73. def _gen_grid(self, width, height):
  74. # Create the grid
  75. self.grid = Grid(width, height)
  76. # Randomly vary the room width and height
  77. width = self._rand_int(5, width + 1)
  78. height = self._rand_int(5, height + 1)
  79. # Generate the surrounding walls
  80. self.grid.wall_rect(0, 0, width, height)
  81. # Generate the 4 doors at random positions
  82. doorPos = []
  83. doorPos.append((self._rand_int(2, width - 2), 0))
  84. doorPos.append((self._rand_int(2, width - 2), height - 1))
  85. doorPos.append((0, self._rand_int(2, height - 2)))
  86. doorPos.append((width - 1, self._rand_int(2, height - 2)))
  87. # Generate the door colors
  88. doorColors = []
  89. while len(doorColors) < len(doorPos):
  90. color = self._rand_elem(COLOR_NAMES)
  91. if color in doorColors:
  92. continue
  93. doorColors.append(color)
  94. # Place the doors in the grid
  95. for idx, pos in enumerate(doorPos):
  96. color = doorColors[idx]
  97. self.grid.set(*pos, Door(color))
  98. # Randomize the agent start position and orientation
  99. self.place_agent(size=(width, height))
  100. # Select a random target door
  101. doorIdx = self._rand_int(0, len(doorPos))
  102. self.target_pos = doorPos[doorIdx]
  103. self.target_color = doorColors[doorIdx]
  104. # Generate the mission string
  105. self.mission = "go to the %s door" % self.target_color
  106. def step(self, action):
  107. obs, reward, terminated, truncated, info = super().step(action)
  108. ax, ay = self.agent_pos
  109. tx, ty = self.target_pos
  110. # Don't let the agent open any of the doors
  111. if action == self.actions.toggle:
  112. terminated = True
  113. # Reward performing done action in front of the target door
  114. if action == self.actions.done:
  115. if (ax == tx and abs(ay - ty) == 1) or (ay == ty and abs(ax - tx) == 1):
  116. reward = self._reward()
  117. terminated = True
  118. return obs, reward, terminated, truncated, info