doorkey.py 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. from gym_minigrid.minigrid import Door, Goal, Grid, Key, MiniGridEnv, MissionSpace
  2. class DoorKeyEnv(MiniGridEnv):
  3. """
  4. Environment with a door and key, sparse reward
  5. """
  6. def __init__(self, size=8, **kwargs):
  7. if "max_steps" not in kwargs:
  8. kwargs["max_steps"] = 10 * size * size
  9. mission_space = MissionSpace(
  10. mission_func=lambda: "use the key to open the door and then get to the goal"
  11. )
  12. super().__init__(mission_space=mission_space, grid_size=size, **kwargs)
  13. def _gen_grid(self, width, height):
  14. # Create an empty grid
  15. self.grid = Grid(width, height)
  16. # Generate the surrounding walls
  17. self.grid.wall_rect(0, 0, width, height)
  18. # Place a goal in the bottom-right corner
  19. self.put_obj(Goal(), width - 2, height - 2)
  20. # Create a vertical splitting wall
  21. splitIdx = self._rand_int(2, width - 2)
  22. self.grid.vert_wall(splitIdx, 0)
  23. # Place the agent at a random position and orientation
  24. # on the left side of the splitting wall
  25. self.place_agent(size=(splitIdx, height))
  26. # Place a door in the wall
  27. doorIdx = self._rand_int(1, width - 2)
  28. self.put_obj(Door("yellow", is_locked=True), splitIdx, doorIdx)
  29. # Place a yellow key on the left side
  30. self.place_obj(obj=Key("yellow"), top=(0, 0), size=(splitIdx, height))
  31. self.mission = "use the key to open the door and then get to the goal"