unlock.py 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. from gym_minigrid.minigrid import MissionSpace
  2. from gym_minigrid.roomgrid import RoomGrid
  3. class UnlockEnv(RoomGrid):
  4. """
  5. Unlock a door
  6. """
  7. def __init__(self, **kwargs):
  8. room_size = 6
  9. mission_space = MissionSpace(mission_func=lambda: "open the door")
  10. super().__init__(
  11. mission_space=mission_space,
  12. num_rows=1,
  13. num_cols=2,
  14. room_size=room_size,
  15. max_steps=8 * room_size**2,
  16. **kwargs
  17. )
  18. def _gen_grid(self, width, height):
  19. super()._gen_grid(width, height)
  20. # Make sure the two rooms are directly connected by a locked door
  21. door, _ = self.add_door(0, 0, 0, locked=True)
  22. # Add a key to unlock the door
  23. self.add_object(0, 0, "key", door.color)
  24. self.place_agent(0, 0)
  25. self.door = door
  26. self.mission = "open the door"
  27. def step(self, action):
  28. obs, reward, terminated, truncated, info = super().step(action)
  29. if action == self.actions.toggle:
  30. if self.door.is_open:
  31. reward = self._reward()
  32. terminated = True
  33. return obs, reward, terminated, truncated, info