コード例 #1
0
    def load_buildings(cls, db, load_now=False):
        cls.log.debug("Entities: loading buildings")
        if hasattr(cls, 'buildings'):
            cls.log.debug("Entities: buildings already loaded")
            return
        cls.buildings = _EntitiesLazyDict()
        from horizons.world.building import BuildingClass
        for root, dirnames, filenames in os.walk('content/objects/buildings'):
            for filename in fnmatch.filter(filenames, '*.yaml'):
                cls.log.debug("Loading: " + filename)
                # This is needed for dict lookups! Do not convert to os.join!
                full_file = root + "/" + filename
                result = YamlCache.get_file(full_file, game_data=True)
                if result is None:  # discard empty yaml files
                    print("Empty yaml file {file} found, not loading!".format(
                        file=full_file))
                    continue

                result['yaml_file'] = full_file

                building_id = int(result['id'])
                cls.buildings.create_on_access(
                    building_id,
                    Callback(BuildingClass,
                             db=db,
                             id=building_id,
                             yaml_data=result))
                # NOTE: The current system now requires all building data to be loaded
                if load_now or True:
                    cls.buildings[building_id]
コード例 #2
0
 def _find_map_filename(self, cur_locale, mapfile=None):
     """Finds the given map's filename with its locale."""
     mapfile = mapfile or self._get_selected_map()
     if mapfile.endswith('.yaml'):
         yamldata = YamlCache.get_file(mapfile, game_data=True)
         split_locale = yamldata['locale']
         mapfile = mapfile.split('_' + split_locale)[0]
     return mapfile + '_' + cur_locale + '.' + SavegameManager.scenario_extension
コード例 #3
0
	def _find_map_filename(self, cur_locale, mapfile=None):
		"""Finds the given map's filename with its locale."""
		mapfile = mapfile or self._get_selected_map()
		if mapfile.endswith('.yaml'):
			yamldata = YamlCache.get_file(mapfile, game_data=True)
			split_locale = yamldata['locale']
			mapfile = mapfile.split('_' + split_locale)[0]
		return mapfile + '_' + cur_locale + '.' + SavegameManager.scenario_extension
コード例 #4
0
	def _loadBuildings(self):
		print("loading UH buildings...")
		for root, dirnames, filenames in os.walk(util.getUHPath() + '/content/objects/buildings'):
			for filename in fnmatch.filter(filenames, '*.yaml'):
				# This is needed for dict lookups! Do not convert to os.join!
				full_file = root + "/" + filename
				result = YamlCache.get_file(full_file)
				result['yaml_file'] = full_file
				self._loadBuilding(result)

		print("finished loading UH objects")
コード例 #5
0
	def _update_scenario_translation_infos(self, new_map_name):
		"""Fill in translation infos of selected scenario to translation label.
		This function also sets scenario map name using locale.
		(e.g. tutorial -> tutorial_en.yaml)"""
		translation_status_label = self.current.findChild(name="translation_status")
		yamldata = YamlCache.get_file(new_map_name, game_data=True)
		translation_status = yamldata.get('translation_status')
		if translation_status:
			translation_status_label.text = translation_status
			translation_status_label.show()
		else:
			translation_status_label.hide()
		self.current.files[ self.active_right_side.collectData('maplist') ] = new_map_name
コード例 #6
0
	def _update_scenario_translation_infos(self, new_map_name):
		"""Fill in translation infos of selected scenario to translation label.
		This function also sets scenario map name using locale.
		(e.g. tutorial -> tutorial_en.yaml)"""
		translation_status_label = self.current.findChild(name="translation_status")
		yamldata = YamlCache.get_file(new_map_name, game_data=True)
		translation_status = yamldata.get('translation_status')
		if translation_status:
			translation_status_label.text = translation_status
			translation_status_label.show()
		else:
			translation_status_label.hide()
		self.current.files[ self.active_right_side.collectData('maplist') ] = new_map_name
コード例 #7
0
	def get_scenario_info(cls, name="", filename=""):
		"""Return this scenario data"""
		sfiles, snames = cls.get_scenarios(include_displaynames = True)
		if name:
			if not name in snames:
				print "Error: Cannot find scenario '{name}'.".format(name=name)
				return {}
			index = snames.index(name)
		elif filename:
			if not filename in sfiles:
				print "Error: Cannot find scenario '{name}'.".format(name=filename)
				return {}
			index = sfiles.index(filename)
		data = YamlCache.get_file(sfiles[index], game_data=True)
		return data
コード例 #8
0
ファイル: entities.py プロジェクト: STEVEOO6/unknown-horizons
	def load_units(cls, load_now=False):
		cls.log.debug("Entities: loading units")
		if hasattr(cls, 'units'):
			cls.log.debug("Entities: units already loaded")
			return
		cls.units = _EntitiesLazyDict()

		from horizons.world.units import UnitClass
		for root, dirnames, filenames in os.walk('content/objects/units'):
			for filename in fnmatch.filter(filenames, '*.yaml'):
				full_file = os.path.join(root, filename)
				result = YamlCache.get_file(full_file, game_data=True)
				unit_id = int(result['id'])
				cls.units.create_on_access(unit_id, Callback(UnitClass, id=unit_id, yaml_data=result))
				if load_now:
					cls.units[unit_id]
コード例 #9
0
 def get_scenario_info(cls, name="", filename=""):
     """Return this scenario data"""
     sfiles, snames = cls.get_scenarios(include_displaynames=True)
     if name:
         if not name in snames:
             print "Error: Cannot find scenario '{name}'.".format(name=name)
             return {}
         index = snames.index(name)
     elif filename:
         if not filename in sfiles:
             print "Error: Cannot find scenario '{name}'.".format(
                 name=filename)
             return {}
         index = sfiles.index(filename)
     data = YamlCache.get_file(sfiles[index], game_data=True)
     return data
コード例 #10
0
	def load_units(cls, load_now=False):
		cls.log.debug("Entities: loading units")
		if hasattr(cls, 'units'):
			cls.log.debug("Entities: units already loaded")
			return
		cls.units = _EntitiesLazyDict()

		from horizons.world.units import UnitClass
		for root, dirnames, filenames in os.walk('content/objects/units'):
			for filename in fnmatch.filter(filenames, '*.yaml'):
				full_file = os.path.join(root, filename)
				result = YamlCache.get_file(full_file, game_data=True)
				unit_id = int(result['id'])
				cls.units.create_on_access(unit_id, Callback(UnitClass, id=unit_id, yaml_data=result))
				if load_now:
					cls.units[unit_id]
コード例 #11
0
	def get_scenario_metadata(cls, scenario="", filename=""):
		"""Return the `metadata` dict for a scenario.

		Pass either the scenario name (*scenario*) or a .yaml *filename*.
		"""
		sfiles, snames = cls.get_scenarios(include_displaynames=True)
		if scenario:
			if scenario not in snames:
				cls.log.error("Error: Cannot find scenario '{name}'.".format(name=scenario))
				return {}
			index = snames.index(scenario)
		elif filename:
			if filename not in sfiles:
				cls.log.error("Error: Cannot find scenario '{name}'.".format(name=filename))
				return {}
			index = sfiles.index(filename)
		data = YamlCache.get_file(sfiles[index], game_data=True)
		return data.get('metadata', {})
コード例 #12
0
	def get_building_tiers(cls):
		"""Returns a dictionary mapping building type ids to their tiers
		@return cached dictionary (don't modifiy)"""
		building_tiers = {}
		data = YamlCache.get_file( cls.build_menu_config_per_tier, game_data=True )
		tier = -1
		for tab, tabdata in sorted(data.iteritems()):
			if tab == "meta":
				continue # not a tab

			tier += 1

			for row in tabdata:
				if isinstance(row, list): # actual content
					for entry in row:
						if isinstance(entry, int): # actual building button
							building_tiers[entry] = tier
		return building_tiers
コード例 #13
0
	def get_building_increments(cls):
		"""Returns a dictionary mapping building type ids to their increments
		@return cached dictionary (don't modifiy)"""
		building_increments = {}
		data = YamlCache.get_file( cls.build_menu_config_per_increment, game_data=True )
		increment = -1
		for tab, tabdata in sorted(data.iteritems()):
			if tab == "meta":
				continue # not a tab

			increment += 1

			for row in tabdata:
				if isinstance(row, list): # actual content
					for entry in row:
						if isinstance(entry, int): # actual building button
							building_increments[entry] = increment
		return building_increments
コード例 #14
0
    def create_tabs(cls, session, build_callback):
        """Create according to current build menu config
		@param build_callback: function to call to enable build mode, has to take building type parameter
		"""
        source = cls.get_saved_buildstyle()
        # parse
        data = YamlCache.get_file(source, game_data=True)
        if 'meta' not in data:
            raise InvalidBuildMenuFileFormat(
                'File does not contain "meta" section')
        metadata = data['meta']
        if 'unlocking_strategy' not in metadata:
            raise InvalidBuildMenuFileFormat(
                '"meta" section does not contain "unlocking_strategy"')
        try:
            unlocking_strategy = cls.unlocking_strategies.get_item_for_string(
                metadata['unlocking_strategy'])
        except KeyError:
            raise InvalidBuildMenuFileFormat(
                'Invalid entry for "unlocking_strategy"')

        # create tab instances
        tabs = []
        for tab, tabdata in sorted(data.items()):
            if tab == "meta":
                continue  # not a tab

            if unlocking_strategy == cls.unlocking_strategies.tab_per_tier and len(
                    tabs) > session.world.player.settler_level:
                break

            try:
                tab = BuildTab(session, len(tabs), tabdata, build_callback,
                               unlocking_strategy, source)
                tabs.append(tab)
            except Exception as e:
                to_add = "\nThis error happened in {} of {} .".format(
                    tab, source)
                e.args = (e.args[0] + to_add, ) + e.args[1:]
                e.message = (e.message + to_add)
                raise

        return tabs
コード例 #15
0
    def create_tabs(cls, session, build_callback):
        """Create according to current build menu config
		@param build_callback: function to call to enable build mode, has to take building type parameter
		"""
        source = cls.cur_build_menu_config

        # parse
        data = YamlCache.get_file(source, game_data=True)
        if "meta" not in data:
            raise InvalidBuildMenuFileFormat('File does not contain "meta" section')
        metadata = data["meta"]
        if "unlocking_strategy" not in metadata:
            raise InvalidBuildMenuFileFormat('"meta" section does not contain "unlocking_strategy"')
        try:
            unlocking_strategy = cls.unlocking_strategies.get_item_for_string(metadata["unlocking_strategy"])
        except KeyError:
            raise InvalidBuildMenuFileFormat('Invalid entry for "unlocking_strategy"')

            # create tab instances
        tabs = []
        for tab, tabdata in sorted(data.iteritems()):
            if tab == "meta":
                continue  # not a tab

            if (
                unlocking_strategy == cls.unlocking_strategies.tab_per_tier
                and len(tabs) > session.world.player.settler_level
            ):
                break

            try:
                tab = BuildTab(session, len(tabs), tabdata, build_callback, unlocking_strategy, source)
                tabs.append(tab)
            except Exception as e:
                to_add = "\nThis error happened in %s of %s ." % (tab, source)
                e.args = (e.args[0] + to_add,) + e.args[1:]
                e.message = e.message + to_add
                raise

        return tabs
コード例 #16
0
	def get_campaigns(cls, include_displaynames=True, include_scenario_list=False, campaign_data=False):
		"""Returns all campaigns
		@param include_displaynames: should we return the name of the campaign
		@param include_scenario_list: should we return the list of scenarios in the campaign
		@param campaign_data: should we return the full campaign data
		@return: (campaign_files, campaign_names, campaign_scenarios, campaign_data) (depending of the parameters)
		"""
		cls.log.debug("Savegamemanager: campaigns from: %s", cls.campaigns_dir)
		files, names = cls.__get_saves_from_dirs([cls.campaigns_dir], include_displaynames, cls.campaign_extension, False)
		if not include_displaynames:
			return (files,)
		if not include_scenario_list:
			return (files, names)
		scenarios_lists = []
		campaign_datas = []
		for i, f in enumerate(files):
			campaign = YamlCache.get_file(f)
			campaign_datas.append(campaign)
			scenarios_lists.append([sc.get('level') for sc in campaign.get('scenarios',[])])
		if not campaign_data:
			return (files, names, scenarios_lists)
		return (files, names, scenarios_lists, campaign_datas)
コード例 #17
0
ファイル: entities.py プロジェクト: STEVEOO6/unknown-horizons
	def load_buildings(cls, db, load_now=False):
		cls.log.debug("Entities: loading buildings")
		if hasattr(cls, 'buildings'):
			cls.log.debug("Entities: buildings already loaded")
			return
		cls.buildings = _EntitiesLazyDict()
		from horizons.world.building import BuildingClass
		for root, dirnames, filenames in os.walk('content/objects/buildings'):
			for filename in fnmatch.filter(filenames, '*.yaml'):
				cls.log.debug("Loading: " + filename)
				# This is needed for dict lookups! Do not convert to os.join!
				full_file = root + "/" + filename
				result = YamlCache.get_file(full_file, game_data=True)
				if result is None: # discard empty yaml files
					print "Empty yaml file {file} found, not loading!".format(file=full_file)
					continue

				result['yaml_file'] = full_file

				building_id = int(result['id'])
				cls.buildings.create_on_access(building_id, Callback(BuildingClass, db=db, id=building_id, yaml_data=result))
				# NOTE: The current system now requires all building data to be loaded
				if load_now or True:
					cls.buildings[building_id]
コード例 #18
0
	def _parse_yaml_file(cls, filename):
		return YamlCache.get_file(filename, game_data=True)
コード例 #19
0
 def _parse_yaml_file(cls, filename):
     return YamlCache.get_file(filename, game_data=True)
コード例 #20
0
	def get_campaign_status(cls):
		"""Read the campaign status from the saved YAML file"""
		if os.path.exists(cls.campaign_status_file):
			return YamlCache.get_file(cls.campaign_status_file)
		return {}