gotoobject.py 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. from gym_minigrid.minigrid import COLOR_NAMES, Ball, Box, Grid, Key, MiniGridEnv
  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__(self, size=6, numObjs=2, **kwargs):
  9. self.numObjs = numObjs
  10. super().__init__(
  11. grid_size=size,
  12. max_steps=5 * size**2,
  13. # Set this to True for maximum speed
  14. see_through_walls=True,
  15. **kwargs,
  16. )
  17. def _gen_grid(self, width, height):
  18. self.grid = Grid(width, height)
  19. # Generate the surrounding walls
  20. self.grid.wall_rect(0, 0, width, height)
  21. # Types and colors of objects we can generate
  22. types = ["key", "ball", "box"]
  23. objs = []
  24. objPos = []
  25. # Until we have generated all the objects
  26. while len(objs) < self.numObjs:
  27. objType = self._rand_elem(types)
  28. objColor = self._rand_elem(COLOR_NAMES)
  29. # If this object already exists, try again
  30. if (objType, objColor) in objs:
  31. continue
  32. if objType == "key":
  33. obj = Key(objColor)
  34. elif objType == "ball":
  35. obj = Ball(objColor)
  36. elif objType == "box":
  37. obj = Box(objColor)
  38. else:
  39. raise ValueError(
  40. "{} object type given. Object type can only be of values key, ball and box.".format(objType)
  41. )
  42. pos = self.place_obj(obj)
  43. objs.append((objType, objColor))
  44. objPos.append(pos)
  45. # Randomize the agent start position and orientation
  46. self.place_agent()
  47. # Choose a random object to be picked up
  48. objIdx = self._rand_int(0, len(objs))
  49. self.targetType, self.target_color = objs[objIdx]
  50. self.target_pos = objPos[objIdx]
  51. descStr = f"{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 = super().step(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 done action next to the target object
  62. if action == self.actions.done:
  63. if abs(ax - tx) <= 1 and abs(ay - ty) <= 1:
  64. reward = self._reward()
  65. done = True
  66. return obs, reward, done, info
  67. register(
  68. id="MiniGrid-GoToObject-6x6-N2-v0",
  69. entry_point="gym_minigrid.envs.gotoobject:GoToObjectEnv",
  70. )
  71. register(
  72. id="MiniGrid-GoToObject-8x8-N2-v0",
  73. entry_point="gym_minigrid.envs.gotoobject:GoToObjectEnv",
  74. size=8,
  75. numObjs=2,
  76. )