doorkey.py 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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.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.startPos = self._randPos(
  21. 1, splitIdx,
  22. 1, height-1
  23. )
  24. self.startDir = 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. while True:
  30. pos = self._randPos(
  31. 1, splitIdx,
  32. 1, height-1
  33. )
  34. if pos == self.startPos:
  35. continue
  36. if self.grid.get(*pos) != None:
  37. continue
  38. self.grid.set(*pos, Key('yellow'))
  39. break
  40. self.mission = "use the key to open the door and then get to the goal"
  41. class DoorKeyEnv5x5(DoorKeyEnv):
  42. def __init__(self):
  43. super().__init__(size=5)
  44. class DoorKeyEnv6x6(DoorKeyEnv):
  45. def __init__(self):
  46. super().__init__(size=6)
  47. class DoorKeyEnv16x16(DoorKeyEnv):
  48. def __init__(self):
  49. super().__init__(size=16)
  50. register(
  51. id='MiniGrid-DoorKey-5x5-v0',
  52. entry_point='gym_minigrid.envs:DoorKeyEnv5x5'
  53. )
  54. register(
  55. id='MiniGrid-DoorKey-6x6-v0',
  56. entry_point='gym_minigrid.envs:DoorKeyEnv6x6'
  57. )
  58. register(
  59. id='MiniGrid-DoorKey-8x8-v0',
  60. entry_point='gym_minigrid.envs:DoorKeyEnv'
  61. )
  62. register(
  63. id='MiniGrid-DoorKey-16x16-v0',
  64. entry_point='gym_minigrid.envs:DoorKeyEnv16x16'
  65. )