Ejemplo n.º 1
0
    def _generate_actions_description(self, full_gdy_path):

        # load a simple griddly env with each tile printed
        loader = GriddlyLoader()

        grid = loader.load_game(full_gdy_path)

        action_mappings = grid.get_action_input_mappings()

        sphinx_string = ''

        for action_name, action_details in action_mappings.items():
            sphinx_string += f'{action_name}\n'
            sphinx_string += '^' * len(action_name) + '\n\n'

            if 'Relative' in action_details and action_details['Relative']:
                sphinx_string += ':Relative: The actions are calculated relative to the object being controlled.\n\n'
            if 'Internal' in action_details and action_details['Internal']:
                sphinx_string += ':Internal: This action can only be called from other actions, not by the player.\n\n'

            sphinx_string += f'.. list-table:: \n   :header-rows: 1\n\n'
            sphinx_string += '   * - Action Id\n     - Mapping\n'
            for action_id, details in sorted(action_details['InputMappings'].items()):
                description = details['Description'] if 'Description' in details else ''
                sphinx_string += f'   * - {action_id}\n     - {description}\n'

            sphinx_string += '\n\n'

        return sphinx_string
Ejemplo n.º 2
0
    def _generate_object_tile_images(self, objects, doc_path, game_name,
                                     gdy_file):

        # img/sokoban-wall-x.png
        tile_images = defaultdict(dict)

        # load a simple griddly env with each tile printed
        loader = GriddlyLoader()
        renderer = RenderToFile()

        level_string = ''
        for i, object in enumerate(objects):
            if 'MapCharacter' in object:
                name = object['Name']
                level_string += f'{object["MapCharacter"]} '

        for observer_type in self._observer_types:
            grid = loader.load_game(gdy_file)

            player_count = grid.get_player_count()
            tileSize = grid.get_tile_size()

            game = grid.create_game(observer_type)

            players = []
            for p in range(player_count):
                players.append(game.register_player(f'P{p}', observer_type))

            observer_type_string = self._get_observer_type_string(
                observer_type)

            game.init()
            grid.load_level_string(f'{level_string}\n')
            game.reset()
            rendered_sprite_map = np.array(game.observe(), copy=False)

            i = 0
            for object in objects:
                if 'MapCharacter' in object:
                    name = object['Name']
                    relative_image_path = os.path.join(
                        'img',
                        f'{game_name.replace(" ", "_")}-object-{observer_type_string}-{name}.png'
                    )
                    doc_image_path = os.path.join(doc_path,
                                                  relative_image_path)

                    single_sprite = rendered_sprite_map[:, i *
                                                        tileSize:i * tileSize +
                                                        tileSize, :]
                    tile_images[observer_type_string][
                        name] = relative_image_path
                    renderer.render(single_sprite, doc_image_path)
                    i += 1

            # We are creating loads of game instances. this forces the release of vulkan resources before the python GC
            game.release()

        return tile_images
Ejemplo n.º 3
0
    def __init__(self, yaml_file=None, level=0, global_observer_type=gd.ObserverType.SPRITE_2D,
                 player_observer_type=gd.ObserverType.SPRITE_2D, max_steps=None, image_path=None, shader_path=None,
                 gdy=None, game=None):
        """
        Currently only supporting a single player (player 1 as defined in the environment yaml
        :param yaml_file:
        :param level:
        :param global_observer_type: the render mode for the global renderer
        :param player_observer_type: the render mode for the players
        """

        super(GymWrapper, self).__init__()

        # Set up multiple render windows so we can see what the AIs see and what the game environment looks like
        self._renderWindow = {}

        # If we are loading a yaml file
        if yaml_file is not None:
            self._is_clone = False
            loader = GriddlyLoader(image_path, shader_path)
            self.gdy = loader.load(yaml_file)
            self.game = self.gdy.create_game(global_observer_type)

            if max_steps is not None:
                self.gdy.set_max_steps(max_steps)

            if level is not None:
                self.game.load_level(level)

        # if we are loading a copy of the game
        elif gdy is not None and game is not None:
            self._is_clone = True
            self.gdy = gdy
            self.game = game

        self._players = []
        self.player_count = self.gdy.get_player_count()

        self._global_observer_type = global_observer_type
        self._player_observer_type = []

        for p in range(self.player_count):
            self._players.append(self.game.register_player(f'Player {p + 1}', player_observer_type))
            self._player_observer_type.append(player_observer_type)

        self._player_last_observation = []
        self._global_last_observation = None

        self._enable_history = False

        self.game.init(self._is_clone)
Ejemplo n.º 4
0
    def _generate_level_data(self, game_name, num_levels, doc_path, yaml_string):

        # load a simple griddly env with each tile printed
        loader = GriddlyLoader()

        renderer = RenderToFile()

        level_images = defaultdict(dict)
        level_sizes = {}

        supported_observer_types = []

        for observer_type in self._observer_types:
            grid = loader.load_string(yaml_string)
            try:
                game = grid.create_game(observer_type)
            except ValueError as e:
                self._logger.debug(f'Skipping observer type {observer_type} for environment {game_name}')
                continue

            supported_observer_types.append(observer_type)

            players = []
            for p in range(grid.get_player_count()):
                players.append(game.register_player(f'P{p}', observer_type))

            game.init()

            for level in range(num_levels):
                observer_type_string = self._get_observer_yaml_key(observer_type)

                grid.load_level(level)
                game.reset()

                rendered_level = np.array(game.observe(), copy=False)

                relative_image_path = os.path.join('img',
                                                   f'{game_name.replace(" ", "_")}-level-{observer_type_string}-{level}.png')
                doc_image_path = os.path.join(doc_path, relative_image_path)
                renderer.render(rendered_level, doc_image_path)
                level_images[observer_type_string][level] = relative_image_path
                level_sizes[level] = {'width': grid.get_width(), 'height': grid.get_height()}

            # We are creating loads of game instances. this forces the release of vulkan resources before the python GC
            game.release()

        return level_images, level_sizes, supported_observer_types
Ejemplo n.º 5
0
    def __init__(self,
                 yaml_file,
                 level=0,
                 global_observer_type=gd.ObserverType.SPRITE_2D,
                 player_observer_type=gd.ObserverType.SPRITE_2D,
                 max_steps=None,
                 image_path=None,
                 shader_path=None):
        """
        Currently only supporting a single player (player 1 as defined in the environment yaml
        :param yaml_file:
        :param level:
        :param global_observer_type: the render mode for the global renderer
        :param player_observer_type: the render mode for the players
        """

        super(GymWrapper, self).__init__()

        # Set up multiple render windows so we can see what the AIs see and what the game environment looks like
        self._renderWindow = {}

        loader = GriddlyLoader(image_path, shader_path)

        self._grid = loader.load_game(yaml_file)
        self._grid.load_level(level)

        self._players = []
        self.player_count = self._grid.get_player_count()

        if max_steps is not None:
            self._grid.set_max_steps(max_steps)

        self.game = self._grid.create_game(global_observer_type)

        self._global_observer_type = global_observer_type
        self._player_observer_type = []

        for p in range(1, self.player_count + 1):
            self._players.append(
                self.game.register_player(f'Player {p}', player_observer_type))
            self._player_observer_type.append(player_observer_type)

        self._last_observation = {}

        self.game.init()
Ejemplo n.º 6
0
    def _generate_level_images(self, game_name, num_levels, doc_path,
                               full_gdy_path):

        # load a simple griddly env with each tile printed
        loader = GriddlyLoader()

        renderer = RenderToFile()

        level_images = defaultdict(dict)

        for observer_type in self._observer_types:
            grid = loader.load_game(full_gdy_path)
            game = grid.create_game(observer_type)

            players = []
            for p in range(grid.get_player_count()):
                players.append(game.register_player(f'P{p}', observer_type))

            game.init()

            for level in range(num_levels):

                observer_type_string = self._get_observer_type_string(
                    observer_type)

                grid.load_level(level)
                game.reset()

                rendered_level = np.array(game.observe(), copy=False)

                relative_image_path = os.path.join(
                    'img',
                    f'{game_name.replace(" ", "_")}-level-{observer_type_string}-{level}.png'
                )
                doc_image_path = os.path.join(doc_path, relative_image_path)
                renderer.render(rendered_level, doc_image_path)
                level_images[observer_type_string][level] = relative_image_path

            # We are creating loads of game instances. this forces the release of vulkan resources before the python GC
            game.release()

        return level_images
Ejemplo n.º 7
0
import sys
import os
import numpy as np

# The griddy lib is in the build directory when built so add it and then import
from griddly import gd, GriddlyLoader
from griddly.RenderTools import RenderToFile

if __name__ == '__main__':

    loader = GriddlyLoader()

    game_description = loader.load_game('resources/ztest.yaml')

    # grid = gdy_description.load_level(0)
    grid = game_description.create_level(5, 5)

    renderWindow = RenderToFile()

    for x in range(0, 5):
        for y in range(0, 5):
            grid.add_object(1, x, y, "ghost")

    for x in range(1, 4):
        for y in range(1, 4):
            grid.add_object(1, x, y, "floor")

    game = grid.create_game(gd.ObserverType.SPRITE_2D)

    # Create a player
    player1 = game.register_player('Bob', gd.ObserverType.VECTOR)
Ejemplo n.º 8
0
    def _generate_object_tile_images(self, game_description, yaml_string, doc_path, game_name):

        # img/sokoban-wall-x.png
        tile_images = defaultdict(dict)

        # load a simple griddly env with each tile printed
        loader = GriddlyLoader()
        renderer = RenderToFile()
        debug_renderer = RenderWindow(320,480)

        objects = game_description['Objects']

        level_string = ''
        for i, object in enumerate(objects):
            if 'MapCharacter' in object:
                name = object['Name']
                level_string += f'{object["MapCharacter"]} '

        supported_observer_types = []

        for observer_type in self._observer_types:
            grid = loader.load_string(yaml_string)

            player_count = grid.get_player_count()

            try:
                game = grid.create_game(observer_type)
            except ValueError as e:
                self._logger.debug(f'Skipping observer type {observer_type} for environment {game_name}')
                continue

            supported_observer_types.append(observer_type)

            players = []
            for p in range(player_count):
                players.append(game.register_player(f'P{p}', observer_type))

            observer_type_string = self._get_observer_yaml_key(observer_type)

            environment = game_description['Environment']
            if 'Observers' in environment and observer_type_string in environment['Observers']:
                observer_config = environment['Observers'][observer_type_string]
                if 'TileSize' in observer_config:
                    tileSize = observer_config['TileSize']
                    if isinstance(tileSize, int):
                        tileSize = [tileSize, tileSize]

                else:
                    tileSize = [24, 24]

                if 'TileOffsetY' in observer_config:
                    tileOffsetY = observer_config['TileOffsetY']
                else:
                    tileOffsetY = 0
            else:
                tileSize = [24, 24]

            game.init()

            if observer_type == gd.ObserverType.ISOMETRIC:
                level_string = level_string.replace(' ', '.')

            grid.load_level_string(f'{level_string}\n')
            game.reset()
            rendered_sprite_map = np.array(game.observe(), copy=False)

            i = 0
            for object in objects:
                if 'MapCharacter' in object:
                    name = object['Name']
                    relative_image_path = os.path.join('img',
                                                       f'{game_name.replace(" ", "_")}-object-{observer_type_string}-{name}.png')
                    doc_image_path = os.path.join(doc_path, relative_image_path)

                    if observer_type == gd.ObserverType.ISOMETRIC:
                        tilePosX = i * int(tileSize[0])
                        tilePosY = i * int(tileSize[1]-32)
                        single_sprite = rendered_sprite_map[
                                        :,
                                        tilePosX:tilePosX + tileSize[0],
                                        tilePosY:tilePosY + tileSize[1]
                                        ]
                        #debug_renderer.render(single_sprite)
                    else:
                        single_sprite = rendered_sprite_map[:, i * tileSize[0]:i * tileSize[0] + tileSize[0], ]
                    tile_images[observer_type_string][name] = relative_image_path
                    renderer.render(single_sprite, doc_image_path)
                    i += 1

            # We are creating loads of game instances. this forces the release of vulkan resources before the python GC
            game.release()

        return tile_images, supported_observer_types
Ejemplo n.º 9
0
from timeit import default_timer as timer
import numpy as np
import gym

from griddly import gd, GriddlyLoader
from griddly.RenderTools import VideoRecorder

if __name__ == '__main__':

    loader = GriddlyLoader()

    observer_type = gd.ObserverType.SPRITE_2D

    game_description = loader.load_game('RTS/basicRTS.yaml')

    grid = game_description.load_level(1)
    game = grid.create_game(observer_type)

    player1 = game.register_player(f'Player 1', observer_type)
    player2 = game.register_player(f'Player 2', observer_type)

    game.init()

    defined_action_count = grid.get_defined_actions_count()
    player_count = grid.get_player_count()

    start = timer()

    frames = 0

    fps_samples = []
Ejemplo n.º 10
0
import sys
import os
import numpy as np

# The griddy lib is in the build directory when built so add it and then import
from griddly import gd, GriddlyLoader
from griddly.RenderTools import RenderToFile

if __name__ == '__main__':

    loader = GriddlyLoader()

    grid = loader.load_game('resources/ztest.yaml')

    # grid = gdy_description.load_level(0)
    grid.create_level(5, 5)

    renderWindow = RenderToFile()

    for x in range(0, 5):
        for y in range(0, 5):
            grid.add_object(1, x, y, "ghost")

    for x in range(1, 4):
        for y in range(1, 4):
            grid.add_object(1, x, y, "floor")

    game = grid.create_game(gd.ObserverType.SPRITE_2D)

    # Create a player
    player1 = game.register_player('Bob', gd.ObserverType.VECTOR)
Ejemplo n.º 11
0
import numpy as np

from griddly import gd, GriddlyLoader
from griddly.RenderTools import RenderToFile

if __name__ == '__main__':

    loader = GriddlyLoader()

    game_description = loader.load_game('resources/bg_tiling.yaml')

    grid = game_description.load_level(0)

    renderWindow = RenderToFile()

    game = grid.create_game(gd.ObserverType.SPRITE_2D)

    # Create a player
    player1 = game.register_player('Bob', gd.ObserverType.VECTOR)

    game.init()

    observation = np.array(game.reset(), copy=False)

    renderWindow.render(observation, "bg_test.png")



Ejemplo n.º 12
0
import numpy as np
from timeit import default_timer as timer

from griddly import gd, GriddlyLoader
from griddly.RenderTools import RenderWindow

window = None

if __name__ == '__main__':

    renderWindow = RenderWindow(500, 500)

    loader = GriddlyLoader()

    grid = loader.load_game('RTS/basicRTS.yaml')
    grid.load_level(1)

    game = grid.create_game(gd.ObserverType.SPRITE_2D)
    action_input_mappings = grid.get_action_input_mappings()
    action_definition_count = len(action_input_mappings)

    available_action_input_mappings = {}

    action_names = []
    for k, mapping in sorted(action_input_mappings.items()):
        if not mapping['Internal']:
            available_action_input_mappings[k] = mapping
            action_names.append(k)

    # Create a player
    player1 = game.register_player('Bob', gd.ObserverType.SPRITE_2D)
Ejemplo n.º 13
0
import numpy as np
from timeit import default_timer as timer

from griddly import gd, GriddlyLoader
from griddly.RenderTools import RenderWindow

window = None

if __name__ == '__main__':

    loader = GriddlyLoader()

    grid = loader.load_game('Single-Player/Mini-Grid/minigrid-doggo.yaml')

    game = grid.create_game(gd.ObserverType.SPRITE_2D)

    # Create a player
    player1 = game.register_player('Bob', gd.ObserverType.BLOCK_2D)

    game.init()

    renderWindow = RenderWindow(700, 700)

    start = timer()

    frames = 0

    # Player objects have the same interface as gym environments
    for l in range(0, 5):
        grid.load_level(l)
        game.reset()
Ejemplo n.º 14
0
import numpy as np
from timeit import default_timer as timer

from griddly import gd, GriddlyLoader
from griddly.RenderTools import RenderWindow

window = None

if __name__ == '__main__':

    loader = GriddlyLoader()

    grid = loader.load_game('Single-Player/GVGAI/spider-nest.yaml')

    game = grid.create_game(gd.ObserverType.ISOMETRIC)

    #grid.set_max_steps(100)

    # Create a player
    player1 = game.register_player('Bob', gd.ObserverType.ISOMETRIC)

    game.init()

    renderWindow = RenderWindow(1200, 500)

    start = timer()

    frames = 0

    # Player objects have the same interface as gym environments
    for l in range(0, 5000):
Ejemplo n.º 15
0
import numpy as np

from griddly import gd, GriddlyLoader
from griddly.RenderTools import RenderToFile

if __name__ == '__main__':

    loader = GriddlyLoader()

    grid = loader.load_game('resources/bg_tiling.yaml')

    grid.load_level(0)

    renderWindow = RenderToFile()

    game = grid.create_game(gd.ObserverType.SPRITE_2D)

    # Create a player
    player1 = game.register_player('Bob', gd.ObserverType.VECTOR)

    game.init()

    observation = np.array(game.reset(), copy=False)

    renderWindow.render(observation, "bg_test.png")