minigrid.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959
  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 _genGrid(self, width, height):
  485. assert False, "_genGrid needs to be implemented by each environment"
  486. def reset(self):
  487. # Generate a new random grid at the start of each episode
  488. # To keep the same grid for each episode, call env.seed() with
  489. # the same seed before calling env.reset()
  490. self._genGrid(self.gridSize, self.gridSize)
  491. # Place the agent in the starting position and direction
  492. self.agentPos = self.startPos
  493. self.agentDir = self.startDir
  494. # Item picked up, being carried, initially nothing
  495. self.carrying = None
  496. # Step count since episode start
  497. self.stepCount = 0
  498. # Return first observation
  499. obs = self._genObs()
  500. return obs
  501. def seed(self, seed=1337):
  502. # Seed the random number generator
  503. self.np_random, _ = seeding.np_random(seed)
  504. return [seed]
  505. def _randInt(self, low, high):
  506. """
  507. Generate random integer in [low,high[
  508. """
  509. return self.np_random.randint(low, high)
  510. def _randElem(self, iterable):
  511. """
  512. Pick a random element in a list
  513. """
  514. lst = list(iterable)
  515. idx = self._randInt(0, len(lst))
  516. return lst[idx]
  517. def _randPos(self, xLow, xHigh, yLow, yHigh):
  518. """
  519. Generate a random (x,y) position tuple
  520. """
  521. return (
  522. self.np_random.randint(xLow, xHigh),
  523. self.np_random.randint(yLow, yHigh)
  524. )
  525. def placeObj(self, obj, top=None, size=None):
  526. """
  527. Place an object at an empty position in the grid
  528. :param top: top-left position of the rectangle where to place
  529. :param size: size of the rectangle where to place
  530. """
  531. if top is None:
  532. top = (0, 0)
  533. if size is None:
  534. size = (self.grid.width, self.grid.height)
  535. while True:
  536. pos = (
  537. self._randInt(top[0], top[0] + size[0]),
  538. self._randInt(top[1], top[1] + size[1])
  539. )
  540. if self.grid.get(*pos) != None:
  541. continue
  542. if pos == self.startPos:
  543. continue
  544. break
  545. self.grid.set(*pos, obj)
  546. return pos
  547. def placeAgent(self, randDir=True):
  548. """
  549. Set the agent's starting point at an empty position in the grid
  550. """
  551. pos = self.placeObj(None)
  552. self.startPos = pos
  553. if randDir:
  554. self.startDir = self._randInt(0, 4)
  555. return pos
  556. def getStepsRemaining(self):
  557. return self.maxSteps - self.stepCount
  558. def getDirVec(self):
  559. """
  560. Get the direction vector for the agent, pointing in the direction
  561. of forward movement.
  562. """
  563. # Pointing right
  564. if self.agentDir == 0:
  565. return (1, 0)
  566. # Down (positive Y)
  567. elif self.agentDir == 1:
  568. return (0, 1)
  569. # Pointing left
  570. elif self.agentDir == 2:
  571. return (-1, 0)
  572. # Up (negative Y)
  573. elif self.agentDir == 3:
  574. return (0, -1)
  575. else:
  576. assert False
  577. def getViewExts(self):
  578. """
  579. Get the extents of the square set of tiles visible to the agent
  580. Note: the bottom extent indices are not included in the set
  581. """
  582. # Facing right
  583. if self.agentDir == 0:
  584. topX = self.agentPos[0]
  585. topY = self.agentPos[1] - AGENT_VIEW_SIZE // 2
  586. # Facing down
  587. elif self.agentDir == 1:
  588. topX = self.agentPos[0] - AGENT_VIEW_SIZE // 2
  589. topY = self.agentPos[1]
  590. # Facing left
  591. elif self.agentDir == 2:
  592. topX = self.agentPos[0] - AGENT_VIEW_SIZE + 1
  593. topY = self.agentPos[1] - AGENT_VIEW_SIZE // 2
  594. # Facing up
  595. elif self.agentDir == 3:
  596. topX = self.agentPos[0] - AGENT_VIEW_SIZE // 2
  597. topY = self.agentPos[1] - AGENT_VIEW_SIZE + 1
  598. else:
  599. assert False, "invalid agent direction"
  600. botX = topX + AGENT_VIEW_SIZE
  601. botY = topY + AGENT_VIEW_SIZE
  602. return (topX, topY, botX, botY)
  603. def agentSees(self, x, y):
  604. """
  605. Check if a grid position is visible to the agent
  606. """
  607. topX, topY, botX, botY = self.getViewExts()
  608. return (x >= topX and x < botX and y >= topY and y < botY)
  609. def step(self, action):
  610. self.stepCount += 1
  611. reward = 0
  612. done = False
  613. # Get the position in front of the agent
  614. u, v = self.getDirVec()
  615. fwdPos = (self.agentPos[0] + u, self.agentPos[1] + v)
  616. # Get the contents of the cell in front of the agent
  617. fwdCell = self.grid.get(*fwdPos)
  618. # Rotate left
  619. if action == self.actions.left:
  620. self.agentDir -= 1
  621. if self.agentDir < 0:
  622. self.agentDir += 4
  623. # Rotate right
  624. elif action == self.actions.right:
  625. self.agentDir = (self.agentDir + 1) % 4
  626. # Move forward
  627. elif action == self.actions.forward:
  628. if fwdCell == None or fwdCell.canOverlap():
  629. self.agentPos = fwdPos
  630. if fwdCell != None and fwdCell.type == 'goal':
  631. done = True
  632. reward = 1000 - self.stepCount
  633. # Pick up an object
  634. elif action == self.actions.pickup:
  635. if fwdCell and fwdCell.canPickup():
  636. if self.carrying is None:
  637. self.carrying = fwdCell
  638. self.grid.set(*fwdPos, None)
  639. # Drop an object
  640. elif action == self.actions.drop:
  641. if not fwdCell and self.carrying:
  642. self.grid.set(*fwdPos, self.carrying)
  643. self.carrying = None
  644. # Toggle/activate an object
  645. elif action == self.actions.toggle:
  646. if fwdCell:
  647. fwdCell.toggle(self, fwdPos)
  648. # Wait/do nothing
  649. elif action == self.actions.wait:
  650. pass
  651. else:
  652. assert False, "unknown action"
  653. if self.stepCount >= self.maxSteps:
  654. done = True
  655. obs = self._genObs()
  656. return obs, reward, done, {}
  657. def _genObs(self):
  658. """
  659. Generate the agent's view (partially observable, low-resolution encoding)
  660. """
  661. topX, topY, botX, botY = self.getViewExts()
  662. grid = self.grid.slice(topX, topY, AGENT_VIEW_SIZE, AGENT_VIEW_SIZE)
  663. for i in range(self.agentDir + 1):
  664. grid = grid.rotateLeft()
  665. # Make it so the agent sees what it's carrying
  666. # We do this by placing the carried object at the agent's position
  667. # in the agent's partially observable view
  668. agentPos = grid.width // 2, grid.height - 1
  669. if self.carrying:
  670. grid.set(*agentPos, self.carrying)
  671. else:
  672. grid.set(*agentPos, None)
  673. # Encode the partially observable view into a numpy array
  674. image = grid.encode()
  675. assert hasattr(self, 'mission'), "environments must define a textual mission string"
  676. # Observations are dictionaries containing:
  677. # - an image (partially observable view of the environment)
  678. # - the agent's direction/orientation (acting as a compass)
  679. # - a textual mission string (instructions for the agent)
  680. obs = {
  681. 'image': image,
  682. 'direction': self.agentDir,
  683. 'mission': self.mission
  684. }
  685. return obs
  686. def getObsRender(self, obs):
  687. """
  688. Render an agent observation for visualization
  689. """
  690. if self.obsRender == None:
  691. self.obsRender = Renderer(
  692. AGENT_VIEW_SIZE * CELL_PIXELS // 2,
  693. AGENT_VIEW_SIZE * CELL_PIXELS // 2
  694. )
  695. r = self.obsRender
  696. r.beginFrame()
  697. grid = Grid.decode(obs)
  698. # Render the whole grid
  699. grid.render(r, CELL_PIXELS // 2)
  700. # Draw the agent
  701. r.push()
  702. r.scale(0.5, 0.5)
  703. r.translate(
  704. CELL_PIXELS * (0.5 + AGENT_VIEW_SIZE // 2),
  705. CELL_PIXELS * (AGENT_VIEW_SIZE - 0.5)
  706. )
  707. r.rotate(3 * 90)
  708. r.setLineColor(255, 0, 0)
  709. r.setColor(255, 0, 0)
  710. r.drawPolygon([
  711. (-12, 10),
  712. ( 12, 0),
  713. (-12, -10)
  714. ])
  715. r.pop()
  716. r.endFrame()
  717. return r.getPixmap()
  718. def render(self, mode='human', close=False):
  719. """
  720. Render the whole-grid human view
  721. """
  722. if close:
  723. if self.gridRender:
  724. self.gridRender.close()
  725. return
  726. if self.gridRender is None:
  727. self.gridRender = Renderer(
  728. self.gridSize * CELL_PIXELS,
  729. self.gridSize * CELL_PIXELS,
  730. True if mode == 'human' else False
  731. )
  732. r = self.gridRender
  733. r.beginFrame()
  734. # Render the whole grid
  735. self.grid.render(r, CELL_PIXELS)
  736. # Draw the agent
  737. r.push()
  738. r.translate(
  739. CELL_PIXELS * (self.agentPos[0] + 0.5),
  740. CELL_PIXELS * (self.agentPos[1] + 0.5)
  741. )
  742. r.rotate(self.agentDir * 90)
  743. r.setLineColor(255, 0, 0)
  744. r.setColor(255, 0, 0)
  745. r.drawPolygon([
  746. (-12, 10),
  747. ( 12, 0),
  748. (-12, -10)
  749. ])
  750. r.pop()
  751. # Highlight what the agent can see
  752. topX, topY, botX, botY = self.getViewExts()
  753. r.fillRect(
  754. topX * CELL_PIXELS,
  755. topY * CELL_PIXELS,
  756. AGENT_VIEW_SIZE * CELL_PIXELS,
  757. AGENT_VIEW_SIZE * CELL_PIXELS,
  758. 200, 200, 200, 75
  759. )
  760. r.endFrame()
  761. if mode == 'rgb_array':
  762. return r.getArray()
  763. elif mode == 'pixmap':
  764. return r.getPixmap()
  765. return r