gotoobject.py 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. from gym_minigrid.minigrid import *
  2. from gym_minigrid.register import register
  3. class GoToObjectEnv(MiniGridEnv):
  4. """
  5. Environment in which the agent is instructed to go to a given object
  6. named using an English text string
  7. """
  8. def __init__(
  9. self,
  10. size=6,
  11. numObjs=2
  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. assert width == height
  18. gridSz = width
  19. # Create a grid surrounded by walls
  20. grid = Grid(width, height)
  21. for i in range(0, width):
  22. grid.set(i, 0, Wall())
  23. grid.set(i, height-1, Wall())
  24. for j in range(0, height):
  25. grid.set(0, j, Wall())
  26. grid.set(width-1, j, Wall())
  27. # Types and colors of objects we can generate
  28. types = ['key', 'ball', 'box']
  29. objs = []
  30. objPos = []
  31. # Until we have generated all the objects
  32. while len(objs) < self.numObjs:
  33. objType = self._randElem(types)
  34. objColor = self._randElem(COLOR_NAMES)
  35. # If this object already exists, try again
  36. if (objType, objColor) in objs:
  37. continue
  38. if objType == 'key':
  39. obj = Key(objColor)
  40. elif objType == 'ball':
  41. obj = Ball(objColor)
  42. elif objType == 'box':
  43. obj = Box(objColor)
  44. pos = self.placeObj(grid, obj, self.startPos)
  45. objs.append((objType, objColor))
  46. objPos.append(pos)
  47. # Choose a random object to be picked up
  48. objIdx = self._randInt(0, len(objs))
  49. self.targetType, self.targetColor = objs[objIdx]
  50. self.targetPos = objPos[objIdx]
  51. descStr = '%s %s' % (self.targetColor, self.targetType)
  52. self.mission = 'go to the %s' % descStr
  53. #print(self.mission)
  54. return grid
  55. def step(self, action):
  56. obs, reward, done, info = MiniGridEnv.step(self, action)
  57. ax, ay = self.agentPos
  58. tx, ty = self.targetPos
  59. # Toggle/pickup action terminates the episode
  60. if action == self.actions.toggle:
  61. done = True
  62. # Reward performing the wait action next to the target object
  63. if action == self.actions.wait:
  64. if abs(ax - tx) <= 1 and abs(ay - ty) <= 1:
  65. reward = 1
  66. done = True
  67. return obs, reward, done, info
  68. class GotoEnv8x8N2(GoToObjectEnv):
  69. def __init__(self):
  70. super().__init__(size=8, numObjs=2)
  71. register(
  72. id='MiniGrid-GoToObject-6x6-N2-v0',
  73. entry_point='gym_minigrid.envs:GoToObjectEnv'
  74. )
  75. register(
  76. id='MiniGrid-GoToObject-8x8-N2-v0',
  77. entry_point='gym_minigrid.envs:GotoEnv8x8N2'
  78. )