window.py 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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. # Let matplotlib process UI events
  34. # This is needed for interactive mode to work properly
  35. plt.pause(0.001)
  36. def set_caption(self, text):
  37. """
  38. Set/update the caption text below the image
  39. """
  40. plt.xlabel(text)
  41. def reg_key_handler(self, key_handler):
  42. """
  43. Register a keyboard event handler
  44. """
  45. # Keyboard handler
  46. self.fig.canvas.mpl_connect('key_press_event', key_handler)
  47. def show(self, block=True):
  48. """
  49. Show the window, and start an event loop
  50. """
  51. # If not blocking, trigger interactive mode
  52. if not block:
  53. print('INTERACTIVE MODE')
  54. plt.ion()
  55. # Show the plot
  56. # In non-interative mode, this enters the matplotlib event loop
  57. # In interactive mode, this call does not block
  58. plt.show()
  59. def close(self):
  60. """
  61. Close the window
  62. """
  63. plt.close()