minigrid.py 32 KB

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