playground.py 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. from minigrid.core.constants import COLOR_NAMES
  2. from minigrid.core.grid import Grid
  3. from minigrid.core.mission import MissionSpace
  4. from minigrid.core.world_object import Ball, Box, Door, Key
  5. from minigrid.minigrid_env import MiniGridEnv
  6. class PlaygroundEnv(MiniGridEnv):
  7. """
  8. Environment with multiple rooms and random objects.
  9. This environment has no specific goals or rewards.
  10. """
  11. def __init__(self, max_steps=100, **kwargs):
  12. mission_space = MissionSpace(mission_func=self._gen_mission)
  13. self.size = 19
  14. super().__init__(
  15. mission_space=mission_space,
  16. width=self.size,
  17. height=self.size,
  18. max_steps=max_steps,
  19. **kwargs
  20. )
  21. @staticmethod
  22. def _gen_mission():
  23. return ""
  24. def _gen_grid(self, width, height):
  25. # Create the grid
  26. self.grid = Grid(width, height)
  27. # Generate the surrounding walls
  28. self.grid.horz_wall(0, 0)
  29. self.grid.horz_wall(0, height - 1)
  30. self.grid.vert_wall(0, 0)
  31. self.grid.vert_wall(width - 1, 0)
  32. roomW = width // 3
  33. roomH = height // 3
  34. # For each row of rooms
  35. for j in range(0, 3):
  36. # For each column
  37. for i in range(0, 3):
  38. xL = i * roomW
  39. yT = j * roomH
  40. xR = xL + roomW
  41. yB = yT + roomH
  42. # Bottom wall and door
  43. if i + 1 < 3:
  44. self.grid.vert_wall(xR, yT, roomH)
  45. pos = (xR, self._rand_int(yT + 1, yB - 1))
  46. color = self._rand_elem(COLOR_NAMES)
  47. self.grid.set(*pos, Door(color))
  48. # Bottom wall and door
  49. if j + 1 < 3:
  50. self.grid.horz_wall(xL, yB, roomW)
  51. pos = (self._rand_int(xL + 1, xR - 1), yB)
  52. color = self._rand_elem(COLOR_NAMES)
  53. self.grid.set(*pos, Door(color))
  54. # Randomize the player start position and orientation
  55. self.place_agent()
  56. # Place random objects in the world
  57. types = ["key", "ball", "box"]
  58. for i in range(0, 12):
  59. objType = self._rand_elem(types)
  60. objColor = self._rand_elem(COLOR_NAMES)
  61. if objType == "key":
  62. obj = Key(objColor)
  63. elif objType == "ball":
  64. obj = Ball(objColor)
  65. elif objType == "box":
  66. obj = Box(objColor)
  67. else:
  68. raise ValueError(
  69. "{} object type given. Object type can only be of values key, ball and box.".format(
  70. objType
  71. )
  72. )
  73. self.place_obj(obj)
  74. # No explicit mission in this environment
  75. self.mission = ""