minigrid.py 28 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057
  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. class WorldObj:
  47. """
  48. Base class for grid world objects
  49. """
  50. def __init__(self, type, color):
  51. assert type in OBJECT_TO_IDX, type
  52. assert color in COLOR_TO_IDX, color
  53. self.type = type
  54. self.color = color
  55. self.contains = None
  56. def canOverlap(self):
  57. """Can the agent overlap with this?"""
  58. return False
  59. def canPickup(self):
  60. """Can the agent pick this up?"""
  61. return False
  62. def canContain(self):
  63. """Can this contain another object?"""
  64. return False
  65. def toggle(self, env, pos):
  66. """Method to trigger/toggle an action this object performs"""
  67. return False
  68. def render(self, r):
  69. assert False
  70. def _setColor(self, r):
  71. c = COLORS[self.color]
  72. r.setLineColor(c[0], c[1], c[2])
  73. r.setColor(c[0], c[1], c[2])
  74. class Goal(WorldObj):
  75. def __init__(self):
  76. super(Goal, self).__init__('goal', 'green')
  77. def canOverlap(self):
  78. return True
  79. def render(self, r):
  80. self._setColor(r)
  81. r.drawPolygon([
  82. (0 , CELL_PIXELS),
  83. (CELL_PIXELS, CELL_PIXELS),
  84. (CELL_PIXELS, 0),
  85. (0 , 0)
  86. ])
  87. class Wall(WorldObj):
  88. def __init__(self, color='grey'):
  89. super(Wall, self).__init__('wall', color)
  90. def render(self, r):
  91. self._setColor(r)
  92. r.drawPolygon([
  93. (0 , CELL_PIXELS),
  94. (CELL_PIXELS, CELL_PIXELS),
  95. (CELL_PIXELS, 0),
  96. (0 , 0)
  97. ])
  98. class Door(WorldObj):
  99. def __init__(self, color, isOpen=False):
  100. super(Door, self).__init__('door', color)
  101. self.isOpen = isOpen
  102. def render(self, r):
  103. c = COLORS[self.color]
  104. r.setLineColor(c[0], c[1], c[2])
  105. r.setColor(0, 0, 0)
  106. if self.isOpen:
  107. r.drawPolygon([
  108. (CELL_PIXELS-2, CELL_PIXELS),
  109. (CELL_PIXELS , CELL_PIXELS),
  110. (CELL_PIXELS , 0),
  111. (CELL_PIXELS-2, 0)
  112. ])
  113. return
  114. r.drawPolygon([
  115. (0 , CELL_PIXELS),
  116. (CELL_PIXELS, CELL_PIXELS),
  117. (CELL_PIXELS, 0),
  118. (0 , 0)
  119. ])
  120. r.drawPolygon([
  121. (2 , CELL_PIXELS-2),
  122. (CELL_PIXELS-2, CELL_PIXELS-2),
  123. (CELL_PIXELS-2, 2),
  124. (2 , 2)
  125. ])
  126. r.drawCircle(CELL_PIXELS * 0.75, CELL_PIXELS * 0.5, 2)
  127. def toggle(self, env, pos):
  128. if not self.isOpen:
  129. self.isOpen = True
  130. return True
  131. return False
  132. def canOverlap(self):
  133. """The agent can only walk over this cell when the door is open"""
  134. return self.isOpen
  135. class LockedDoor(WorldObj):
  136. def __init__(self, color, isOpen=False):
  137. super(LockedDoor, self).__init__('locked_door', color)
  138. self.isOpen = isOpen
  139. def render(self, r):
  140. c = COLORS[self.color]
  141. r.setLineColor(c[0], c[1], c[2])
  142. r.setColor(c[0], c[1], c[2], 50)
  143. if self.isOpen:
  144. r.drawPolygon([
  145. (CELL_PIXELS-2, CELL_PIXELS),
  146. (CELL_PIXELS , CELL_PIXELS),
  147. (CELL_PIXELS , 0),
  148. (CELL_PIXELS-2, 0)
  149. ])
  150. return
  151. r.drawPolygon([
  152. (0 , CELL_PIXELS),
  153. (CELL_PIXELS, CELL_PIXELS),
  154. (CELL_PIXELS, 0),
  155. (0 , 0)
  156. ])
  157. r.drawPolygon([
  158. (2 , CELL_PIXELS-2),
  159. (CELL_PIXELS-2, CELL_PIXELS-2),
  160. (CELL_PIXELS-2, 2),
  161. (2 , 2)
  162. ])
  163. r.drawLine(
  164. CELL_PIXELS * 0.55,
  165. CELL_PIXELS * 0.5,
  166. CELL_PIXELS * 0.75,
  167. CELL_PIXELS * 0.5
  168. )
  169. def toggle(self, env, pos):
  170. # If the player has the right key to open the door
  171. if isinstance(env.carrying, Key) and env.carrying.color == self.color:
  172. self.isOpen = True
  173. # The key has been used, remove it from the agent
  174. env.carrying = None
  175. return True
  176. return False
  177. def canOverlap(self):
  178. """The agent can only walk over this cell when the door is open"""
  179. return self.isOpen
  180. class Key(WorldObj):
  181. def __init__(self, color='blue'):
  182. super(Key, self).__init__('key', color)
  183. def canPickup(self):
  184. return True
  185. def render(self, r):
  186. self._setColor(r)
  187. # Vertical quad
  188. r.drawPolygon([
  189. (16, 10),
  190. (20, 10),
  191. (20, 28),
  192. (16, 28)
  193. ])
  194. # Teeth
  195. r.drawPolygon([
  196. (12, 19),
  197. (16, 19),
  198. (16, 21),
  199. (12, 21)
  200. ])
  201. r.drawPolygon([
  202. (12, 26),
  203. (16, 26),
  204. (16, 28),
  205. (12, 28)
  206. ])
  207. r.drawCircle(18, 9, 6)
  208. r.setLineColor(0, 0, 0)
  209. r.setColor(0, 0, 0)
  210. r.drawCircle(18, 9, 2)
  211. class Ball(WorldObj):
  212. def __init__(self, color='blue'):
  213. super(Ball, self).__init__('ball', color)
  214. def canPickup(self):
  215. return True
  216. def render(self, r):
  217. self._setColor(r)
  218. r.drawCircle(CELL_PIXELS * 0.5, CELL_PIXELS * 0.5, 10)
  219. class Box(WorldObj):
  220. def __init__(self, color, contains=None):
  221. super(Box, self).__init__('box', color)
  222. self.contains = contains
  223. def canPickup(self):
  224. return True
  225. def render(self, r):
  226. c = COLORS[self.color]
  227. r.setLineColor(c[0], c[1], c[2])
  228. r.setColor(0, 0, 0)
  229. r.setLineWidth(2)
  230. r.drawPolygon([
  231. (4 , CELL_PIXELS-4),
  232. (CELL_PIXELS-4, CELL_PIXELS-4),
  233. (CELL_PIXELS-4, 4),
  234. (4 , 4)
  235. ])
  236. r.drawLine(
  237. 4,
  238. CELL_PIXELS / 2,
  239. CELL_PIXELS - 4,
  240. CELL_PIXELS / 2
  241. )
  242. r.setLineWidth(1)
  243. def toggle(self, env, pos):
  244. # Replace the box by its contents
  245. env.grid.set(*pos, self.contains)
  246. return True
  247. class Grid:
  248. """
  249. Represent a grid and operations on it
  250. """
  251. def __init__(self, width, height):
  252. assert width >= 4
  253. assert height >= 4
  254. self.width = width
  255. self.height = height
  256. self.grid = [None] * width * height
  257. def __contains__(self, key):
  258. if isinstance(key, WorldObj):
  259. for e in self.grid:
  260. if e is key:
  261. return True
  262. elif isinstance(key, tuple):
  263. for e in self.grid:
  264. if e is None:
  265. continue
  266. if (e.color, e.type) == key:
  267. return True
  268. return False
  269. def __eq__(self, other):
  270. grid1 = self.encode()
  271. grid2 = other.encode()
  272. return np.array_equal(grid2, grid1)
  273. def __ne__(self, other):
  274. return not self == other
  275. def __str__(self):
  276. return self.prettystring()
  277. def copy(self):
  278. from copy import deepcopy
  279. return deepcopy(self)
  280. def set(self, i, j, v):
  281. assert i >= 0 and i < self.width
  282. assert j >= 0 and j < self.height
  283. self.grid[j * self.width + i] = v
  284. def get(self, i, j):
  285. assert i >= 0 and i < self.width
  286. assert j >= 0 and j < self.height
  287. return self.grid[j * self.width + i]
  288. def horzWall(self, x, y, length=None):
  289. if length is None:
  290. length = self.width - x
  291. for i in range(0, length):
  292. self.set(x + i, y, Wall())
  293. def vertWall(self, x, y, length=None):
  294. if length is None:
  295. length = self.height - y
  296. for j in range(0, length):
  297. self.set(x, y + j, Wall())
  298. def wallRect(self, x, y, w, h):
  299. self.horzWall(x, y, w)
  300. self.horzWall(x, y+h-1, w)
  301. self.vertWall(x, y, h)
  302. self.vertWall(x+w-1, y, h)
  303. def rotateLeft(self):
  304. """
  305. Rotate the grid to the left (counter-clockwise)
  306. """
  307. grid = Grid(self.width, self.height)
  308. for j in range(0, self.height):
  309. for i in range(0, self.width):
  310. v = self.get(self.width - 1 - j, i)
  311. grid.set(i, j, v)
  312. return grid
  313. def slice(self, topX, topY, width, height):
  314. """
  315. Get a subset of the grid
  316. """
  317. grid = Grid(width, height)
  318. for j in range(0, height):
  319. for i in range(0, width):
  320. x = topX + i
  321. y = topY + j
  322. if x >= 0 and x < self.width and \
  323. y >= 0 and y < self.height:
  324. v = self.get(x, y)
  325. else:
  326. v = Wall()
  327. grid.set(i, j, v)
  328. return grid
  329. def render(self, r, tileSize):
  330. """
  331. Render this grid at a given scale
  332. :param r: target renderer object
  333. :param tileSize: tile size in pixels
  334. """
  335. assert r.width == self.width * tileSize
  336. assert r.height == self.height * tileSize
  337. # Total grid size at native scale
  338. widthPx = self.width * CELL_PIXELS
  339. heightPx = self.height * CELL_PIXELS
  340. # Draw background (out-of-world) tiles the same colors as walls
  341. # so the agent understands these areas are not reachable
  342. c = COLORS['grey']
  343. r.setLineColor(c[0], c[1], c[2])
  344. r.setColor(c[0], c[1], c[2])
  345. r.drawPolygon([
  346. (0 , heightPx),
  347. (widthPx, heightPx),
  348. (widthPx, 0),
  349. (0 , 0)
  350. ])
  351. r.push()
  352. # Internally, we draw at the "large" full-grid resolution, but we
  353. # use the renderer to scale back to the desired size
  354. r.scale(tileSize / CELL_PIXELS, tileSize / CELL_PIXELS)
  355. # Draw the background of the in-world cells black
  356. r.fillRect(
  357. 0,
  358. 0,
  359. widthPx,
  360. heightPx,
  361. 0, 0, 0
  362. )
  363. # Draw grid lines
  364. r.setLineColor(100, 100, 100)
  365. for rowIdx in range(0, self.height):
  366. y = CELL_PIXELS * rowIdx
  367. r.drawLine(0, y, widthPx, y)
  368. for colIdx in range(0, self.width):
  369. x = CELL_PIXELS * colIdx
  370. r.drawLine(x, 0, x, heightPx)
  371. # Render the grid
  372. for j in range(0, self.height):
  373. for i in range(0, self.width):
  374. cell = self.get(i, j)
  375. if cell == None:
  376. continue
  377. r.push()
  378. r.translate(i * CELL_PIXELS, j * CELL_PIXELS)
  379. cell.render(r)
  380. r.pop()
  381. r.pop()
  382. def encode(self):
  383. """
  384. Produce a compact numpy encoding of the grid
  385. """
  386. codeSize = self.width * self.height * 3
  387. array = np.zeros(shape=(self.width, self.height, 3), dtype='uint8')
  388. for j in range(0, self.height):
  389. for i in range(0, self.width):
  390. v = self.get(i, j)
  391. if v == None:
  392. continue
  393. array[i, j, 0] = OBJECT_TO_IDX[v.type]
  394. array[i, j, 1] = COLOR_TO_IDX[v.color]
  395. if hasattr(v, 'isOpen') and v.isOpen:
  396. array[i, j, 2] = 1
  397. return array
  398. def prettyencode(self, env=None):
  399. """
  400. Produce a compact 2d-array encoding of the grid with pretty pixels
  401. """
  402. from copy import deepcopy
  403. def rotate_left(array):
  404. new_array = deepcopy(array)
  405. for i in range(len(array)):
  406. for j in range(len(array[0])):
  407. new_array[j][len(array[0])-1-i] = array[i][j]
  408. return new_array
  409. def vertically_symmetrize(array):
  410. new_array = deepcopy(array)
  411. for i in range(len(array)):
  412. for j in range(len(array[0])):
  413. new_array[i][len(array[0])-1-j] = array[i][j]
  414. return new_array
  415. # Map of object id to short string
  416. OBJECT_IDX_TO_IDS = {
  417. 0: ' ',
  418. 1: 'W',
  419. 2: 'D',
  420. 3: 'L',
  421. 4: 'K',
  422. 5: 'B',
  423. 6: 'X',
  424. 7: 'G'
  425. }
  426. # Short string for opened door
  427. OPENDED_DOOR_IDS = '_'
  428. # Map of color id to short string
  429. COLOR_IDX_TO_IDS = {
  430. 0: 'R',
  431. 1: 'G',
  432. 2: 'B',
  433. 3: 'P',
  434. 4: 'Y',
  435. 5: 'E'
  436. }
  437. # Map agent's direction to short string
  438. AGENT_DIR_TO_IDS = {
  439. 0: '⏩',
  440. 1: '⏬',
  441. 2: '⏪',
  442. 3: '⏫'
  443. }
  444. array = self.encode()
  445. array = rotate_left(array)
  446. array = vertically_symmetrize(array)
  447. new_array = []
  448. for line in array:
  449. new_line = []
  450. for pixel in line:
  451. # If the door is opened
  452. if pixel[0] in [2, 3] and pixel[2] == 1:
  453. object_ids = OPENDED_DOOR_IDS
  454. else:
  455. object_ids = OBJECT_IDX_TO_IDS[pixel[0]]
  456. # If no object
  457. if pixel[0] == 0:
  458. color_ids = ' '
  459. else:
  460. color_ids = COLOR_IDX_TO_IDS[pixel[1]]
  461. new_line.append(object_ids + color_ids)
  462. new_array.append(new_line)
  463. if env != None:
  464. # Add the agent
  465. new_array[env.agentPos[1]][env.agentPos[0]] = AGENT_DIR_TO_IDS[env.agentDir]
  466. return new_array
  467. def prettystring(self, env=None):
  468. """
  469. Produce a pretty string of the grid
  470. """
  471. array = self.prettyencode(env)
  472. return "\n".join([" ".join(line) for line in array])
  473. def decode(array):
  474. """
  475. Decode an array grid encoding back into a grid
  476. """
  477. width = array.shape[0]
  478. height = array.shape[1]
  479. assert array.shape[2] == 3
  480. grid = Grid(width, height)
  481. for j in range(0, height):
  482. for i in range(0, width):
  483. typeIdx = array[i, j, 0]
  484. colorIdx = array[i, j, 1]
  485. openIdx = array[i, j, 2]
  486. if typeIdx == 0:
  487. continue
  488. objType = IDX_TO_OBJECT[typeIdx]
  489. color = IDX_TO_COLOR[colorIdx]
  490. isOpen = True if openIdx == 1 else 0
  491. if objType == 'wall':
  492. v = Wall(color)
  493. elif objType == 'ball':
  494. v = Ball(color)
  495. elif objType == 'key':
  496. v = Key(color)
  497. elif objType == 'box':
  498. v = Box(color)
  499. elif objType == 'door':
  500. v = Door(color, isOpen)
  501. elif objType == 'locked_door':
  502. v = LockedDoor(color, isOpen)
  503. elif objType == 'goal':
  504. v = Goal()
  505. else:
  506. assert False, "unknown obj type in decode '%s'" % objType
  507. grid.set(i, j, v)
  508. return grid
  509. class MiniGridEnv(gym.Env):
  510. """
  511. 2D grid world game environment
  512. """
  513. metadata = {
  514. 'render.modes': ['human', 'rgb_array', 'pixmap'],
  515. 'video.frames_per_second' : 10
  516. }
  517. # Enumeration of possible actions
  518. class Actions(IntEnum):
  519. # Turn left, turn right, move forward
  520. left = 0
  521. right = 1
  522. forward = 2
  523. # Pick up an object
  524. pickup = 3
  525. # Drop an object
  526. drop = 4
  527. # Toggle/activate an object
  528. toggle = 5
  529. # Wait/stay put/do nothing
  530. wait = 6
  531. def __init__(self, gridSize=16, maxSteps=100):
  532. # Action enumeration for this environment
  533. self.actions = MiniGridEnv.Actions
  534. # Actions are discrete integer values
  535. self.action_space = spaces.Discrete(len(self.actions))
  536. # Observations are dictionaries containing an
  537. # encoding of the grid and a textual 'mission' string
  538. self.observation_space = spaces.Box(
  539. low=0,
  540. high=255,
  541. shape=OBS_ARRAY_SIZE,
  542. dtype='uint8'
  543. )
  544. self.observation_space = spaces.Dict({
  545. 'image': self.observation_space
  546. })
  547. # Range of possible rewards
  548. self.reward_range = (-1, 1000)
  549. # Renderer object used to render the whole grid (full-scale)
  550. self.gridRender = None
  551. # Renderer used to render observations (small-scale agent view)
  552. self.obsRender = None
  553. # Environment configuration
  554. self.gridSize = gridSize
  555. self.maxSteps = maxSteps
  556. self.startPos = (1, 1)
  557. self.startDir = 0
  558. # Initialize the state
  559. self.seed()
  560. self.reset()
  561. def _genGrid(self, width, height):
  562. assert False, "_genGrid needs to be implemented by each environment"
  563. def reset(self):
  564. # Generate a new random grid at the start of each episode
  565. # To keep the same grid for each episode, call env.seed() with
  566. # the same seed before calling env.reset()
  567. self._genGrid(self.gridSize, self.gridSize)
  568. # Place the agent in the starting position and direction
  569. self.agentPos = self.startPos
  570. self.agentDir = self.startDir
  571. # Item picked up, being carried, initially nothing
  572. self.carrying = None
  573. # Step count since episode start
  574. self.stepCount = 0
  575. # Return first observation
  576. obs = self._genObs()
  577. return obs
  578. def seed(self, seed=1337):
  579. # Seed the random number generator
  580. self.np_random, _ = seeding.np_random(seed)
  581. return [seed]
  582. def _randInt(self, low, high):
  583. """
  584. Generate random integer in [low,high[
  585. """
  586. return self.np_random.randint(low, high)
  587. def _randElem(self, iterable):
  588. """
  589. Pick a random element in a list
  590. """
  591. lst = list(iterable)
  592. idx = self._randInt(0, len(lst))
  593. return lst[idx]
  594. def _randPos(self, xLow, xHigh, yLow, yHigh):
  595. """
  596. Generate a random (x,y) position tuple
  597. """
  598. return (
  599. self.np_random.randint(xLow, xHigh),
  600. self.np_random.randint(yLow, yHigh)
  601. )
  602. def placeObj(self, obj, top=None, size=None):
  603. """
  604. Place an object at an empty position in the grid
  605. :param top: top-left position of the rectangle where to place
  606. :param size: size of the rectangle where to place
  607. """
  608. if top is None:
  609. top = (0, 0)
  610. if size is None:
  611. size = (self.grid.width, self.grid.height)
  612. while True:
  613. pos = (
  614. self._randInt(top[0], top[0] + size[0]),
  615. self._randInt(top[1], top[1] + size[1])
  616. )
  617. if self.grid.get(*pos) != None:
  618. continue
  619. if pos == self.startPos:
  620. continue
  621. break
  622. self.grid.set(*pos, obj)
  623. return pos
  624. def placeAgent(self, randDir=True):
  625. """
  626. Set the agent's starting point at an empty position in the grid
  627. """
  628. pos = self.placeObj(None)
  629. self.startPos = pos
  630. if randDir:
  631. self.startDir = self._randInt(0, 4)
  632. return pos
  633. def getStepsRemaining(self):
  634. return self.maxSteps - self.stepCount
  635. def getDirVec(self):
  636. """
  637. Get the direction vector for the agent, pointing in the direction
  638. of forward movement.
  639. """
  640. # Pointing right
  641. if self.agentDir == 0:
  642. return (1, 0)
  643. # Down (positive Y)
  644. elif self.agentDir == 1:
  645. return (0, 1)
  646. # Pointing left
  647. elif self.agentDir == 2:
  648. return (-1, 0)
  649. # Up (negative Y)
  650. elif self.agentDir == 3:
  651. return (0, -1)
  652. else:
  653. assert False
  654. def getViewExts(self):
  655. """
  656. Get the extents of the square set of tiles visible to the agent
  657. Note: the bottom extent indices are not included in the set
  658. """
  659. # Facing right
  660. if self.agentDir == 0:
  661. topX = self.agentPos[0]
  662. topY = self.agentPos[1] - AGENT_VIEW_SIZE // 2
  663. # Facing down
  664. elif self.agentDir == 1:
  665. topX = self.agentPos[0] - AGENT_VIEW_SIZE // 2
  666. topY = self.agentPos[1]
  667. # Facing left
  668. elif self.agentDir == 2:
  669. topX = self.agentPos[0] - AGENT_VIEW_SIZE + 1
  670. topY = self.agentPos[1] - AGENT_VIEW_SIZE // 2
  671. # Facing up
  672. elif self.agentDir == 3:
  673. topX = self.agentPos[0] - AGENT_VIEW_SIZE // 2
  674. topY = self.agentPos[1] - AGENT_VIEW_SIZE + 1
  675. else:
  676. assert False, "invalid agent direction"
  677. botX = topX + AGENT_VIEW_SIZE
  678. botY = topY + AGENT_VIEW_SIZE
  679. return (topX, topY, botX, botY)
  680. def agentSees(self, x, y):
  681. """
  682. Check if a grid position is visible to the agent
  683. """
  684. topX, topY, botX, botY = self.getViewExts()
  685. return (x >= topX and x < botX and y >= topY and y < botY)
  686. def step(self, action):
  687. self.stepCount += 1
  688. reward = 0
  689. done = False
  690. # Get the position in front of the agent
  691. u, v = self.getDirVec()
  692. fwdPos = (self.agentPos[0] + u, self.agentPos[1] + v)
  693. # Get the contents of the cell in front of the agent
  694. fwdCell = self.grid.get(*fwdPos)
  695. # Rotate left
  696. if action == self.actions.left:
  697. self.agentDir -= 1
  698. if self.agentDir < 0:
  699. self.agentDir += 4
  700. # Rotate right
  701. elif action == self.actions.right:
  702. self.agentDir = (self.agentDir + 1) % 4
  703. # Move forward
  704. elif action == self.actions.forward:
  705. if fwdCell == None or fwdCell.canOverlap():
  706. self.agentPos = fwdPos
  707. if fwdCell != None and fwdCell.type == 'goal':
  708. done = True
  709. reward = 1000 - self.stepCount
  710. # Pick up an object
  711. elif action == self.actions.pickup:
  712. if fwdCell and fwdCell.canPickup():
  713. if self.carrying is None:
  714. self.carrying = fwdCell
  715. self.grid.set(*fwdPos, None)
  716. # Drop an object
  717. elif action == self.actions.drop:
  718. if not fwdCell and self.carrying:
  719. self.grid.set(*fwdPos, self.carrying)
  720. self.carrying = None
  721. # Toggle/activate an object
  722. elif action == self.actions.toggle:
  723. if fwdCell:
  724. fwdCell.toggle(self, fwdPos)
  725. # Wait/do nothing
  726. elif action == self.actions.wait:
  727. pass
  728. else:
  729. assert False, "unknown action"
  730. if self.stepCount >= self.maxSteps:
  731. done = True
  732. obs = self._genObs()
  733. return obs, reward, done, {}
  734. def _genObs(self):
  735. """
  736. Generate the agent's view (partially observable, low-resolution encoding)
  737. """
  738. topX, topY, botX, botY = self.getViewExts()
  739. grid = self.grid.slice(topX, topY, AGENT_VIEW_SIZE, AGENT_VIEW_SIZE)
  740. for i in range(self.agentDir + 1):
  741. grid = grid.rotateLeft()
  742. # Make it so the agent sees what it's carrying
  743. # We do this by placing the carried object at the agent's position
  744. # in the agent's partially observable view
  745. agentPos = grid.width // 2, grid.height - 1
  746. if self.carrying:
  747. grid.set(*agentPos, self.carrying)
  748. else:
  749. grid.set(*agentPos, None)
  750. # Encode the partially observable view into a numpy array
  751. image = grid.encode()
  752. assert hasattr(self, 'mission'), "environments must define a textual mission string"
  753. # Observations are dictionaries containing:
  754. # - an image (partially observable view of the environment)
  755. # - the agent's direction/orientation (acting as a compass)
  756. # - a textual mission string (instructions for the agent)
  757. obs = {
  758. 'image': image,
  759. 'direction': self.agentDir,
  760. 'mission': self.mission
  761. }
  762. return obs
  763. def getObsRender(self, obs):
  764. """
  765. Render an agent observation for visualization
  766. """
  767. if self.obsRender == None:
  768. self.obsRender = Renderer(
  769. AGENT_VIEW_SIZE * CELL_PIXELS // 2,
  770. AGENT_VIEW_SIZE * CELL_PIXELS // 2
  771. )
  772. r = self.obsRender
  773. r.beginFrame()
  774. grid = Grid.decode(obs)
  775. # Render the whole grid
  776. grid.render(r, CELL_PIXELS // 2)
  777. # Draw the agent
  778. r.push()
  779. r.scale(0.5, 0.5)
  780. r.translate(
  781. CELL_PIXELS * (0.5 + AGENT_VIEW_SIZE // 2),
  782. CELL_PIXELS * (AGENT_VIEW_SIZE - 0.5)
  783. )
  784. r.rotate(3 * 90)
  785. r.setLineColor(255, 0, 0)
  786. r.setColor(255, 0, 0)
  787. r.drawPolygon([
  788. (-12, 10),
  789. ( 12, 0),
  790. (-12, -10)
  791. ])
  792. r.pop()
  793. r.endFrame()
  794. return r.getPixmap()
  795. def render(self, mode='human', close=False):
  796. """
  797. Render the whole-grid human view
  798. """
  799. if close:
  800. if self.gridRender:
  801. self.gridRender.close()
  802. return
  803. if self.gridRender is None:
  804. self.gridRender = Renderer(
  805. self.gridSize * CELL_PIXELS,
  806. self.gridSize * CELL_PIXELS,
  807. True if mode == 'human' else False
  808. )
  809. r = self.gridRender
  810. r.beginFrame()
  811. # Render the whole grid
  812. self.grid.render(r, CELL_PIXELS)
  813. # Draw the agent
  814. r.push()
  815. r.translate(
  816. CELL_PIXELS * (self.agentPos[0] + 0.5),
  817. CELL_PIXELS * (self.agentPos[1] + 0.5)
  818. )
  819. r.rotate(self.agentDir * 90)
  820. r.setLineColor(255, 0, 0)
  821. r.setColor(255, 0, 0)
  822. r.drawPolygon([
  823. (-12, 10),
  824. ( 12, 0),
  825. (-12, -10)
  826. ])
  827. r.pop()
  828. # Highlight what the agent can see
  829. topX, topY, botX, botY = self.getViewExts()
  830. r.fillRect(
  831. topX * CELL_PIXELS,
  832. topY * CELL_PIXELS,
  833. AGENT_VIEW_SIZE * CELL_PIXELS,
  834. AGENT_VIEW_SIZE * CELL_PIXELS,
  835. 200, 200, 200, 75
  836. )
  837. r.endFrame()
  838. if mode == 'rgb_array':
  839. return r.getArray()
  840. elif mode == 'pixmap':
  841. return r.getPixmap()
  842. return r