window.py 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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.set_xticks([], [])
  23. self.ax.set_yticks([], [])
  24. def show_img(self, img):
  25. """
  26. Show an image or update the image being shown
  27. """
  28. # Show the first image of the environment
  29. if self.imshow_obj is None:
  30. self.imshow_obj = self.ax.imshow(img, interpolation='bilinear')
  31. self.imshow_obj.set_data(img)
  32. self.fig.canvas.draw()
  33. def set_caption(self, text):
  34. """
  35. Set/update the caption text below the image
  36. """
  37. plt.xlabel(text)
  38. def reg_key_handler(self, key_handler):
  39. """
  40. Register a keyboard event handler
  41. """
  42. # Keyboard handler
  43. self.fig.canvas.mpl_connect('key_press_event', key_handler)
  44. def show(self, block=True):
  45. """
  46. Show the window, and start an event loop
  47. """
  48. # If not blocking, trigger interactive mode
  49. if not block:
  50. plt.ion()
  51. # Show the plot, enter the matplotlib event loop
  52. plt.show(block=block)
  53. def close(self):
  54. """
  55. Close the window
  56. """
  57. plt.close()