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 copy(self):
  276. from copy import deepcopy
  277. return deepcopy(self)
  278. def set(self, i, j, v):
  279. assert i >= 0 and i < self.width
  280. assert j >= 0 and j < self.height
  281. self.grid[j * self.width + i] = v
  282. def get(self, i, j):
  283. assert i >= 0 and i < self.width
  284. assert j >= 0 and j < self.height
  285. return self.grid[j * self.width + i]
  286. def horzWall(self, x, y, length=None):
  287. if length is None:
  288. length = self.width - x
  289. for i in range(0, length):
  290. self.set(x + i, y, Wall())
  291. def vertWall(self, x, y, length=None):
  292. if length is None:
  293. length = self.height - y
  294. for j in range(0, length):
  295. self.set(x, y + j, Wall())
  296. def wallRect(self, x, y, w, h):
  297. self.horzWall(x, y, w)
  298. self.horzWall(x, y+h-1, w)
  299. self.vertWall(x, y, h)
  300. self.vertWall(x+w-1, y, h)
  301. def rotateLeft(self):
  302. """
  303. Rotate the grid to the left (counter-clockwise)
  304. """
  305. grid = Grid(self.width, self.height)
  306. for j in range(0, self.height):
  307. for i in range(0, self.width):
  308. v = self.get(self.width - 1 - j, i)
  309. grid.set(i, j, v)
  310. return grid
  311. def slice(self, topX, topY, width, height):
  312. """
  313. Get a subset of the grid
  314. """
  315. grid = Grid(width, height)
  316. for j in range(0, height):
  317. for i in range(0, width):
  318. x = topX + i
  319. y = topY + j
  320. if x >= 0 and x < self.width and \
  321. y >= 0 and y < self.height:
  322. v = self.get(x, y)
  323. else:
  324. v = Wall()
  325. grid.set(i, j, v)
  326. return grid
  327. def render(self, r, tileSize):
  328. """
  329. Render this grid at a given scale
  330. :param r: target renderer object
  331. :param tileSize: tile size in pixels
  332. """
  333. assert r.width == self.width * tileSize
  334. assert r.height == self.height * tileSize
  335. # Total grid size at native scale
  336. widthPx = self.width * CELL_PIXELS
  337. heightPx = self.height * CELL_PIXELS
  338. # Draw background (out-of-world) tiles the same colors as walls
  339. # so the agent understands these areas are not reachable
  340. c = COLORS['grey']
  341. r.setLineColor(c[0], c[1], c[2])
  342. r.setColor(c[0], c[1], c[2])
  343. r.drawPolygon([
  344. (0 , heightPx),
  345. (widthPx, heightPx),
  346. (widthPx, 0),
  347. (0 , 0)
  348. ])
  349. r.push()
  350. # Internally, we draw at the "large" full-grid resolution, but we
  351. # use the renderer to scale back to the desired size
  352. r.scale(tileSize / CELL_PIXELS, tileSize / CELL_PIXELS)
  353. # Draw the background of the in-world cells black
  354. r.fillRect(
  355. 0,
  356. 0,
  357. widthPx,
  358. heightPx,
  359. 0, 0, 0
  360. )
  361. # Draw grid lines
  362. r.setLineColor(100, 100, 100)
  363. for rowIdx in range(0, self.height):
  364. y = CELL_PIXELS * rowIdx
  365. r.drawLine(0, y, widthPx, y)
  366. for colIdx in range(0, self.width):
  367. x = CELL_PIXELS * colIdx
  368. r.drawLine(x, 0, x, heightPx)
  369. # Render the grid
  370. for j in range(0, self.height):
  371. for i in range(0, self.width):
  372. cell = self.get(i, j)
  373. if cell == None:
  374. continue
  375. r.push()
  376. r.translate(i * CELL_PIXELS, j * CELL_PIXELS)
  377. cell.render(r)
  378. r.pop()
  379. r.pop()
  380. def encode(self):
  381. """
  382. Produce a compact numpy encoding of the grid
  383. """
  384. codeSize = self.width * self.height * 3
  385. array = np.zeros(shape=(self.width, self.height, 3), dtype='uint8')
  386. for j in range(0, self.height):
  387. for i in range(0, self.width):
  388. v = self.get(i, j)
  389. if v == None:
  390. continue
  391. array[i, j, 0] = OBJECT_TO_IDX[v.type]
  392. array[i, j, 1] = COLOR_TO_IDX[v.color]
  393. if hasattr(v, 'isOpen') and v.isOpen:
  394. array[i, j, 2] = 1
  395. return array
  396. def decode(array):
  397. """
  398. Decode an array grid encoding back into a grid
  399. """
  400. width = array.shape[0]
  401. height = array.shape[1]
  402. assert array.shape[2] == 3
  403. grid = Grid(width, height)
  404. for j in range(0, height):
  405. for i in range(0, width):
  406. typeIdx = array[i, j, 0]
  407. colorIdx = array[i, j, 1]
  408. openIdx = array[i, j, 2]
  409. if typeIdx == 0:
  410. continue
  411. objType = IDX_TO_OBJECT[typeIdx]
  412. color = IDX_TO_COLOR[colorIdx]
  413. isOpen = True if openIdx == 1 else 0
  414. if objType == 'wall':
  415. v = Wall(color)
  416. elif objType == 'ball':
  417. v = Ball(color)
  418. elif objType == 'key':
  419. v = Key(color)
  420. elif objType == 'box':
  421. v = Box(color)
  422. elif objType == 'door':
  423. v = Door(color, isOpen)
  424. elif objType == 'locked_door':
  425. v = LockedDoor(color, isOpen)
  426. elif objType == 'goal':
  427. v = Goal()
  428. else:
  429. assert False, "unknown obj type in decode '%s'" % objType
  430. grid.set(i, j, v)
  431. return grid
  432. class MiniGridEnv(gym.Env):
  433. """
  434. 2D grid world game environment
  435. """
  436. metadata = {
  437. 'render.modes': ['human', 'rgb_array', 'pixmap'],
  438. 'video.frames_per_second' : 10
  439. }
  440. # Enumeration of possible actions
  441. class Actions(IntEnum):
  442. # Turn left, turn right, move forward
  443. left = 0
  444. right = 1
  445. forward = 2
  446. # Pick up an object
  447. pickup = 3
  448. # Drop an object
  449. drop = 4
  450. # Toggle/activate an object
  451. toggle = 5
  452. # Wait/stay put/do nothing
  453. wait = 6
  454. def __init__(self, gridSize=16, maxSteps=100):
  455. # Action enumeration for this environment
  456. self.actions = MiniGridEnv.Actions
  457. # Actions are discrete integer values
  458. self.action_space = spaces.Discrete(len(self.actions))
  459. # Observations are dictionaries containing an
  460. # encoding of the grid and a textual 'mission' string
  461. self.observation_space = spaces.Box(
  462. low=0,
  463. high=255,
  464. shape=OBS_ARRAY_SIZE,
  465. dtype='uint8'
  466. )
  467. self.observation_space = spaces.Dict({
  468. 'image': self.observation_space
  469. })
  470. # Range of possible rewards
  471. self.reward_range = (-1, 1000)
  472. # Renderer object used to render the whole grid (full-scale)
  473. self.gridRender = None
  474. # Renderer used to render observations (small-scale agent view)
  475. self.obsRender = None
  476. # Environment configuration
  477. self.gridSize = gridSize
  478. self.maxSteps = maxSteps
  479. self.startPos = (1, 1)
  480. self.startDir = 0
  481. # Initialize the state
  482. self.seed()
  483. self.reset()
  484. def __str__(self):
  485. """
  486. Produce a pretty string of the environment's grid along with the agent.
  487. The agent is represented by `⏩`. A grid pixel is represented by 2-character
  488. string, the first one for the object and the second one for the color.
  489. """
  490. from copy import deepcopy
  491. def rotate_left(array):
  492. new_array = deepcopy(array)
  493. for i in range(len(array)):
  494. for j in range(len(array[0])):
  495. new_array[j][len(array[0])-1-i] = array[i][j]
  496. return new_array
  497. def vertically_symmetrize(array):
  498. new_array = deepcopy(array)
  499. for i in range(len(array)):
  500. for j in range(len(array[0])):
  501. new_array[i][len(array[0])-1-j] = array[i][j]
  502. return new_array
  503. # Map of object id to short string
  504. OBJECT_IDX_TO_IDS = {
  505. 0: ' ',
  506. 1: 'W',
  507. 2: 'D',
  508. 3: 'L',
  509. 4: 'K',
  510. 5: 'B',
  511. 6: 'X',
  512. 7: 'G'
  513. }
  514. # Short string for opened door
  515. OPENDED_DOOR_IDS = '_'
  516. # Map of color id to short string
  517. COLOR_IDX_TO_IDS = {
  518. 0: 'R',
  519. 1: 'G',
  520. 2: 'B',
  521. 3: 'P',
  522. 4: 'Y',
  523. 5: 'E'
  524. }
  525. # Map agent's direction to short string
  526. AGENT_DIR_TO_IDS = {
  527. 0: '⏩',
  528. 1: '⏬',
  529. 2: '⏪',
  530. 3: '⏫'
  531. }
  532. array = self.grid.encode()
  533. array = rotate_left(array)
  534. array = vertically_symmetrize(array)
  535. new_array = []
  536. for line in array:
  537. new_line = []
  538. for pixel in line:
  539. # If the door is opened
  540. if pixel[0] in [2, 3] and pixel[2] == 1:
  541. object_ids = OPENDED_DOOR_IDS
  542. else:
  543. object_ids = OBJECT_IDX_TO_IDS[pixel[0]]
  544. # If no object
  545. if pixel[0] == 0:
  546. color_ids = ' '
  547. else:
  548. color_ids = COLOR_IDX_TO_IDS[pixel[1]]
  549. new_line.append(object_ids + color_ids)
  550. new_array.append(new_line)
  551. # Add the agent
  552. new_array[self.agentPos[1]][self.agentPos[0]] = AGENT_DIR_TO_IDS[self.agentDir]
  553. return "\n".join([" ".join(line) for line in new_array])
  554. def _genGrid(self, width, height):
  555. assert False, "_genGrid needs to be implemented by each environment"
  556. def reset(self):
  557. # Generate a new random grid at the start of each episode
  558. # To keep the same grid for each episode, call env.seed() with
  559. # the same seed before calling env.reset()
  560. self._genGrid(self.gridSize, self.gridSize)
  561. # Place the agent in the starting position and direction
  562. self.agentPos = self.startPos
  563. self.agentDir = self.startDir
  564. # Item picked up, being carried, initially nothing
  565. self.carrying = None
  566. # Step count since episode start
  567. self.stepCount = 0
  568. # Return first observation
  569. obs = self._genObs()
  570. return obs
  571. def seed(self, seed=1337):
  572. # Seed the random number generator
  573. self.np_random, _ = seeding.np_random(seed)
  574. return [seed]
  575. def _randInt(self, low, high):
  576. """
  577. Generate random integer in [low,high[
  578. """
  579. return self.np_random.randint(low, high)
  580. def _randElem(self, iterable):
  581. """
  582. Pick a random element in a list
  583. """
  584. lst = list(iterable)
  585. idx = self._randInt(0, len(lst))
  586. return lst[idx]
  587. def _randPos(self, xLow, xHigh, yLow, yHigh):
  588. """
  589. Generate a random (x,y) position tuple
  590. """
  591. return (
  592. self.np_random.randint(xLow, xHigh),
  593. self.np_random.randint(yLow, yHigh)
  594. )
  595. def placeObj(self, obj, top=None, size=None, reject_fn=None):
  596. """
  597. Place an object at an empty position in the grid
  598. :param top: top-left position of the rectangle where to place
  599. :param size: size of the rectangle where to place
  600. :param reject_fn: function to filter out potential positions
  601. """
  602. if top is None:
  603. top = (0, 0)
  604. if size is None:
  605. size = (self.grid.width, self.grid.height)
  606. while True:
  607. pos = (
  608. self._randInt(top[0], top[0] + size[0]),
  609. self._randInt(top[1], top[1] + size[1])
  610. )
  611. # Don't place the object on top of another object
  612. if self.grid.get(*pos) != None:
  613. continue
  614. # Don't place the object where the agent is
  615. if pos == self.startPos:
  616. continue
  617. # Check if there is a filtering criterion
  618. if reject_fn and reject_fn(self, pos):
  619. continue
  620. break
  621. self.grid.set(*pos, obj)
  622. return pos
  623. def placeAgent(self, randDir=True):
  624. """
  625. Set the agent's starting point at an empty position in the grid
  626. """
  627. pos = self.placeObj(None)
  628. self.startPos = pos
  629. if randDir:
  630. self.startDir = self._randInt(0, 4)
  631. return pos
  632. def getStepsRemaining(self):
  633. return self.maxSteps - self.stepCount
  634. def getDirVec(self):
  635. """
  636. Get the direction vector for the agent, pointing in the direction
  637. of forward movement.
  638. """
  639. # Pointing right
  640. if self.agentDir == 0:
  641. return (1, 0)
  642. # Down (positive Y)
  643. elif self.agentDir == 1:
  644. return (0, 1)
  645. # Pointing left
  646. elif self.agentDir == 2:
  647. return (-1, 0)
  648. # Up (negative Y)
  649. elif self.agentDir == 3:
  650. return (0, -1)
  651. else:
  652. assert False
  653. def getViewExts(self):
  654. """
  655. Get the extents of the square set of tiles visible to the agent
  656. Note: the bottom extent indices are not included in the set
  657. """
  658. # Facing right
  659. if self.agentDir == 0:
  660. topX = self.agentPos[0]
  661. topY = self.agentPos[1] - AGENT_VIEW_SIZE // 2
  662. # Facing down
  663. elif self.agentDir == 1:
  664. topX = self.agentPos[0] - AGENT_VIEW_SIZE // 2
  665. topY = self.agentPos[1]
  666. # Facing left
  667. elif self.agentDir == 2:
  668. topX = self.agentPos[0] - AGENT_VIEW_SIZE + 1
  669. topY = self.agentPos[1] - AGENT_VIEW_SIZE // 2
  670. # Facing up
  671. elif self.agentDir == 3:
  672. topX = self.agentPos[0] - AGENT_VIEW_SIZE // 2
  673. topY = self.agentPos[1] - AGENT_VIEW_SIZE + 1
  674. else:
  675. assert False, "invalid agent direction"
  676. botX = topX + AGENT_VIEW_SIZE
  677. botY = topY + AGENT_VIEW_SIZE
  678. return (topX, topY, botX, botY)
  679. def agentSees(self, x, y):
  680. """
  681. Check if a grid position is visible to the agent
  682. """
  683. topX, topY, botX, botY = self.getViewExts()
  684. return (x >= topX and x < botX and y >= topY and y < botY)
  685. def step(self, action):
  686. self.stepCount += 1
  687. reward = 0
  688. done = False
  689. # Get the position in front of the agent
  690. u, v = self.getDirVec()
  691. fwdPos = (self.agentPos[0] + u, self.agentPos[1] + v)
  692. # Get the contents of the cell in front of the agent
  693. fwdCell = self.grid.get(*fwdPos)
  694. # Rotate left
  695. if action == self.actions.left:
  696. self.agentDir -= 1
  697. if self.agentDir < 0:
  698. self.agentDir += 4
  699. # Rotate right
  700. elif action == self.actions.right:
  701. self.agentDir = (self.agentDir + 1) % 4
  702. # Move forward
  703. elif action == self.actions.forward:
  704. if fwdCell == None or fwdCell.canOverlap():
  705. self.agentPos = fwdPos
  706. if fwdCell != None and fwdCell.type == 'goal':
  707. done = True
  708. reward = 1000 - self.stepCount
  709. # Pick up an object
  710. elif action == self.actions.pickup:
  711. if fwdCell and fwdCell.canPickup():
  712. if self.carrying is None:
  713. self.carrying = fwdCell
  714. self.grid.set(*fwdPos, None)
  715. # Drop an object
  716. elif action == self.actions.drop:
  717. if not fwdCell and self.carrying:
  718. self.grid.set(*fwdPos, self.carrying)
  719. self.carrying = None
  720. # Toggle/activate an object
  721. elif action == self.actions.toggle:
  722. if fwdCell:
  723. fwdCell.toggle(self, fwdPos)
  724. # Wait/do nothing
  725. elif action == self.actions.wait:
  726. pass
  727. else:
  728. assert False, "unknown action"
  729. if self.stepCount >= self.maxSteps:
  730. done = True
  731. obs = self._genObs()
  732. return obs, reward, done, {}
  733. def _genObs(self):
  734. """
  735. Generate the agent's view (partially observable, low-resolution encoding)
  736. """
  737. topX, topY, botX, botY = self.getViewExts()
  738. grid = self.grid.slice(topX, topY, AGENT_VIEW_SIZE, AGENT_VIEW_SIZE)
  739. for i in range(self.agentDir + 1):
  740. grid = grid.rotateLeft()
  741. # Make it so the agent sees what it's carrying
  742. # We do this by placing the carried object at the agent's position
  743. # in the agent's partially observable view
  744. agentPos = grid.width // 2, grid.height - 1
  745. if self.carrying:
  746. grid.set(*agentPos, self.carrying)
  747. else:
  748. grid.set(*agentPos, None)
  749. # Encode the partially observable view into a numpy array
  750. image = grid.encode()
  751. assert hasattr(self, 'mission'), "environments must define a textual mission string"
  752. # Observations are dictionaries containing:
  753. # - an image (partially observable view of the environment)
  754. # - the agent's direction/orientation (acting as a compass)
  755. # - a textual mission string (instructions for the agent)
  756. obs = {
  757. 'image': image,
  758. 'direction': self.agentDir,
  759. 'mission': self.mission
  760. }
  761. return obs
  762. def getObsRender(self, obs):
  763. """
  764. Render an agent observation for visualization
  765. """
  766. if self.obsRender == None:
  767. self.obsRender = Renderer(
  768. AGENT_VIEW_SIZE * CELL_PIXELS // 2,
  769. AGENT_VIEW_SIZE * CELL_PIXELS // 2
  770. )
  771. r = self.obsRender
  772. r.beginFrame()
  773. grid = Grid.decode(obs)
  774. # Render the whole grid
  775. grid.render(r, CELL_PIXELS // 2)
  776. # Draw the agent
  777. r.push()
  778. r.scale(0.5, 0.5)
  779. r.translate(
  780. CELL_PIXELS * (0.5 + AGENT_VIEW_SIZE // 2),
  781. CELL_PIXELS * (AGENT_VIEW_SIZE - 0.5)
  782. )
  783. r.rotate(3 * 90)
  784. r.setLineColor(255, 0, 0)
  785. r.setColor(255, 0, 0)
  786. r.drawPolygon([
  787. (-12, 10),
  788. ( 12, 0),
  789. (-12, -10)
  790. ])
  791. r.pop()
  792. r.endFrame()
  793. return r.getPixmap()
  794. def render(self, mode='human', close=False):
  795. """
  796. Render the whole-grid human view
  797. """
  798. if close:
  799. if self.gridRender:
  800. self.gridRender.close()
  801. return
  802. if self.gridRender is None:
  803. self.gridRender = Renderer(
  804. self.gridSize * CELL_PIXELS,
  805. self.gridSize * CELL_PIXELS,
  806. True if mode == 'human' else False
  807. )
  808. r = self.gridRender
  809. r.beginFrame()
  810. # Render the whole grid
  811. self.grid.render(r, CELL_PIXELS)
  812. # Draw the agent
  813. r.push()
  814. r.translate(
  815. CELL_PIXELS * (self.agentPos[0] + 0.5),
  816. CELL_PIXELS * (self.agentPos[1] + 0.5)
  817. )
  818. r.rotate(self.agentDir * 90)
  819. r.setLineColor(255, 0, 0)
  820. r.setColor(255, 0, 0)
  821. r.drawPolygon([
  822. (-12, 10),
  823. ( 12, 0),
  824. (-12, -10)
  825. ])
  826. r.pop()
  827. # Highlight what the agent can see
  828. topX, topY, botX, botY = self.getViewExts()
  829. r.fillRect(
  830. topX * CELL_PIXELS,
  831. topY * CELL_PIXELS,
  832. AGENT_VIEW_SIZE * CELL_PIXELS,
  833. AGENT_VIEW_SIZE * CELL_PIXELS,
  834. 200, 200, 200, 75
  835. )
  836. r.endFrame()
  837. if mode == 'rgb_array':
  838. return r.getArray()
  839. elif mode == 'pixmap':
  840. return r.getPixmap()
  841. return r