fetch.py 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. from gym_minigrid.minigrid import *
  2. from gym_minigrid.register import register
  3. class FetchEnv(MiniGridEnv):
  4. """
  5. Environment in which the agent has to fetch a random object
  6. named using English text strings
  7. """
  8. def __init__(
  9. self,
  10. size=8,
  11. numObjs=3
  12. ):
  13. self.numObjs = numObjs
  14. super().__init__(gridSize=size, maxSteps=5*size)
  15. self.reward_range = (0, 1)
  16. def _genGrid(self, width, height):
  17. self.grid = Grid(width, height)
  18. # Generate the surrounding walls
  19. self.grid.horzWall(0, 0)
  20. self.grid.horzWall(0, height-1)
  21. self.grid.vertWall(0, 0)
  22. self.grid.vertWall(width-1, 0)
  23. types = ['key', 'ball']
  24. objs = []
  25. # For each object to be generated
  26. while len(objs) < self.numObjs:
  27. objType = self._randElem(types)
  28. objColor = self._randElem(COLOR_NAMES)
  29. if objType == 'key':
  30. obj = Key(objColor)
  31. elif objType == 'ball':
  32. obj = Ball(objColor)
  33. self.placeObj(obj)
  34. objs.append(obj)
  35. # Randomize the player start position and orientation
  36. self.placeAgent()
  37. # Choose a random object to be picked up
  38. target = objs[self._randInt(0, len(objs))]
  39. self.targetType = target.type
  40. self.targetColor = target.color
  41. descStr = '%s %s' % (self.targetColor, self.targetType)
  42. # Generate the mission string
  43. idx = self._randInt(0, 5)
  44. if idx == 0:
  45. self.mission = 'get a %s' % descStr
  46. elif idx == 1:
  47. self.mission = 'go get a %s' % descStr
  48. elif idx == 2:
  49. self.mission = 'fetch a %s' % descStr
  50. elif idx == 3:
  51. self.mission = 'go fetch a %s' % descStr
  52. elif idx == 4:
  53. self.mission = 'you must fetch a %s' % descStr
  54. assert hasattr(self, 'mission')
  55. def step(self, action):
  56. obs, reward, done, info = MiniGridEnv.step(self, action)
  57. if self.carrying:
  58. if self.carrying.color == self.targetColor and \
  59. self.carrying.type == self.targetType:
  60. reward = 1
  61. done = True
  62. else:
  63. reward = 0
  64. done = True
  65. return obs, reward, done, info
  66. class FetchEnv5x5N2(FetchEnv):
  67. def __init__(self):
  68. super().__init__(size=5, numObjs=2)
  69. class FetchEnv6x6N2(FetchEnv):
  70. def __init__(self):
  71. super().__init__(size=6, numObjs=2)
  72. register(
  73. id='MiniGrid-Fetch-5x5-N2-v0',
  74. entry_point='gym_minigrid.envs:FetchEnv5x5N2'
  75. )
  76. register(
  77. id='MiniGrid-Fetch-6x6-N2-v0',
  78. entry_point='gym_minigrid.envs:FetchEnv6x6N2'
  79. )
  80. register(
  81. id='MiniGrid-Fetch-8x8-N3-v0',
  82. entry_point='gym_minigrid.envs:FetchEnv'
  83. )