manual_control.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  1. #!/usr/bin/env python3
  2. import time
  3. import argparse
  4. import numpy as np
  5. import gym
  6. import gym_minigrid
  7. from gym_minigrid.wrappers import *
  8. from gym_minigrid.window import Window
  9. def redraw(img):
  10. if not args.agent_view:
  11. img = env.render('rgb_array', tile_size=args.tile_size)
  12. window.show_img(img)
  13. def reset():
  14. if args.seed != -1:
  15. env.seed(args.seed)
  16. obs = env.reset()
  17. if hasattr(env, 'mission'):
  18. print('Mission: %s' % env.mission)
  19. window.set_caption(env.mission)
  20. redraw(obs)
  21. def step(action):
  22. obs, reward, done, info = env.step(action)
  23. print('step=%s, reward=%.2f' % (env.step_count, reward))
  24. if done:
  25. print('done!')
  26. reset()
  27. else:
  28. redraw(obs)
  29. def key_handler(event):
  30. print('pressed', event.key)
  31. if event.key == 'escape':
  32. window.close()
  33. return
  34. if event.key == 'backspace':
  35. reset()
  36. return
  37. if event.key == 'left':
  38. step(env.actions.left)
  39. return
  40. if event.key == 'right':
  41. step(env.actions.right)
  42. return
  43. if event.key == 'up':
  44. step(env.actions.forward)
  45. return
  46. # Spacebar
  47. if event.key == ' ':
  48. step(env.actions.toggle)
  49. return
  50. if event.key == 'pageup':
  51. step(env.actions.pickup)
  52. return
  53. if event.key == 'pagedown':
  54. step(env.actions.drop)
  55. return
  56. if event.key == 'enter':
  57. step(env.actions.done)
  58. return
  59. parser = argparse.ArgumentParser()
  60. parser.add_argument(
  61. "--env",
  62. help="gym environment to load",
  63. default='MiniGrid-MultiRoom-N6-v0'
  64. )
  65. parser.add_argument(
  66. "--seed",
  67. type=int,
  68. help="random seed to generate the environment with",
  69. default=-1
  70. )
  71. parser.add_argument(
  72. "--tile_size",
  73. type=int,
  74. help="size at which to render tiles",
  75. default=32
  76. )
  77. parser.add_argument(
  78. '--agent_view',
  79. default=False,
  80. help="draw the agent sees (partially observable view)",
  81. action='store_true'
  82. )
  83. args = parser.parse_args()
  84. env = gym.make(args.env)
  85. if args.agent_view:
  86. env = RGBImgPartialObsWrapper(env)
  87. env = ImgObsWrapper(env)
  88. window = Window('gym_minigrid - ' + args.env)
  89. window.reg_key_handler(key_handler)
  90. reset()
  91. # Blocking event loop
  92. window.show(block=True)