window.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. import sys
  2. import numpy as np
  3. # Only ask users to install matplotlib if they actually need it
  4. try:
  5. import matplotlib.pyplot as plt
  6. except:
  7. print('To display the environment in a window, please install matplotlib, eg:')
  8. print('pip3 install --user matplotlib')
  9. sys.exit(-1)
  10. class Window:
  11. """
  12. Window to draw a gridworld instance using Matplotlib
  13. """
  14. def __init__(self, title):
  15. self.fig = None
  16. self.imshow_obj = None
  17. # Create the figure and axes
  18. self.fig, self.ax = plt.subplots()
  19. # Show the env name in the window title
  20. self.fig.canvas.set_window_title(title)
  21. # Turn off x/y axis numbering/ticks
  22. self.ax.xaxis.set_ticks_position('none')
  23. self.ax.yaxis.set_ticks_position('none')
  24. _ = self.ax.set_xticklabels([])
  25. _ = self.ax.set_yticklabels([])
  26. # Flag indicating the window was closed
  27. self.closed = False
  28. def close_handler(evt):
  29. self.closed = True
  30. self.fig.canvas.mpl_connect('close_event', close_handler)
  31. def show_img(self, img):
  32. """
  33. Show an image or update the image being shown
  34. """
  35. # Show the first image of the environment
  36. if self.imshow_obj is None:
  37. self.imshow_obj = self.ax.imshow(img, interpolation='bilinear')
  38. self.imshow_obj.set_data(img)
  39. self.fig.canvas.draw()
  40. # Let matplotlib process UI events
  41. # This is needed for interactive mode to work properly
  42. plt.pause(0.001)
  43. def set_caption(self, text):
  44. """
  45. Set/update the caption text below the image
  46. """
  47. plt.xlabel(text)
  48. def reg_key_handler(self, key_handler):
  49. """
  50. Register a keyboard event handler
  51. """
  52. # Keyboard handler
  53. self.fig.canvas.mpl_connect('key_press_event', key_handler)
  54. def show(self, block=True):
  55. """
  56. Show the window, and start an event loop
  57. """
  58. # If not blocking, trigger interactive mode
  59. if not block:
  60. plt.ion()
  61. # Show the plot
  62. # In non-interative mode, this enters the matplotlib event loop
  63. # In interactive mode, this call does not block
  64. plt.show()
  65. def close(self):
  66. """
  67. Close the window
  68. """
  69. plt.close()