roomgrid.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  1. from gym_minigrid.minigrid import COLOR_NAMES, Ball, Box, Door, Grid, Key, MiniGridEnv
  2. def reject_next_to(env, pos):
  3. """
  4. Function to filter out object positions that are right next to
  5. the agent's starting point
  6. """
  7. sx, sy = env.agent_pos
  8. x, y = pos
  9. d = abs(sx - x) + abs(sy - y)
  10. return d < 2
  11. class Room:
  12. def __init__(self, top, size):
  13. # Top-left corner and size (tuples)
  14. self.top = top
  15. self.size = size
  16. # List of door objects and door positions
  17. # Order of the doors is right, down, left, up
  18. self.doors = [None] * 4
  19. self.door_pos = [None] * 4
  20. # List of rooms adjacent to this one
  21. # Order of the neighbors is right, down, left, up
  22. self.neighbors = [None] * 4
  23. # Indicates if this room is behind a locked door
  24. self.locked = False
  25. # List of objects contained
  26. self.objs = []
  27. def rand_pos(self, env):
  28. topX, topY = self.top
  29. sizeX, sizeY = self.size
  30. return env._randPos(topX + 1, topX + sizeX - 1, topY + 1, topY + sizeY - 1)
  31. def pos_inside(self, x, y):
  32. """
  33. Check if a position is within the bounds of this room
  34. """
  35. topX, topY = self.top
  36. sizeX, sizeY = self.size
  37. if x < topX or y < topY:
  38. return False
  39. if x >= topX + sizeX or y >= topY + sizeY:
  40. return False
  41. return True
  42. class RoomGrid(MiniGridEnv):
  43. """
  44. Environment with multiple rooms and random objects.
  45. This is meant to serve as a base class for other environments.
  46. """
  47. def __init__(
  48. self,
  49. room_size=7,
  50. num_rows=3,
  51. num_cols=3,
  52. max_steps=100,
  53. seed=0,
  54. agent_view_size=7,
  55. ):
  56. assert room_size > 0
  57. assert room_size >= 3
  58. assert num_rows > 0
  59. assert num_cols > 0
  60. self.room_size = room_size
  61. self.num_rows = num_rows
  62. self.num_cols = num_cols
  63. height = (room_size - 1) * num_rows + 1
  64. width = (room_size - 1) * num_cols + 1
  65. # By default, this environment has no mission
  66. self.mission = ""
  67. super().__init__(
  68. width=width,
  69. height=height,
  70. max_steps=max_steps,
  71. see_through_walls=False,
  72. seed=seed,
  73. agent_view_size=agent_view_size,
  74. )
  75. def room_from_pos(self, x, y):
  76. """Get the room a given position maps to"""
  77. assert x >= 0
  78. assert y >= 0
  79. i = x // (self.room_size - 1)
  80. j = y // (self.room_size - 1)
  81. assert i < self.num_cols
  82. assert j < self.num_rows
  83. return self.room_grid[j][i]
  84. def get_room(self, i, j):
  85. assert i < self.num_cols
  86. assert j < self.num_rows
  87. return self.room_grid[j][i]
  88. def _gen_grid(self, width, height):
  89. # Create the grid
  90. self.grid = Grid(width, height)
  91. self.room_grid = []
  92. # For each row of rooms
  93. for j in range(0, self.num_rows):
  94. row = []
  95. # For each column of rooms
  96. for i in range(0, self.num_cols):
  97. room = Room(
  98. (i * (self.room_size - 1), j * (self.room_size - 1)),
  99. (self.room_size, self.room_size),
  100. )
  101. row.append(room)
  102. # Generate the walls for this room
  103. self.grid.wall_rect(*room.top, *room.size)
  104. self.room_grid.append(row)
  105. # For each row of rooms
  106. for j in range(0, self.num_rows):
  107. # For each column of rooms
  108. for i in range(0, self.num_cols):
  109. room = self.room_grid[j][i]
  110. x_l, y_l = (room.top[0] + 1, room.top[1] + 1)
  111. x_m, y_m = (
  112. room.top[0] + room.size[0] - 1,
  113. room.top[1] + room.size[1] - 1,
  114. )
  115. # Door positions, order is right, down, left, up
  116. if i < self.num_cols - 1:
  117. room.neighbors[0] = self.room_grid[j][i + 1]
  118. room.door_pos[0] = (x_m, self._rand_int(y_l, y_m))
  119. if j < self.num_rows - 1:
  120. room.neighbors[1] = self.room_grid[j + 1][i]
  121. room.door_pos[1] = (self._rand_int(x_l, x_m), y_m)
  122. if i > 0:
  123. room.neighbors[2] = self.room_grid[j][i - 1]
  124. room.door_pos[2] = room.neighbors[2].door_pos[0]
  125. if j > 0:
  126. room.neighbors[3] = self.room_grid[j - 1][i]
  127. room.door_pos[3] = room.neighbors[3].door_pos[1]
  128. # The agent starts in the middle, facing right
  129. self.agent_pos = (
  130. (self.num_cols // 2) * (self.room_size - 1) + (self.room_size // 2),
  131. (self.num_rows // 2) * (self.room_size - 1) + (self.room_size // 2),
  132. )
  133. self.agent_dir = 0
  134. def place_in_room(self, i, j, obj):
  135. """
  136. Add an existing object to room (i, j)
  137. """
  138. room = self.get_room(i, j)
  139. pos = self.place_obj(
  140. obj, room.top, room.size, reject_fn=reject_next_to, max_tries=1000
  141. )
  142. room.objs.append(obj)
  143. return obj, pos
  144. def add_object(self, i, j, kind=None, color=None):
  145. """
  146. Add a new object to room (i, j)
  147. """
  148. if kind is None:
  149. kind = self._rand_elem(["key", "ball", "box"])
  150. if color is None:
  151. color = self._rand_color()
  152. # TODO: we probably want to add an Object.make helper function
  153. assert kind in ["key", "ball", "box"]
  154. if kind == "key":
  155. obj = Key(color)
  156. elif kind == "ball":
  157. obj = Ball(color)
  158. elif kind == "box":
  159. obj = Box(color)
  160. return self.place_in_room(i, j, obj)
  161. def add_door(self, i, j, door_idx=None, color=None, locked=None):
  162. """
  163. Add a door to a room, connecting it to a neighbor
  164. """
  165. room = self.get_room(i, j)
  166. if door_idx is None:
  167. # Need to make sure that there is a neighbor along this wall
  168. # and that there is not already a door
  169. while True:
  170. door_idx = self._rand_int(0, 4)
  171. if room.neighbors[door_idx] and room.doors[door_idx] is None:
  172. break
  173. if color is None:
  174. color = self._rand_color()
  175. if locked is None:
  176. locked = self._rand_bool()
  177. assert room.doors[door_idx] is None, "door already exists"
  178. room.locked = locked
  179. door = Door(color, is_locked=locked)
  180. pos = room.door_pos[door_idx]
  181. self.grid.set(*pos, door)
  182. door.cur_pos = pos
  183. neighbor = room.neighbors[door_idx]
  184. room.doors[door_idx] = door
  185. neighbor.doors[(door_idx + 2) % 4] = door
  186. return door, pos
  187. def remove_wall(self, i, j, wall_idx):
  188. """
  189. Remove a wall between two rooms
  190. """
  191. room = self.get_room(i, j)
  192. assert wall_idx >= 0 and wall_idx < 4
  193. assert room.doors[wall_idx] is None, "door exists on this wall"
  194. assert room.neighbors[wall_idx], "invalid wall"
  195. neighbor = room.neighbors[wall_idx]
  196. tx, ty = room.top
  197. w, h = room.size
  198. # Ordering of walls is right, down, left, up
  199. if wall_idx == 0:
  200. for i in range(1, h - 1):
  201. self.grid.set(tx + w - 1, ty + i, None)
  202. elif wall_idx == 1:
  203. for i in range(1, w - 1):
  204. self.grid.set(tx + i, ty + h - 1, None)
  205. elif wall_idx == 2:
  206. for i in range(1, h - 1):
  207. self.grid.set(tx, ty + i, None)
  208. elif wall_idx == 3:
  209. for i in range(1, w - 1):
  210. self.grid.set(tx + i, ty, None)
  211. else:
  212. assert False, "invalid wall index"
  213. # Mark the rooms as connected
  214. room.doors[wall_idx] = True
  215. neighbor.doors[(wall_idx + 2) % 4] = True
  216. def place_agent(self, i=None, j=None, rand_dir=True):
  217. """
  218. Place the agent in a room
  219. """
  220. if i is None:
  221. i = self._rand_int(0, self.num_cols)
  222. if j is None:
  223. j = self._rand_int(0, self.num_rows)
  224. room = self.room_grid[j][i]
  225. # Find a position that is not right in front of an object
  226. while True:
  227. super().place_agent(room.top, room.size, rand_dir, max_tries=1000)
  228. front_cell = self.grid.get(*self.front_pos)
  229. if front_cell is None or front_cell.type == "wall":
  230. break
  231. return self.agent_pos
  232. def connect_all(self, door_colors=COLOR_NAMES, max_itrs=5000):
  233. """
  234. Make sure that all rooms are reachable by the agent from its
  235. starting position
  236. """
  237. start_room = self.room_from_pos(*self.agent_pos)
  238. added_doors = []
  239. def find_reach():
  240. reach = set()
  241. stack = [start_room]
  242. while len(stack) > 0:
  243. room = stack.pop()
  244. if room in reach:
  245. continue
  246. reach.add(room)
  247. for i in range(0, 4):
  248. if room.doors[i]:
  249. stack.append(room.neighbors[i])
  250. return reach
  251. num_itrs = 0
  252. while True:
  253. # This is to handle rare situations where random sampling produces
  254. # a level that cannot be connected, producing in an infinite loop
  255. if num_itrs > max_itrs:
  256. raise RecursionError("connect_all failed")
  257. num_itrs += 1
  258. # If all rooms are reachable, stop
  259. reach = find_reach()
  260. if len(reach) == self.num_rows * self.num_cols:
  261. break
  262. # Pick a random room and door position
  263. i = self._rand_int(0, self.num_cols)
  264. j = self._rand_int(0, self.num_rows)
  265. k = self._rand_int(0, 4)
  266. room = self.get_room(i, j)
  267. # If there is already a door there, skip
  268. if not room.door_pos[k] or room.doors[k]:
  269. continue
  270. if room.locked or room.neighbors[k].locked:
  271. continue
  272. color = self._rand_elem(door_colors)
  273. door, _ = self.add_door(i, j, k, color, False)
  274. added_doors.append(door)
  275. return added_doors
  276. def add_distractors(self, i=None, j=None, num_distractors=10, all_unique=True):
  277. """
  278. Add random objects that can potentially distract/confuse the agent.
  279. """
  280. # Collect a list of existing objects
  281. objs = []
  282. for row in self.room_grid:
  283. for room in row:
  284. for obj in room.objs:
  285. objs.append((obj.type, obj.color))
  286. # List of distractors added
  287. dists = []
  288. while len(dists) < num_distractors:
  289. color = self._rand_elem(COLOR_NAMES)
  290. type = self._rand_elem(["key", "ball", "box"])
  291. obj = (type, color)
  292. if all_unique and obj in objs:
  293. continue
  294. # Add the object to a random room if no room specified
  295. room_i = i
  296. room_j = j
  297. if room_i is None:
  298. room_i = self._rand_int(0, self.num_cols)
  299. if room_j is None:
  300. room_j = self._rand_int(0, self.num_rows)
  301. dist, pos = self.add_object(room_i, room_j, *obj)
  302. objs.append(obj)
  303. dists.append(dist)
  304. return dists