minigrid.py 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381
  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.width, self.height)
  390. for j in range(0, self.height):
  391. for i in range(0, self.width):
  392. v = self.get(self.width - 1 - j, i)
  393. grid.set(i, j, 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. codeSize = self.width * self.height * 3
  458. array = np.zeros(shape=(self.width, self.height, 3), dtype='uint8')
  459. for j in range(0, self.height):
  460. for i in range(0, self.width):
  461. v = self.get(i, j)
  462. if v == None:
  463. continue
  464. array[i, j, 0] = OBJECT_TO_IDX[v.type]
  465. array[i, j, 1] = COLOR_TO_IDX[v.color]
  466. if hasattr(v, 'is_open') and v.is_open:
  467. array[i, j, 2] = 1
  468. return array
  469. def decode(array):
  470. """
  471. Decode an array grid encoding back into a grid
  472. """
  473. width = array.shape[0]
  474. height = array.shape[1]
  475. assert array.shape[2] == 3
  476. grid = Grid(width, height)
  477. for j in range(0, height):
  478. for i in range(0, width):
  479. typeIdx = array[i, j, 0]
  480. colorIdx = array[i, j, 1]
  481. openIdx = array[i, j, 2]
  482. if typeIdx == 0:
  483. continue
  484. objType = IDX_TO_OBJECT[typeIdx]
  485. color = IDX_TO_COLOR[colorIdx]
  486. is_open = True if openIdx == 1 else 0
  487. if objType == 'wall':
  488. v = Wall(color)
  489. elif objType == 'floor':
  490. v = Floor(color)
  491. elif objType == 'ball':
  492. v = Ball(color)
  493. elif objType == 'key':
  494. v = Key(color)
  495. elif objType == 'box':
  496. v = Box(color)
  497. elif objType == 'door':
  498. v = Door(color, is_open)
  499. elif objType == 'locked_door':
  500. v = LockedDoor(color, is_open)
  501. elif objType == 'goal':
  502. v = Goal()
  503. elif objType == 'lava':
  504. v = Lava()
  505. else:
  506. assert False, "unknown obj type in decode '%s'" % objType
  507. grid.set(i, j, v)
  508. return grid
  509. def process_vis(grid, agent_pos):
  510. mask = np.zeros(shape=(grid.width, grid.height), dtype=np.bool)
  511. mask[agent_pos[0], agent_pos[1]] = True
  512. for j in reversed(range(1, grid.height)):
  513. for i in range(0, grid.width-1):
  514. if not mask[i, j]:
  515. continue
  516. cell = grid.get(i, j)
  517. if cell and not cell.see_behind():
  518. continue
  519. mask[i+1, j] = True
  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-1] = True
  529. mask[i-1, j] = True
  530. mask[i, j-1] = True
  531. for j in range(0, grid.height):
  532. for i in range(0, grid.width):
  533. if not mask[i, j]:
  534. grid.set(i, j, None)
  535. return mask
  536. class MiniGridEnv(gym.Env):
  537. """
  538. 2D grid world game environment
  539. """
  540. metadata = {
  541. 'render.modes': ['human', 'rgb_array', 'pixmap'],
  542. 'video.frames_per_second' : 10
  543. }
  544. # Enumeration of possible actions
  545. class Actions(IntEnum):
  546. # Turn left, turn right, move forward
  547. left = 0
  548. right = 1
  549. forward = 2
  550. # Pick up an object
  551. pickup = 3
  552. # Drop an object
  553. drop = 4
  554. # Toggle/activate an object
  555. toggle = 5
  556. # Done completing task
  557. done = 6
  558. def __init__(
  559. self,
  560. grid_size=16,
  561. max_steps=100,
  562. see_through_walls=False,
  563. seed=1337
  564. ):
  565. # Action enumeration for this environment
  566. self.actions = MiniGridEnv.Actions
  567. # Actions are discrete integer values
  568. self.action_space = spaces.Discrete(len(self.actions))
  569. # Observations are dictionaries containing an
  570. # encoding of the grid and a textual 'mission' string
  571. self.observation_space = spaces.Box(
  572. low=0,
  573. high=255,
  574. shape=OBS_ARRAY_SIZE,
  575. dtype='uint8'
  576. )
  577. self.observation_space = spaces.Dict({
  578. 'image': self.observation_space
  579. })
  580. # Range of possible rewards
  581. self.reward_range = (0, 1)
  582. # Renderer object used to render the whole grid (full-scale)
  583. self.grid_render = None
  584. # Renderer used to render observations (small-scale agent view)
  585. self.obs_render = None
  586. # Environment configuration
  587. self.grid_size = grid_size
  588. self.max_steps = max_steps
  589. self.see_through_walls = see_through_walls
  590. # Starting position and direction for the agent
  591. self.start_pos = None
  592. self.start_dir = None
  593. # Initialize the RNG
  594. self.seed(seed=seed)
  595. # Initialize the state
  596. self.reset()
  597. def reset(self):
  598. # Generate a new random grid at the start of each episode
  599. # To keep the same grid for each episode, call env.seed() with
  600. # the same seed before calling env.reset()
  601. self._gen_grid(self.grid_size, self.grid_size)
  602. # These fields should be defined by _gen_grid
  603. assert self.start_pos is not None
  604. assert self.start_dir is not None
  605. # Check that the agent doesn't overlap with an object
  606. start_cell = self.grid.get(*self.start_pos)
  607. assert start_cell is None or start_cell.can_overlap()
  608. # Place the agent in the starting position and direction
  609. self.agent_pos = self.start_pos
  610. self.agent_dir = self.start_dir
  611. # Item picked up, being carried, initially nothing
  612. self.carrying = None
  613. # Step count since episode start
  614. self.step_count = 0
  615. # Return first observation
  616. obs = self.gen_obs()
  617. return obs
  618. def seed(self, seed=1337):
  619. # Seed the random number generator
  620. self.np_random, _ = seeding.np_random(seed)
  621. return [seed]
  622. @property
  623. def steps_remaining(self):
  624. return self.max_steps - self.step_count
  625. def __str__(self):
  626. """
  627. Produce a pretty string of the environment's grid along with the agent.
  628. The agent is represented by `⏩`. A grid pixel is represented by 2-character
  629. string, the first one for the object and the second one for the color.
  630. """
  631. from copy import deepcopy
  632. def rotate_left(array):
  633. new_array = deepcopy(array)
  634. for i in range(len(array)):
  635. for j in range(len(array[0])):
  636. new_array[j][len(array[0])-1-i] = array[i][j]
  637. return new_array
  638. def vertically_symmetrize(array):
  639. new_array = deepcopy(array)
  640. for i in range(len(array)):
  641. for j in range(len(array[0])):
  642. new_array[i][len(array[0])-1-j] = array[i][j]
  643. return new_array
  644. # Map of object id to short string
  645. OBJECT_IDX_TO_IDS = {
  646. 0: ' ',
  647. 1: 'W',
  648. 2: 'D',
  649. 3: 'L',
  650. 4: 'K',
  651. 5: 'B',
  652. 6: 'X',
  653. 7: 'G'
  654. }
  655. # Short string for opened door
  656. OPENDED_DOOR_IDS = '_'
  657. # Map of color id to short string
  658. COLOR_IDX_TO_IDS = {
  659. 0: 'R',
  660. 1: 'G',
  661. 2: 'B',
  662. 3: 'P',
  663. 4: 'Y',
  664. 5: 'E'
  665. }
  666. # Map agent's direction to short string
  667. AGENT_DIR_TO_IDS = {
  668. 0: '⏩ ',
  669. 1: '⏬ ',
  670. 2: '⏪ ',
  671. 3: '⏫ '
  672. }
  673. array = self.grid.encode()
  674. array = rotate_left(array)
  675. array = vertically_symmetrize(array)
  676. new_array = []
  677. for line in array:
  678. new_line = []
  679. for pixel in line:
  680. # If the door is opened
  681. if pixel[0] in [2, 3] and pixel[2] == 1:
  682. object_ids = OPENDED_DOOR_IDS
  683. else:
  684. object_ids = OBJECT_IDX_TO_IDS[pixel[0]]
  685. # If no object
  686. if pixel[0] == 0:
  687. color_ids = ' '
  688. else:
  689. color_ids = COLOR_IDX_TO_IDS[pixel[1]]
  690. new_line.append(object_ids + color_ids)
  691. new_array.append(new_line)
  692. # Add the agent
  693. new_array[self.agent_pos[1]][self.agent_pos[0]] = AGENT_DIR_TO_IDS[self.agent_dir]
  694. return "\n".join([" ".join(line) for line in new_array])
  695. def _gen_grid(self, width, height):
  696. assert False, "_gen_grid needs to be implemented by each environment"
  697. def _reward(self):
  698. """
  699. Compute the reward to be given upon success
  700. """
  701. return 1 - 0.9 * (self.step_count / self.max_steps)
  702. def _rand_int(self, low, high):
  703. """
  704. Generate random integer in [low,high[
  705. """
  706. return self.np_random.randint(low, high)
  707. def _rand_float(self, low, high):
  708. """
  709. Generate random float in [low,high[
  710. """
  711. return self.np_random.uniform(low, high)
  712. def _rand_bool(self):
  713. """
  714. Generate random boolean value
  715. """
  716. return (self.np_random.randint(0, 2) == 0)
  717. def _rand_elem(self, iterable):
  718. """
  719. Pick a random element in a list
  720. """
  721. lst = list(iterable)
  722. idx = self._rand_int(0, len(lst))
  723. return lst[idx]
  724. def _rand_subset(self, iterable, num_elems):
  725. """
  726. Sample a random subset of distinct elements of a list
  727. """
  728. lst = list(iterable)
  729. assert num_elems <= len(lst)
  730. out = []
  731. while len(out) < num_elems:
  732. elem = self._rand_elem(lst)
  733. lst.remove(elem)
  734. out.append(elem)
  735. return out
  736. def _rand_color(self):
  737. """
  738. Generate a random color name (string)
  739. """
  740. return self._rand_elem(COLOR_NAMES)
  741. def _rand_pos(self, xLow, xHigh, yLow, yHigh):
  742. """
  743. Generate a random (x,y) position tuple
  744. """
  745. return (
  746. self.np_random.randint(xLow, xHigh),
  747. self.np_random.randint(yLow, yHigh)
  748. )
  749. def place_obj(self,
  750. obj,
  751. top=None,
  752. size=None,
  753. reject_fn=None,
  754. max_tries=math.inf
  755. ):
  756. """
  757. Place an object at an empty position in the grid
  758. :param top: top-left position of the rectangle where to place
  759. :param size: size of the rectangle where to place
  760. :param reject_fn: function to filter out potential positions
  761. """
  762. if top is None:
  763. top = (0, 0)
  764. if size is None:
  765. size = (self.grid.width, self.grid.height)
  766. num_tries = 0
  767. while True:
  768. # This is to handle with rare cases where rejection sampling
  769. # gets stuck in an infinite loop
  770. if num_tries > max_tries:
  771. raise RecursionError('rejection sampling failed in place_obj')
  772. num_tries += 1
  773. pos = np.array((
  774. self._rand_int(top[0], top[0] + size[0]),
  775. self._rand_int(top[1], top[1] + size[1])
  776. ))
  777. # Don't place the object on top of another object
  778. if self.grid.get(*pos) != None:
  779. continue
  780. # Don't place the object where the agent is
  781. if np.array_equal(pos, self.start_pos):
  782. continue
  783. # Check if there is a filtering criterion
  784. if reject_fn and reject_fn(self, pos):
  785. continue
  786. break
  787. self.grid.set(*pos, obj)
  788. if obj is not None:
  789. obj.init_pos = pos
  790. obj.cur_pos = pos
  791. return pos
  792. def place_agent(
  793. self,
  794. top=None,
  795. size=None,
  796. rand_dir=True,
  797. max_tries=math.inf
  798. ):
  799. """
  800. Set the agent's starting point at an empty position in the grid
  801. """
  802. self.start_pos = None
  803. pos = self.place_obj(None, top, size, max_tries=max_tries)
  804. self.start_pos = pos
  805. if rand_dir:
  806. self.start_dir = self._rand_int(0, 4)
  807. return pos
  808. @property
  809. def dir_vec(self):
  810. """
  811. Get the direction vector for the agent, pointing in the direction
  812. of forward movement.
  813. """
  814. assert self.agent_dir >= 0 and self.agent_dir < 4
  815. return DIR_TO_VEC[self.agent_dir]
  816. @property
  817. def right_vec(self):
  818. """
  819. Get the vector pointing to the right of the agent.
  820. """
  821. dx, dy = self.dir_vec
  822. return np.array((-dy, dx))
  823. @property
  824. def front_pos(self):
  825. """
  826. Get the position of the cell that is right in front of the agent
  827. """
  828. return self.agent_pos + self.dir_vec
  829. def get_view_coords(self, i, j):
  830. """
  831. Translate and rotate absolute grid coordinates (i, j) into the
  832. agent's partially observable view (sub-grid). Note that the resulting
  833. coordinates may be negative or outside of the agent's view size.
  834. """
  835. ax, ay = self.agent_pos
  836. dx, dy = self.dir_vec
  837. rx, ry = self.right_vec
  838. # Compute the absolute coordinates of the top-left view corner
  839. sz = AGENT_VIEW_SIZE
  840. hs = AGENT_VIEW_SIZE // 2
  841. tx = ax + (dx * (sz-1)) - (rx * hs)
  842. ty = ay + (dy * (sz-1)) - (ry * hs)
  843. lx = i - tx
  844. ly = j - ty
  845. # Project the coordinates of the object relative to the top-left
  846. # corner onto the agent's own coordinate system
  847. vx = (rx*lx + ry*ly)
  848. vy = -(dx*lx + dy*ly)
  849. return vx, vy
  850. def get_view_exts(self):
  851. """
  852. Get the extents of the square set of tiles visible to the agent
  853. Note: the bottom extent indices are not included in the set
  854. """
  855. # Facing right
  856. if self.agent_dir == 0:
  857. topX = self.agent_pos[0]
  858. topY = self.agent_pos[1] - AGENT_VIEW_SIZE // 2
  859. # Facing down
  860. elif self.agent_dir == 1:
  861. topX = self.agent_pos[0] - AGENT_VIEW_SIZE // 2
  862. topY = self.agent_pos[1]
  863. # Facing left
  864. elif self.agent_dir == 2:
  865. topX = self.agent_pos[0] - AGENT_VIEW_SIZE + 1
  866. topY = self.agent_pos[1] - AGENT_VIEW_SIZE // 2
  867. # Facing up
  868. elif self.agent_dir == 3:
  869. topX = self.agent_pos[0] - AGENT_VIEW_SIZE // 2
  870. topY = self.agent_pos[1] - AGENT_VIEW_SIZE + 1
  871. else:
  872. assert False, "invalid agent direction"
  873. botX = topX + AGENT_VIEW_SIZE
  874. botY = topY + AGENT_VIEW_SIZE
  875. return (topX, topY, botX, botY)
  876. def relative_coords(self, x, y):
  877. """
  878. Check if a grid position belongs to the agent's field of view, and returns the corresponding coordinates
  879. """
  880. vx, vy = self.get_view_coords(x, y)
  881. if vx < 0 or vy < 0 or vx >= AGENT_VIEW_SIZE or vy >= AGENT_VIEW_SIZE:
  882. return None
  883. return vx, vy
  884. def in_view(self, x, y):
  885. """
  886. check if a grid position is visible to the agent
  887. """
  888. return self.relative_coords(x, y) is not None
  889. def agent_sees(self, x, y):
  890. """
  891. Check if a non-empty grid position is visible to the agent
  892. """
  893. coordinates = self.relative_coords(x, y)
  894. if coordinates is None:
  895. return False
  896. vx, vy = coordinates
  897. obs = self.gen_obs()
  898. obs_grid = Grid.decode(obs['image'])
  899. obs_cell = obs_grid.get(vx, vy)
  900. world_cell = self.grid.get(x, y)
  901. return obs_cell is not None and obs_cell.type == world_cell.type
  902. def step(self, action):
  903. self.step_count += 1
  904. reward = 0
  905. done = False
  906. # Get the position in front of the agent
  907. fwd_pos = self.front_pos
  908. # Get the contents of the cell in front of the agent
  909. fwd_cell = self.grid.get(*fwd_pos)
  910. # Rotate left
  911. if action == self.actions.left:
  912. self.agent_dir -= 1
  913. if self.agent_dir < 0:
  914. self.agent_dir += 4
  915. # Rotate right
  916. elif action == self.actions.right:
  917. self.agent_dir = (self.agent_dir + 1) % 4
  918. # Move forward
  919. elif action == self.actions.forward:
  920. if fwd_cell == None or fwd_cell.can_overlap():
  921. self.agent_pos = fwd_pos
  922. if fwd_cell != None and fwd_cell.type == 'goal':
  923. done = True
  924. reward = self._reward()
  925. if fwd_cell != None and fwd_cell.type == 'lava':
  926. done = True
  927. # Pick up an object
  928. elif action == self.actions.pickup:
  929. if fwd_cell and fwd_cell.can_pickup():
  930. if self.carrying is None:
  931. self.carrying = fwd_cell
  932. self.carrying.cur_pos = np.array([-1, -1])
  933. self.grid.set(*fwd_pos, None)
  934. # Drop an object
  935. elif action == self.actions.drop:
  936. if not fwd_cell and self.carrying:
  937. self.grid.set(*fwd_pos, self.carrying)
  938. self.carrying.cur_pos = fwd_pos
  939. self.carrying = None
  940. # Toggle/activate an object
  941. elif action == self.actions.toggle:
  942. if fwd_cell:
  943. fwd_cell.toggle(self, fwd_pos)
  944. # Done action (not used by default)
  945. elif action == self.actions.done:
  946. pass
  947. else:
  948. assert False, "unknown action"
  949. if self.step_count >= self.max_steps:
  950. done = True
  951. obs = self.gen_obs()
  952. return obs, reward, done, {}
  953. def gen_obs_grid(self):
  954. """
  955. Generate the sub-grid observed by the agent.
  956. This method also outputs a visibility mask telling us which grid
  957. cells the agent can actually see.
  958. """
  959. topX, topY, botX, botY = self.get_view_exts()
  960. grid = self.grid.slice(topX, topY, AGENT_VIEW_SIZE, AGENT_VIEW_SIZE)
  961. for i in range(self.agent_dir + 1):
  962. grid = grid.rotate_left()
  963. # Process occluders and visibility
  964. # Note that this incurs some performance cost
  965. if not self.see_through_walls:
  966. vis_mask = grid.process_vis(agent_pos=(AGENT_VIEW_SIZE // 2 , AGENT_VIEW_SIZE - 1))
  967. else:
  968. vis_mask = np.ones(shape=(grid.width, grid.height), dtype=np.bool)
  969. # Make it so the agent sees what it's carrying
  970. # We do this by placing the carried object at the agent's position
  971. # in the agent's partially observable view
  972. agent_pos = grid.width // 2, grid.height - 1
  973. if self.carrying:
  974. grid.set(*agent_pos, self.carrying)
  975. else:
  976. grid.set(*agent_pos, None)
  977. return grid, vis_mask
  978. def gen_obs(self):
  979. """
  980. Generate the agent's view (partially observable, low-resolution encoding)
  981. """
  982. grid, vis_mask = self.gen_obs_grid()
  983. # Encode the partially observable view into a numpy array
  984. image = grid.encode()
  985. assert hasattr(self, 'mission'), "environments must define a textual mission string"
  986. # Observations are dictionaries containing:
  987. # - an image (partially observable view of the environment)
  988. # - the agent's direction/orientation (acting as a compass)
  989. # - a textual mission string (instructions for the agent)
  990. obs = {
  991. 'image': image,
  992. 'direction': self.agent_dir,
  993. 'mission': self.mission
  994. }
  995. return obs
  996. def get_obs_render(self, obs, tile_pixels=CELL_PIXELS//2):
  997. """
  998. Render an agent observation for visualization
  999. """
  1000. if self.obs_render == None:
  1001. from gym_minigrid.rendering import Renderer
  1002. self.obs_render = Renderer(
  1003. AGENT_VIEW_SIZE * tile_pixels,
  1004. AGENT_VIEW_SIZE * tile_pixels
  1005. )
  1006. r = self.obs_render
  1007. r.beginFrame()
  1008. grid = Grid.decode(obs)
  1009. # Render the whole grid
  1010. grid.render(r, tile_pixels)
  1011. # Draw the agent
  1012. ratio = tile_pixels / CELL_PIXELS
  1013. r.push()
  1014. r.scale(ratio, ratio)
  1015. r.translate(
  1016. CELL_PIXELS * (0.5 + AGENT_VIEW_SIZE // 2),
  1017. CELL_PIXELS * (AGENT_VIEW_SIZE - 0.5)
  1018. )
  1019. r.rotate(3 * 90)
  1020. r.setLineColor(255, 0, 0)
  1021. r.setColor(255, 0, 0)
  1022. r.drawPolygon([
  1023. (-12, 10),
  1024. ( 12, 0),
  1025. (-12, -10)
  1026. ])
  1027. r.pop()
  1028. r.endFrame()
  1029. return r.getPixmap()
  1030. def render(self, mode='human', close=False):
  1031. """
  1032. Render the whole-grid human view
  1033. """
  1034. if close:
  1035. if self.grid_render:
  1036. self.grid_render.close()
  1037. return
  1038. if self.grid_render is None:
  1039. from gym_minigrid.rendering import Renderer
  1040. self.grid_render = Renderer(
  1041. self.grid_size * CELL_PIXELS,
  1042. self.grid_size * CELL_PIXELS,
  1043. True if mode == 'human' else False
  1044. )
  1045. r = self.grid_render
  1046. r.beginFrame()
  1047. # Render the whole grid
  1048. self.grid.render(r, CELL_PIXELS)
  1049. # Draw the agent
  1050. r.push()
  1051. r.translate(
  1052. CELL_PIXELS * (self.agent_pos[0] + 0.5),
  1053. CELL_PIXELS * (self.agent_pos[1] + 0.5)
  1054. )
  1055. r.rotate(self.agent_dir * 90)
  1056. r.setLineColor(255, 0, 0)
  1057. r.setColor(255, 0, 0)
  1058. r.drawPolygon([
  1059. (-12, 10),
  1060. ( 12, 0),
  1061. (-12, -10)
  1062. ])
  1063. r.pop()
  1064. # Compute which cells are visible to the agent
  1065. _, vis_mask = self.gen_obs_grid()
  1066. # Compute the absolute coordinates of the bottom-left corner
  1067. # of the agent's view area
  1068. f_vec = self.dir_vec
  1069. r_vec = self.right_vec
  1070. top_left = self.agent_pos + f_vec * (AGENT_VIEW_SIZE-1) - r_vec * (AGENT_VIEW_SIZE // 2)
  1071. # For each cell in the visibility mask
  1072. for vis_j in range(0, AGENT_VIEW_SIZE):
  1073. for vis_i in range(0, AGENT_VIEW_SIZE):
  1074. # If this cell is not visible, don't highlight it
  1075. if not vis_mask[vis_i, vis_j]:
  1076. continue
  1077. # Compute the world coordinates of this cell
  1078. abs_i, abs_j = top_left - (f_vec * vis_j) + (r_vec * vis_i)
  1079. # Highlight the cell
  1080. r.fillRect(
  1081. abs_i * CELL_PIXELS,
  1082. abs_j * CELL_PIXELS,
  1083. CELL_PIXELS,
  1084. CELL_PIXELS,
  1085. 255, 255, 255, 75
  1086. )
  1087. r.endFrame()
  1088. if mode == 'rgb_array':
  1089. return r.getArray()
  1090. elif mode == 'pixmap':
  1091. return r.getPixmap()
  1092. return r