fetch.py 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  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. def _genGrid(self, width, height):
  16. assert width == height
  17. gridSz = width
  18. # Create a grid surrounded by walls
  19. grid = Grid(width, height)
  20. for i in range(0, width):
  21. grid.set(i, 0, Wall())
  22. grid.set(i, height-1, Wall())
  23. for j in range(0, height):
  24. grid.set(0, j, Wall())
  25. grid.set(width-1, j, Wall())
  26. types = ['key', 'ball']
  27. colors = list(COLORS.keys())
  28. objs = []
  29. # For each object to be generated
  30. for i in range(0, self.numObjs):
  31. objType = self._randElem(types)
  32. objColor = self._randElem(colors)
  33. if objType == 'key':
  34. obj = Key(objColor)
  35. elif objType == 'ball':
  36. obj = Ball(objColor)
  37. while True:
  38. pos = (
  39. self._randInt(1, gridSz - 1),
  40. self._randInt(1, gridSz - 1)
  41. )
  42. if pos != self.startPos:
  43. grid.set(*pos, obj)
  44. break
  45. objs.append(obj)
  46. # Choose a random object to be picked up
  47. target = objs[self._randInt(0, len(objs))]
  48. self.targetType = target.type
  49. self.targetColor = target.color
  50. descStr = '%s %s' % (self.targetColor, self.targetType)
  51. # Generate the mission string
  52. idx = self._randInt(0, 5)
  53. if idx == 0:
  54. self.mission = 'get a %s' % descStr
  55. elif idx == 1:
  56. self.mission = 'go get a %s' % descStr
  57. elif idx == 2:
  58. self.mission = 'fetch a %s' % descStr
  59. elif idx == 3:
  60. self.mission = 'go fetch a %s' % descStr
  61. elif idx == 4:
  62. self.mission = 'you must fetch a %s' % descStr
  63. assert hasattr(self, 'mission')
  64. return grid
  65. def _reset(self):
  66. obs = MiniGridEnv._reset(self)
  67. obs = {
  68. 'image': obs,
  69. 'mission': self.mission,
  70. 'advice' : ''
  71. }
  72. return obs
  73. def _step(self, action):
  74. obs, reward, done, info = MiniGridEnv._step(self, action)
  75. if self.carrying:
  76. if self.carrying.color == self.targetColor and \
  77. self.carrying.type == self.targetType:
  78. reward = 1000 - self.stepCount
  79. done = True
  80. else:
  81. reward = -1
  82. done = True
  83. obs = {
  84. 'image': obs,
  85. 'mission': self.mission,
  86. 'advice': ''
  87. }
  88. return obs, reward, done, info
  89. register(
  90. id='MiniGrid-Fetch-8x8-v0',
  91. entry_point='gym_minigrid.envs:FetchEnv'
  92. )