gotoobject.py 2.7 KB

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