roomgrid.py 11 KB

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