playground.py 2.6 KB

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