minigrid.py 25 KB

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