def load(self):
		"""Load selected scenario and show strings"""
		if self.listbox.selected == -1:
			self._gui.findChild(name="hintlbl").text = u"Select a scenario first."
		else:
			self._gui.findChild(name="hintlbl").text = u""

			# remember current entry
			cur_entry = self.logbook.get_cur_entry()
			cur_entry = cur_entry if cur_entry is not None else 0
			self.logbook.clear()

			# get logbook actions from scenario file and add them to our logbook
			scenario_file_path = self.scenarios[0][self.listbox.selected]
			data = YamlCache.load_yaml_data(open(scenario_file_path, 'r'))
			events = data['events']
			for event in events:
				for action in event['actions']:
					if action['type'] in ('logbook', 'logbook'):
						self.logbook.add_captainslog_entry(action['arguments'], show_logbook=False)

			try:
				self.logbook.set_cur_entry(cur_entry)
			except ValueError:
				pass # no entries
			self.logbook._redraw_captainslog()
			self.logbook.show()
Ejemplo n.º 2
0
	def update_infos(self):
		"""Updates the status label while scrolling the scenario list. No up-
		date to logbook messages. Those are loaded after Load/Reload is clicked.
		"""
		scenario_file_path = self.scenarios[0][self.listbox.selected]
		data = YamlCache.load_yaml_data(open(scenario_file_path, 'r'))
		stats = data.get('translation_status', '') # no stats available => empty label
		self.statslabel.text = unicode(stats)
	def update_infos(self):
		"""Updates the status label while scrolling the scenario list. No up-
		date to logbook messages. Those are loaded after Load/Reload is clicked.
		"""
		scenario_file_path = self.scenarios[0][self.listbox.selected]
		data = YamlCache.load_yaml_data(open(scenario_file_path, 'r'))
		try:
			stats = data['translation_status']
		except KeyError as err:
			stats = '' # no translation stats available, display empty label
		self.statslabel.text = unicode(stats)
Ejemplo n.º 4
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])
		return data
Ejemplo n.º 5
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 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]
Ejemplo n.º 6
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
Ejemplo n.º 7
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_increment
                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
Ejemplo n.º 8
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)
Ejemplo n.º 9
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 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]
	def _parse_yaml_file(cls, filename):
		return YamlCache.get_file(filename, game_data=True)
	def _parse_yaml(string_or_stream):
		try:
			return YamlCache.load_yaml_data(string_or_stream)
		except Exception as e: # catch anything yaml or functions that yaml calls might throw
			raise InvalidScenarioFileFormat(str(e))
Ejemplo n.º 12
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 {}
Ejemplo n.º 13
0
	def _parse_yaml_file(cls, filename):
		return YamlCache.get_file(filename)