当前位置: 首页>>代码示例>>Python>>正文


Python scenario.ScenarioEventHandler类代码示例

本文整理汇总了Python中horizons.scenario.ScenarioEventHandler的典型用法代码示例。如果您正苦于以下问题:Python ScenarioEventHandler类的具体用法?Python ScenarioEventHandler怎么用?Python ScenarioEventHandler使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了ScenarioEventHandler类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: _update_infos

					def _update_infos():
						"""Fill in infos of selected scenario to label"""
						try:
							difficulty = ScenarioEventHandler.get_difficulty_from_file( self.__get_selected_map() )
							desc = ScenarioEventHandler.get_description_from_file( self.__get_selected_map() )
							author = ScenarioEventHandler.get_author_from_file( self.__get_selected_map() )
						except InvalidScenarioFileFormat, e:
							self.__show_invalid_scenario_file_popup(e)
							return
开发者ID:court-jus,项目名称:unknown-horizons,代码行数:9,代码来源:singleplayermenu.py

示例2: _update_infos

					def _update_infos():
						"""Fill in infos of selected scenario to label"""
						try:
							difficulty = ScenarioEventHandler.get_difficulty_from_file( self._get_selected_map() )
							desc = ScenarioEventHandler.get_description_from_file( self._get_selected_map() )
							author = ScenarioEventHandler.get_author_from_file( self._get_selected_map() )
						except InvalidScenarioFileFormat as e:
							self._show_invalid_scenario_file_popup(e)
							return
						self.current.findChild(name="map_difficulty").text = \
							_("Difficulty: {difficulty}").format(difficulty=difficulty) #xgettext:python-format
						self.current.findChild(name="map_author").text = \
							_("Author: {author}").format(author=author) #xgettext:python-format
						self.current.findChild(name="map_desc").text = \
							_("Description: {desc}").format(desc=desc) #xgettext:python-format
开发者ID:perher,项目名称:unknown-horizons,代码行数:15,代码来源:singleplayermenu.py

示例3: __init__

	def __init__(self, db, rng_seed=None, ingame_gui_class=IngameGui):
		super(Session, self).__init__()
		assert isinstance(db, horizons.util.uhdbaccessor.UhDbAccessor)
		self.log.debug("Initing session")
		self.db = db # main db for game data (game.sql)
		# this saves how often the current game has been saved
		self.savecounter = 0
		self.is_alive = True

		self._clear_caches()

		#game
		self.random = self.create_rng(rng_seed)
		assert isinstance(self.random, Random)
		self.timer = self.create_timer()
		Scheduler.create_instance(self.timer)
		self.manager = self.create_manager()
		self.view = View()
		Entities.load(self.db)
		self.scenario_eventhandler = ScenarioEventHandler(self) # dummy handler with no events

		#GUI
		self._ingame_gui_class = ingame_gui_class

		self.selected_instances = set()
		# List of sets that holds the player assigned unit groups.
		self.selection_groups = [set()] * 10

		self._old_autosave_interval = None
开发者ID:Octavianuspg,项目名称:unknown-horizons,代码行数:29,代码来源:session.py

示例4: __init__

	def __init__(self, gui, db):
		super(Session, self).__init__()
		self.log.debug("Initing session")
		self.gui = gui # main gui, not ingame gui
		self.db = db # main db for game data (game.sqlite)
		# this saves how often the current game has been saved
		self.savecounter = 0
		self.is_alive = True

		WorldObject.reset()
		NamedObject.reset()

		#game
		self.random = self.create_rng()
		self.timer = Timer()
		Scheduler.create_instance(self.timer)
		self.manager = self.create_manager()
		self.view = View(self, (15, 15))
		Entities.load(self.db)
		self.scenario_eventhandler = ScenarioEventHandler(self) # dummy handler with no events
		self.campaign = {}

		#GUI
		self.gui.session = self
		self.ingame_gui = IngameGui(self, self.gui)
		self.keylistener = IngameKeyListener(self)
		self.display_speed()

		self.selected_instances = set()
		self.selection_groups = [set()] * 10 # List of sets that holds the player assigned unit groups.
开发者ID:court-jus,项目名称:unknown-horizons,代码行数:30,代码来源:session.py

示例5: load

	def load(self, savegame, players, is_scenario=False, campaign={}):
		"""Loads a map.
		@param savegame: path to the savegame database.
		@param players: iterable of dictionaries containing id, name, color and local
		@param is_scenario: Bool whether the loaded map is a scenario or not
		"""
		if is_scenario:
			# savegame is a yaml file, that contains reference to actual map file
			self.scenario_eventhandler = ScenarioEventHandler(self, savegame)
			savegame = os.path.join(SavegameManager.maps_dir, \
			                        self.scenario_eventhandler.get_map_file())
		self.campaign = campaign

		self.log.debug("Session: Loading from %s", savegame)
		savegame_db = SavegameAccessor(savegame) # Initialize new dbreader
		try:
			# load how often the game has been saved (used to know the difference between
			# a loaded and a new game)
			self.savecounter = SavegameManager.get_metadata(savegame)['savecounter']
		except KeyError:
			self.savecounter = 0

		self.world = World(self) # Load horizons.world module (check horizons/world/__init__.py)
		self.world._init(savegame_db)
		self.view.load(savegame_db) # load view
		if not self.is_game_loaded():
			# NOTE: this must be sorted before iteration, cause there is no defined order for
			#       iterating a dict, and it must happen in the same order for mp games.
			for i in sorted(players):
				self.world.setup_player(i['id'], i['name'], i['color'], i['local'])
			center = self.world.init_new_world()
			self.view.center(center[0], center[1])
		else:
			# try to load scenario data
			self.scenario_eventhandler.load(savegame_db)
		self.manager.load(savegame_db) # load the manager (there might me old scheduled ticks).
		self.ingame_gui.load(savegame_db) # load the old gui positions and stuff

		for instance_id in savegame_db("SELECT id FROM selected WHERE `group` IS NULL"): # Set old selected instance
			obj = WorldObject.get_object_by_id(instance_id[0])
			self.selected_instances.add(obj)
			obj.select()
		for group in xrange(len(self.selection_groups)): # load user defined unit groups
			for instance_id in savegame_db("SELECT id FROM selected WHERE `group` = ?", group):
				self.selection_groups[group].add(WorldObject.get_object_by_id(instance_id[0]))

		# cursor has to be inited last, else player interacts with a not inited world with it.
		self.cursor = SelectionTool(self)
		self.cursor.apply_select() # Set cursor correctly, menus might need to be opened.

		assert hasattr(self.world, "player"), 'Error: there is no human player'
		"""
开发者ID:court-jus,项目名称:unknown-horizons,代码行数:52,代码来源:session.py

示例6: _update_infos

	def _update_infos(self):
		"""Fill in infos of selected scenario to label"""
		lang_list = self._gui.findChild(name="uni_langlist")
		cur_selected_language = lang_list.selected_item
		lang_list.items = self._get_available_languages()
		if cur_selected_language in lang_list.items:
			lang_list.selected = lang_list.items.index(cur_selected_language)
		else:
			lang_list.selected = 0

		cur_locale = LANGUAGENAMES.get_by_value(lang_list.selected_item)
		translated_scenario = self._find_map_filename(cur_locale)
		if os.path.exists(translated_scenario):
			self._update_scenario_translation_infos(translated_scenario)
		else:
			try:
				default_locale, default_encoding = locale.getdefaultlocale()
			except ValueError: # OS X sometimes returns 'UTF-8' as locale, which is a ValueError
				default_locale = 'en'

			possibilities = [ # try to find a file for the system locale before falling back to en
				default_locale,
				default_locale.split('_')[0],
				'en',
			]

			lang_list.selected = 0
			for lang in possibilities:
				if LANGUAGENAMES[lang] in lang_list.items:
					lang_list.selected = lang_list.items.index(LANGUAGENAMES[lang])
					break

		try:
			difficulty, author, desc = ScenarioEventHandler.get_metadata_from_file(self._get_selected_map())
		except InvalidScenarioFileFormat as e:
			self._show_invalid_scenario_file_popup(e)
			return

		lbl = self._gui.findChild(name="uni_map_difficulty")
		#xgettext:python-format
		lbl.text = _("Difficulty: {difficulty}").format(difficulty=difficulty)

		lbl = self._gui.findChild(name="uni_map_author")
		#xgettext:python-format
		lbl.text = _("Author: {author}").format(author=author)

		lbl = self._gui.findChild(name="uni_map_desc")
		#xgettext:python-format
		lbl.text = _("Description: {desc}").format(desc=desc)
开发者ID:ThePawnBreak,项目名称:unknown-horizons,代码行数:49,代码来源:singleplayermenu.py

示例7: __init__

	def __init__(self, gui, db, rng_seed=None):
		super(Session, self).__init__()
		assert isinstance(db, horizons.util.uhdbaccessor.UhDbAccessor)
		self.log.debug("Initing session")
		self.gui = gui # main gui, not ingame gui
		self.db = db # main db for game data (game.sql)
		# this saves how often the current game has been saved
		self.savecounter = 0
		self.is_alive = True

		self._clear_caches()

		#game
		self.random = self.create_rng(rng_seed)
		assert isinstance(self.random, Random)
		self.timer = self.create_timer()
		Scheduler.create_instance(self.timer)
		self.manager = self.create_manager()
		self.view = View(self)
		Entities.load(self.db)
		self.scenario_eventhandler = ScenarioEventHandler(self) # dummy handler with no events
		self.campaign = {}

		#GUI
		self.gui.session = self
		self.ingame_gui = IngameGui(self, self.gui)
		self.keylistener = IngameKeyListener(self)
		self.coordinates_tooltip = None
		self.display_speed()
		LastActivePlayerSettlementManager.create_instance(self)


		self.status_icon_manager = StatusIconManager(
		  renderer=self.view.renderer['GenericRenderer'],
		  layer=self.view.layers[LAYERS.OBJECTS]
		  )
		self.production_finished_icon_manager = None
		self.create_production_finished_icon_manager()


		self.selected_instances = set()
		self.selection_groups = [set() for _ in range(10)]  # List of sets that holds the player assigned unit groups.

		self._old_autosave_interval = None
开发者ID:acieroid,项目名称:unknown-horizons,代码行数:44,代码来源:session.py

示例8: __init__

	def __init__(self, gui, db, rng_seed=None):
		super(Session, self).__init__()
		assert isinstance(gui, Gui)
		assert isinstance(db, horizons.util.uhdbaccessor.UhDbAccessor)
		self.log.debug("Initing session")
		self.gui = gui # main gui, not ingame gui
		self.db = db # main db for game data (game.sql)
		# this saves how often the current game has been saved
		self.savecounter = 0
		self.is_alive = True

		self.message_bus = MessageBus()

		# misc
		WorldObject.reset()
		NamedComponent.reset()
		AIPlayer.clear_caches()

		#game
		self.random = self.create_rng(rng_seed)
		assert isinstance(self.random, Random)
		self.timer = self.create_timer()
		Scheduler.create_instance(self.timer)
		self.manager = self.create_manager()
		self.view = View(self)
		Entities.load(self.db)
		self.scenario_eventhandler = ScenarioEventHandler(self) # dummy handler with no events
		self.campaign = {}

		#GUI
		self.gui.session = self
		self.ingame_gui = IngameGui(self, self.gui)
		self.keylistener = IngameKeyListener(self)
		self.coordinates_tooltip = None
		self.display_speed()
		LastActivePlayerSettlementManager.create_instance(self)


		self.status_icon_manager = StatusIconManager(self)

		self.selected_instances = set()
		self.selection_groups = [set()] * 10 # List of sets that holds the player assigned unit groups.
开发者ID:perher,项目名称:unknown-horizons,代码行数:42,代码来源:session.py

示例9: _update_scenario_translation_infos

	def _update_scenario_translation_infos(self, scenario):
		"""Fill in translation infos of selected scenario to translation label."""
		try:
			metadata = ScenarioEventHandler.get_metadata_from_file(scenario)
		except InvalidScenarioFileFormat as e:
			self._show_invalid_scenario_file_popup(e)
			return

		translation_status = metadata.get('translation_status', u'')
		lbl = self._gui.findChild(name="translation_status")
		lbl.text = translation_status

		lbl = self._gui.findChild(name="uni_map_difficulty")
		lbl.text = _("Difficulty: {difficulty}").format(difficulty=metadata['difficulty'])

		lbl = self._gui.findChild(name="uni_map_author")
		lbl.text = _("Author: {author}").format(author=metadata['author'])

		lbl = self._gui.findChild(name="uni_map_desc")
		lbl.text = _("Description: {desc}").format(desc=metadata['description'])
开发者ID:Rareson,项目名称:unknown-horizons,代码行数:20,代码来源:singleplayermenu.py

示例10: load

	def load(self, options):
		"""Loads a map. Key method for starting a game."""
		"""
		TUTORIAL: Here you see how the vital game elements (and some random things that are also required)
		are initialised.
		"""
		if options.is_scenario:
			# game_identifier is a yaml file, that contains reference to actual map file
			self.scenario_eventhandler = ScenarioEventHandler(self, options.game_identifier)
			# scenario maps can be normal maps or scenario maps:
			map_filename = self.scenario_eventhandler.get_map_file()
			options.game_identifier = os.path.join(SavegameManager.scenario_maps_dir, map_filename)
			if not os.path.exists(options.game_identifier):
				options.game_identifier = os.path.join(SavegameManager.maps_dir, map_filename)
			options.is_map = True

		self.log.debug("Session: Loading from %s", options.game_identifier)
		savegame_db = SavegameAccessor(options.game_identifier, options.is_map) # Initialize new dbreader
		savegame_data = SavegameManager.get_metadata(savegame_db.db_path)
		self.view.resize_layers(savegame_db)

		# load how often the game has been saved (used to know the difference between
		# a loaded and a new game)
		self.savecounter = savegame_data.get('savecounter', 0)

		if savegame_data.get('rng_state', None):
			rng_state_list = json.loads(savegame_data['rng_state'])
			# json treats tuples as lists, but we need tuples here, so convert back
			def rec_list_to_tuple(x):
				if isinstance(x, list):
					return tuple(rec_list_to_tuple(i) for i in x)
				else:
					return x
			rng_state_tuple = rec_list_to_tuple(rng_state_list)
			# changing the rng is safe for mp, as all players have to have the same map
			self.random.setstate(rng_state_tuple)

		self.world = World(self) # Load horizons.world module (check horizons/world/__init__.py)
		self.world._init(savegame_db, options.force_player_id, disasters_enabled=options.disasters_enabled)
		self.view.load(savegame_db) # load view
		if not self.is_game_loaded():
			options.init_new_world(self)
		else:
			# try to load scenario data
			self.scenario_eventhandler.load(savegame_db)
		self.manager.load(savegame_db) # load the manager (there might me old scheduled ticks).
		self.world.init_fish_indexer() # now the fish should exist
		if self.is_game_loaded():
			LastActivePlayerSettlementManager().load(savegame_db) # before ingamegui
		self.ingame_gui.load(savegame_db) # load the old gui positions and stuff

		for instance_id in savegame_db("SELECT id FROM selected WHERE `group` IS NULL"): # Set old selected instance
			obj = WorldObject.get_object_by_id(instance_id[0])
			self.selected_instances.add(obj)
			obj.get_component(SelectableComponent).select()
		for group in xrange(len(self.selection_groups)): # load user defined unit groups
			for instance_id in savegame_db("SELECT id FROM selected WHERE `group` = ?", group):
				self.selection_groups[group].add(WorldObject.get_object_by_id(instance_id[0]))

		# cursor has to be inited last, else player interacts with a not inited world with it.
		self.current_cursor = 'default'
		self.cursor = SelectionTool(self)
		# Set cursor correctly, menus might need to be opened.
		# Open menus later; they may need unit data not yet inited
		self.cursor.apply_select()

		Scheduler().before_ticking()
		savegame_db.close()

		assert hasattr(self.world, "player"), 'Error: there is no human player'
		"""
开发者ID:kendhia,项目名称:unknown-horizons,代码行数:71,代码来源:session.py

示例11: Session

class Session(LivingObject):
	"""Session class represents the games main ingame view and controls cameras and map loading.
	It is alive as long as a game is running.
	Many objects require a reference to this, which makes it a pseudo-global, from what we would
	like to move away long-term. This is where we hope the components come into play, which
	you will encounter later

	This is the most important class if you are going to hack on Unknown Horizons, it provides most of
	the important ingame variables.
	Here's a small list of commonly used attributes:

	* world - horizons.world instance of the currently running horizons. Stores players and islands,
		which store settlements, which store buildings, which have productions and collectors.
		Therefore world deserves its name, it contains the whole game state.
	* scheduler - horizons.scheduler instance. Used to execute timed events. Master of time in UH.
	* manager - horizons.manager instance. Used to execute commands (used to apply user interactions).
		There is a singleplayer and a multiplayer version. Our mp system works by the mp-manager not
		executing the commands directly, but sending them to all players, where they will be executed
		at the same tick.
	* view - horizons.view instance. Used to control the ingame camera.
	* ingame_gui - horizons.gui.ingame_gui instance. Used to control the ingame gui framework.
		(This is different from gui, which is the main menu and general session-independent gui)
	* cursor - horizons.gui.{navigation/cursor/selection/building}tool instance. Used to handle
			   mouse events.
	* selected_instances - Set that holds the currently selected instances (building, units).

	TUTORIAL:
	For further digging you should now be checking out the load() function.
	"""
	timer = livingProperty()
	manager = livingProperty()
	view = livingProperty()
	ingame_gui = livingProperty()
	keylistener = livingProperty()
	world = livingProperty()
	scenario_eventhandler = livingProperty()

	log = logging.getLogger('session')

	def __init__(self, gui, db, rng_seed=None):
		super(Session, self).__init__()
		assert isinstance(gui, Gui)
		assert isinstance(db, horizons.util.uhdbaccessor.UhDbAccessor)
		self.log.debug("Initing session")
		self.gui = gui # main gui, not ingame gui
		self.db = db # main db for game data (game.sql)
		# this saves how often the current game has been saved
		self.savecounter = 0
		self.is_alive = True

		self.message_bus = MessageBus()

		# misc
		WorldObject.reset()
		NamedComponent.reset()
		AIPlayer.clear_caches()

		#game
		self.random = self.create_rng(rng_seed)
		assert isinstance(self.random, Random)
		self.timer = self.create_timer()
		Scheduler.create_instance(self.timer)
		self.manager = self.create_manager()
		self.view = View(self)
		Entities.load(self.db)
		self.scenario_eventhandler = ScenarioEventHandler(self) # dummy handler with no events
		self.campaign = {}

		#GUI
		self.gui.session = self
		self.ingame_gui = IngameGui(self, self.gui)
		self.keylistener = IngameKeyListener(self)
		self.coordinates_tooltip = None
		self.display_speed()
		LastActivePlayerSettlementManager.create_instance(self)


		self.status_icon_manager = StatusIconManager(self)

		self.selected_instances = set()
		self.selection_groups = [set()] * 10 # List of sets that holds the player assigned unit groups.

	def start(self):
		"""Actually starts the game."""
		self.timer.activate()

	def create_manager(self):
		"""Returns instance of command manager (currently MPManager or SPManager)"""
		raise NotImplementedError

	def create_rng(self, seed=None):
		"""Returns a RNG (random number generator). Must support the python random.Random interface"""
		raise NotImplementedError

	def create_timer(self):
		"""Returns a Timer instance."""
		raise NotImplementedError

	def end(self):
		self.log.debug("Ending session")
#.........这里部分代码省略.........
开发者ID:perher,项目名称:unknown-horizons,代码行数:101,代码来源:session.py

示例12: load

	def load(self, savegame, players, trader_enabled, pirate_enabled,
	         natural_resource_multiplier, is_scenario=False, campaign=None,
	         force_player_id=None, disasters_enabled=True, is_multiplayer=False):
		"""Loads a map. Key method for starting a game.
		@param savegame: path to the savegame database.
		@param players: iterable of dictionaries containing id, name, color, local, ai, and difficulty
		@param is_scenario: Bool whether the loaded map is a scenario or not
		@param force_player_id: the worldid of the selected human player or default if None (debug option)
		"""
		"""
		TUTORIAL: Here you see how the vital game elements (and some random things that are also required)
		are initialised.
		"""
		if is_scenario:
			# savegame is a yaml file, that contains reference to actual map file
			self.scenario_eventhandler = ScenarioEventHandler(self, savegame)
			# scenario maps can be normal maps or scenario maps:
			map_filename = self.scenario_eventhandler.get_map_file()
			savegame = os.path.join(SavegameManager.scenario_maps_dir, map_filename)
			if not os.path.exists(savegame):
				savegame = os.path.join(SavegameManager.maps_dir, map_filename)
		self.campaign = {} if not campaign else campaign

		self.log.debug("Session: Loading from %s", savegame)
		savegame_db = SavegameAccessor(savegame) # Initialize new dbreader
		savegame_data = SavegameManager.get_metadata(savegame)

		# load how often the game has been saved (used to know the difference between
		# a loaded and a new game)
		self.savecounter = savegame_data.get('savecounter', 0)

		if savegame_data.get('rng_state', None):
			rng_state_list = json.loads( savegame_data['rng_state'] )
			# json treats tuples as lists, but we need tuples here, so convert back
			def rec_list_to_tuple(x):
				if isinstance(x, list):
					return tuple( rec_list_to_tuple(i) for i in x )
				else:
					return x
			rng_state_tuple = rec_list_to_tuple(rng_state_list)
			# changing the rng is safe for mp, as all players have to have the same map
			self.random.setstate( rng_state_tuple )

		self.world = World(self) # Load horizons.world module (check horizons/world/__init__.py)
		self.world._init(savegame_db, force_player_id, disasters_enabled=disasters_enabled)
		self.view.load(savegame_db) # load view
		if not self.is_game_loaded():
			# NOTE: this must be sorted before iteration, cause there is no defined order for
			#       iterating a dict, and it must happen in the same order for mp games.
			for i in sorted(players, lambda p1, p2: cmp(p1['id'], p2['id'])):
				self.world.setup_player(i['id'], i['name'], i['color'], i['clientid'] if is_multiplayer else None, i['local'], i['ai'], i['difficulty'])
			self.world.set_forced_player(force_player_id)
			center = self.world.init_new_world(trader_enabled, pirate_enabled, natural_resource_multiplier)
			self.view.center(center[0], center[1])
		else:
			# try to load scenario data
			self.scenario_eventhandler.load(savegame_db)
		self.manager.load(savegame_db) # load the manager (there might me old scheduled ticks).
		self.world.init_fish_indexer() # now the fish should exist
		if self.is_game_loaded():
			LastActivePlayerSettlementManager().load(savegame_db) # before ingamegui
		self.ingame_gui.load(savegame_db) # load the old gui positions and stuff

		for instance_id in savegame_db("SELECT id FROM selected WHERE `group` IS NULL"): # Set old selected instance
			obj = WorldObject.get_object_by_id(instance_id[0])
			self.selected_instances.add(obj)
			obj.get_component(SelectableComponent).select()
		for group in xrange(len(self.selection_groups)): # load user defined unit groups
			for instance_id in savegame_db("SELECT id FROM selected WHERE `group` = ?", group):
				self.selection_groups[group].add(WorldObject.get_object_by_id(instance_id[0]))

		# cursor has to be inited last, else player interacts with a not inited world with it.
		self.current_cursor = 'default'
		self.cursor = SelectionTool(self)
		# Set cursor correctly, menus might need to be opened.
		# Open menus later; they may need unit data not yet inited
		self.cursor.apply_select()

		Scheduler().before_ticking()
		savegame_db.close()

		assert hasattr(self.world, "player"), 'Error: there is no human player'
		"""
开发者ID:acieroid,项目名称:unknown-horizons,代码行数:83,代码来源:session.py

示例13: Session

class Session(LivingObject):
	"""The Session class represents the game's main ingame view and controls cameras and map loading.
	It is alive as long as a game is running.
	Many objects require a reference to this, which makes it a pseudo-global, from which we would
	like to move away in the long term. This is where we hope the components come into play, which
	you will encounter later.

	This is the most important class if you are going to hack on Unknown Horizons; it provides most of
	the important ingame variables.
	Here's a small list of commonly used attributes:

	* world - horizons.world instance of the currently running horizons. Stores players and islands,
		which store settlements, which store buildings, which have productions and collectors.
		Therefore, world deserves its name -- it contains the whole game state.
	* scheduler - horizons.scheduler instance. Used to execute timed events. Master of time in UH.
	* manager - horizons.manager instance. Used to execute commands (used to apply user interactions).
		There is a singleplayer and a multiplayer version. Our mp system works by the mp-manager not
		executing the commands directly, but sending them to all players, where they will be executed
		at the same tick.
	* view - horizons.view instance. Used to control the ingame camera.
	* ingame_gui - horizons.gui.ingame_gui instance. Used to control the ingame gui framework.
		(This is different from gui, which is the main menu and general session-independent gui)
	* cursor - horizons.gui.{navigation/cursor/selection/building}tool instance. Used to handle
			   mouse events.
	* selected_instances - Set that holds the currently selected instances (building, units).

	TUTORIAL:
	For further digging you should now be checking out the load() function.
	"""
	timer = livingProperty()
	manager = livingProperty()
	view = livingProperty()
	ingame_gui = livingProperty()
	keylistener = livingProperty()
	scenario_eventhandler = livingProperty()

	log = logging.getLogger('session')

	def __init__(self, gui, db, rng_seed=None):
		super(Session, self).__init__()
		assert isinstance(db, horizons.util.uhdbaccessor.UhDbAccessor)
		self.log.debug("Initing session")
		self.gui = gui # main gui, not ingame gui
		self.db = db # main db for game data (game.sql)
		# this saves how often the current game has been saved
		self.savecounter = 0
		self.is_alive = True

		self._clear_caches()

		#game
		self.random = self.create_rng(rng_seed)
		assert isinstance(self.random, Random)
		self.timer = self.create_timer()
		Scheduler.create_instance(self.timer)
		self.manager = self.create_manager()
		self.view = View(self)
		Entities.load(self.db)
		self.scenario_eventhandler = ScenarioEventHandler(self) # dummy handler with no events
		self.campaign = {}

		#GUI
		self.gui.session = self
		self.ingame_gui = IngameGui(self, self.gui)
		self.keylistener = IngameKeyListener(self)
		self.coordinates_tooltip = None
		self.display_speed()
		LastActivePlayerSettlementManager.create_instance(self)


		self.status_icon_manager = StatusIconManager(
		  renderer=self.view.renderer['GenericRenderer'],
		  layer=self.view.layers[LAYERS.OBJECTS]
		  )
		self.production_finished_icon_manager = None
		self.create_production_finished_icon_manager()


		self.selected_instances = set()
		self.selection_groups = [set() for _ in range(10)]  # List of sets that holds the player assigned unit groups.

		self._old_autosave_interval = None

	def create_production_finished_icon_manager(self):
		""" Checks the settings if we should display resrouce icons.
		If True: Create the ProductionFinishedIconManager
		If False and a manager is currently running: End it
		"""
		show_resource_icons = bool(horizons.globals.fife.get_uh_setting("ShowResourceIcons"))
		if show_resource_icons:
			self.production_finished_icon_manager = ProductionFinishedIconManager(
				renderer=self.view.renderer['GenericRenderer'],
				layer=self.view.layers[LAYERS.OBJECTS]
			)
		else:
			self.end_production_finished_icon_manager()

	def start(self):
		"""Actually starts the game."""
		self.timer.activate()
#.........这里部分代码省略.........
开发者ID:acieroid,项目名称:unknown-horizons,代码行数:101,代码来源:session.py

示例14: _update_infos


#.........这里部分代码省略.........
							#if selected map's file ends with .yaml then get current locale
							#to remove locale postfix from selected_map's name
							else:
								#get current locale to split current map file name
								current_locale =  yamlcache.YamlCache.get_file(self._get_selected_map(), \
													       game_data=True)['locale']
								new_map_name = self._get_selected_map()[:self._get_selected_map().\
									       find('_' + current_locale)] + '_' + \
									       this_locale + '.' + \
									       SavegameManager.scenario_extension

							return new_map_name
							
						cur_selected_language = lang_list.selected_item
						selectable_languages = []
						#show only selectable languages
						for i in find_available_languages().keys():
							if os.path.exists(_find_map_filename(i)):
								selectable_languages.append(LANGUAGENAMES[i])
						selectable_languages.sort()
						lang_list.items = selectable_languages
						if cur_selected_language in lang_list.items:
							lang_list.selected = lang_list.items.index(cur_selected_language)
						else:
							lang_list.selected = 0
						
						def _update_translation_infos(new_map_name):
							"""Fill in translation infos of selected scenario to translation label.

							It gets translation_status from new_map_file. If there is no attribute 
							like translation_status then selected locale is the original locale of 
							the selected scenario. In this case, hide translation_status_label.

							If there are fuzzy translations, show them as untranslated.

							This function also sets scenario map name using locale.
						(e.g. tutorial -> tutorial_en.yaml)"""
					
							translation_status_label = self.current.findChild(name="translation_status")
							try:
								#get translation status
								translation_status_message = yamlcache.YamlCache.get_file(new_map_name, \
														  game_data=True)['translation_status']
								#find integers in translation_levels string
								translation_levels = [int(x) for x in re.findall(r'\d+', translation_status_message)]
								#if translation_levels' len is 3 it shows us there are fuzzy ones
								#show them as untranslated
								if len(translation_levels) == 3:
									translation_levels[2] += translation_levels[1]
								#if everything is translated then set untranslated count as 0
								if len(translation_levels) == 1:
									translation_levels.append(0)
								translation_status_label.text = _("Translation status:") + '\n' + \
									_("{translated} translated messages, {untranslated} untranslated messages")\
									.format(translated=translation_levels[0], \
										untranslated=translation_levels[-1])
								#if selected language is english then don't show translation status
								translation_status_label.show()
							#if there is no translation_status then hide it
							except KeyError:
								translation_status_label.hide()

							self.current.files[ self.active_right_side.collectData('maplist') ] = new_map_name 
							

						#Add locale postfix to fix scenario file
						try:
							_update_translation_infos(_find_map_filename())
						#if there is no scenario with selected locale then select system's default
						except IOError:
							default_locale = ""
							_default_locale, default_encoding = locale.getdefaultlocale()
							try:
								default_locale = _default_locale.split('_')[0]
							except:
								# If default locale could not be detected use 'EN' as fallback
								default_locale = "en"

							#check if default_locale is in list
							if LANGUAGENAMES[default_locale] in lang_list.items:
								lang_list.selected = lang_list.items.index(LANGUAGENAMES[default_locale])
							#if default locale is not in list then select first one
							else:
								lang_list.selected = 0

							_update_infos()
							
						try:
							difficulty = ScenarioEventHandler.get_difficulty_from_file( self._get_selected_map() )
							desc = ScenarioEventHandler.get_description_from_file( self._get_selected_map() )
							author = ScenarioEventHandler.get_author_from_file( self._get_selected_map() )
						except InvalidScenarioFileFormat as e:
							self._show_invalid_scenario_file_popup(e)
							return
						self.current.findChild(name="uni_map_difficulty").text = \
							_("Difficulty: {difficulty}").format(difficulty=difficulty) #xgettext:python-format
						self.current.findChild(name="uni_map_author").text = \
							_("Author: {author}").format(author=author) #xgettext:python-format
						self.current.findChild(name="uni_map_desc").text = \
							_("Description: {desc}").format(desc=desc) #xgettext:python-format
开发者ID:MasterofJOKers,项目名称:unknown-horizons,代码行数:101,代码来源:singleplayermenu.py

示例15: load

	def load(self, savegame, players, is_scenario=False, campaign=None):
		"""Loads a map.
		@param savegame: path to the savegame database.
		@param players: iterable of dictionaries containing id, name, color, local, ai, and difficulty
		@param is_scenario: Bool whether the loaded map is a scenario or not
		"""
		if is_scenario:
			# savegame is a yaml file, that contains reference to actual map file
			self.scenario_eventhandler = ScenarioEventHandler(self, savegame)
			savegame = os.path.join(SavegameManager.maps_dir, \
			                        self.scenario_eventhandler.get_map_file())
		self.campaign = {} if not campaign else campaign

		self.log.debug("Session: Loading from %s", savegame)
		savegame_db = SavegameAccessor(savegame) # Initialize new dbreader
		savegame_data = SavegameManager.get_metadata(savegame)

		# load how often the game has been saved (used to know the difference between
		# a loaded and a new game)
		self.savecounter = 0 if not 'savecounter' in savegame_data else savegame_data['savecounter']

		if savegame_data.get('rng_state', None):
			rng_state_list = json.loads( savegame_data['rng_state'] )
			# json treats tuples as lists, but we need tuples here, so convert back
			def rec_list_to_tuple(x):
				if isinstance(x, list):
					return tuple( rec_list_to_tuple(i) for i in x )
				else:
					return x
			rng_state_tuple = rec_list_to_tuple(rng_state_list)
			# changing the rng is safe for mp, as all players have to have the same map
			self.random.setstate( rng_state_tuple )

		self.world = World(self) # Load horizons.world module (check horizons/world/__init__.py)
		self.world._init(savegame_db)
		self.view.load(savegame_db) # load view
		if not self.is_game_loaded():
			# NOTE: this must be sorted before iteration, cause there is no defined order for
			#       iterating a dict, and it must happen in the same order for mp games.
			for i in sorted(players, lambda p1, p2: cmp(p1['id'], p2['id'])):
				self.world.setup_player(i['id'], i['name'], i['color'], i['local'], i['ai'], i['difficulty'])
			center = self.world.init_new_world()
			self.view.center(center[0], center[1])
		else:
			# try to load scenario data
			self.scenario_eventhandler.load(savegame_db)
		self.manager.load(savegame_db) # load the manager (there might me old scheduled ticks).
		self.world.init_fish_indexer() # now the fish should exist
		self.ingame_gui.load(savegame_db) # load the old gui positions and stuff

		for instance_id in savegame_db("SELECT id FROM selected WHERE `group` IS NULL"): # Set old selected instance
			obj = WorldObject.get_object_by_id(instance_id[0])
			self.selected_instances.add(obj)
			obj.select()
		for group in xrange(len(self.selection_groups)): # load user defined unit groups
			for instance_id in savegame_db("SELECT id FROM selected WHERE `group` = ?", group):
				self.selection_groups[group].add(WorldObject.get_object_by_id(instance_id[0]))

		# cursor has to be inited last, else player interacts with a not inited world with it.
		self.cursor = SelectionTool(self)
        # Set cursor correctly, menus might need to be opened.
		# Open menus later, they may need unit data not yet inited
		self.cursor.apply_select()

		assert hasattr(self.world, "player"), 'Error: there is no human player'
		"""
开发者ID:mitfik,项目名称:unknown-horizons,代码行数:66,代码来源:session.py


注:本文中的horizons.scenario.ScenarioEventHandler类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。