playground.py 2.6 KB

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