gotoobject.py 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  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__(
  15. grid_size=size,
  16. max_steps=5*size,
  17. # Set this to True for maximum speed
  18. see_through_walls=True
  19. )
  20. self.reward_range = (0, 1)
  21. def _gen_grid(self, width, height):
  22. self.grid = Grid(width, height)
  23. # Generate the surrounding walls
  24. self.grid.wallRect(0, 0, width, height)
  25. # Types and colors of objects we can generate
  26. types = ['key', 'ball', 'box']
  27. objs = []
  28. objPos = []
  29. # Until we have generated all the objects
  30. while len(objs) < self.numObjs:
  31. objType = self._randElem(types)
  32. objColor = self._randElem(COLOR_NAMES)
  33. # If this object already exists, try again
  34. if (objType, objColor) in objs:
  35. continue
  36. if objType == 'key':
  37. obj = Key(objColor)
  38. elif objType == 'ball':
  39. obj = Ball(objColor)
  40. elif objType == 'box':
  41. obj = Box(objColor)
  42. pos = self.placeObj(obj)
  43. objs.append((objType, objColor))
  44. objPos.append(pos)
  45. # Randomize the agent start position and orientation
  46. self.placeAgent()
  47. # Choose a random object to be picked up
  48. objIdx = self._randInt(0, len(objs))
  49. self.targetType, self.target_color = objs[objIdx]
  50. self.target_pos = objPos[objIdx]
  51. descStr = '%s %s' % (self.target_color, self.targetType)
  52. self.mission = 'go to the %s' % descStr
  53. #print(self.mission)
  54. def step(self, action):
  55. obs, reward, done, info = MiniGridEnv.step(self, action)
  56. ax, ay = self.agent_pos
  57. tx, ty = self.target_pos
  58. # Toggle/pickup action terminates the episode
  59. if action == self.actions.toggle:
  60. done = True
  61. # Reward performing the wait action next to the target object
  62. if action == self.actions.wait:
  63. if abs(ax - tx) <= 1 and abs(ay - ty) <= 1:
  64. reward = 1
  65. done = True
  66. return obs, reward, done, info
  67. class GotoEnv8x8N2(GoToObjectEnv):
  68. def __init__(self):
  69. super().__init__(size=8, numObjs=2)
  70. register(
  71. id='MiniGrid-GoToObject-6x6-N2-v0',
  72. entry_point='gym_minigrid.envs:GoToObjectEnv'
  73. )
  74. register(
  75. id='MiniGrid-GoToObject-8x8-N2-v0',
  76. entry_point='gym_minigrid.envs:GotoEnv8x8N2'
  77. )