minigrid.py 32 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208
  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. r.push()
  361. # Internally, we draw at the "large" full-grid resolution, but we
  362. # use the renderer to scale back to the desired size
  363. r.scale(tile_size / CELL_PIXELS, tile_size / CELL_PIXELS)
  364. # Draw the background of the in-world cells black
  365. r.fillRect(
  366. 0,
  367. 0,
  368. widthPx,
  369. heightPx,
  370. 0, 0, 0
  371. )
  372. # Draw grid lines
  373. r.setLineColor(100, 100, 100)
  374. for rowIdx in range(0, self.height):
  375. y = CELL_PIXELS * rowIdx
  376. r.drawLine(0, y, widthPx, y)
  377. for colIdx in range(0, self.width):
  378. x = CELL_PIXELS * colIdx
  379. r.drawLine(x, 0, x, heightPx)
  380. # Render the grid
  381. for j in range(0, self.height):
  382. for i in range(0, self.width):
  383. cell = self.get(i, j)
  384. if cell == None:
  385. continue
  386. r.push()
  387. r.translate(i * CELL_PIXELS, j * CELL_PIXELS)
  388. cell.render(r)
  389. r.pop()
  390. r.pop()
  391. def encode(self):
  392. """
  393. Produce a compact numpy encoding of the grid
  394. """
  395. codeSize = self.width * self.height * 3
  396. array = np.zeros(shape=(self.width, self.height, 3), dtype='uint8')
  397. for j in range(0, self.height):
  398. for i in range(0, self.width):
  399. v = self.get(i, j)
  400. if v == None:
  401. continue
  402. array[i, j, 0] = OBJECT_TO_IDX[v.type]
  403. array[i, j, 1] = COLOR_TO_IDX[v.color]
  404. if hasattr(v, 'is_open') and v.is_open:
  405. array[i, j, 2] = 1
  406. return array
  407. def decode(array):
  408. """
  409. Decode an array grid encoding back into a grid
  410. """
  411. width = array.shape[0]
  412. height = array.shape[1]
  413. assert array.shape[2] == 3
  414. grid = Grid(width, height)
  415. for j in range(0, height):
  416. for i in range(0, width):
  417. typeIdx = array[i, j, 0]
  418. colorIdx = array[i, j, 1]
  419. openIdx = array[i, j, 2]
  420. if typeIdx == 0:
  421. continue
  422. objType = IDX_TO_OBJECT[typeIdx]
  423. color = IDX_TO_COLOR[colorIdx]
  424. is_open = True if openIdx == 1 else 0
  425. if objType == 'wall':
  426. v = Wall(color)
  427. elif objType == 'ball':
  428. v = Ball(color)
  429. elif objType == 'key':
  430. v = Key(color)
  431. elif objType == 'box':
  432. v = Box(color)
  433. elif objType == 'door':
  434. v = Door(color, is_open)
  435. elif objType == 'locked_door':
  436. v = LockedDoor(color, is_open)
  437. elif objType == 'goal':
  438. v = Goal()
  439. else:
  440. assert False, "unknown obj type in decode '%s'" % objType
  441. grid.set(i, j, v)
  442. return grid
  443. def process_vis(grid, agent_pos):
  444. mask = np.zeros(shape=(grid.width, grid.height), dtype=np.bool)
  445. mask[agent_pos[0], agent_pos[1]] = True
  446. for j in reversed(range(1, grid.height)):
  447. for i in range(0, grid.width-1):
  448. if not mask[i, j]:
  449. continue
  450. cell = grid.get(i, j)
  451. if cell and not cell.see_behind():
  452. continue
  453. mask[i+1, j] = True
  454. mask[i+1, j-1] = True
  455. mask[i, j-1] = True
  456. for i in reversed(range(1, grid.width)):
  457. if not mask[i, j]:
  458. continue
  459. cell = grid.get(i, j)
  460. if cell and not cell.see_behind():
  461. continue
  462. mask[i-1, j-1] = True
  463. mask[i-1, j] = True
  464. mask[i, j-1] = True
  465. for j in range(0, grid.height):
  466. for i in range(0, grid.width):
  467. if not mask[i, j]:
  468. grid.set(i, j, None)
  469. return mask
  470. class MiniGridEnv(gym.Env):
  471. """
  472. 2D grid world game environment
  473. """
  474. metadata = {
  475. 'render.modes': ['human', 'rgb_array', 'pixmap'],
  476. 'video.frames_per_second' : 10
  477. }
  478. # Enumeration of possible actions
  479. class Actions(IntEnum):
  480. # Turn left, turn right, move forward
  481. left = 0
  482. right = 1
  483. forward = 2
  484. # Pick up an object
  485. pickup = 3
  486. # Drop an object
  487. drop = 4
  488. # Toggle/activate an object
  489. toggle = 5
  490. # Wait/stay put/do nothing
  491. wait = 6
  492. def __init__(
  493. self,
  494. grid_size=16,
  495. max_steps=100,
  496. see_through_walls=False,
  497. seed=1337
  498. ):
  499. # Action enumeration for this environment
  500. self.actions = MiniGridEnv.Actions
  501. # Actions are discrete integer values
  502. self.action_space = spaces.Discrete(len(self.actions))
  503. # Observations are dictionaries containing an
  504. # encoding of the grid and a textual 'mission' string
  505. self.observation_space = spaces.Box(
  506. low=0,
  507. high=255,
  508. shape=OBS_ARRAY_SIZE,
  509. dtype='uint8'
  510. )
  511. self.observation_space = spaces.Dict({
  512. 'image': self.observation_space
  513. })
  514. # Range of possible rewards
  515. self.reward_range = (0, 1)
  516. # Renderer object used to render the whole grid (full-scale)
  517. self.grid_render = None
  518. # Renderer used to render observations (small-scale agent view)
  519. self.obs_render = None
  520. # Environment configuration
  521. self.grid_size = grid_size
  522. self.max_steps = max_steps
  523. self.see_through_walls = see_through_walls
  524. # Starting position and direction for the agent
  525. self.start_pos = None
  526. self.start_dir = None
  527. # Initialize the RNG
  528. self.seed(seed=seed)
  529. # Initialize the state
  530. self.reset()
  531. def reset(self):
  532. # Generate a new random grid at the start of each episode
  533. # To keep the same grid for each episode, call env.seed() with
  534. # the same seed before calling env.reset()
  535. self._gen_grid(self.grid_size, self.grid_size)
  536. # These fields should be defined by _gen_grid
  537. assert self.start_pos is not None
  538. assert self.start_dir is not None
  539. # Check that the agent doesn't overlap with an object
  540. assert self.grid.get(*self.start_pos) is None
  541. # Place the agent in the starting position and direction
  542. self.agent_pos = self.start_pos
  543. self.agent_dir = self.start_dir
  544. # Item picked up, being carried, initially nothing
  545. self.carrying = None
  546. # Step count since episode start
  547. self.step_count = 0
  548. # Return first observation
  549. obs = self.gen_obs()
  550. return obs
  551. def seed(self, seed=1337):
  552. # Seed the random number generator
  553. self.np_random, _ = seeding.np_random(seed)
  554. return [seed]
  555. @property
  556. def steps_remaining(self):
  557. return self.max_steps - self.step_count
  558. def __str__(self):
  559. """
  560. Produce a pretty string of the environment's grid along with the agent.
  561. The agent is represented by `⏩`. A grid pixel is represented by 2-character
  562. string, the first one for the object and the second one for the color.
  563. """
  564. from copy import deepcopy
  565. def rotate_left(array):
  566. new_array = deepcopy(array)
  567. for i in range(len(array)):
  568. for j in range(len(array[0])):
  569. new_array[j][len(array[0])-1-i] = array[i][j]
  570. return new_array
  571. def vertically_symmetrize(array):
  572. new_array = deepcopy(array)
  573. for i in range(len(array)):
  574. for j in range(len(array[0])):
  575. new_array[i][len(array[0])-1-j] = array[i][j]
  576. return new_array
  577. # Map of object id to short string
  578. OBJECT_IDX_TO_IDS = {
  579. 0: ' ',
  580. 1: 'W',
  581. 2: 'D',
  582. 3: 'L',
  583. 4: 'K',
  584. 5: 'B',
  585. 6: 'X',
  586. 7: 'G'
  587. }
  588. # Short string for opened door
  589. OPENDED_DOOR_IDS = '_'
  590. # Map of color id to short string
  591. COLOR_IDX_TO_IDS = {
  592. 0: 'R',
  593. 1: 'G',
  594. 2: 'B',
  595. 3: 'P',
  596. 4: 'Y',
  597. 5: 'E'
  598. }
  599. # Map agent's direction to short string
  600. AGENT_DIR_TO_IDS = {
  601. 0: '⏩',
  602. 1: '⏬',
  603. 2: '⏪',
  604. 3: '⏫'
  605. }
  606. array = self.grid.encode()
  607. array = rotate_left(array)
  608. array = vertically_symmetrize(array)
  609. new_array = []
  610. for line in array:
  611. new_line = []
  612. for pixel in line:
  613. # If the door is opened
  614. if pixel[0] in [2, 3] and pixel[2] == 1:
  615. object_ids = OPENDED_DOOR_IDS
  616. else:
  617. object_ids = OBJECT_IDX_TO_IDS[pixel[0]]
  618. # If no object
  619. if pixel[0] == 0:
  620. color_ids = ' '
  621. else:
  622. color_ids = COLOR_IDX_TO_IDS[pixel[1]]
  623. new_line.append(object_ids + color_ids)
  624. new_array.append(new_line)
  625. # Add the agent
  626. new_array[self.agent_pos[1]][self.agent_pos[0]] = AGENT_DIR_TO_IDS[self.agent_dir]
  627. return "\n".join([" ".join(line) for line in new_array])
  628. def _gen_grid(self, width, height):
  629. assert False, "_gen_grid needs to be implemented by each environment"
  630. def _rand_int(self, low, high):
  631. """
  632. Generate random integer in [low,high[
  633. """
  634. return self.np_random.randint(low, high)
  635. def _rand_bool(self):
  636. """
  637. Generate random boolean value
  638. """
  639. return (self.np_random.randint(0, 2) == 0)
  640. def _rand_elem(self, iterable):
  641. """
  642. Pick a random element in a list
  643. """
  644. lst = list(iterable)
  645. idx = self._rand_int(0, len(lst))
  646. return lst[idx]
  647. def _rand_color(self):
  648. """
  649. Generate a random color name (string)
  650. """
  651. return self._rand_elem(COLOR_NAMES)
  652. def _rand_pos(self, xLow, xHigh, yLow, yHigh):
  653. """
  654. Generate a random (x,y) position tuple
  655. """
  656. return (
  657. self.np_random.randint(xLow, xHigh),
  658. self.np_random.randint(yLow, yHigh)
  659. )
  660. def place_obj(self, obj, top=None, size=None, reject_fn=None):
  661. """
  662. Place an object at an empty position in the grid
  663. :param top: top-left position of the rectangle where to place
  664. :param size: size of the rectangle where to place
  665. :param reject_fn: function to filter out potential positions
  666. """
  667. if top is None:
  668. top = (0, 0)
  669. if size is None:
  670. size = (self.grid.width, self.grid.height)
  671. while True:
  672. pos = np.array((
  673. self._rand_int(top[0], top[0] + size[0]),
  674. self._rand_int(top[1], top[1] + size[1])
  675. ))
  676. # Don't place the object on top of another object
  677. if self.grid.get(*pos) != None:
  678. continue
  679. # Don't place the object where the agent is
  680. if np.array_equal(pos, self.start_pos):
  681. continue
  682. # Check if there is a filtering criterion
  683. if reject_fn and reject_fn(self, pos):
  684. continue
  685. break
  686. self.grid.set(*pos, obj)
  687. return pos
  688. def place_agent(self, top=None, size=None, rand_dir=True):
  689. """
  690. Set the agent's starting point at an empty position in the grid
  691. """
  692. pos = self.place_obj(None, top, size)
  693. self.start_pos = pos
  694. if rand_dir:
  695. self.start_dir = self._rand_int(0, 4)
  696. return pos
  697. def get_dir_vec(self):
  698. """
  699. Get the direction vector for the agent, pointing in the direction
  700. of forward movement.
  701. """
  702. assert self.agent_dir >= 0 and self.agent_dir < 4
  703. return DIR_TO_VEC[self.agent_dir]
  704. def get_right_vec(self):
  705. """
  706. Get the vector pointing to the right of the agent.
  707. """
  708. dx, dy = self.get_dir_vec()
  709. return np.array((-dy, dx))
  710. def get_view_coords(self, i, j):
  711. """
  712. Translate and rotate absolute grid coordinates (i, j) into the
  713. agent's partially observable view (sub-grid). Note that the resulting
  714. coordinates may be negative or outside of the agent's view size.
  715. """
  716. ax, ay = self.agent_pos
  717. dx, dy = self.get_dir_vec()
  718. rx, ry = self.get_right_vec()
  719. # Compute the absolute coordinates of the top-left view corner
  720. sz = AGENT_VIEW_SIZE
  721. hs = AGENT_VIEW_SIZE // 2
  722. tx = ax + (dx * (sz-1)) - (rx * hs)
  723. ty = ay + (dy * (sz-1)) - (ry * hs)
  724. lx = i - tx
  725. ly = j - ty
  726. # Project the coordinates of the object relative to the top-left
  727. # corner onto the agent's own coordinate system
  728. vx = (rx*lx + ry*ly)
  729. vy = -(dx*lx + dy*ly)
  730. return vx, vy
  731. def get_view_exts(self):
  732. """
  733. Get the extents of the square set of tiles visible to the agent
  734. Note: the bottom extent indices are not included in the set
  735. """
  736. # Facing right
  737. if self.agent_dir == 0:
  738. topX = self.agent_pos[0]
  739. topY = self.agent_pos[1] - AGENT_VIEW_SIZE // 2
  740. # Facing down
  741. elif self.agent_dir == 1:
  742. topX = self.agent_pos[0] - AGENT_VIEW_SIZE // 2
  743. topY = self.agent_pos[1]
  744. # Facing left
  745. elif self.agent_dir == 2:
  746. topX = self.agent_pos[0] - AGENT_VIEW_SIZE + 1
  747. topY = self.agent_pos[1] - AGENT_VIEW_SIZE // 2
  748. # Facing up
  749. elif self.agent_dir == 3:
  750. topX = self.agent_pos[0] - AGENT_VIEW_SIZE // 2
  751. topY = self.agent_pos[1] - AGENT_VIEW_SIZE + 1
  752. else:
  753. assert False, "invalid agent direction"
  754. botX = topX + AGENT_VIEW_SIZE
  755. botY = topY + AGENT_VIEW_SIZE
  756. return (topX, topY, botX, botY)
  757. def agent_sees(self, x, y):
  758. """
  759. Check if a grid position is visible to the agent
  760. """
  761. vx, vy = self.get_view_coords(x, y)
  762. if vx < 0 or vy < 0 or vx >= AGENT_VIEW_SIZE or vy >= AGENT_VIEW_SIZE:
  763. return False
  764. obs = self.gen_obs()
  765. obs_grid = Grid.decode(obs['image'])
  766. obs_cell = obs_grid.get(vx, vy)
  767. world_cell = self.grid.get(x, y)
  768. return obs_cell is not None and obs_cell.type == world_cell.type
  769. def step(self, action):
  770. self.step_count += 1
  771. reward = 0
  772. done = False
  773. # Get the position in front of the agent
  774. fwd_pos = self.agent_pos + self.get_dir_vec()
  775. # Get the contents of the cell in front of the agent
  776. fwd_cell = self.grid.get(*fwd_pos)
  777. # Rotate left
  778. if action == self.actions.left:
  779. self.agent_dir -= 1
  780. if self.agent_dir < 0:
  781. self.agent_dir += 4
  782. # Rotate right
  783. elif action == self.actions.right:
  784. self.agent_dir = (self.agent_dir + 1) % 4
  785. # Move forward
  786. elif action == self.actions.forward:
  787. if fwd_cell == None or fwd_cell.can_overlap():
  788. self.agent_pos = fwd_pos
  789. if fwd_cell != None and fwd_cell.type == 'goal':
  790. done = True
  791. reward = 1
  792. # Pick up an object
  793. elif action == self.actions.pickup:
  794. if fwd_cell and fwd_cell.can_pickup():
  795. if self.carrying is None:
  796. self.carrying = fwd_cell
  797. self.grid.set(*fwd_pos, None)
  798. # Drop an object
  799. elif action == self.actions.drop:
  800. if not fwd_cell and self.carrying:
  801. self.grid.set(*fwd_pos, self.carrying)
  802. self.carrying = None
  803. # Toggle/activate an object
  804. elif action == self.actions.toggle:
  805. if fwd_cell:
  806. fwd_cell.toggle(self, fwd_pos)
  807. # Wait/do nothing
  808. elif action == self.actions.wait:
  809. pass
  810. else:
  811. assert False, "unknown action"
  812. if self.step_count >= self.max_steps:
  813. done = True
  814. obs = self.gen_obs()
  815. return obs, reward, done, {}
  816. def gen_obs_grid(self):
  817. """
  818. Generate the sub-grid observed by the agent.
  819. This method also outputs a visibility mask telling us which grid
  820. cells the agent can actually see.
  821. """
  822. topX, topY, botX, botY = self.get_view_exts()
  823. grid = self.grid.slice(topX, topY, AGENT_VIEW_SIZE, AGENT_VIEW_SIZE)
  824. for i in range(self.agent_dir + 1):
  825. grid = grid.rotate_left()
  826. # Process occluders and visibility
  827. # Note that this incurs some performance cost
  828. if not self.see_through_walls:
  829. vis_mask = grid.process_vis(agent_pos=(3, 6))
  830. else:
  831. vis_mask = np.ones(shape=(grid.width, grid.height), dtype=np.bool)
  832. # Make it so the agent sees what it's carrying
  833. # We do this by placing the carried object at the agent's position
  834. # in the agent's partially observable view
  835. agent_pos = grid.width // 2, grid.height - 1
  836. if self.carrying:
  837. grid.set(*agent_pos, self.carrying)
  838. else:
  839. grid.set(*agent_pos, None)
  840. return grid, vis_mask
  841. def gen_obs(self):
  842. """
  843. Generate the agent's view (partially observable, low-resolution encoding)
  844. """
  845. grid, vis_mask = self.gen_obs_grid()
  846. # Encode the partially observable view into a numpy array
  847. image = grid.encode()
  848. assert hasattr(self, 'mission'), "environments must define a textual mission string"
  849. # Observations are dictionaries containing:
  850. # - an image (partially observable view of the environment)
  851. # - the agent's direction/orientation (acting as a compass)
  852. # - a textual mission string (instructions for the agent)
  853. obs = {
  854. 'image': image,
  855. 'direction': self.agent_dir,
  856. 'mission': self.mission
  857. }
  858. return obs
  859. def get_obs_render(self, obs):
  860. """
  861. Render an agent observation for visualization
  862. """
  863. if self.obs_render == None:
  864. self.obs_render = Renderer(
  865. AGENT_VIEW_SIZE * CELL_PIXELS // 2,
  866. AGENT_VIEW_SIZE * CELL_PIXELS // 2
  867. )
  868. r = self.obs_render
  869. r.beginFrame()
  870. grid = Grid.decode(obs)
  871. # Render the whole grid
  872. grid.render(r, CELL_PIXELS // 2)
  873. # Draw the agent
  874. r.push()
  875. r.scale(0.5, 0.5)
  876. r.translate(
  877. CELL_PIXELS * (0.5 + AGENT_VIEW_SIZE // 2),
  878. CELL_PIXELS * (AGENT_VIEW_SIZE - 0.5)
  879. )
  880. r.rotate(3 * 90)
  881. r.setLineColor(255, 0, 0)
  882. r.setColor(255, 0, 0)
  883. r.drawPolygon([
  884. (-12, 10),
  885. ( 12, 0),
  886. (-12, -10)
  887. ])
  888. r.pop()
  889. r.endFrame()
  890. return r.getPixmap()
  891. def render(self, mode='human', close=False):
  892. """
  893. Render the whole-grid human view
  894. """
  895. if close:
  896. if self.grid_render:
  897. self.grid_render.close()
  898. return
  899. if self.grid_render is None:
  900. self.grid_render = Renderer(
  901. self.grid_size * CELL_PIXELS,
  902. self.grid_size * CELL_PIXELS,
  903. True if mode == 'human' else False
  904. )
  905. r = self.grid_render
  906. r.beginFrame()
  907. # Render the whole grid
  908. self.grid.render(r, CELL_PIXELS)
  909. # Draw the agent
  910. r.push()
  911. r.translate(
  912. CELL_PIXELS * (self.agent_pos[0] + 0.5),
  913. CELL_PIXELS * (self.agent_pos[1] + 0.5)
  914. )
  915. r.rotate(self.agent_dir * 90)
  916. r.setLineColor(255, 0, 0)
  917. r.setColor(255, 0, 0)
  918. r.drawPolygon([
  919. (-12, 10),
  920. ( 12, 0),
  921. (-12, -10)
  922. ])
  923. r.pop()
  924. # Compute which cells are visible to the agent
  925. _, vis_mask = self.gen_obs_grid()
  926. # Compute the absolute coordinates of the bottom-left corner
  927. # of the agent's view area
  928. f_vec = self.get_dir_vec()
  929. r_vec = self.get_right_vec()
  930. top_left = self.agent_pos + f_vec * (AGENT_VIEW_SIZE-1) - r_vec * (AGENT_VIEW_SIZE // 2)
  931. # For each cell in the visibility mask
  932. for vis_j in range(0, AGENT_VIEW_SIZE):
  933. for vis_i in range(0, AGENT_VIEW_SIZE):
  934. # If this cell is not visible, don't highlight it
  935. if not vis_mask[vis_i, vis_j]:
  936. continue
  937. # Compute the world coordinates of this cell
  938. abs_i, abs_j = top_left - (f_vec * vis_j) + (r_vec * vis_i)
  939. # Highlight the cell
  940. r.fillRect(
  941. abs_i * CELL_PIXELS,
  942. abs_j * CELL_PIXELS,
  943. CELL_PIXELS,
  944. CELL_PIXELS,
  945. 255, 255, 255, 75
  946. )
  947. r.endFrame()
  948. if mode == 'rgb_array':
  949. return r.getArray()
  950. elif mode == 'pixmap':
  951. return r.getPixmap()
  952. return r