roomgrid.py 11 KB

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