minigrid.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047
  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):
  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. """
  601. if top is None:
  602. top = (0, 0)
  603. if size is None:
  604. size = (self.grid.width, self.grid.height)
  605. while True:
  606. pos = (
  607. self._randInt(top[0], top[0] + size[0]),
  608. self._randInt(top[1], top[1] + size[1])
  609. )
  610. if self.grid.get(*pos) != None:
  611. continue
  612. if pos == self.startPos:
  613. continue
  614. break
  615. self.grid.set(*pos, obj)
  616. return pos
  617. def placeAgent(self, randDir=True):
  618. """
  619. Set the agent's starting point at an empty position in the grid
  620. """
  621. pos = self.placeObj(None)
  622. self.startPos = pos
  623. if randDir:
  624. self.startDir = self._randInt(0, 4)
  625. return pos
  626. def getStepsRemaining(self):
  627. return self.maxSteps - self.stepCount
  628. def getDirVec(self):
  629. """
  630. Get the direction vector for the agent, pointing in the direction
  631. of forward movement.
  632. """
  633. # Pointing right
  634. if self.agentDir == 0:
  635. return (1, 0)
  636. # Down (positive Y)
  637. elif self.agentDir == 1:
  638. return (0, 1)
  639. # Pointing left
  640. elif self.agentDir == 2:
  641. return (-1, 0)
  642. # Up (negative Y)
  643. elif self.agentDir == 3:
  644. return (0, -1)
  645. else:
  646. assert False
  647. def getViewExts(self):
  648. """
  649. Get the extents of the square set of tiles visible to the agent
  650. Note: the bottom extent indices are not included in the set
  651. """
  652. # Facing right
  653. if self.agentDir == 0:
  654. topX = self.agentPos[0]
  655. topY = self.agentPos[1] - AGENT_VIEW_SIZE // 2
  656. # Facing down
  657. elif self.agentDir == 1:
  658. topX = self.agentPos[0] - AGENT_VIEW_SIZE // 2
  659. topY = self.agentPos[1]
  660. # Facing left
  661. elif self.agentDir == 2:
  662. topX = self.agentPos[0] - AGENT_VIEW_SIZE + 1
  663. topY = self.agentPos[1] - AGENT_VIEW_SIZE // 2
  664. # Facing up
  665. elif self.agentDir == 3:
  666. topX = self.agentPos[0] - AGENT_VIEW_SIZE // 2
  667. topY = self.agentPos[1] - AGENT_VIEW_SIZE + 1
  668. else:
  669. assert False, "invalid agent direction"
  670. botX = topX + AGENT_VIEW_SIZE
  671. botY = topY + AGENT_VIEW_SIZE
  672. return (topX, topY, botX, botY)
  673. def agentSees(self, x, y):
  674. """
  675. Check if a grid position is visible to the agent
  676. """
  677. topX, topY, botX, botY = self.getViewExts()
  678. return (x >= topX and x < botX and y >= topY and y < botY)
  679. def step(self, action):
  680. self.stepCount += 1
  681. reward = 0
  682. done = False
  683. # Get the position in front of the agent
  684. u, v = self.getDirVec()
  685. fwdPos = (self.agentPos[0] + u, self.agentPos[1] + v)
  686. # Get the contents of the cell in front of the agent
  687. fwdCell = self.grid.get(*fwdPos)
  688. # Rotate left
  689. if action == self.actions.left:
  690. self.agentDir -= 1
  691. if self.agentDir < 0:
  692. self.agentDir += 4
  693. # Rotate right
  694. elif action == self.actions.right:
  695. self.agentDir = (self.agentDir + 1) % 4
  696. # Move forward
  697. elif action == self.actions.forward:
  698. if fwdCell == None or fwdCell.canOverlap():
  699. self.agentPos = fwdPos
  700. if fwdCell != None and fwdCell.type == 'goal':
  701. done = True
  702. reward = 1000 - self.stepCount
  703. # Pick up an object
  704. elif action == self.actions.pickup:
  705. if fwdCell and fwdCell.canPickup():
  706. if self.carrying is None:
  707. self.carrying = fwdCell
  708. self.grid.set(*fwdPos, None)
  709. # Drop an object
  710. elif action == self.actions.drop:
  711. if not fwdCell and self.carrying:
  712. self.grid.set(*fwdPos, self.carrying)
  713. self.carrying = None
  714. # Toggle/activate an object
  715. elif action == self.actions.toggle:
  716. if fwdCell:
  717. fwdCell.toggle(self, fwdPos)
  718. # Wait/do nothing
  719. elif action == self.actions.wait:
  720. pass
  721. else:
  722. assert False, "unknown action"
  723. if self.stepCount >= self.maxSteps:
  724. done = True
  725. obs = self._genObs()
  726. return obs, reward, done, {}
  727. def _genObs(self):
  728. """
  729. Generate the agent's view (partially observable, low-resolution encoding)
  730. """
  731. topX, topY, botX, botY = self.getViewExts()
  732. grid = self.grid.slice(topX, topY, AGENT_VIEW_SIZE, AGENT_VIEW_SIZE)
  733. for i in range(self.agentDir + 1):
  734. grid = grid.rotateLeft()
  735. # Make it so the agent sees what it's carrying
  736. # We do this by placing the carried object at the agent's position
  737. # in the agent's partially observable view
  738. agentPos = grid.width // 2, grid.height - 1
  739. if self.carrying:
  740. grid.set(*agentPos, self.carrying)
  741. else:
  742. grid.set(*agentPos, None)
  743. # Encode the partially observable view into a numpy array
  744. image = grid.encode()
  745. assert hasattr(self, 'mission'), "environments must define a textual mission string"
  746. # Observations are dictionaries containing:
  747. # - an image (partially observable view of the environment)
  748. # - the agent's direction/orientation (acting as a compass)
  749. # - a textual mission string (instructions for the agent)
  750. obs = {
  751. 'image': image,
  752. 'direction': self.agentDir,
  753. 'mission': self.mission
  754. }
  755. return obs
  756. def getObsRender(self, obs):
  757. """
  758. Render an agent observation for visualization
  759. """
  760. if self.obsRender == None:
  761. self.obsRender = Renderer(
  762. AGENT_VIEW_SIZE * CELL_PIXELS // 2,
  763. AGENT_VIEW_SIZE * CELL_PIXELS // 2
  764. )
  765. r = self.obsRender
  766. r.beginFrame()
  767. grid = Grid.decode(obs)
  768. # Render the whole grid
  769. grid.render(r, CELL_PIXELS // 2)
  770. # Draw the agent
  771. r.push()
  772. r.scale(0.5, 0.5)
  773. r.translate(
  774. CELL_PIXELS * (0.5 + AGENT_VIEW_SIZE // 2),
  775. CELL_PIXELS * (AGENT_VIEW_SIZE - 0.5)
  776. )
  777. r.rotate(3 * 90)
  778. r.setLineColor(255, 0, 0)
  779. r.setColor(255, 0, 0)
  780. r.drawPolygon([
  781. (-12, 10),
  782. ( 12, 0),
  783. (-12, -10)
  784. ])
  785. r.pop()
  786. r.endFrame()
  787. return r.getPixmap()
  788. def render(self, mode='human', close=False):
  789. """
  790. Render the whole-grid human view
  791. """
  792. if close:
  793. if self.gridRender:
  794. self.gridRender.close()
  795. return
  796. if self.gridRender is None:
  797. self.gridRender = Renderer(
  798. self.gridSize * CELL_PIXELS,
  799. self.gridSize * CELL_PIXELS,
  800. True if mode == 'human' else False
  801. )
  802. r = self.gridRender
  803. r.beginFrame()
  804. # Render the whole grid
  805. self.grid.render(r, CELL_PIXELS)
  806. # Draw the agent
  807. r.push()
  808. r.translate(
  809. CELL_PIXELS * (self.agentPos[0] + 0.5),
  810. CELL_PIXELS * (self.agentPos[1] + 0.5)
  811. )
  812. r.rotate(self.agentDir * 90)
  813. r.setLineColor(255, 0, 0)
  814. r.setColor(255, 0, 0)
  815. r.drawPolygon([
  816. (-12, 10),
  817. ( 12, 0),
  818. (-12, -10)
  819. ])
  820. r.pop()
  821. # Highlight what the agent can see
  822. topX, topY, botX, botY = self.getViewExts()
  823. r.fillRect(
  824. topX * CELL_PIXELS,
  825. topY * CELL_PIXELS,
  826. AGENT_VIEW_SIZE * CELL_PIXELS,
  827. AGENT_VIEW_SIZE * CELL_PIXELS,
  828. 200, 200, 200, 75
  829. )
  830. r.endFrame()
  831. if mode == 'rgb_array':
  832. return r.getArray()
  833. elif mode == 'pixmap':
  834. return r.getPixmap()
  835. return r