Example #1
0
class LevelManager:
    """
    Load and manage levels.
    """
    def __init__(self, origin, player=None):
        """
        Takes a path to the level file and the player object to manipulate

        :param origin: *string* origin of loading
        :param player: An instance of a class that has a rect property
        """
        self.player = player
        self.levels = []
        self._current_level = -1
        self.loader = ImageLoader(origin)

    def __call__(self):
        """
        A shortcut for level_manager.current_level
        :rtype: Level
        """
        return self._get_current_level()

    def load_level(self, path):
        """
        Load a level relative to the origin

        :param path: Path to the level in list format
        """
        map_path = join(self.loader.get_path(path), "map")
        with open(map_path, 'r') as level_file:
            as_list = level_file.read().split("\n")
        separator = as_list.index("")
        config = parse_config(as_list[0:separator])
        data = LevelManager._parse_level(as_list[separator + 1:])
        tiles = self.loader.load_all(path + ["tiles"], True)
        backgrounds = self.loader.load_all(path + ["backgrounds"], True)
        animations = []
        if 'animations' in config:
            for folder, interval, x, y in config['animations']:
                surfs = self.loader.load_all_frames(path + ["animations", folder], True)
                animations.append((Animation(surfs, interval), (x, y)))
        self.levels.append(Level(config, data, tiles, player=self.player,
                                 backgrounds=backgrounds, animations=animations))

    def next_level(self):
        """
        Advance current_level
        """
        if len(self.levels) >= self._current_level + 1:
            self._current_level += 1
            return True
        return False

    def previous_level(self):
        """
        Set current_level to the previous level
        """
        if self._current_level - 1 >= 0:
            self._current_level -= 1
            return True
        return False

    def _get_current_level(self):
        """
        :rtype: Level
        """
        return self.levels[self._current_level]

    #: Current level object, set by using :func:`next_level` and :func:`previous_level`
    current_level = property(_get_current_level)

    @staticmethod
    def _parse_level(raw_level):
        level = []
        for l in raw_level:
            level.append([x for x in l.strip()])
        return level