gotoobject.py 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. from __future__ import annotations
  2. from minigrid.core.constants import COLOR_NAMES
  3. from minigrid.core.grid import Grid
  4. from minigrid.core.mission import MissionSpace
  5. from minigrid.core.world_object import Ball, Box, Key
  6. from minigrid.minigrid_env import MiniGridEnv
  7. class GoToObjectEnv(MiniGridEnv):
  8. """
  9. Environment in which the agent is instructed to go to a given object
  10. named using an English text string
  11. """
  12. def __init__(self, size=6, numObjs=2, max_steps: int | None = None, **kwargs):
  13. self.numObjs = numObjs
  14. self.size = size
  15. # Types of objects to be generated
  16. self.obj_types = ["key", "ball", "box"]
  17. mission_space = MissionSpace(
  18. mission_func=self._gen_mission,
  19. ordered_placeholders=[COLOR_NAMES, self.obj_types],
  20. )
  21. if max_steps is None:
  22. max_steps = 5 * size**2
  23. super().__init__(
  24. mission_space=mission_space,
  25. width=size,
  26. height=size,
  27. # Set this to True for maximum speed
  28. see_through_walls=True,
  29. max_steps=max_steps,
  30. **kwargs,
  31. )
  32. @staticmethod
  33. def _gen_mission(color: str, obj_type: str):
  34. return f"go to the {color} {obj_type}"
  35. def _gen_grid(self, width, height):
  36. self.grid = Grid(width, height)
  37. # Generate the surrounding walls
  38. self.grid.wall_rect(0, 0, width, height)
  39. # Types and colors of objects we can generate
  40. types = ["key", "ball", "box"]
  41. objs = []
  42. objPos = []
  43. # Until we have generated all the objects
  44. while len(objs) < self.numObjs:
  45. objType = self._rand_elem(types)
  46. objColor = self._rand_elem(COLOR_NAMES)
  47. # If this object already exists, try again
  48. if (objType, objColor) in objs:
  49. continue
  50. if objType == "key":
  51. obj = Key(objColor)
  52. elif objType == "ball":
  53. obj = Ball(objColor)
  54. elif objType == "box":
  55. obj = Box(objColor)
  56. else:
  57. raise ValueError(
  58. "{} object type given. Object type can only be of values key, ball and box.".format(
  59. objType
  60. )
  61. )
  62. pos = self.place_obj(obj)
  63. objs.append((objType, objColor))
  64. objPos.append(pos)
  65. # Randomize the agent start position and orientation
  66. self.place_agent()
  67. # Choose a random object to be picked up
  68. objIdx = self._rand_int(0, len(objs))
  69. self.targetType, self.target_color = objs[objIdx]
  70. self.target_pos = objPos[objIdx]
  71. descStr = f"{self.target_color} {self.targetType}"
  72. self.mission = "go to the %s" % descStr
  73. # print(self.mission)
  74. def step(self, action):
  75. obs, reward, terminated, truncated, info = super().step(action)
  76. ax, ay = self.agent_pos
  77. tx, ty = self.target_pos
  78. # Toggle/pickup action terminates the episode
  79. if action == self.actions.toggle:
  80. terminated = True
  81. # Reward performing the done action next to the target object
  82. if action == self.actions.done:
  83. if abs(ax - tx) <= 1 and abs(ay - ty) <= 1:
  84. reward = self._reward()
  85. terminated = True
  86. return obs, reward, terminated, truncated, info