def __setstate__(self, d): self.__dict__ = d #since we skipped the gvgai env, we need to create a new one. # NOTE: THIS IS SUPER-F*****G-EXPENSIVE if self.args.engine == 'GDY': from griddly import gd from griddly import GymWrapperFactory wrapper = GymWrapperFactory() if self.pics: self.observer = gd.ObserverType.SPRITE_2D else: self.observer = gd.ObserverType.VECTOR # print(self.observer) try: wrapper.build_gym_from_yaml( f'{self.game}-custom', os.path.join(self.dir_path, f'{self.game}.yaml'), level=0, global_observer_type=self.observer, player_observer_type=self.observer ) except gym.error.Error: pass else: raise ValueError("gvgai is not supported anymore. Please use Griddly.") self.__dict__['env'] = gym.make(f'{self.args.engine}-{self.game}-custom-v0')
def griddly(gdy_file): from griddly import GymWrapperFactory, gd wrapper = GymWrapperFactory() wrapper.build_gym_from_yaml("Griddly", gdy_file, player_observer_type=gd.ObserverType.SPRITE_2D, level=0) return gym.make(f'GDY-Griddly-v0')
def build_and_reset(test_name, yaml_file, global_observations=False): wrapper_factory = GymWrapperFactory() wrapper_factory.build_gym_from_yaml( test_name, yaml_file, global_observer_type=gd.ObserverType.VECTOR, player_observer_type=gd.ObserverType.VECTOR, ) env = gym.make(f'GDY-{test_name}-v0') return env.reset(global_observations=global_observations)
def make_env(name): wrapper = GymWrapperFactory() wrapper.build_gym_from_yaml(name, 'Single-Player/GVGAI/sokoban.yaml', player_observer_type=gd.ObserverType.SPRITE_2D, global_observer_type=gd.ObserverType.BLOCK_2D, level=0) env = gym.make(f'GDY-{name}-v0') env.enable_history(True) env.reset() return env
def build_test_env(test_name, yaml_file, enable_history=True): wrapper_factory = GymWrapperFactory() wrapper_factory.build_gym_from_yaml( test_name, yaml_file, global_observer_type=gd.ObserverType.VECTOR, player_observer_type=gd.ObserverType.VECTOR, ) env = gym.make(f'GDY-{test_name}-v0') env.reset() env.enable_history(enable_history) return env
def callback(env): render_window = RenderWindow(800, 800) def _callback(prev_obs, obs, action, rew, env_done, info): render_window.render(env.render(observer='global', mode="rgb_array").swapaxes(0,2)) if rew != 0: print(f'Reward: {rew}') if env_done: print(f'Done!') return _callback if __name__ == '__main__': wrapper = GymWrapperFactory() environment_name = 'GVGAI/bait_keys' # environment_name = 'Mini-Grid/minigrid-drunkdwarf' # environment_name = 'Mini-Grid/minigrid-spiders' # environment_name = 'GVGAI/clusters' # environment_name = 'GVGAI/labyrinth_partially_observable' level = 2 wrapper.build_gym_from_yaml(environment_name, f'Single-Player/{environment_name}.yaml', player_observer_type=gd.ObserverType.BLOCK_2D, global_observer_type=gd.ObserverType.SPRITE_2D, level=level, tile_size=50) env = gym.make(f'GDY-{environment_name}-v0') play(env, callback=callback(env), fps=10, zoom=3)
import gym from griddly import GymWrapperFactory, gd if __name__ == '__main__': wrapper = GymWrapperFactory() wrapper.build_gym_from_yaml( 'Sokoban-Adv', 'Single-Player/GVGAI/sokoban.yaml', player_observer_type=gd.ObserverType.SPRITE_2D, level=2 ) env = gym.make('GDY-Sokoban-Adv-v0') env.reset()
recorder.add_frame(global_obs.swapaxes(0, 2)) render_window.render(global_obs.swapaxes(0, 2)) if rew != 0: print(f'Reward: {rew}') if env_done: print(f'Done!') #recorder.close() if len(info) > 0: print(info) return _callback if __name__ == '__main__': wrapper = GymWrapperFactory() environment_name = 'TestEnv' # yaml_path = 'Single-Player/GVGAI/bait_keys.yaml' # yaml_path = 'Single-Player/Mini-Grid/minigrid-drunkdwarf.yaml' yaml_path = 'Single-Player/Mini-Grid/minigrid-spiders.yaml' # yaml_path = 'Single-Player/GVGAI/spider-nest.yaml' # yaml_path = 'Single-Player/GVGAI/cookmepasta.yaml' # yaml_path = 'Single-Player/GVGAI/clusters.yaml' # yaml_path = 'Single-Player/GVGAI/sokoban2.yaml' # yaml_path = 'Single-Player/GVGAI/labyrinth_partially_observable.yaml' # yaml_path = 'zelda.yaml' level = 0
from timeit import default_timer as timer import numpy as np import gym from griddly import GymWrapperFactory, gd from griddly.RenderTools import VideoRecorder if __name__ == '__main__': wrapper = GymWrapperFactory() name = '4rooms' wrapper.build_gym_from_yaml( name, 'Single-Player/Mini-Grid/minigrid-spiders.yaml', player_observer_type=gd.ObserverType.SPRITE_2D, global_observer_type=gd.ObserverType.SPRITE_2D, level=4) env = gym.make(f'GDY-{name}-v0') env.reset() start = timer() frames = 0 fps_samples = [] player_recorder = VideoRecorder() player_visualization = env.render(mode='rgb_array')
import gym from griddly import GymWrapperFactory from griddly.RenderTools import RenderToFile if __name__ == '__main__': # A nice tool to save png images file_renderer = RenderToFile() # This is what to use if you want to use OpenAI gym environments wrapper = GymWrapperFactory() # There are two levels here level = 0 wrapper.build_gym_from_yaml('GameOfLife', 'game-of-life.yaml', level=level) # Create the Environment env = gym.make(f'GDY-GameOfLife-v0') observation = env.reset() file_renderer.render(observation, f'sokoban-level-{level}.png')
from timeit import default_timer as timer import numpy as np import gym from griddly import GymWrapperFactory, gd from griddly.RenderTools import VideoRecorder from griddly.util.wrappers import InvalidMaskingRTSWrapper if __name__ == '__main__': wrapper = GymWrapperFactory() wrapper.build_gym_from_yaml("GriddlyRTS-Adv", 'RTS/GriddlyRTS.yaml', global_observer_type=gd.ObserverType.ISOMETRIC, player_observer_type=gd.ObserverType.ISOMETRIC, level=2) env_original = gym.make(f'GDY-GriddlyRTS-Adv-v0') # env_original = gym.make(f'GDY-GriddlyRTS-Adv-v0') env_original.reset() env = InvalidMaskingRTSWrapper(env_original) start = timer() frames = 0 fps_samples = [] player1_recorder = VideoRecorder()
import gym import numpy as np from griddly import GymWrapperFactory, gd if __name__ == '__main__': wrapper = GymWrapperFactory() wrapper.build_gym_from_yaml( "ExampleEnv", 'Single-Player/Mini-Grid/minigrid-drunkdwarf.yaml', level=0) env = gym.make('GDY-ExampleEnv-v0') env.reset() # Replace with your own control algorithm! for s in range(1000): obs, reward, done, info = env.step(env.action_space.sample()) env.render() env.render(observer='global')
def __init__(self, game=None, play_length=None, prefix='..', args_file='./args.yml', path='./levels', lvl_name='start.txt', mechanics=[], locations={}, gen_id=0, images=False, shape=(9, 13)): """Returns Grid instead of pixels Sets the reward Generates new level on reset -------- """ self.args_file = args_file self.args = load_from_yaml(args_file) self.prefix = prefix self.game = game if game is not None else self.args.game self.dir_path = path # gvgai.dir path + envs/games/zelda_v0 self.lvl_name = lvl_name self.lvl_path = os.path.join(path, lvl_name) self.mechanics = mechanics if not bool(mechanics) else self.args.mechanics if self.args.generatorType == "evolutionary": # if we do not have parsed location data on the sprites, read in a level and use that if not bool(locations): #set up first level, read it in from disk. lvl = _initialize(self.lvl_path, d=shape[0]) self.lvl_shape = lvl.shape self.generator = EvolutionaryGenerator(game=self.game, args_file=args_file, tile_world=lvl, shape=lvl.shape, path=path, mechanics=self.mechanics, generation=gen_id, locations=locations) # this condition will be used 99% of the time. else: # use generated lvl contained within locations dict. self.lvl_shape = shape self.generator = EvolutionaryGenerator(game=self.game, args_file=args_file, tile_world=None, shape=shape, path=path, mechanics=self.mechanics, generation=gen_id, locations=locations) # save to disk, can comment out if that lets me multithread. # self.generator.to_file(GridGame.env_count, self.game) elif self.args.generatorType == "illuminating": self.generator = IlluminatingGenerator(shape=shape, args_file=args_file, path=path, generation=gen_id, run_folder=prefix) # return picture states? self.pics = images if self.args.engine == 'GDY': from griddly import gd from griddly import GymWrapperFactory wrapper = GymWrapperFactory() if self.pics: self.observer = gd.ObserverType.SPRITE_2D else: self.observer = gd.ObserverType.VECTOR print(self.observer) try: wrapper.build_gym_from_yaml( f'{game}-custom', os.path.join(self.dir_path, f'{self.game}.yaml'), level=0, global_observer_type=self.observer, player_observer_type=self.observer ) except gym.error.Error: pass else: raise ValueError("gvgai is not supported anymore. Please use Griddly.") self.env = gym.make(f"{self.args.engine}-{game}-custom-v0") _ = self.env.reset() # count the number of distinct discrete actions # subtract the zero sub-action from each unique action # add back in a zero action at the end # THIS ASSUMES ACTION SPACES ARE DISCRETE actionType = self.env.action_space if type(actionType) == MultiDiscrete: self.nActions = 1 for d in actionType.nvec: self.nActions += (d - 1) elif type(actionType) == Discrete: self.nActions = actionType.n else: raise ValueError(f"Unsupported action type in game: {self.game}. " f"Only Discrete and MultiDiscrete are supported") self.env.enable_history(True) # update static count of number of all envs self.id = GridGame.env_count GridGame.env_count += 1 self.depth = None # gets set in self.reset() # env must exist to reset self.win = False self.steps = 0 self.score = 0 self.play_length = play_length if play_length is not None else self.args.game_len self.info_list = [] self.reset() self.orientation = np.eye(4, dtype=int) self.prev_move = 4 self.rotating_actions = [1, 2, 3, 4]
import gym from griddly import GymWrapperFactory, gd from griddly.RenderTools import RenderToFile if __name__ == '__main__': # A nice tool to save png images file_renderer = RenderToFile() # This is what to use if you want to use OpenAI gym environments wrapper = GymWrapperFactory() # There are two levels here level = 1 wrapper.build_gym_from_yaml('Sokoban', 'tutorials/sokoban.yaml', player_observer_type=gd.ObserverType.BLOCK_2D, level=level) # Create the Environment env = gym.make(f'GDY-Sokoban-v0') observation = env.reset() file_renderer.render(observation, f'sokoban-level-{level}.png')
fig.canvas.draw() X = np.array(fig.canvas.renderer.buffer_rgba()) Image.fromarray(X) rgb_image = np.array(Image.fromarray(X).convert('RGB')) plt.close(fig) q_value_rgb_array = rgb_image return np.append(env_rgb_array, q_value_rgb_array, axis=1) else: super().render(mode) # TRY NOT TO MODIFY: setup the environment griddly_gdy_filename = args.griddly_gdy_file griddly_level = args.griddly_level wrapper = GymWrapperFactory() name = os.path.basename(griddly_gdy_filename).replace('.yaml', '') env_name = f'Griddly-{name}-{griddly_level}' experiment_name = f"{env_name}__{args.exp_name}__{args.seed}__{int(time.time())}" writer = SummaryWriter(f"runs/{experiment_name}") writer.add_text( 'hyperparameters', "|param|value|\n|-|-|\n%s" % ('\n'.join([f"|{key}|{value}|" for key, value in vars(args).items()]))) if args.prod_mode: import wandb wandb.init(project=args.wandb_project_name, entity=args.wandb_entity, sync_tensorboard=True, config=vars(args),
from timeit import default_timer as timer import numpy as np import gym from griddly import GymWrapperFactory, gd from griddly.RenderTools import VideoRecorder if __name__ == '__main__': wrapper = GymWrapperFactory() wrapper.build_gym_from_yaml("BWDistantResources32x32", 'RTS/BWDistantResources32x32.yaml', player_observer_type=gd.ObserverType.SPRITE_2D, level=0) env = gym.make(f'GDY-BWDistantResources32x32-v0') env.reset() start = timer() frames = 0 fps_samples = [] observation_shape = env.observation_space.shape player1_recorder = VideoRecorder() player1_recorder.start("player1_video_test.mp4", observation_shape) player2_recorder = VideoRecorder()