gotoobject.py 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  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. pos = self.place_obj(obj)
  39. objs.append((objType, objColor))
  40. objPos.append(pos)
  41. # Randomize the agent start position and orientation
  42. self.place_agent()
  43. # Choose a random object to be picked up
  44. objIdx = self._rand_int(0, len(objs))
  45. self.targetType, self.target_color = objs[objIdx]
  46. self.target_pos = objPos[objIdx]
  47. descStr = f"{self.target_color} {self.targetType}"
  48. self.mission = "go to the %s" % descStr
  49. # print(self.mission)
  50. def step(self, action):
  51. obs, reward, done, info = super().step(action)
  52. ax, ay = self.agent_pos
  53. tx, ty = self.target_pos
  54. # Toggle/pickup action terminates the episode
  55. if action == self.actions.toggle:
  56. done = True
  57. # Reward performing the done action next to the target object
  58. if action == self.actions.done:
  59. if abs(ax - tx) <= 1 and abs(ay - ty) <= 1:
  60. reward = self._reward()
  61. done = True
  62. return obs, reward, done, info
  63. register(
  64. id="MiniGrid-GoToObject-6x6-N2-v0",
  65. entry_point="gym_minigrid.envs.gotoobject:GoToObjectEnv",
  66. )
  67. register(
  68. id="MiniGrid-GoToObject-8x8-N2-v0",
  69. entry_point="gym_minigrid.envs.gotoobject:GoToObjectEnv",
  70. size=8,
  71. numObjs=2,
  72. )