doorkey.py 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. from gym_minigrid.minigrid import *
  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=4 * size)
  9. def _genGrid(self, width, height):
  10. # Create an empty grid
  11. self.grid = Grid(width, height)
  12. # Generate the surrounding walls
  13. self.grid.wallRect(0, 0, width, height)
  14. # Place a goal in the bottom-right corner
  15. self.grid.set(width - 2, height - 2, Goal())
  16. # Create a vertical splitting wall
  17. splitIdx = self._randInt(2, width-2)
  18. self.grid.vertWall(splitIdx, 0)
  19. # Place the agent at a random position and orientation
  20. self.start_pos = self._randPos(
  21. 1, splitIdx,
  22. 1, height-1
  23. )
  24. self.start_dir = self._randInt(0, 4)
  25. # Place a door in the wall
  26. doorIdx = self._randInt(1, width-2)
  27. self.grid.set(splitIdx, doorIdx, LockedDoor('yellow'))
  28. # Place a yellow key on the left side
  29. self.placeObj(
  30. obj=Key('yellow'),
  31. top=(0, 0),
  32. size=(splitIdx, height)
  33. )
  34. self.mission = "use the key to open the door and then get to the goal"
  35. class DoorKeyEnv5x5(DoorKeyEnv):
  36. def __init__(self):
  37. super().__init__(size=5)
  38. class DoorKeyEnv6x6(DoorKeyEnv):
  39. def __init__(self):
  40. super().__init__(size=6)
  41. class DoorKeyEnv16x16(DoorKeyEnv):
  42. def __init__(self):
  43. super().__init__(size=16)
  44. register(
  45. id='MiniGrid-DoorKey-5x5-v0',
  46. entry_point='gym_minigrid.envs:DoorKeyEnv5x5'
  47. )
  48. register(
  49. id='MiniGrid-DoorKey-6x6-v0',
  50. entry_point='gym_minigrid.envs:DoorKeyEnv6x6'
  51. )
  52. register(
  53. id='MiniGrid-DoorKey-8x8-v0',
  54. entry_point='gym_minigrid.envs:DoorKeyEnv'
  55. )
  56. register(
  57. id='MiniGrid-DoorKey-16x16-v0',
  58. entry_point='gym_minigrid.envs:DoorKeyEnv16x16'
  59. )