gotoobject.py 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  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.wallRect(0, 0, width, height)
  20. # Types and colors of objects we can generate
  21. types = ['key', 'ball', 'box']
  22. objs = []
  23. objPos = []
  24. # Until we have generated all the objects
  25. while len(objs) < self.numObjs:
  26. objType = self._randElem(types)
  27. objColor = self._randElem(COLOR_NAMES)
  28. # If this object already exists, try again
  29. if (objType, objColor) in objs:
  30. continue
  31. if objType == 'key':
  32. obj = Key(objColor)
  33. elif objType == 'ball':
  34. obj = Ball(objColor)
  35. elif objType == 'box':
  36. obj = Box(objColor)
  37. pos = self.placeObj(obj)
  38. objs.append((objType, objColor))
  39. objPos.append(pos)
  40. # Randomize the player start position and orientation
  41. self.placeAgent()
  42. # Choose a random object to be picked up
  43. objIdx = self._randInt(0, len(objs))
  44. self.targetType, self.targetColor = objs[objIdx]
  45. self.targetPos = objPos[objIdx]
  46. descStr = '%s %s' % (self.targetColor, self.targetType)
  47. self.mission = 'go to the %s' % descStr
  48. #print(self.mission)
  49. def step(self, action):
  50. obs, reward, done, info = MiniGridEnv.step(self, action)
  51. ax, ay = self.agentPos
  52. tx, ty = self.targetPos
  53. # Toggle/pickup action terminates the episode
  54. if action == self.actions.toggle:
  55. done = True
  56. # Reward performing the wait action next to the target object
  57. if action == self.actions.wait:
  58. if abs(ax - tx) <= 1 and abs(ay - ty) <= 1:
  59. reward = 1
  60. done = True
  61. return obs, reward, done, info
  62. class GotoEnv8x8N2(GoToObjectEnv):
  63. def __init__(self):
  64. super().__init__(size=8, numObjs=2)
  65. register(
  66. id='MiniGrid-GoToObject-6x6-N2-v0',
  67. entry_point='gym_minigrid.envs:GoToObjectEnv'
  68. )
  69. register(
  70. id='MiniGrid-GoToObject-8x8-N2-v0',
  71. entry_point='gym_minigrid.envs:GotoEnv8x8N2'
  72. )