manual_control.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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 == 'PAGE_UP':
  44. action = env.actions.pickup
  45. elif keyName == 'PAGE_DOWN':
  46. action = env.actions.drop
  47. elif keyName == 'RETURN':
  48. action = env.actions.done
  49. else:
  50. print("unknown key %s" % keyName)
  51. return
  52. obs, reward, done, info = env.step(action)
  53. print('step=%s, reward=%.2f' % (env.step_count, reward))
  54. if done:
  55. print('done!')
  56. resetEnv()
  57. renderer.window.setKeyDownCb(keyDownCb)
  58. while True:
  59. env.render('human')
  60. time.sleep(0.01)
  61. # If the window was closed
  62. if renderer.window == None:
  63. break
  64. if __name__ == "__main__":
  65. main()