doorkey.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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__(gridSize=size, maxSteps=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.horzWall(0, 0)
  14. self.grid.horzWall(0, height-1)
  15. self.grid.vertWall(0, 0)
  16. self.grid.vertWall(width-1, 0)
  17. # Place a goal in the bottom-right corner
  18. self.grid.set(width - 2, height - 2, Goal())
  19. # Create a vertical splitting wall
  20. splitIdx = self._randInt(2, width-2)
  21. self.grid.vertWall(splitIdx, 0)
  22. # Place the agent at a random position and orientation
  23. self.startPos = self._randPos(
  24. 1, splitIdx,
  25. 1, height-1
  26. )
  27. self.startDir = self._randInt(0, 4)
  28. # Place a door in the wall
  29. doorIdx = self._randInt(1, width-2)
  30. self.grid.set(splitIdx, doorIdx, LockedDoor('yellow'))
  31. # Place a yellow key on the left side
  32. while True:
  33. pos = self._randPos(
  34. 1, splitIdx,
  35. 1, height-1
  36. )
  37. if pos == self.startPos:
  38. continue
  39. if self.grid.get(*pos) != None:
  40. continue
  41. self.grid.set(*pos, Key('yellow'))
  42. break
  43. self.mission = "use the key to open the door and then get to the goal"
  44. class DoorKeyEnv5x5(DoorKeyEnv):
  45. def __init__(self):
  46. super().__init__(size=5)
  47. class DoorKeyEnv6x6(DoorKeyEnv):
  48. def __init__(self):
  49. super().__init__(size=6)
  50. class DoorKeyEnv16x16(DoorKeyEnv):
  51. def __init__(self):
  52. super().__init__(size=16)
  53. register(
  54. id='MiniGrid-DoorKey-5x5-v0',
  55. entry_point='gym_minigrid.envs:DoorKeyEnv5x5'
  56. )
  57. register(
  58. id='MiniGrid-DoorKey-6x6-v0',
  59. entry_point='gym_minigrid.envs:DoorKeyEnv6x6'
  60. )
  61. register(
  62. id='MiniGrid-DoorKey-8x8-v0',
  63. entry_point='gym_minigrid.envs:DoorKeyEnv'
  64. )
  65. register(
  66. id='MiniGrid-DoorKey-16x16-v0',
  67. entry_point='gym_minigrid.envs:DoorKeyEnv16x16'
  68. )