standalone.py 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. #!/usr/bin/env python3
  2. from __future__ import division, print_function
  3. import sys
  4. import numpy
  5. import gym
  6. import time
  7. from optparse import OptionParser
  8. import gym_minigrid
  9. def main():
  10. parser = OptionParser()
  11. parser.add_option(
  12. "-e",
  13. "--env-name",
  14. dest="env_name",
  15. help="gym environment to load",
  16. default='MiniGrid-MultiRoom-N6-v0'
  17. )
  18. (options, args) = parser.parse_args()
  19. # Load the gym environment
  20. env = gym.make(options.env_name)
  21. def resetEnv():
  22. env.reset()
  23. if hasattr(env, 'mission'):
  24. print('Mission: %s' % env.mission)
  25. resetEnv()
  26. # Create a window to render into
  27. renderer = env.render('human')
  28. def keyDownCb(keyName):
  29. if keyName == 'BACKSPACE':
  30. resetEnv()
  31. return
  32. if keyName == 'ESCAPE':
  33. sys.exit(0)
  34. action = 0
  35. if keyName == 'LEFT':
  36. action = env.actions.left
  37. elif keyName == 'RIGHT':
  38. action = env.actions.right
  39. elif keyName == 'UP':
  40. action = env.actions.forward
  41. elif keyName == 'SPACE':
  42. action = env.actions.toggle
  43. elif keyName == 'CTRL':
  44. action = env.actions.wait
  45. else:
  46. print("unknown key %s" % keyName)
  47. return
  48. obs, reward, done, info = env.step(action)
  49. print('step=%s, reward=%s' % (env.stepCount, reward))
  50. if done:
  51. print('done!')
  52. resetEnv()
  53. renderer.window.setKeyDownCb(keyDownCb)
  54. while True:
  55. env.render('human')
  56. time.sleep(0.01)
  57. # If the window was closed
  58. if renderer.window == None:
  59. break
  60. if __name__ == "__main__":
  61. main()