doorkey.py 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. from gym_minigrid.minigrid import Door, Goal, Grid, Key, MiniGridEnv
  2. from gym_minigrid.register import register
  3. class DoorKeyEnv(MiniGridEnv):
  4. """
  5. Environment with a door and key, sparse reward
  6. """
  7. def __init__(self, size=8):
  8. super().__init__(grid_size=size, max_steps=10 * size * size)
  9. def _gen_grid(self, width, height):
  10. # Create an empty grid
  11. self.grid = Grid(width, height)
  12. # Generate the surrounding walls
  13. self.grid.wall_rect(0, 0, width, height)
  14. # Place a goal in the bottom-right corner
  15. self.put_obj(Goal(), width - 2, height - 2)
  16. # Create a vertical splitting wall
  17. splitIdx = self._rand_int(2, width - 2)
  18. self.grid.vert_wall(splitIdx, 0)
  19. # Place the agent at a random position and orientation
  20. # on the left side of the splitting wall
  21. self.place_agent(size=(splitIdx, height))
  22. # Place a door in the wall
  23. doorIdx = self._rand_int(1, width - 2)
  24. self.put_obj(Door("yellow", is_locked=True), splitIdx, doorIdx)
  25. # Place a yellow key on the left side
  26. self.place_obj(obj=Key("yellow"), top=(0, 0), size=(splitIdx, height))
  27. self.mission = "use the key to open the door and then get to the goal"
  28. class DoorKeyEnv5x5(DoorKeyEnv):
  29. def __init__(self):
  30. super().__init__(size=5)
  31. class DoorKeyEnv6x6(DoorKeyEnv):
  32. def __init__(self):
  33. super().__init__(size=6)
  34. class DoorKeyEnv16x16(DoorKeyEnv):
  35. def __init__(self):
  36. super().__init__(size=16)
  37. register(id="MiniGrid-DoorKey-5x5-v0", entry_point="gym_minigrid.envs:DoorKeyEnv5x5")
  38. register(id="MiniGrid-DoorKey-6x6-v0", entry_point="gym_minigrid.envs:DoorKeyEnv6x6")
  39. register(id="MiniGrid-DoorKey-8x8-v0", entry_point="gym_minigrid.envs:DoorKeyEnv")
  40. register(
  41. id="MiniGrid-DoorKey-16x16-v0", entry_point="gym_minigrid.envs:DoorKeyEnv16x16"
  42. )