minigrid.py 37 KB

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