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