minigrid.py 45 KB

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