run_tests.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. #!/usr/bin/env python3
  2. import random
  3. import numpy as np
  4. import gym
  5. from gym_minigrid.register import env_list
  6. from gym_minigrid.minigrid import Grid
  7. # Test specifically importing a specific environment
  8. from gym_minigrid.envs import DoorKeyEnv
  9. # Test importing wrappers
  10. from gym_minigrid.wrappers import *
  11. ##############################################################################
  12. print('%d environments registered' % len(env_list))
  13. for envName in env_list:
  14. print('testing "%s"' % envName)
  15. # Load the gym environment
  16. env = gym.make(envName)
  17. env.reset()
  18. env.render('rgb_array')
  19. # Verify that the same seed always produces the same environment
  20. for i in range(0, 5):
  21. seed = 1337 + i
  22. env.seed(seed)
  23. grid1 = env.grid
  24. env.seed(seed)
  25. grid2 = env.grid
  26. assert grid1 == grid2
  27. env.reset()
  28. # Run for a few episodes
  29. num_episodes = 0
  30. while num_episodes < 5:
  31. # Pick a random action
  32. action = random.randint(0, env.action_space.n - 1)
  33. obs, reward, done, info = env.step(action)
  34. # Test observation encode/decode roundtrip
  35. img = obs['image']
  36. grid = Grid.decode(img)
  37. img2 = grid.encode()
  38. assert np.array_equal(img, img2)
  39. # Check that the reward is within the specified range
  40. assert reward >= env.reward_range[0], reward
  41. assert reward <= env.reward_range[1], reward
  42. if done:
  43. num_episodes += 1
  44. env.reset()
  45. env.render('rgb_array')
  46. env.close()
  47. ##############################################################################
  48. print('testing agent_sees method')
  49. env = gym.make('MiniGrid-DoorKey-6x6-v0')
  50. goal_pos = (env.grid.width - 2, env.grid.height - 2)
  51. # Test the "in" operator on grid objects
  52. assert ('green', 'goal') in env.grid
  53. assert ('blue', 'key') not in env.grid
  54. # Test the env.agent_sees() function
  55. env.reset()
  56. for i in range(0, 500):
  57. action = random.randint(0, env.action_space.n - 1)
  58. obs, reward, done, info = env.step(action)
  59. goal_visible = ('green', 'goal') in Grid.decode(obs['image'])
  60. agent_sees_goal = env.agent_sees(*goal_pos)
  61. assert agent_sees_goal == goal_visible
  62. if done:
  63. env.reset()