minigrid.py 37 KB

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