fourrooms.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. from gym_minigrid.minigrid import *
  4. from gym_minigrid.register import register
  5. class FourRoomsEnv(MiniGridEnv):
  6. """
  7. Classical 4 rooms Gridworld environmnet.
  8. Can specify agent and goal position, if not it set at random.
  9. """
  10. def __init__(self, agent_pos=None, goal_pos=None):
  11. self._agent_default_pos = agent_pos
  12. self._goal_default_pos = goal_pos
  13. super().__init__(grid_size=19, max_steps=100)
  14. def _gen_grid(self, width, height):
  15. # Create the grid
  16. self.grid = Grid(width, height)
  17. # Generate the surrounding walls
  18. self.grid.horz_wall(0, 0)
  19. self.grid.horz_wall(0, height - 1)
  20. self.grid.vert_wall(0, 0)
  21. self.grid.vert_wall(width - 1, 0)
  22. room_w = width // 2
  23. room_h = height // 2
  24. # For each row of rooms
  25. for j in range(0, 2):
  26. # For each column
  27. for i in range(0, 2):
  28. xL = i * room_w
  29. yT = j * room_h
  30. xR = xL + room_w
  31. yB = yT + room_h
  32. # Bottom wall and door
  33. if i + 1 < 2:
  34. self.grid.vert_wall(xR, yT, room_h)
  35. pos = (xR, self._rand_int(yT + 1, yB))
  36. self.grid.set(*pos, None)
  37. # Bottom wall and door
  38. if j + 1 < 2:
  39. self.grid.horz_wall(xL, yB, room_w)
  40. pos = (self._rand_int(xL + 1, xR), yB)
  41. self.grid.set(*pos, None)
  42. # Randomize the player start position and orientation
  43. if self._agent_default_pos is not None:
  44. self.start_pos = self._agent_default_pos
  45. self.grid.set(*self._agent_default_pos, None)
  46. self.start_dir = self._rand_int(0, 4) # assuming random start direction
  47. else:
  48. self.place_agent()
  49. if self._goal_default_pos is not None:
  50. goal = Goal()
  51. self.grid.set(*self._goal_default_pos, goal)
  52. goal.init_pos, goal.cur_pos = self._goal_default_pos
  53. else:
  54. self.place_obj(Goal())
  55. self.mission = 'Reach the goal'
  56. def step(self, action):
  57. obs, reward, done, info = MiniGridEnv.step(self, action)
  58. return obs, reward, done, info
  59. register(
  60. id='MiniGrid-FourRooms-v0',
  61. entry_point='gym_minigrid.envs:FourRoomsEnv'
  62. )