gotoobject.py 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. from gym_minigrid.minigrid import *
  2. from gym_minigrid.register import register
  3. class GoToObjectEnv(MiniGridEnv):
  4. """
  5. Environment in which the agent is instructed to go to a given object
  6. named using an English text string
  7. """
  8. def __init__(
  9. self,
  10. size=6,
  11. numObjs=2
  12. ):
  13. self.numObjs = numObjs
  14. super().__init__(gridSize=size, maxSteps=5*size)
  15. self.reward_range = (0, 1)
  16. def _genGrid(self, width, height):
  17. self.grid = Grid(width, height)
  18. # Generate the surrounding walls
  19. self.grid.horzWall(0, 0)
  20. self.grid.horzWall(0, height-1)
  21. self.grid.vertWall(0, 0)
  22. self.grid.vertWall(width-1, 0)
  23. # Types and colors of objects we can generate
  24. types = ['key', 'ball', 'box']
  25. objs = []
  26. objPos = []
  27. # Until we have generated all the objects
  28. while len(objs) < self.numObjs:
  29. objType = self._randElem(types)
  30. objColor = self._randElem(COLOR_NAMES)
  31. # If this object already exists, try again
  32. if (objType, objColor) in objs:
  33. continue
  34. if objType == 'key':
  35. obj = Key(objColor)
  36. elif objType == 'ball':
  37. obj = Ball(objColor)
  38. elif objType == 'box':
  39. obj = Box(objColor)
  40. pos = self.placeObj(obj)
  41. objs.append((objType, objColor))
  42. objPos.append(pos)
  43. # Randomize the player start position and orientation
  44. self.placeAgent()
  45. # Choose a random object to be picked up
  46. objIdx = self._randInt(0, len(objs))
  47. self.targetType, self.targetColor = objs[objIdx]
  48. self.targetPos = objPos[objIdx]
  49. descStr = '%s %s' % (self.targetColor, self.targetType)
  50. self.mission = 'go to the %s' % descStr
  51. #print(self.mission)
  52. def step(self, action):
  53. obs, reward, done, info = MiniGridEnv.step(self, action)
  54. ax, ay = self.agentPos
  55. tx, ty = self.targetPos
  56. # Toggle/pickup action terminates the episode
  57. if action == self.actions.toggle:
  58. done = True
  59. # Reward performing the wait action next to the target object
  60. if action == self.actions.wait:
  61. if abs(ax - tx) <= 1 and abs(ay - ty) <= 1:
  62. reward = 1
  63. done = True
  64. return obs, reward, done, info
  65. class GotoEnv8x8N2(GoToObjectEnv):
  66. def __init__(self):
  67. super().__init__(size=8, numObjs=2)
  68. register(
  69. id='MiniGrid-GoToObject-6x6-N2-v0',
  70. entry_point='gym_minigrid.envs:GoToObjectEnv'
  71. )
  72. register(
  73. id='MiniGrid-GoToObject-8x8-N2-v0',
  74. entry_point='gym_minigrid.envs:GotoEnv8x8N2'
  75. )