minigrid.py 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503
  1. import hashlib
  2. import math
  3. from abc import abstractmethod
  4. from enum import IntEnum
  5. from typing import Any, Callable, Optional, Union
  6. import gym
  7. import numpy as np
  8. from gym import spaces
  9. from gym.utils import seeding
  10. # Size in pixels of a tile in the full-scale human view
  11. from gym_minigrid.rendering import (
  12. downsample,
  13. fill_coords,
  14. highlight_img,
  15. point_in_circle,
  16. point_in_line,
  17. point_in_rect,
  18. point_in_triangle,
  19. rotate_fn,
  20. )
  21. from gym_minigrid.window import Window
  22. TILE_PIXELS = 32
  23. # Map of color names to RGB values
  24. COLORS = {
  25. "red": np.array([255, 0, 0]),
  26. "green": np.array([0, 255, 0]),
  27. "blue": np.array([0, 0, 255]),
  28. "purple": np.array([112, 39, 195]),
  29. "yellow": np.array([255, 255, 0]),
  30. "grey": np.array([100, 100, 100]),
  31. }
  32. COLOR_NAMES = sorted(list(COLORS.keys()))
  33. # Used to map colors to integers
  34. COLOR_TO_IDX = {"red": 0, "green": 1, "blue": 2, "purple": 3, "yellow": 4, "grey": 5}
  35. IDX_TO_COLOR = dict(zip(COLOR_TO_IDX.values(), COLOR_TO_IDX.keys()))
  36. # Map of object type to integers
  37. OBJECT_TO_IDX = {
  38. "unseen": 0,
  39. "empty": 1,
  40. "wall": 2,
  41. "floor": 3,
  42. "door": 4,
  43. "key": 5,
  44. "ball": 6,
  45. "box": 7,
  46. "goal": 8,
  47. "lava": 9,
  48. "agent": 10,
  49. }
  50. IDX_TO_OBJECT = dict(zip(OBJECT_TO_IDX.values(), OBJECT_TO_IDX.keys()))
  51. # Map of state names to integers
  52. STATE_TO_IDX = {
  53. "open": 0,
  54. "closed": 1,
  55. "locked": 2,
  56. }
  57. # Map of agent direction indices to vectors
  58. DIR_TO_VEC = [
  59. # Pointing right (positive X)
  60. np.array((1, 0)),
  61. # Down (positive Y)
  62. np.array((0, 1)),
  63. # Pointing left (negative X)
  64. np.array((-1, 0)),
  65. # Up (negative Y)
  66. np.array((0, -1)),
  67. ]
  68. def check_if_no_duplicate(duplicate_list: list) -> bool:
  69. """Check if given list contains any duplicates"""
  70. return len(set(duplicate_list)) == len(duplicate_list)
  71. class MissionSpace(spaces.Space[str]):
  72. r"""A space representing a mission for the Gym-Minigrid environments.
  73. The space allows generating random mission strings constructed with an input placeholder list.
  74. Example Usage::
  75. >>> observation_space = MissionSpace(mission_func=lambda color: f"Get the {color} ball.",
  76. ordered_placeholders=[["green", "blue"]])
  77. >>> observation_space.sample()
  78. "Get the green ball."
  79. >>> observation_space = MissionSpace(mission_func=lambda : "Get the ball.".,
  80. ordered_placeholders=None)
  81. >>> observation_space.sample()
  82. "Get the ball."
  83. """
  84. def __init__(
  85. self,
  86. mission_func: Callable[..., str],
  87. ordered_placeholders: Optional["list[list[str]]"] = None,
  88. seed: Optional[Union[int, seeding.RandomNumberGenerator]] = None,
  89. ):
  90. r"""Constructor of :class:`MissionSpace` space.
  91. Args:
  92. mission_func (lambda _placeholders(str): _mission(str)): Function that generates a mission string from random placeholders.
  93. ordered_placeholders (Optional["list[list[str]]"]): List of lists of placeholders ordered in placing order in the mission function mission_func.
  94. seed: seed: The seed for sampling from the space.
  95. """
  96. # Check that the ordered placeholders and mission function are well defined.
  97. if ordered_placeholders is not None:
  98. assert (
  99. len(ordered_placeholders) == mission_func.__code__.co_argcount
  100. ), f"The number of placeholders {len(ordered_placeholders)} is different from the number of parameters in the mission function {mission_func.__code__.co_argcount}."
  101. for placeholder_list in ordered_placeholders:
  102. assert check_if_no_duplicate(
  103. placeholder_list
  104. ), "Make sure that the placeholders don't have any duplicate values."
  105. else:
  106. assert (
  107. mission_func.__code__.co_argcount == 0
  108. ), f"If the ordered placeholders are {ordered_placeholders}, the mission function shouldn't have any parameters."
  109. self.ordered_placeholders = ordered_placeholders
  110. self.mission_func = mission_func
  111. super().__init__(dtype=str, seed=seed)
  112. # Check that mission_func returns a string
  113. sampled_mission = self.sample()
  114. assert isinstance(
  115. sampled_mission, str
  116. ), f"mission_func must return type str not {type(sampled_mission)}"
  117. def sample(self) -> str:
  118. """Sample a random mission string."""
  119. if self.ordered_placeholders is not None:
  120. placeholders = []
  121. for rand_var_list in self.ordered_placeholders:
  122. idx = self.np_random.integers(0, len(rand_var_list))
  123. placeholders.append(rand_var_list[idx])
  124. return self.mission_func(*placeholders)
  125. else:
  126. return self.mission_func()
  127. def contains(self, x: Any) -> bool:
  128. """Return boolean specifying if x is a valid member of this space."""
  129. # Store a list of all the placeholders from self.ordered_placeholders that appear in x
  130. if self.ordered_placeholders is not None:
  131. check_placeholder_list = []
  132. for placeholder_list in self.ordered_placeholders:
  133. for placeholder in placeholder_list:
  134. if placeholder in x:
  135. check_placeholder_list.append(placeholder)
  136. # Remove duplicates from the list
  137. check_placeholder_list = list(set(check_placeholder_list))
  138. start_id_placeholder = []
  139. end_id_placeholder = []
  140. # Get the starting and ending id of the identified placeholders with possible duplicates
  141. new_check_placeholder_list = []
  142. for placeholder in check_placeholder_list:
  143. new_start_id_placeholder = [
  144. i for i in range(len(x)) if x.startswith(placeholder, i)
  145. ]
  146. new_check_placeholder_list += [placeholder] * len(
  147. new_start_id_placeholder
  148. )
  149. end_id_placeholder += [
  150. start_id + len(placeholder) - 1
  151. for start_id in new_start_id_placeholder
  152. ]
  153. start_id_placeholder += new_start_id_placeholder
  154. # Order by starting id the placeholders
  155. ordered_placeholder_list = sorted(
  156. zip(
  157. start_id_placeholder, end_id_placeholder, new_check_placeholder_list
  158. )
  159. )
  160. # Check for repeated placeholders contained in each other
  161. remove_placeholder_id = []
  162. for i, placeholder_1 in enumerate(ordered_placeholder_list):
  163. starting_id = i + 1
  164. for j, placeholder_2 in enumerate(
  165. ordered_placeholder_list[starting_id:]
  166. ):
  167. # Check if place holder ids overlap and keep the longest
  168. if max(placeholder_1[0], placeholder_2[0]) < min(
  169. placeholder_1[1], placeholder_2[1]
  170. ):
  171. remove_placeholder = min(
  172. placeholder_1[2], placeholder_2[2], key=len
  173. )
  174. if remove_placeholder == placeholder_1[2]:
  175. remove_placeholder_id.append(i)
  176. else:
  177. remove_placeholder_id.append(i + j + 1)
  178. for id in remove_placeholder_id:
  179. del ordered_placeholder_list[id]
  180. final_placeholders = [
  181. placeholder[2] for placeholder in ordered_placeholder_list
  182. ]
  183. # Check that the identified final placeholders are in the same order as the original placeholders.
  184. for orered_placeholder, final_placeholder in zip(
  185. self.ordered_placeholders, final_placeholders
  186. ):
  187. if final_placeholder in orered_placeholder:
  188. continue
  189. else:
  190. return False
  191. try:
  192. mission_string_with_placeholders = self.mission_func(
  193. *final_placeholders
  194. )
  195. except Exception as e:
  196. print(
  197. f"{x} is not contained in MissionSpace due to the following exception: {e}"
  198. )
  199. return False
  200. return bool(mission_string_with_placeholders == x)
  201. else:
  202. return bool(self.mission_func() == x)
  203. def __repr__(self) -> str:
  204. """Gives a string representation of this space."""
  205. return f"MissionSpace({self.mission_func}, {self.ordered_placeholders})"
  206. def __eq__(self, other) -> bool:
  207. """Check whether ``other`` is equivalent to this instance."""
  208. if isinstance(other, MissionSpace):
  209. # Check that place holder lists are the same
  210. if self.ordered_placeholders is not None:
  211. # Check length
  212. if len(self.order_placeholder) == len(other.order_placeholder):
  213. # Placeholder list are ordered in placing order in the mission string
  214. for placeholder, other_placeholder in zip(
  215. self.order_placeholder, other.order_placeholder
  216. ):
  217. if set(placeholder) == set(other_placeholder):
  218. continue
  219. else:
  220. return False
  221. # Check mission string is the same with dummy space placeholders
  222. test_placeholders = [""] * len(self.order_placeholder)
  223. mission = self.mission_func(*test_placeholders)
  224. other_mission = other.mission_func(*test_placeholders)
  225. return mission == other_mission
  226. else:
  227. # Check that other is also None
  228. if other.ordered_placeholders is None:
  229. # Check mission string is the same
  230. mission = self.mission_func()
  231. other_mission = other.mission_func()
  232. return mission == other_mission
  233. # If none of the statements above return then False
  234. return False
  235. class WorldObj:
  236. """
  237. Base class for grid world objects
  238. """
  239. def __init__(self, type, color):
  240. assert type in OBJECT_TO_IDX, type
  241. assert color in COLOR_TO_IDX, color
  242. self.type = type
  243. self.color = color
  244. self.contains = None
  245. # Initial position of the object
  246. self.init_pos = None
  247. # Current position of the object
  248. self.cur_pos = None
  249. def can_overlap(self):
  250. """Can the agent overlap with this?"""
  251. return False
  252. def can_pickup(self):
  253. """Can the agent pick this up?"""
  254. return False
  255. def can_contain(self):
  256. """Can this contain another object?"""
  257. return False
  258. def see_behind(self):
  259. """Can the agent see behind this object?"""
  260. return True
  261. def toggle(self, env, pos):
  262. """Method to trigger/toggle an action this object performs"""
  263. return False
  264. def encode(self):
  265. """Encode the a description of this object as a 3-tuple of integers"""
  266. return (OBJECT_TO_IDX[self.type], COLOR_TO_IDX[self.color], 0)
  267. @staticmethod
  268. def decode(type_idx, color_idx, state):
  269. """Create an object from a 3-tuple state description"""
  270. obj_type = IDX_TO_OBJECT[type_idx]
  271. color = IDX_TO_COLOR[color_idx]
  272. if obj_type == "empty" or obj_type == "unseen":
  273. return None
  274. # State, 0: open, 1: closed, 2: locked
  275. is_open = state == 0
  276. is_locked = state == 2
  277. if obj_type == "wall":
  278. v = Wall(color)
  279. elif obj_type == "floor":
  280. v = Floor(color)
  281. elif obj_type == "ball":
  282. v = Ball(color)
  283. elif obj_type == "key":
  284. v = Key(color)
  285. elif obj_type == "box":
  286. v = Box(color)
  287. elif obj_type == "door":
  288. v = Door(color, is_open, is_locked)
  289. elif obj_type == "goal":
  290. v = Goal()
  291. elif obj_type == "lava":
  292. v = Lava()
  293. else:
  294. assert False, "unknown object type in decode '%s'" % obj_type
  295. return v
  296. def render(self, r):
  297. """Draw this object with the given renderer"""
  298. raise NotImplementedError
  299. class Goal(WorldObj):
  300. def __init__(self):
  301. super().__init__("goal", "green")
  302. def can_overlap(self):
  303. return True
  304. def render(self, img):
  305. fill_coords(img, point_in_rect(0, 1, 0, 1), COLORS[self.color])
  306. class Floor(WorldObj):
  307. """
  308. Colored floor tile the agent can walk over
  309. """
  310. def __init__(self, color="blue"):
  311. super().__init__("floor", color)
  312. def can_overlap(self):
  313. return True
  314. def render(self, img):
  315. # Give the floor a pale color
  316. color = COLORS[self.color] / 2
  317. fill_coords(img, point_in_rect(0.031, 1, 0.031, 1), color)
  318. class Lava(WorldObj):
  319. def __init__(self):
  320. super().__init__("lava", "red")
  321. def can_overlap(self):
  322. return True
  323. def render(self, img):
  324. c = (255, 128, 0)
  325. # Background color
  326. fill_coords(img, point_in_rect(0, 1, 0, 1), c)
  327. # Little waves
  328. for i in range(3):
  329. ylo = 0.3 + 0.2 * i
  330. yhi = 0.4 + 0.2 * i
  331. fill_coords(img, point_in_line(0.1, ylo, 0.3, yhi, r=0.03), (0, 0, 0))
  332. fill_coords(img, point_in_line(0.3, yhi, 0.5, ylo, r=0.03), (0, 0, 0))
  333. fill_coords(img, point_in_line(0.5, ylo, 0.7, yhi, r=0.03), (0, 0, 0))
  334. fill_coords(img, point_in_line(0.7, yhi, 0.9, ylo, r=0.03), (0, 0, 0))
  335. class Wall(WorldObj):
  336. def __init__(self, color="grey"):
  337. super().__init__("wall", color)
  338. def see_behind(self):
  339. return False
  340. def render(self, img):
  341. fill_coords(img, point_in_rect(0, 1, 0, 1), COLORS[self.color])
  342. class Door(WorldObj):
  343. def __init__(self, color, is_open=False, is_locked=False):
  344. super().__init__("door", color)
  345. self.is_open = is_open
  346. self.is_locked = is_locked
  347. def can_overlap(self):
  348. """The agent can only walk over this cell when the door is open"""
  349. return self.is_open
  350. def see_behind(self):
  351. return self.is_open
  352. def toggle(self, env, pos):
  353. # If the player has the right key to open the door
  354. if self.is_locked:
  355. if isinstance(env.carrying, Key) and env.carrying.color == self.color:
  356. self.is_locked = False
  357. self.is_open = True
  358. return True
  359. return False
  360. self.is_open = not self.is_open
  361. return True
  362. def encode(self):
  363. """Encode the a description of this object as a 3-tuple of integers"""
  364. # State, 0: open, 1: closed, 2: locked
  365. if self.is_open:
  366. state = 0
  367. elif self.is_locked:
  368. state = 2
  369. # if door is closed and unlocked
  370. elif not self.is_open:
  371. state = 1
  372. else:
  373. raise ValueError(
  374. f"There is no possible state encoding for the state:\n -Door Open: {self.is_open}\n -Door Closed: {not self.is_open}\n -Door Locked: {self.is_locked}"
  375. )
  376. return (OBJECT_TO_IDX[self.type], COLOR_TO_IDX[self.color], state)
  377. def render(self, img):
  378. c = COLORS[self.color]
  379. if self.is_open:
  380. fill_coords(img, point_in_rect(0.88, 1.00, 0.00, 1.00), c)
  381. fill_coords(img, point_in_rect(0.92, 0.96, 0.04, 0.96), (0, 0, 0))
  382. return
  383. # Door frame and door
  384. if self.is_locked:
  385. fill_coords(img, point_in_rect(0.00, 1.00, 0.00, 1.00), c)
  386. fill_coords(img, point_in_rect(0.06, 0.94, 0.06, 0.94), 0.45 * np.array(c))
  387. # Draw key slot
  388. fill_coords(img, point_in_rect(0.52, 0.75, 0.50, 0.56), c)
  389. else:
  390. fill_coords(img, point_in_rect(0.00, 1.00, 0.00, 1.00), c)
  391. fill_coords(img, point_in_rect(0.04, 0.96, 0.04, 0.96), (0, 0, 0))
  392. fill_coords(img, point_in_rect(0.08, 0.92, 0.08, 0.92), c)
  393. fill_coords(img, point_in_rect(0.12, 0.88, 0.12, 0.88), (0, 0, 0))
  394. # Draw door handle
  395. fill_coords(img, point_in_circle(cx=0.75, cy=0.50, r=0.08), c)
  396. class Key(WorldObj):
  397. def __init__(self, color="blue"):
  398. super().__init__("key", color)
  399. def can_pickup(self):
  400. return True
  401. def render(self, img):
  402. c = COLORS[self.color]
  403. # Vertical quad
  404. fill_coords(img, point_in_rect(0.50, 0.63, 0.31, 0.88), c)
  405. # Teeth
  406. fill_coords(img, point_in_rect(0.38, 0.50, 0.59, 0.66), c)
  407. fill_coords(img, point_in_rect(0.38, 0.50, 0.81, 0.88), c)
  408. # Ring
  409. fill_coords(img, point_in_circle(cx=0.56, cy=0.28, r=0.190), c)
  410. fill_coords(img, point_in_circle(cx=0.56, cy=0.28, r=0.064), (0, 0, 0))
  411. class Ball(WorldObj):
  412. def __init__(self, color="blue"):
  413. super().__init__("ball", color)
  414. def can_pickup(self):
  415. return True
  416. def render(self, img):
  417. fill_coords(img, point_in_circle(0.5, 0.5, 0.31), COLORS[self.color])
  418. class Box(WorldObj):
  419. def __init__(self, color, contains=None):
  420. super().__init__("box", color)
  421. self.contains = contains
  422. def can_pickup(self):
  423. return True
  424. def render(self, img):
  425. c = COLORS[self.color]
  426. # Outline
  427. fill_coords(img, point_in_rect(0.12, 0.88, 0.12, 0.88), c)
  428. fill_coords(img, point_in_rect(0.18, 0.82, 0.18, 0.82), (0, 0, 0))
  429. # Horizontal slit
  430. fill_coords(img, point_in_rect(0.16, 0.84, 0.47, 0.53), c)
  431. def toggle(self, env, pos):
  432. # Replace the box by its contents
  433. env.grid.set(*pos, self.contains)
  434. return True
  435. class Grid:
  436. """
  437. Represent a grid and operations on it
  438. """
  439. # Static cache of pre-renderer tiles
  440. tile_cache = {}
  441. def __init__(self, width, height):
  442. assert width >= 3
  443. assert height >= 3
  444. self.width = width
  445. self.height = height
  446. self.grid = [None] * width * height
  447. def __contains__(self, key):
  448. if isinstance(key, WorldObj):
  449. for e in self.grid:
  450. if e is key:
  451. return True
  452. elif isinstance(key, tuple):
  453. for e in self.grid:
  454. if e is None:
  455. continue
  456. if (e.color, e.type) == key:
  457. return True
  458. if key[0] is None and key[1] == e.type:
  459. return True
  460. return False
  461. def __eq__(self, other):
  462. grid1 = self.encode()
  463. grid2 = other.encode()
  464. return np.array_equal(grid2, grid1)
  465. def __ne__(self, other):
  466. return not self == other
  467. def copy(self):
  468. from copy import deepcopy
  469. return deepcopy(self)
  470. def set(self, i, j, v):
  471. assert i >= 0 and i < self.width
  472. assert j >= 0 and j < self.height
  473. self.grid[j * self.width + i] = v
  474. def get(self, i, j):
  475. assert i >= 0 and i < self.width
  476. assert j >= 0 and j < self.height
  477. return self.grid[j * self.width + i]
  478. def horz_wall(self, x, y, length=None, obj_type=Wall):
  479. if length is None:
  480. length = self.width - x
  481. for i in range(0, length):
  482. self.set(x + i, y, obj_type())
  483. def vert_wall(self, x, y, length=None, obj_type=Wall):
  484. if length is None:
  485. length = self.height - y
  486. for j in range(0, length):
  487. self.set(x, y + j, obj_type())
  488. def wall_rect(self, x, y, w, h):
  489. self.horz_wall(x, y, w)
  490. self.horz_wall(x, y + h - 1, w)
  491. self.vert_wall(x, y, h)
  492. self.vert_wall(x + w - 1, y, h)
  493. def rotate_left(self):
  494. """
  495. Rotate the grid to the left (counter-clockwise)
  496. """
  497. grid = Grid(self.height, self.width)
  498. for i in range(self.width):
  499. for j in range(self.height):
  500. v = self.get(i, j)
  501. grid.set(j, grid.height - 1 - i, v)
  502. return grid
  503. def slice(self, topX, topY, width, height):
  504. """
  505. Get a subset of the grid
  506. """
  507. grid = Grid(width, height)
  508. for j in range(0, height):
  509. for i in range(0, width):
  510. x = topX + i
  511. y = topY + j
  512. if x >= 0 and x < self.width and y >= 0 and y < self.height:
  513. v = self.get(x, y)
  514. else:
  515. v = Wall()
  516. grid.set(i, j, v)
  517. return grid
  518. @classmethod
  519. def render_tile(
  520. cls, obj, agent_dir=None, highlight=False, tile_size=TILE_PIXELS, subdivs=3
  521. ):
  522. """
  523. Render a tile and cache the result
  524. """
  525. # Hash map lookup key for the cache
  526. key = (agent_dir, highlight, tile_size)
  527. key = obj.encode() + key if obj else key
  528. if key in cls.tile_cache:
  529. return cls.tile_cache[key]
  530. img = np.zeros(
  531. shape=(tile_size * subdivs, tile_size * subdivs, 3), dtype=np.uint8
  532. )
  533. # Draw the grid lines (top and left edges)
  534. fill_coords(img, point_in_rect(0, 0.031, 0, 1), (100, 100, 100))
  535. fill_coords(img, point_in_rect(0, 1, 0, 0.031), (100, 100, 100))
  536. if obj is not None:
  537. obj.render(img)
  538. # Overlay the agent on top
  539. if agent_dir is not None:
  540. tri_fn = point_in_triangle(
  541. (0.12, 0.19),
  542. (0.87, 0.50),
  543. (0.12, 0.81),
  544. )
  545. # Rotate the agent based on its direction
  546. tri_fn = rotate_fn(tri_fn, cx=0.5, cy=0.5, theta=0.5 * math.pi * agent_dir)
  547. fill_coords(img, tri_fn, (255, 0, 0))
  548. # Highlight the cell if needed
  549. if highlight:
  550. highlight_img(img)
  551. # Downsample the image to perform supersampling/anti-aliasing
  552. img = downsample(img, subdivs)
  553. # Cache the rendered tile
  554. cls.tile_cache[key] = img
  555. return img
  556. def render(self, tile_size, agent_pos=None, agent_dir=None, highlight_mask=None):
  557. """
  558. Render this grid at a given scale
  559. :param r: target renderer object
  560. :param tile_size: tile size in pixels
  561. """
  562. if highlight_mask is None:
  563. highlight_mask = np.zeros(shape=(self.width, self.height), dtype=bool)
  564. # Compute the total grid size
  565. width_px = self.width * tile_size
  566. height_px = self.height * tile_size
  567. img = np.zeros(shape=(height_px, width_px, 3), dtype=np.uint8)
  568. # Render the grid
  569. for j in range(0, self.height):
  570. for i in range(0, self.width):
  571. cell = self.get(i, j)
  572. agent_here = np.array_equal(agent_pos, (i, j))
  573. tile_img = Grid.render_tile(
  574. cell,
  575. agent_dir=agent_dir if agent_here else None,
  576. highlight=highlight_mask[i, j],
  577. tile_size=tile_size,
  578. )
  579. ymin = j * tile_size
  580. ymax = (j + 1) * tile_size
  581. xmin = i * tile_size
  582. xmax = (i + 1) * tile_size
  583. img[ymin:ymax, xmin:xmax, :] = tile_img
  584. return img
  585. def encode(self, vis_mask=None):
  586. """
  587. Produce a compact numpy encoding of the grid
  588. """
  589. if vis_mask is None:
  590. vis_mask = np.ones((self.width, self.height), dtype=bool)
  591. array = np.zeros((self.width, self.height, 3), dtype="uint8")
  592. for i in range(self.width):
  593. for j in range(self.height):
  594. if vis_mask[i, j]:
  595. v = self.get(i, j)
  596. if v is None:
  597. array[i, j, 0] = OBJECT_TO_IDX["empty"]
  598. array[i, j, 1] = 0
  599. array[i, j, 2] = 0
  600. else:
  601. array[i, j, :] = v.encode()
  602. return array
  603. @staticmethod
  604. def decode(array):
  605. """
  606. Decode an array grid encoding back into a grid
  607. """
  608. width, height, channels = array.shape
  609. assert channels == 3
  610. vis_mask = np.ones(shape=(width, height), dtype=bool)
  611. grid = Grid(width, height)
  612. for i in range(width):
  613. for j in range(height):
  614. type_idx, color_idx, state = array[i, j]
  615. v = WorldObj.decode(type_idx, color_idx, state)
  616. grid.set(i, j, v)
  617. vis_mask[i, j] = type_idx != OBJECT_TO_IDX["unseen"]
  618. return grid, vis_mask
  619. def process_vis(self, agent_pos):
  620. mask = np.zeros(shape=(self.width, self.height), dtype=bool)
  621. mask[agent_pos[0], agent_pos[1]] = True
  622. for j in reversed(range(0, self.height)):
  623. for i in range(0, self.width - 1):
  624. if not mask[i, j]:
  625. continue
  626. cell = self.get(i, j)
  627. if cell and not cell.see_behind():
  628. continue
  629. mask[i + 1, j] = True
  630. if j > 0:
  631. mask[i + 1, j - 1] = True
  632. mask[i, j - 1] = True
  633. for i in reversed(range(1, self.width)):
  634. if not mask[i, j]:
  635. continue
  636. cell = self.get(i, j)
  637. if cell and not cell.see_behind():
  638. continue
  639. mask[i - 1, j] = True
  640. if j > 0:
  641. mask[i - 1, j - 1] = True
  642. mask[i, j - 1] = True
  643. for j in range(0, self.height):
  644. for i in range(0, self.width):
  645. if not mask[i, j]:
  646. self.set(i, j, None)
  647. return mask
  648. class MiniGridEnv(gym.Env):
  649. """
  650. 2D grid world game environment
  651. """
  652. metadata = {
  653. # Deprecated: use 'render_modes' instead
  654. "render.modes": ["human", "rgb_array"],
  655. "video.frames_per_second": 10, # Deprecated: use 'render_fps' instead
  656. "render_modes": ["human", "rgb_array", "single_rgb_array"],
  657. "render_fps": 10,
  658. }
  659. # Enumeration of possible actions
  660. class Actions(IntEnum):
  661. # Turn left, turn right, move forward
  662. left = 0
  663. right = 1
  664. forward = 2
  665. # Pick up an object
  666. pickup = 3
  667. # Drop an object
  668. drop = 4
  669. # Toggle/activate an object
  670. toggle = 5
  671. # Done completing task
  672. done = 6
  673. def __init__(
  674. self,
  675. mission_space: MissionSpace,
  676. grid_size: int = None,
  677. width: int = None,
  678. height: int = None,
  679. max_steps: int = 100,
  680. see_through_walls: bool = False,
  681. agent_view_size: int = 7,
  682. highlight: bool = True,
  683. tile_size: int = TILE_PIXELS,
  684. **kwargs,
  685. ):
  686. # Initialize mission
  687. self.mission = mission_space.sample()
  688. # Can't set both grid_size and width/height
  689. if grid_size:
  690. assert width is None and height is None
  691. width = grid_size
  692. height = grid_size
  693. # Action enumeration for this environment
  694. self.actions = MiniGridEnv.Actions
  695. # Actions are discrete integer values
  696. self.action_space = spaces.Discrete(len(self.actions))
  697. # Number of cells (width and height) in the agent view
  698. assert agent_view_size % 2 == 1
  699. assert agent_view_size >= 3
  700. self.agent_view_size = agent_view_size
  701. # Observations are dictionaries containing an
  702. # encoding of the grid and a textual 'mission' string
  703. image_observation_space = spaces.Box(
  704. low=0,
  705. high=255,
  706. shape=(self.agent_view_size, self.agent_view_size, 3),
  707. dtype="uint8",
  708. )
  709. self.observation_space = spaces.Dict(
  710. {
  711. "image": image_observation_space,
  712. "direction": spaces.Discrete(4),
  713. "mission": mission_space,
  714. }
  715. )
  716. # Range of possible rewards
  717. self.reward_range = (0, 1)
  718. self.window: Window = None
  719. # Environment configuration
  720. self.width = width
  721. self.height = height
  722. self.max_steps = max_steps
  723. self.see_through_walls = see_through_walls
  724. # Current position and direction of the agent
  725. self.agent_pos: np.ndarray = None
  726. self.agent_dir: int = None
  727. # Initialize the state
  728. self.reset()
  729. def reset(self, *, seed=None, return_info=False, options=None):
  730. super().reset(seed=seed)
  731. # Current position and direction of the agent
  732. self.agent_pos = None
  733. self.agent_dir = None
  734. # Generate a new random grid at the start of each episode
  735. self._gen_grid(self.width, self.height)
  736. # These fields should be defined by _gen_grid
  737. assert self.agent_pos is not None
  738. assert self.agent_dir is not None
  739. # Check that the agent doesn't overlap with an object
  740. start_cell = self.grid.get(*self.agent_pos)
  741. assert start_cell is None or start_cell.can_overlap()
  742. # Item picked up, being carried, initially nothing
  743. self.carrying = None
  744. # Step count since episode start
  745. self.step_count = 0
  746. # Return first observation
  747. obs = self.gen_obs()
  748. if not return_info:
  749. return obs
  750. else:
  751. return obs, {}
  752. def hash(self, size=16):
  753. """Compute a hash that uniquely identifies the current state of the environment.
  754. :param size: Size of the hashing
  755. """
  756. sample_hash = hashlib.sha256()
  757. to_encode = [self.grid.encode().tolist(), self.agent_pos, self.agent_dir]
  758. for item in to_encode:
  759. sample_hash.update(str(item).encode("utf8"))
  760. return sample_hash.hexdigest()[:size]
  761. @property
  762. def steps_remaining(self):
  763. return self.max_steps - self.step_count
  764. def __str__(self):
  765. """
  766. Produce a pretty string of the environment's grid along with the agent.
  767. A grid cell is represented by 2-character string, the first one for
  768. the object and the second one for the color.
  769. """
  770. # Map of object types to short string
  771. OBJECT_TO_STR = {
  772. "wall": "W",
  773. "floor": "F",
  774. "door": "D",
  775. "key": "K",
  776. "ball": "A",
  777. "box": "B",
  778. "goal": "G",
  779. "lava": "V",
  780. }
  781. # Map agent's direction to short string
  782. AGENT_DIR_TO_STR = {0: ">", 1: "V", 2: "<", 3: "^"}
  783. str = ""
  784. for j in range(self.grid.height):
  785. for i in range(self.grid.width):
  786. if i == self.agent_pos[0] and j == self.agent_pos[1]:
  787. str += 2 * AGENT_DIR_TO_STR[self.agent_dir]
  788. continue
  789. c = self.grid.get(i, j)
  790. if c is None:
  791. str += " "
  792. continue
  793. if c.type == "door":
  794. if c.is_open:
  795. str += "__"
  796. elif c.is_locked:
  797. str += "L" + c.color[0].upper()
  798. else:
  799. str += "D" + c.color[0].upper()
  800. continue
  801. str += OBJECT_TO_STR[c.type] + c.color[0].upper()
  802. if j < self.grid.height - 1:
  803. str += "\n"
  804. return str
  805. @abstractmethod
  806. def _gen_grid(self, width, height):
  807. pass
  808. def _reward(self):
  809. """
  810. Compute the reward to be given upon success
  811. """
  812. return 1 - 0.9 * (self.step_count / self.max_steps)
  813. def _rand_int(self, low, high):
  814. """
  815. Generate random integer in [low,high[
  816. """
  817. return self.np_random.integers(low, high)
  818. def _rand_float(self, low, high):
  819. """
  820. Generate random float in [low,high[
  821. """
  822. return self.np_random.uniform(low, high)
  823. def _rand_bool(self):
  824. """
  825. Generate random boolean value
  826. """
  827. return self.np_random.integers(0, 2) == 0
  828. def _rand_elem(self, iterable):
  829. """
  830. Pick a random element in a list
  831. """
  832. lst = list(iterable)
  833. idx = self._rand_int(0, len(lst))
  834. return lst[idx]
  835. def _rand_subset(self, iterable, num_elems):
  836. """
  837. Sample a random subset of distinct elements of a list
  838. """
  839. lst = list(iterable)
  840. assert num_elems <= len(lst)
  841. out = []
  842. while len(out) < num_elems:
  843. elem = self._rand_elem(lst)
  844. lst.remove(elem)
  845. out.append(elem)
  846. return out
  847. def _rand_color(self):
  848. """
  849. Generate a random color name (string)
  850. """
  851. return self._rand_elem(COLOR_NAMES)
  852. def _rand_pos(self, xLow, xHigh, yLow, yHigh):
  853. """
  854. Generate a random (x,y) position tuple
  855. """
  856. return (
  857. self.np_random.integers(xLow, xHigh),
  858. self.np_random.integers(yLow, yHigh),
  859. )
  860. def place_obj(self, obj, top=None, size=None, reject_fn=None, max_tries=math.inf):
  861. """
  862. Place an object at an empty position in the grid
  863. :param top: top-left position of the rectangle where to place
  864. :param size: size of the rectangle where to place
  865. :param reject_fn: function to filter out potential positions
  866. """
  867. if top is None:
  868. top = (0, 0)
  869. else:
  870. top = (max(top[0], 0), max(top[1], 0))
  871. if size is None:
  872. size = (self.grid.width, self.grid.height)
  873. num_tries = 0
  874. while True:
  875. # This is to handle with rare cases where rejection sampling
  876. # gets stuck in an infinite loop
  877. if num_tries > max_tries:
  878. raise RecursionError("rejection sampling failed in place_obj")
  879. num_tries += 1
  880. pos = np.array(
  881. (
  882. self._rand_int(top[0], min(top[0] + size[0], self.grid.width)),
  883. self._rand_int(top[1], min(top[1] + size[1], self.grid.height)),
  884. )
  885. )
  886. # Don't place the object on top of another object
  887. if self.grid.get(*pos) is not None:
  888. continue
  889. # Don't place the object where the agent is
  890. if np.array_equal(pos, self.agent_pos):
  891. continue
  892. # Check if there is a filtering criterion
  893. if reject_fn and reject_fn(self, pos):
  894. continue
  895. break
  896. self.grid.set(*pos, obj)
  897. if obj is not None:
  898. obj.init_pos = pos
  899. obj.cur_pos = pos
  900. return pos
  901. def put_obj(self, obj, i, j):
  902. """
  903. Put an object at a specific position in the grid
  904. """
  905. self.grid.set(i, j, obj)
  906. obj.init_pos = (i, j)
  907. obj.cur_pos = (i, j)
  908. def place_agent(self, top=None, size=None, rand_dir=True, max_tries=math.inf):
  909. """
  910. Set the agent's starting point at an empty position in the grid
  911. """
  912. self.agent_pos = None
  913. pos = self.place_obj(None, top, size, max_tries=max_tries)
  914. self.agent_pos = pos
  915. if rand_dir:
  916. self.agent_dir = self._rand_int(0, 4)
  917. return pos
  918. @property
  919. def dir_vec(self):
  920. """
  921. Get the direction vector for the agent, pointing in the direction
  922. of forward movement.
  923. """
  924. assert self.agent_dir >= 0 and self.agent_dir < 4
  925. return DIR_TO_VEC[self.agent_dir]
  926. @property
  927. def right_vec(self):
  928. """
  929. Get the vector pointing to the right of the agent.
  930. """
  931. dx, dy = self.dir_vec
  932. return np.array((-dy, dx))
  933. @property
  934. def front_pos(self):
  935. """
  936. Get the position of the cell that is right in front of the agent
  937. """
  938. return self.agent_pos + self.dir_vec
  939. def get_view_coords(self, i, j):
  940. """
  941. Translate and rotate absolute grid coordinates (i, j) into the
  942. agent's partially observable view (sub-grid). Note that the resulting
  943. coordinates may be negative or outside of the agent's view size.
  944. """
  945. ax, ay = self.agent_pos
  946. dx, dy = self.dir_vec
  947. rx, ry = self.right_vec
  948. # Compute the absolute coordinates of the top-left view corner
  949. sz = self.agent_view_size
  950. hs = self.agent_view_size // 2
  951. tx = ax + (dx * (sz - 1)) - (rx * hs)
  952. ty = ay + (dy * (sz - 1)) - (ry * hs)
  953. lx = i - tx
  954. ly = j - ty
  955. # Project the coordinates of the object relative to the top-left
  956. # corner onto the agent's own coordinate system
  957. vx = rx * lx + ry * ly
  958. vy = -(dx * lx + dy * ly)
  959. return vx, vy
  960. def get_view_exts(self, agent_view_size=None):
  961. """
  962. Get the extents of the square set of tiles visible to the agent
  963. Note: the bottom extent indices are not included in the set
  964. if agent_view_size is None, use self.agent_view_size
  965. """
  966. agent_view_size = agent_view_size or self.agent_view_size
  967. # Facing right
  968. if self.agent_dir == 0:
  969. topX = self.agent_pos[0]
  970. topY = self.agent_pos[1] - agent_view_size // 2
  971. # Facing down
  972. elif self.agent_dir == 1:
  973. topX = self.agent_pos[0] - agent_view_size // 2
  974. topY = self.agent_pos[1]
  975. # Facing left
  976. elif self.agent_dir == 2:
  977. topX = self.agent_pos[0] - agent_view_size + 1
  978. topY = self.agent_pos[1] - agent_view_size // 2
  979. # Facing up
  980. elif self.agent_dir == 3:
  981. topX = self.agent_pos[0] - agent_view_size // 2
  982. topY = self.agent_pos[1] - agent_view_size + 1
  983. else:
  984. assert False, "invalid agent direction"
  985. botX = topX + agent_view_size
  986. botY = topY + agent_view_size
  987. return (topX, topY, botX, botY)
  988. def relative_coords(self, x, y):
  989. """
  990. Check if a grid position belongs to the agent's field of view, and returns the corresponding coordinates
  991. """
  992. vx, vy = self.get_view_coords(x, y)
  993. if vx < 0 or vy < 0 or vx >= self.agent_view_size or vy >= self.agent_view_size:
  994. return None
  995. return vx, vy
  996. def in_view(self, x, y):
  997. """
  998. check if a grid position is visible to the agent
  999. """
  1000. return self.relative_coords(x, y) is not None
  1001. def agent_sees(self, x, y):
  1002. """
  1003. Check if a non-empty grid position is visible to the agent
  1004. """
  1005. coordinates = self.relative_coords(x, y)
  1006. if coordinates is None:
  1007. return False
  1008. vx, vy = coordinates
  1009. obs = self.gen_obs()
  1010. obs_grid, _ = Grid.decode(obs["image"])
  1011. obs_cell = obs_grid.get(vx, vy)
  1012. world_cell = self.grid.get(x, y)
  1013. return obs_cell is not None and obs_cell.type == world_cell.type
  1014. def step(self, action):
  1015. self.step_count += 1
  1016. reward = 0
  1017. done = False
  1018. # Get the position in front of the agent
  1019. fwd_pos = self.front_pos
  1020. # Get the contents of the cell in front of the agent
  1021. fwd_cell = self.grid.get(*fwd_pos)
  1022. # Rotate left
  1023. if action == self.actions.left:
  1024. self.agent_dir -= 1
  1025. if self.agent_dir < 0:
  1026. self.agent_dir += 4
  1027. # Rotate right
  1028. elif action == self.actions.right:
  1029. self.agent_dir = (self.agent_dir + 1) % 4
  1030. # Move forward
  1031. elif action == self.actions.forward:
  1032. if fwd_cell is None or fwd_cell.can_overlap():
  1033. self.agent_pos = fwd_pos
  1034. if fwd_cell is not None and fwd_cell.type == "goal":
  1035. done = True
  1036. reward = self._reward()
  1037. if fwd_cell is not None and fwd_cell.type == "lava":
  1038. done = True
  1039. # Pick up an object
  1040. elif action == self.actions.pickup:
  1041. if fwd_cell and fwd_cell.can_pickup():
  1042. if self.carrying is None:
  1043. self.carrying = fwd_cell
  1044. self.carrying.cur_pos = np.array([-1, -1])
  1045. self.grid.set(*fwd_pos, None)
  1046. # Drop an object
  1047. elif action == self.actions.drop:
  1048. if not fwd_cell and self.carrying:
  1049. self.grid.set(*fwd_pos, self.carrying)
  1050. self.carrying.cur_pos = fwd_pos
  1051. self.carrying = None
  1052. # Toggle/activate an object
  1053. elif action == self.actions.toggle:
  1054. if fwd_cell:
  1055. fwd_cell.toggle(self, fwd_pos)
  1056. # Done action (not used by default)
  1057. elif action == self.actions.done:
  1058. pass
  1059. else:
  1060. assert False, "unknown action"
  1061. if self.step_count >= self.max_steps:
  1062. done = True
  1063. obs = self.gen_obs()
  1064. return obs, reward, done, {}
  1065. def gen_obs_grid(self, agent_view_size=None):
  1066. """
  1067. Generate the sub-grid observed by the agent.
  1068. This method also outputs a visibility mask telling us which grid
  1069. cells the agent can actually see.
  1070. if agent_view_size is None, self.agent_view_size is used
  1071. """
  1072. topX, topY, botX, botY = self.get_view_exts(agent_view_size)
  1073. agent_view_size = agent_view_size or self.agent_view_size
  1074. grid = self.grid.slice(topX, topY, agent_view_size, agent_view_size)
  1075. for i in range(self.agent_dir + 1):
  1076. grid = grid.rotate_left()
  1077. # Process occluders and visibility
  1078. # Note that this incurs some performance cost
  1079. if not self.see_through_walls:
  1080. vis_mask = grid.process_vis(
  1081. agent_pos=(agent_view_size // 2, agent_view_size - 1)
  1082. )
  1083. else:
  1084. vis_mask = np.ones(shape=(grid.width, grid.height), dtype=bool)
  1085. # Make it so the agent sees what it's carrying
  1086. # We do this by placing the carried object at the agent's position
  1087. # in the agent's partially observable view
  1088. agent_pos = grid.width // 2, grid.height - 1
  1089. if self.carrying:
  1090. grid.set(*agent_pos, self.carrying)
  1091. else:
  1092. grid.set(*agent_pos, None)
  1093. return grid, vis_mask
  1094. def gen_obs(self):
  1095. """
  1096. Generate the agent's view (partially observable, low-resolution encoding)
  1097. """
  1098. grid, vis_mask = self.gen_obs_grid()
  1099. # Encode the partially observable view into a numpy array
  1100. image = grid.encode(vis_mask)
  1101. assert hasattr(
  1102. self, "mission"
  1103. ), "environments must define a textual mission string"
  1104. # Observations are dictionaries containing:
  1105. # - an image (partially observable view of the environment)
  1106. # - the agent's direction/orientation (acting as a compass)
  1107. # - a textual mission string (instructions for the agent)
  1108. obs = {"image": image, "direction": self.agent_dir, "mission": self.mission}
  1109. return obs
  1110. def get_obs_render(self, obs, tile_size=TILE_PIXELS // 2):
  1111. """
  1112. Render an agent observation for visualization
  1113. """
  1114. grid, vis_mask = Grid.decode(obs)
  1115. # Render the whole grid
  1116. img = grid.render(
  1117. tile_size,
  1118. agent_pos=(self.agent_view_size // 2, self.agent_view_size - 1),
  1119. agent_dir=3,
  1120. highlight_mask=vis_mask,
  1121. )
  1122. return img
  1123. def render(self, mode="human", highlight=True, tile_size=TILE_PIXELS):
  1124. assert mode in self.metadata["render_modes"]
  1125. """
  1126. Render the whole-grid human view
  1127. """
  1128. if mode == "human" and not self.window:
  1129. self.window = Window("gym_minigrid")
  1130. self.window.show(block=False)
  1131. # Compute which cells are visible to the agent
  1132. _, vis_mask = self.gen_obs_grid()
  1133. # Compute the world coordinates of the bottom-left corner
  1134. # of the agent's view area
  1135. f_vec = self.dir_vec
  1136. r_vec = self.right_vec
  1137. top_left = (
  1138. self.agent_pos
  1139. + f_vec * (self.agent_view_size - 1)
  1140. - r_vec * (self.agent_view_size // 2)
  1141. )
  1142. # Mask of which cells to highlight
  1143. highlight_mask = np.zeros(shape=(self.width, self.height), dtype=bool)
  1144. # For each cell in the visibility mask
  1145. for vis_j in range(0, self.agent_view_size):
  1146. for vis_i in range(0, self.agent_view_size):
  1147. # If this cell is not visible, don't highlight it
  1148. if not vis_mask[vis_i, vis_j]:
  1149. continue
  1150. # Compute the world coordinates of this cell
  1151. abs_i, abs_j = top_left - (f_vec * vis_j) + (r_vec * vis_i)
  1152. if abs_i < 0 or abs_i >= self.width:
  1153. continue
  1154. if abs_j < 0 or abs_j >= self.height:
  1155. continue
  1156. # Mark this cell to be highlighted
  1157. highlight_mask[abs_i, abs_j] = True
  1158. # Render the whole grid
  1159. img = self.grid.render(
  1160. tile_size,
  1161. self.agent_pos,
  1162. self.agent_dir,
  1163. highlight_mask=highlight_mask if highlight else None,
  1164. )
  1165. if mode == "human":
  1166. self.window.set_caption(self.mission)
  1167. self.window.show_img(img)
  1168. else:
  1169. return img
  1170. def close(self):
  1171. if self.window:
  1172. self.window.close()