minigrid.py 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384
  1. import math
  2. import gym
  3. from enum import IntEnum
  4. import numpy as np
  5. from gym import error, spaces, utils
  6. from gym.utils import seeding
  7. # Size in pixels of a cell in the full-scale human view
  8. CELL_PIXELS = 32
  9. # Number of cells (width and height) in the agent view
  10. AGENT_VIEW_SIZE = 7
  11. # Size of the array given as an observation to the agent
  12. OBS_ARRAY_SIZE = (AGENT_VIEW_SIZE, AGENT_VIEW_SIZE, 3)
  13. # Map of color names to RGB values
  14. COLORS = {
  15. 'red' : np.array([255, 0, 0]),
  16. 'green' : np.array([0, 255, 0]),
  17. 'blue' : np.array([0, 0, 255]),
  18. 'purple': np.array([112, 39, 195]),
  19. 'yellow': np.array([255, 255, 0]),
  20. 'grey' : np.array([100, 100, 100])
  21. }
  22. COLOR_NAMES = sorted(list(COLORS.keys()))
  23. # Used to map colors to integers
  24. COLOR_TO_IDX = {
  25. 'red' : 0,
  26. 'green' : 1,
  27. 'blue' : 2,
  28. 'purple': 3,
  29. 'yellow': 4,
  30. 'grey' : 5
  31. }
  32. IDX_TO_COLOR = dict(zip(COLOR_TO_IDX.values(), COLOR_TO_IDX.keys()))
  33. # Map of object type to integers
  34. OBJECT_TO_IDX = {
  35. 'empty' : 0,
  36. 'wall' : 1,
  37. 'floor' : 2,
  38. 'door' : 3,
  39. 'locked_door' : 4,
  40. 'key' : 5,
  41. 'ball' : 6,
  42. 'box' : 7,
  43. 'goal' : 8,
  44. 'lava' : 9
  45. }
  46. IDX_TO_OBJECT = dict(zip(OBJECT_TO_IDX.values(), OBJECT_TO_IDX.keys()))
  47. # Map of agent direction indices to vectors
  48. DIR_TO_VEC = [
  49. # Pointing right (positive X)
  50. np.array((1, 0)),
  51. # Down (positive Y)
  52. np.array((0, 1)),
  53. # Pointing left (negative X)
  54. np.array((-1, 0)),
  55. # Up (negative Y)
  56. np.array((0, -1)),
  57. ]
  58. class WorldObj:
  59. """
  60. Base class for grid world objects
  61. """
  62. def __init__(self, type, color):
  63. assert type in OBJECT_TO_IDX, type
  64. assert color in COLOR_TO_IDX, color
  65. self.type = type
  66. self.color = color
  67. self.contains = None
  68. # Initial position of the object
  69. self.init_pos = None
  70. # Current position of the object
  71. self.cur_pos = None
  72. def can_overlap(self):
  73. """Can the agent overlap with this?"""
  74. return False
  75. def can_pickup(self):
  76. """Can the agent pick this up?"""
  77. return False
  78. def can_contain(self):
  79. """Can this contain another object?"""
  80. return False
  81. def see_behind(self):
  82. """Can the agent see behind this object?"""
  83. return True
  84. def toggle(self, env, pos):
  85. """Method to trigger/toggle an action this object performs"""
  86. return False
  87. def render(self, r):
  88. """Draw this object with the given renderer"""
  89. raise NotImplementedError
  90. def _set_color(self, r):
  91. """Set the color of this object as the active drawing color"""
  92. c = COLORS[self.color]
  93. r.setLineColor(c[0], c[1], c[2])
  94. r.setColor(c[0], c[1], c[2])
  95. class Goal(WorldObj):
  96. def __init__(self):
  97. super().__init__('goal', 'green')
  98. def can_overlap(self):
  99. return True
  100. def render(self, r):
  101. self._set_color(r)
  102. r.drawPolygon([
  103. (0 , CELL_PIXELS),
  104. (CELL_PIXELS, CELL_PIXELS),
  105. (CELL_PIXELS, 0),
  106. (0 , 0)
  107. ])
  108. class Floor(WorldObj):
  109. """
  110. Colored floor tile the agent can walk over
  111. """
  112. def __init__(self, color='blue'):
  113. super().__init__('floor', color)
  114. def can_overlap(self):
  115. return True
  116. def render(self, r):
  117. # Give the floor a pale color
  118. c = COLORS[self.color]
  119. r.setLineColor(100, 100, 100, 0)
  120. r.setColor(*c/2)
  121. r.drawPolygon([
  122. (1 , CELL_PIXELS),
  123. (CELL_PIXELS, CELL_PIXELS),
  124. (CELL_PIXELS, 1),
  125. (1 , 1)
  126. ])
  127. class Lava(WorldObj):
  128. def __init__(self):
  129. super().__init__('lava', 'red')
  130. def can_overlap(self):
  131. return True
  132. def render(self, r):
  133. orange = 255, 128, 0
  134. r.setLineColor(*orange)
  135. r.setColor(*orange)
  136. r.drawPolygon([
  137. (0 , CELL_PIXELS),
  138. (CELL_PIXELS, CELL_PIXELS),
  139. (CELL_PIXELS, 0),
  140. (0 , 0)
  141. ])
  142. # drawing the waves
  143. r.setLineColor(0, 0, 0)
  144. r.drawPolyline([
  145. (.1 * CELL_PIXELS, .3 * CELL_PIXELS),
  146. (.3 * CELL_PIXELS, .4 * CELL_PIXELS),
  147. (.5 * CELL_PIXELS, .3 * CELL_PIXELS),
  148. (.7 * CELL_PIXELS, .4 * CELL_PIXELS),
  149. (.9 * CELL_PIXELS, .3 * CELL_PIXELS),
  150. ])
  151. r.drawPolyline([
  152. (.1 * CELL_PIXELS, .5 * CELL_PIXELS),
  153. (.3 * CELL_PIXELS, .6 * CELL_PIXELS),
  154. (.5 * CELL_PIXELS, .5 * CELL_PIXELS),
  155. (.7 * CELL_PIXELS, .6 * CELL_PIXELS),
  156. (.9 * CELL_PIXELS, .5 * CELL_PIXELS),
  157. ])
  158. r.drawPolyline([
  159. (.1 * CELL_PIXELS, .7 * CELL_PIXELS),
  160. (.3 * CELL_PIXELS, .8 * CELL_PIXELS),
  161. (.5 * CELL_PIXELS, .7 * CELL_PIXELS),
  162. (.7 * CELL_PIXELS, .8 * CELL_PIXELS),
  163. (.9 * CELL_PIXELS, .7 * CELL_PIXELS),
  164. ])
  165. class Wall(WorldObj):
  166. def __init__(self, color='grey'):
  167. super().__init__('wall', color)
  168. def see_behind(self):
  169. return False
  170. def render(self, r):
  171. self._set_color(r)
  172. r.drawPolygon([
  173. (0 , CELL_PIXELS),
  174. (CELL_PIXELS, CELL_PIXELS),
  175. (CELL_PIXELS, 0),
  176. (0 , 0)
  177. ])
  178. class Door(WorldObj):
  179. def __init__(self, color, is_open=False):
  180. super().__init__('door', color)
  181. self.is_open = is_open
  182. def can_overlap(self):
  183. """The agent can only walk over this cell when the door is open"""
  184. return self.is_open
  185. def see_behind(self):
  186. return self.is_open
  187. def toggle(self, env, pos):
  188. self.is_open = not self.is_open
  189. return True
  190. def render(self, r):
  191. c = COLORS[self.color]
  192. r.setLineColor(c[0], c[1], c[2])
  193. r.setColor(0, 0, 0)
  194. if self.is_open:
  195. r.drawPolygon([
  196. (CELL_PIXELS-2, CELL_PIXELS),
  197. (CELL_PIXELS , CELL_PIXELS),
  198. (CELL_PIXELS , 0),
  199. (CELL_PIXELS-2, 0)
  200. ])
  201. return
  202. r.drawPolygon([
  203. (0 , CELL_PIXELS),
  204. (CELL_PIXELS, CELL_PIXELS),
  205. (CELL_PIXELS, 0),
  206. (0 , 0)
  207. ])
  208. r.drawPolygon([
  209. (2 , CELL_PIXELS-2),
  210. (CELL_PIXELS-2, CELL_PIXELS-2),
  211. (CELL_PIXELS-2, 2),
  212. (2 , 2)
  213. ])
  214. r.drawCircle(CELL_PIXELS * 0.75, CELL_PIXELS * 0.5, 2)
  215. class LockedDoor(WorldObj):
  216. def __init__(self, color, is_open=False):
  217. super(LockedDoor, self).__init__('locked_door', color)
  218. self.is_open = is_open
  219. def toggle(self, env, pos):
  220. # If the player has the right key to open the door
  221. if isinstance(env.carrying, Key) and env.carrying.color == self.color:
  222. self.is_open = True
  223. # The key has been used, remove it from the agent
  224. env.carrying = None
  225. return True
  226. return False
  227. def can_overlap(self):
  228. """The agent can only walk over this cell when the door is open"""
  229. return self.is_open
  230. def see_behind(self):
  231. return self.is_open
  232. def render(self, r):
  233. c = COLORS[self.color]
  234. r.setLineColor(c[0], c[1], c[2])
  235. r.setColor(c[0], c[1], c[2], 50)
  236. if self.is_open:
  237. r.drawPolygon([
  238. (CELL_PIXELS-2, CELL_PIXELS),
  239. (CELL_PIXELS , CELL_PIXELS),
  240. (CELL_PIXELS , 0),
  241. (CELL_PIXELS-2, 0)
  242. ])
  243. return
  244. r.drawPolygon([
  245. (0 , CELL_PIXELS),
  246. (CELL_PIXELS, CELL_PIXELS),
  247. (CELL_PIXELS, 0),
  248. (0 , 0)
  249. ])
  250. r.drawPolygon([
  251. (2 , CELL_PIXELS-2),
  252. (CELL_PIXELS-2, CELL_PIXELS-2),
  253. (CELL_PIXELS-2, 2),
  254. (2 , 2)
  255. ])
  256. r.drawLine(
  257. CELL_PIXELS * 0.55,
  258. CELL_PIXELS * 0.5,
  259. CELL_PIXELS * 0.75,
  260. CELL_PIXELS * 0.5
  261. )
  262. class Key(WorldObj):
  263. def __init__(self, color='blue'):
  264. super(Key, self).__init__('key', color)
  265. def can_pickup(self):
  266. return True
  267. def render(self, r):
  268. self._set_color(r)
  269. # Vertical quad
  270. r.drawPolygon([
  271. (16, 10),
  272. (20, 10),
  273. (20, 28),
  274. (16, 28)
  275. ])
  276. # Teeth
  277. r.drawPolygon([
  278. (12, 19),
  279. (16, 19),
  280. (16, 21),
  281. (12, 21)
  282. ])
  283. r.drawPolygon([
  284. (12, 26),
  285. (16, 26),
  286. (16, 28),
  287. (12, 28)
  288. ])
  289. r.drawCircle(18, 9, 6)
  290. r.setLineColor(0, 0, 0)
  291. r.setColor(0, 0, 0)
  292. r.drawCircle(18, 9, 2)
  293. class Ball(WorldObj):
  294. def __init__(self, color='blue'):
  295. super(Ball, self).__init__('ball', color)
  296. def can_pickup(self):
  297. return True
  298. def render(self, r):
  299. self._set_color(r)
  300. r.drawCircle(CELL_PIXELS * 0.5, CELL_PIXELS * 0.5, 10)
  301. class Box(WorldObj):
  302. def __init__(self, color, contains=None):
  303. super(Box, self).__init__('box', color)
  304. self.contains = contains
  305. def can_pickup(self):
  306. return True
  307. def render(self, r):
  308. c = COLORS[self.color]
  309. r.setLineColor(c[0], c[1], c[2])
  310. r.setColor(0, 0, 0)
  311. r.setLineWidth(2)
  312. r.drawPolygon([
  313. (4 , CELL_PIXELS-4),
  314. (CELL_PIXELS-4, CELL_PIXELS-4),
  315. (CELL_PIXELS-4, 4),
  316. (4 , 4)
  317. ])
  318. r.drawLine(
  319. 4,
  320. CELL_PIXELS / 2,
  321. CELL_PIXELS - 4,
  322. CELL_PIXELS / 2
  323. )
  324. r.setLineWidth(1)
  325. def toggle(self, env, pos):
  326. # Replace the box by its contents
  327. env.grid.set(*pos, self.contains)
  328. return True
  329. class Grid:
  330. """
  331. Represent a grid and operations on it
  332. """
  333. def __init__(self, width, height):
  334. assert width >= 4
  335. assert height >= 4
  336. self.width = width
  337. self.height = height
  338. self.grid = [None] * width * height
  339. def __contains__(self, key):
  340. if isinstance(key, WorldObj):
  341. for e in self.grid:
  342. if e is key:
  343. return True
  344. elif isinstance(key, tuple):
  345. for e in self.grid:
  346. if e is None:
  347. continue
  348. if (e.color, e.type) == key:
  349. return True
  350. if key[0] is None and key[1] == e.type:
  351. return True
  352. return False
  353. def __eq__(self, other):
  354. grid1 = self.encode()
  355. grid2 = other.encode()
  356. return np.array_equal(grid2, grid1)
  357. def __ne__(self, other):
  358. return not self == other
  359. def copy(self):
  360. from copy import deepcopy
  361. return deepcopy(self)
  362. def set(self, i, j, v):
  363. assert i >= 0 and i < self.width
  364. assert j >= 0 and j < self.height
  365. self.grid[j * self.width + i] = v
  366. def get(self, i, j):
  367. assert i >= 0 and i < self.width
  368. assert j >= 0 and j < self.height
  369. return self.grid[j * self.width + i]
  370. def horz_wall(self, x, y, length=None):
  371. if length is None:
  372. length = self.width - x
  373. for i in range(0, length):
  374. self.set(x + i, y, Wall())
  375. def vert_wall(self, x, y, length=None):
  376. if length is None:
  377. length = self.height - y
  378. for j in range(0, length):
  379. self.set(x, y + j, Wall())
  380. def wall_rect(self, x, y, w, h):
  381. self.horz_wall(x, y, w)
  382. self.horz_wall(x, y+h-1, w)
  383. self.vert_wall(x, y, h)
  384. self.vert_wall(x+w-1, y, h)
  385. def rotate_left(self):
  386. """
  387. Rotate the grid to the left (counter-clockwise)
  388. """
  389. grid = Grid(self.height, self.width)
  390. for i in range(self.width):
  391. for j in range(self.height):
  392. v = self.get(i, j)
  393. grid.set(j, grid.height - 1 - i, v)
  394. return grid
  395. def slice(self, topX, topY, width, height):
  396. """
  397. Get a subset of the grid
  398. """
  399. grid = Grid(width, height)
  400. for j in range(0, height):
  401. for i in range(0, width):
  402. x = topX + i
  403. y = topY + j
  404. if x >= 0 and x < self.width and \
  405. y >= 0 and y < self.height:
  406. v = self.get(x, y)
  407. else:
  408. v = Wall()
  409. grid.set(i, j, v)
  410. return grid
  411. def render(self, r, tile_size):
  412. """
  413. Render this grid at a given scale
  414. :param r: target renderer object
  415. :param tile_size: tile size in pixels
  416. """
  417. assert r.width == self.width * tile_size
  418. assert r.height == self.height * tile_size
  419. # Total grid size at native scale
  420. widthPx = self.width * CELL_PIXELS
  421. heightPx = self.height * CELL_PIXELS
  422. r.push()
  423. # Internally, we draw at the "large" full-grid resolution, but we
  424. # use the renderer to scale back to the desired size
  425. r.scale(tile_size / CELL_PIXELS, tile_size / CELL_PIXELS)
  426. # Draw the background of the in-world cells black
  427. r.fillRect(
  428. 0,
  429. 0,
  430. widthPx,
  431. heightPx,
  432. 0, 0, 0
  433. )
  434. # Draw grid lines
  435. r.setLineColor(100, 100, 100)
  436. for rowIdx in range(0, self.height):
  437. y = CELL_PIXELS * rowIdx
  438. r.drawLine(0, y, widthPx, y)
  439. for colIdx in range(0, self.width):
  440. x = CELL_PIXELS * colIdx
  441. r.drawLine(x, 0, x, heightPx)
  442. # Render the grid
  443. for j in range(0, self.height):
  444. for i in range(0, self.width):
  445. cell = self.get(i, j)
  446. if cell == None:
  447. continue
  448. r.push()
  449. r.translate(i * CELL_PIXELS, j * CELL_PIXELS)
  450. cell.render(r)
  451. r.pop()
  452. r.pop()
  453. def encode(self):
  454. """
  455. Produce a compact numpy encoding of the grid
  456. """
  457. array = np.zeros(shape=(self.width, self.height, 3), dtype='uint8')
  458. for j in range(0, self.height):
  459. for i in range(0, self.width):
  460. v = self.get(i, j)
  461. if v == None:
  462. continue
  463. array[i, j, 0] = OBJECT_TO_IDX[v.type]
  464. array[i, j, 1] = COLOR_TO_IDX[v.color]
  465. if hasattr(v, 'is_open') and v.is_open:
  466. array[i, j, 2] = 1
  467. return array
  468. def decode(array):
  469. """
  470. Decode an array grid encoding back into a grid
  471. """
  472. width = array.shape[0]
  473. height = array.shape[1]
  474. assert array.shape[2] == 3
  475. grid = Grid(width, height)
  476. for j in range(0, height):
  477. for i in range(0, width):
  478. typeIdx = array[i, j, 0]
  479. colorIdx = array[i, j, 1]
  480. openIdx = array[i, j, 2]
  481. if typeIdx == 0:
  482. continue
  483. objType = IDX_TO_OBJECT[typeIdx]
  484. color = IDX_TO_COLOR[colorIdx]
  485. is_open = True if openIdx == 1 else 0
  486. if objType == 'wall':
  487. v = Wall(color)
  488. elif objType == 'floor':
  489. v = Floor(color)
  490. elif objType == 'ball':
  491. v = Ball(color)
  492. elif objType == 'key':
  493. v = Key(color)
  494. elif objType == 'box':
  495. v = Box(color)
  496. elif objType == 'door':
  497. v = Door(color, is_open)
  498. elif objType == 'locked_door':
  499. v = LockedDoor(color, is_open)
  500. elif objType == 'goal':
  501. v = Goal()
  502. elif objType == 'lava':
  503. v = Lava()
  504. else:
  505. assert False, "unknown obj type in decode '%s'" % objType
  506. grid.set(i, j, v)
  507. return grid
  508. def process_vis(grid, agent_pos):
  509. mask = np.zeros(shape=(grid.width, grid.height), dtype=np.bool)
  510. mask[agent_pos[0], agent_pos[1]] = True
  511. for j in reversed(range(0, grid.height)):
  512. for i in range(0, grid.width-1):
  513. if not mask[i, j]:
  514. continue
  515. cell = grid.get(i, j)
  516. if cell and not cell.see_behind():
  517. continue
  518. mask[i+1, j] = True
  519. if j > 0:
  520. mask[i+1, j-1] = True
  521. mask[i, j-1] = True
  522. for i in reversed(range(1, grid.width)):
  523. if not mask[i, j]:
  524. continue
  525. cell = grid.get(i, j)
  526. if cell and not cell.see_behind():
  527. continue
  528. mask[i-1, j] = True
  529. if j > 0:
  530. mask[i-1, j-1] = True
  531. mask[i, j-1] = True
  532. for j in range(0, grid.height):
  533. for i in range(0, grid.width):
  534. if not mask[i, j]:
  535. grid.set(i, j, None)
  536. return mask
  537. class MiniGridEnv(gym.Env):
  538. """
  539. 2D grid world game environment
  540. """
  541. metadata = {
  542. 'render.modes': ['human', 'rgb_array', 'pixmap'],
  543. 'video.frames_per_second' : 10
  544. }
  545. # Enumeration of possible actions
  546. class Actions(IntEnum):
  547. # Turn left, turn right, move forward
  548. left = 0
  549. right = 1
  550. forward = 2
  551. # Pick up an object
  552. pickup = 3
  553. # Drop an object
  554. drop = 4
  555. # Toggle/activate an object
  556. toggle = 5
  557. # Done completing task
  558. done = 6
  559. def __init__(
  560. self,
  561. grid_size=16,
  562. max_steps=100,
  563. see_through_walls=False,
  564. seed=1337
  565. ):
  566. # Action enumeration for this environment
  567. self.actions = MiniGridEnv.Actions
  568. # Actions are discrete integer values
  569. self.action_space = spaces.Discrete(len(self.actions))
  570. # Observations are dictionaries containing an
  571. # encoding of the grid and a textual 'mission' string
  572. self.observation_space = spaces.Box(
  573. low=0,
  574. high=255,
  575. shape=OBS_ARRAY_SIZE,
  576. dtype='uint8'
  577. )
  578. self.observation_space = spaces.Dict({
  579. 'image': self.observation_space
  580. })
  581. # Range of possible rewards
  582. self.reward_range = (0, 1)
  583. # Renderer object used to render the whole grid (full-scale)
  584. self.grid_render = None
  585. # Renderer used to render observations (small-scale agent view)
  586. self.obs_render = None
  587. # Environment configuration
  588. self.grid_size = grid_size
  589. self.max_steps = max_steps
  590. self.see_through_walls = see_through_walls
  591. # Starting position and direction for the agent
  592. self.start_pos = None
  593. self.start_dir = None
  594. # Initialize the RNG
  595. self.seed(seed=seed)
  596. # Initialize the state
  597. self.reset()
  598. def reset(self):
  599. # Generate a new random grid at the start of each episode
  600. # To keep the same grid for each episode, call env.seed() with
  601. # the same seed before calling env.reset()
  602. self._gen_grid(self.grid_size, self.grid_size)
  603. # These fields should be defined by _gen_grid
  604. assert self.start_pos is not None
  605. assert self.start_dir is not None
  606. # Check that the agent doesn't overlap with an object
  607. start_cell = self.grid.get(*self.start_pos)
  608. assert start_cell is None or start_cell.can_overlap()
  609. # Place the agent in the starting position and direction
  610. self.agent_pos = self.start_pos
  611. self.agent_dir = self.start_dir
  612. # Item picked up, being carried, initially nothing
  613. self.carrying = None
  614. # Step count since episode start
  615. self.step_count = 0
  616. # Return first observation
  617. obs = self.gen_obs()
  618. return obs
  619. def seed(self, seed=1337):
  620. # Seed the random number generator
  621. self.np_random, _ = seeding.np_random(seed)
  622. return [seed]
  623. @property
  624. def steps_remaining(self):
  625. return self.max_steps - self.step_count
  626. def __str__(self):
  627. """
  628. Produce a pretty string of the environment's grid along with the agent.
  629. The agent is represented by `⏩`. A grid pixel is represented by 2-character
  630. string, the first one for the object and the second one for the color.
  631. """
  632. from copy import deepcopy
  633. def rotate_left(array):
  634. new_array = deepcopy(array)
  635. for i in range(len(array)):
  636. for j in range(len(array[0])):
  637. new_array[j][len(array[0])-1-i] = array[i][j]
  638. return new_array
  639. def vertically_symmetrize(array):
  640. new_array = deepcopy(array)
  641. for i in range(len(array)):
  642. for j in range(len(array[0])):
  643. new_array[i][len(array[0])-1-j] = array[i][j]
  644. return new_array
  645. # Map of object id to short string
  646. OBJECT_IDX_TO_IDS = {
  647. 0: ' ',
  648. 1: 'W',
  649. 2: 'D',
  650. 3: 'L',
  651. 4: 'K',
  652. 5: 'B',
  653. 6: 'X',
  654. 7: 'G'
  655. }
  656. # Short string for opened door
  657. OPENDED_DOOR_IDS = '_'
  658. # Map of color id to short string
  659. COLOR_IDX_TO_IDS = {
  660. 0: 'R',
  661. 1: 'G',
  662. 2: 'B',
  663. 3: 'P',
  664. 4: 'Y',
  665. 5: 'E'
  666. }
  667. # Map agent's direction to short string
  668. AGENT_DIR_TO_IDS = {
  669. 0: '⏩ ',
  670. 1: '⏬ ',
  671. 2: '⏪ ',
  672. 3: '⏫ '
  673. }
  674. array = self.grid.encode()
  675. array = rotate_left(array)
  676. array = vertically_symmetrize(array)
  677. new_array = []
  678. for line in array:
  679. new_line = []
  680. for pixel in line:
  681. # If the door is opened
  682. if pixel[0] in [2, 3] and pixel[2] == 1:
  683. object_ids = OPENDED_DOOR_IDS
  684. else:
  685. object_ids = OBJECT_IDX_TO_IDS[pixel[0]]
  686. # If no object
  687. if pixel[0] == 0:
  688. color_ids = ' '
  689. else:
  690. color_ids = COLOR_IDX_TO_IDS[pixel[1]]
  691. new_line.append(object_ids + color_ids)
  692. new_array.append(new_line)
  693. # Add the agent
  694. new_array[self.agent_pos[1]][self.agent_pos[0]] = AGENT_DIR_TO_IDS[self.agent_dir]
  695. return "\n".join([" ".join(line) for line in new_array])
  696. def _gen_grid(self, width, height):
  697. assert False, "_gen_grid needs to be implemented by each environment"
  698. def _reward(self):
  699. """
  700. Compute the reward to be given upon success
  701. """
  702. return 1 - 0.9 * (self.step_count / self.max_steps)
  703. def _rand_int(self, low, high):
  704. """
  705. Generate random integer in [low,high[
  706. """
  707. return self.np_random.randint(low, high)
  708. def _rand_float(self, low, high):
  709. """
  710. Generate random float in [low,high[
  711. """
  712. return self.np_random.uniform(low, high)
  713. def _rand_bool(self):
  714. """
  715. Generate random boolean value
  716. """
  717. return (self.np_random.randint(0, 2) == 0)
  718. def _rand_elem(self, iterable):
  719. """
  720. Pick a random element in a list
  721. """
  722. lst = list(iterable)
  723. idx = self._rand_int(0, len(lst))
  724. return lst[idx]
  725. def _rand_subset(self, iterable, num_elems):
  726. """
  727. Sample a random subset of distinct elements of a list
  728. """
  729. lst = list(iterable)
  730. assert num_elems <= len(lst)
  731. out = []
  732. while len(out) < num_elems:
  733. elem = self._rand_elem(lst)
  734. lst.remove(elem)
  735. out.append(elem)
  736. return out
  737. def _rand_color(self):
  738. """
  739. Generate a random color name (string)
  740. """
  741. return self._rand_elem(COLOR_NAMES)
  742. def _rand_pos(self, xLow, xHigh, yLow, yHigh):
  743. """
  744. Generate a random (x,y) position tuple
  745. """
  746. return (
  747. self.np_random.randint(xLow, xHigh),
  748. self.np_random.randint(yLow, yHigh)
  749. )
  750. def place_obj(self,
  751. obj,
  752. top=None,
  753. size=None,
  754. reject_fn=None,
  755. max_tries=math.inf
  756. ):
  757. """
  758. Place an object at an empty position in the grid
  759. :param top: top-left position of the rectangle where to place
  760. :param size: size of the rectangle where to place
  761. :param reject_fn: function to filter out potential positions
  762. """
  763. if top is None:
  764. top = (0, 0)
  765. if size is None:
  766. size = (self.grid.width, self.grid.height)
  767. num_tries = 0
  768. while True:
  769. # This is to handle with rare cases where rejection sampling
  770. # gets stuck in an infinite loop
  771. if num_tries > max_tries:
  772. raise RecursionError('rejection sampling failed in place_obj')
  773. num_tries += 1
  774. pos = np.array((
  775. self._rand_int(top[0], top[0] + size[0]),
  776. self._rand_int(top[1], top[1] + size[1])
  777. ))
  778. # Don't place the object on top of another object
  779. if self.grid.get(*pos) != None:
  780. continue
  781. # Don't place the object where the agent is
  782. if np.array_equal(pos, self.start_pos):
  783. continue
  784. # Check if there is a filtering criterion
  785. if reject_fn and reject_fn(self, pos):
  786. continue
  787. break
  788. self.grid.set(*pos, obj)
  789. if obj is not None:
  790. obj.init_pos = pos
  791. obj.cur_pos = pos
  792. return pos
  793. def place_agent(
  794. self,
  795. top=None,
  796. size=None,
  797. rand_dir=True,
  798. max_tries=math.inf
  799. ):
  800. """
  801. Set the agent's starting point at an empty position in the grid
  802. """
  803. self.start_pos = None
  804. pos = self.place_obj(None, top, size, max_tries=max_tries)
  805. self.start_pos = pos
  806. if rand_dir:
  807. self.start_dir = self._rand_int(0, 4)
  808. return pos
  809. @property
  810. def dir_vec(self):
  811. """
  812. Get the direction vector for the agent, pointing in the direction
  813. of forward movement.
  814. """
  815. assert self.agent_dir >= 0 and self.agent_dir < 4
  816. return DIR_TO_VEC[self.agent_dir]
  817. @property
  818. def right_vec(self):
  819. """
  820. Get the vector pointing to the right of the agent.
  821. """
  822. dx, dy = self.dir_vec
  823. return np.array((-dy, dx))
  824. @property
  825. def front_pos(self):
  826. """
  827. Get the position of the cell that is right in front of the agent
  828. """
  829. return self.agent_pos + self.dir_vec
  830. def get_view_coords(self, i, j):
  831. """
  832. Translate and rotate absolute grid coordinates (i, j) into the
  833. agent's partially observable view (sub-grid). Note that the resulting
  834. coordinates may be negative or outside of the agent's view size.
  835. """
  836. ax, ay = self.agent_pos
  837. dx, dy = self.dir_vec
  838. rx, ry = self.right_vec
  839. # Compute the absolute coordinates of the top-left view corner
  840. sz = AGENT_VIEW_SIZE
  841. hs = AGENT_VIEW_SIZE // 2
  842. tx = ax + (dx * (sz-1)) - (rx * hs)
  843. ty = ay + (dy * (sz-1)) - (ry * hs)
  844. lx = i - tx
  845. ly = j - ty
  846. # Project the coordinates of the object relative to the top-left
  847. # corner onto the agent's own coordinate system
  848. vx = (rx*lx + ry*ly)
  849. vy = -(dx*lx + dy*ly)
  850. return vx, vy
  851. def get_view_exts(self):
  852. """
  853. Get the extents of the square set of tiles visible to the agent
  854. Note: the bottom extent indices are not included in the set
  855. """
  856. # Facing right
  857. if self.agent_dir == 0:
  858. topX = self.agent_pos[0]
  859. topY = self.agent_pos[1] - AGENT_VIEW_SIZE // 2
  860. # Facing down
  861. elif self.agent_dir == 1:
  862. topX = self.agent_pos[0] - AGENT_VIEW_SIZE // 2
  863. topY = self.agent_pos[1]
  864. # Facing left
  865. elif self.agent_dir == 2:
  866. topX = self.agent_pos[0] - AGENT_VIEW_SIZE + 1
  867. topY = self.agent_pos[1] - AGENT_VIEW_SIZE // 2
  868. # Facing up
  869. elif self.agent_dir == 3:
  870. topX = self.agent_pos[0] - AGENT_VIEW_SIZE // 2
  871. topY = self.agent_pos[1] - AGENT_VIEW_SIZE + 1
  872. else:
  873. assert False, "invalid agent direction"
  874. botX = topX + AGENT_VIEW_SIZE
  875. botY = topY + AGENT_VIEW_SIZE
  876. return (topX, topY, botX, botY)
  877. def relative_coords(self, x, y):
  878. """
  879. Check if a grid position belongs to the agent's field of view, and returns the corresponding coordinates
  880. """
  881. vx, vy = self.get_view_coords(x, y)
  882. if vx < 0 or vy < 0 or vx >= AGENT_VIEW_SIZE or vy >= AGENT_VIEW_SIZE:
  883. return None
  884. return vx, vy
  885. def in_view(self, x, y):
  886. """
  887. check if a grid position is visible to the agent
  888. """
  889. return self.relative_coords(x, y) is not None
  890. def agent_sees(self, x, y):
  891. """
  892. Check if a non-empty grid position is visible to the agent
  893. """
  894. coordinates = self.relative_coords(x, y)
  895. if coordinates is None:
  896. return False
  897. vx, vy = coordinates
  898. obs = self.gen_obs()
  899. obs_grid = Grid.decode(obs['image'])
  900. obs_cell = obs_grid.get(vx, vy)
  901. world_cell = self.grid.get(x, y)
  902. return obs_cell is not None and obs_cell.type == world_cell.type
  903. def step(self, action):
  904. self.step_count += 1
  905. reward = 0
  906. done = False
  907. # Get the position in front of the agent
  908. fwd_pos = self.front_pos
  909. # Get the contents of the cell in front of the agent
  910. fwd_cell = self.grid.get(*fwd_pos)
  911. # Rotate left
  912. if action == self.actions.left:
  913. self.agent_dir -= 1
  914. if self.agent_dir < 0:
  915. self.agent_dir += 4
  916. # Rotate right
  917. elif action == self.actions.right:
  918. self.agent_dir = (self.agent_dir + 1) % 4
  919. # Move forward
  920. elif action == self.actions.forward:
  921. if fwd_cell == None or fwd_cell.can_overlap():
  922. self.agent_pos = fwd_pos
  923. if fwd_cell != None and fwd_cell.type == 'goal':
  924. done = True
  925. reward = self._reward()
  926. if fwd_cell != None and fwd_cell.type == 'lava':
  927. done = True
  928. # Pick up an object
  929. elif action == self.actions.pickup:
  930. if fwd_cell and fwd_cell.can_pickup():
  931. if self.carrying is None:
  932. self.carrying = fwd_cell
  933. self.carrying.cur_pos = np.array([-1, -1])
  934. self.grid.set(*fwd_pos, None)
  935. # Drop an object
  936. elif action == self.actions.drop:
  937. if not fwd_cell and self.carrying:
  938. self.grid.set(*fwd_pos, self.carrying)
  939. self.carrying.cur_pos = fwd_pos
  940. self.carrying = None
  941. # Toggle/activate an object
  942. elif action == self.actions.toggle:
  943. if fwd_cell:
  944. fwd_cell.toggle(self, fwd_pos)
  945. # Done action (not used by default)
  946. elif action == self.actions.done:
  947. pass
  948. else:
  949. assert False, "unknown action"
  950. if self.step_count >= self.max_steps:
  951. done = True
  952. obs = self.gen_obs()
  953. return obs, reward, done, {}
  954. def gen_obs_grid(self):
  955. """
  956. Generate the sub-grid observed by the agent.
  957. This method also outputs a visibility mask telling us which grid
  958. cells the agent can actually see.
  959. """
  960. topX, topY, botX, botY = self.get_view_exts()
  961. grid = self.grid.slice(topX, topY, AGENT_VIEW_SIZE, AGENT_VIEW_SIZE)
  962. for i in range(self.agent_dir + 1):
  963. grid = grid.rotate_left()
  964. # Process occluders and visibility
  965. # Note that this incurs some performance cost
  966. if not self.see_through_walls:
  967. vis_mask = grid.process_vis(agent_pos=(AGENT_VIEW_SIZE // 2 , AGENT_VIEW_SIZE - 1))
  968. else:
  969. vis_mask = np.ones(shape=(grid.width, grid.height), dtype=np.bool)
  970. # Make it so the agent sees what it's carrying
  971. # We do this by placing the carried object at the agent's position
  972. # in the agent's partially observable view
  973. agent_pos = grid.width // 2, grid.height - 1
  974. if self.carrying:
  975. grid.set(*agent_pos, self.carrying)
  976. else:
  977. grid.set(*agent_pos, None)
  978. return grid, vis_mask
  979. def gen_obs(self):
  980. """
  981. Generate the agent's view (partially observable, low-resolution encoding)
  982. """
  983. grid, vis_mask = self.gen_obs_grid()
  984. # Encode the partially observable view into a numpy array
  985. image = grid.encode()
  986. assert hasattr(self, 'mission'), "environments must define a textual mission string"
  987. # Observations are dictionaries containing:
  988. # - an image (partially observable view of the environment)
  989. # - the agent's direction/orientation (acting as a compass)
  990. # - a textual mission string (instructions for the agent)
  991. obs = {
  992. 'image': image,
  993. 'direction': self.agent_dir,
  994. 'mission': self.mission
  995. }
  996. return obs
  997. def get_obs_render(self, obs, tile_pixels=CELL_PIXELS//2):
  998. """
  999. Render an agent observation for visualization
  1000. """
  1001. if self.obs_render == None:
  1002. from gym_minigrid.rendering import Renderer
  1003. self.obs_render = Renderer(
  1004. AGENT_VIEW_SIZE * tile_pixels,
  1005. AGENT_VIEW_SIZE * tile_pixels
  1006. )
  1007. r = self.obs_render
  1008. r.beginFrame()
  1009. grid = Grid.decode(obs)
  1010. # Render the whole grid
  1011. grid.render(r, tile_pixels)
  1012. # Draw the agent
  1013. ratio = tile_pixels / CELL_PIXELS
  1014. r.push()
  1015. r.scale(ratio, ratio)
  1016. r.translate(
  1017. CELL_PIXELS * (0.5 + AGENT_VIEW_SIZE // 2),
  1018. CELL_PIXELS * (AGENT_VIEW_SIZE - 0.5)
  1019. )
  1020. r.rotate(3 * 90)
  1021. r.setLineColor(255, 0, 0)
  1022. r.setColor(255, 0, 0)
  1023. r.drawPolygon([
  1024. (-12, 10),
  1025. ( 12, 0),
  1026. (-12, -10)
  1027. ])
  1028. r.pop()
  1029. r.endFrame()
  1030. return r.getPixmap()
  1031. def render(self, mode='human', close=False):
  1032. """
  1033. Render the whole-grid human view
  1034. """
  1035. if close:
  1036. if self.grid_render:
  1037. self.grid_render.close()
  1038. return
  1039. if self.grid_render is None:
  1040. from gym_minigrid.rendering import Renderer
  1041. self.grid_render = Renderer(
  1042. self.grid_size * CELL_PIXELS,
  1043. self.grid_size * CELL_PIXELS,
  1044. True if mode == 'human' else False
  1045. )
  1046. r = self.grid_render
  1047. if r.window:
  1048. r.window.setText(self.mission)
  1049. r.beginFrame()
  1050. # Render the whole grid
  1051. self.grid.render(r, CELL_PIXELS)
  1052. # Draw the agent
  1053. r.push()
  1054. r.translate(
  1055. CELL_PIXELS * (self.agent_pos[0] + 0.5),
  1056. CELL_PIXELS * (self.agent_pos[1] + 0.5)
  1057. )
  1058. r.rotate(self.agent_dir * 90)
  1059. r.setLineColor(255, 0, 0)
  1060. r.setColor(255, 0, 0)
  1061. r.drawPolygon([
  1062. (-12, 10),
  1063. ( 12, 0),
  1064. (-12, -10)
  1065. ])
  1066. r.pop()
  1067. # Compute which cells are visible to the agent
  1068. _, vis_mask = self.gen_obs_grid()
  1069. # Compute the absolute coordinates of the bottom-left corner
  1070. # of the agent's view area
  1071. f_vec = self.dir_vec
  1072. r_vec = self.right_vec
  1073. top_left = self.agent_pos + f_vec * (AGENT_VIEW_SIZE-1) - r_vec * (AGENT_VIEW_SIZE // 2)
  1074. # For each cell in the visibility mask
  1075. for vis_j in range(0, AGENT_VIEW_SIZE):
  1076. for vis_i in range(0, AGENT_VIEW_SIZE):
  1077. # If this cell is not visible, don't highlight it
  1078. if not vis_mask[vis_i, vis_j]:
  1079. continue
  1080. # Compute the world coordinates of this cell
  1081. abs_i, abs_j = top_left - (f_vec * vis_j) + (r_vec * vis_i)
  1082. # Highlight the cell
  1083. r.fillRect(
  1084. abs_i * CELL_PIXELS,
  1085. abs_j * CELL_PIXELS,
  1086. CELL_PIXELS,
  1087. CELL_PIXELS,
  1088. 255, 255, 255, 75
  1089. )
  1090. r.endFrame()
  1091. if mode == 'rgb_array':
  1092. return r.getArray()
  1093. elif mode == 'pixmap':
  1094. return r.getPixmap()
  1095. return r