minigrid.py 37 KB

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