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


Python World._init方法代码示例

本文整理汇总了Python中horizons.world.World._init方法的典型用法代码示例。如果您正苦于以下问题:Python World._init方法的具体用法?Python World._init怎么用?Python World._init使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在horizons.world.World的用法示例。


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

示例1: Session

# 需要导入模块: from horizons.world import World [as 别名]
# 或者: from horizons.world.World import _init [as 别名]
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,代码行数:103,代码来源:session.py

示例2: Session

# 需要导入模块: from horizons.world import World [as 别名]
# 或者: from horizons.world.World import _init [as 别名]
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)
	* 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()
	scenario_eventhandler = livingProperty()

	log = logging.getLogger('session')

	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

	def start(self):
		"""Actually starts the game."""
		self.timer.activate()
		self.scenario_eventhandler.start()
		self.reset_autosave()
		SettingChanged.subscribe(self._on_setting_changed)

	def reset_autosave(self):
		"""(Re-)Set up autosave. Called if autosave interval has been changed."""
		# get_uh_setting returns floats like 4.0 and 42.0 since slider stepping is 1.0.
		interval = int(horizons.globals.fife.get_uh_setting("AutosaveInterval"))
		if interval != self._old_autosave_interval:
			self._old_autosave_interval = interval
			ExtScheduler().rem_call(self, self.autosave)
			if interval != 0: #autosave
				self.log.debug("Initing autosave every %s minutes", interval)
				ExtScheduler().add_new_object(self.autosave, self, interval * 60, -1)

	def _on_setting_changed(self, message):
		if message.setting_name == 'AutosaveInterval':
			self.reset_autosave()

	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

	@classmethod
#.........这里部分代码省略.........
开发者ID:Octavianuspg,项目名称:unknown-horizons,代码行数:103,代码来源:session.py

示例3: Session

# 需要导入模块: from horizons.world import World [as 别名]
# 或者: from horizons.world.World import _init [as 别名]
class Session(LivingObject):
	"""Session class represents the games main ingame view and controls cameras and map loading.

	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:
	* manager - horizons.manager instance. Used to execute commands that need to be tick,
				synchronized check the class for more information.
	* scheduler - horizons.scheduler instance. Used to execute timed events that do not effect
	              network games but rather control the local simulation.
	* view - horizons.view instance. Used to control the ingame camera.
	* ingame_gui - horizons.gui.ingame_gui instance. Used to controll the ingame gui.
	* cursor - horizons.gui.{navigation/cursor/selection/building}tool instance. Used to controll
			   mouse events, check the classes for more info.
	* selected_instances - Set that holds the currently selected instances (building, units).
	* world - horizons.world instance of the currently running horizons. Stores islands, players,
	          for later access.

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

	log = logging.getLogger('session')

	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.

	def start(self):
		"""Acctually 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):
		"""Returns a RNG (random number generator). Must support the python random.Random interface"""
		raise NotImplementedError

	def end(self):
		self.log.debug("Ending session")
		self.is_alive = False

		self.gui.session = None

		Scheduler().rem_all_classinst_calls(self)
		ExtScheduler().rem_all_classinst_calls(self)

		if horizons.main.fife.get_fife_setting("PlaySounds"):
			for emitter in horizons.main.fife.emitter['ambient'][:]:
				emitter.stop()
				horizons.main.fife.emitter['ambient'].remove(emitter)
			horizons.main.fife.emitter['effects'].stop()
			horizons.main.fife.emitter['speech'].stop()
		self.cursor = None
		self.world = None
		self.keylistener = None
		self.ingame_gui = None
		self.view = None
		self.manager = None
		self.timer = None
		self.scenario_eventhandler = None
		Scheduler.destroy_instance()

#.........这里部分代码省略.........
开发者ID:court-jus,项目名称:unknown-horizons,代码行数:103,代码来源:session.py

示例4: SPTestSession

# 需要导入模块: from horizons.world import World [as 别名]
# 或者: from horizons.world.World import _init [as 别名]
class SPTestSession(SPSession):

	def __init__(self, db, rng_seed=None):
		"""
		Unfortunately, right now there is no other way to setup Dummy versions of the GUI,
		View etc., unless we want to patch the references in the session module.
		"""
		super(LivingObject, self).__init__()
		self.gui = Dummy()
		self.db = db
		self.savecounter = 0	# this is a new game.
		self.is_alive = True

		WorldObject.reset()
		NamedObject.reset()
		AIPlayer.clear_caches()

		# Game
		self.current_tick = 0
		self.random = self.create_rng(rng_seed)
		self.timer = self.create_timer()
		Scheduler.create_instance(self.timer)
		ExtScheduler.create_instance(Dummy)
		self.manager = self.create_manager()
		self.view = Dummy()
		self.view.renderer = Dummy()
		Entities.load(self.db)
		self.scenario_eventhandler = Dummy()
		self.campaign = {}
		self.selected_instances = []

		# GUI
		self.gui.session = self
		self.ingame_gui = Dummy()

		GAME_SPEED.TICKS_PER_SECOND = 16

	def load(self, savegame, players):
		"""
		Stripped version of the original code. We don't need to load selections,
		or a scenario, setting up the gui or view.
		"""
		self.savegame = savegame
		self.savegame_db = SavegameAccessor(self.savegame)

		self.world = World(self)
		self.world._init(self.savegame_db)
		for i in sorted(players):
			self.world.setup_player(i['id'], i['name'], i['color'], i['local'], i['is_ai'], i['difficulty'])
		self.manager.load(self.savegame_db)

	def end(self):
		"""
		Clean up temporary files.
		"""
		super(SPTestSession, self).end()
		# Find all islands in the map first
		random_map = False
		for (island_file, ) in self.savegame_db('SELECT file FROM island'):
			if island_file[:7] != 'random:': # random islands don't exist as files
				os.remove(island_file)
			else:
				random_map = True
				break
		# Finally remove savegame
		self.savegame_db.close()
		if not random_map:
			os.remove(self.savegame)

	def run(self, ticks=1, seconds=None):
		"""
		Run the scheduler the given count of ticks or (in-game) seconds. Default is 1 tick,
		if seconds are passed, they will overwrite the tick count.
		"""
		if seconds:
			ticks = self.timer.get_ticks(seconds)

		for i in range(ticks):
			Scheduler().tick(self.current_tick)
			self.current_tick += 1
开发者ID:mihaibivol,项目名称:unknown-horizons,代码行数:82,代码来源:__init__.py

示例5: SPTestSession

# 需要导入模块: from horizons.world import World [as 别名]
# 或者: from horizons.world.World import _init [as 别名]
class SPTestSession(SPSession):

	def __init__(self, db, rng_seed=None):
		"""
		Unfortunately, right now there is no other way to setup Dummy versions of the GUI,
		View etc., unless we want to patch the references in the session module.
		"""
		super(LivingObject, self).__init__()
		self.gui = Dummy()
		self.db = db
		self.savecounter = 0	# this is a new game.
		self.is_alive = True

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

		# Game
		self.random = self.create_rng(rng_seed)
		self.timer = self.create_timer()
		Scheduler.create_instance(self.timer)
		ExtScheduler.create_instance(Dummy)
		self.manager = self.create_manager()
		self.view = Dummy()
		self.view.renderer = Dummy()
		Entities.load(self.db)
		self.scenario_eventhandler = Dummy()
		self.campaign = {}

		self.message_bus = MessageBus()
		self.status_icon_manager = StatusIconManager(self)


		# GUI
		self.gui.session = self
		self.ingame_gui = Dummy()
		LastActivePlayerSettlementManager.create_instance(self)

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

		GAME_SPEED.TICKS_PER_SECOND = 16

	def save(self, *args, **kwargs):
		"""
		Wrapper around original save function to fix some things.
		"""
		# SavegameManager.write_metadata tries to create a screenshot and breaks when
		# accessing fife properties
		with mock.patch('horizons.spsession.SavegameManager'):
			# We need to covert Dummy() objects to a sensible value that can be stored
			# in the database
			with _dbreader_convert_dummy_objects():
				return super(SPTestSession, self).save(*args, **kwargs)

	def load(self, savegame, players):
		"""
		Stripped version of the original code. We don't need to load selections,
		or a scenario, setting up the gui or view.
		"""
		self.savegame = savegame
		self.savegame_db = SavegameAccessor(self.savegame)

		self.savecounter = 1

		self.world = World(self)
		self.world._init(self.savegame_db)
		for i in sorted(players):
			self.world.setup_player(i['id'], i['name'], i['color'], i['local'], i['is_ai'], i['difficulty'])
		self.manager.load(self.savegame_db)

	def end(self, keep_map=False, remove_savegame=True):
		"""
		Clean up temporary files.
		"""
		super(SPTestSession, self).end()
		# Find all islands in the map first
		if not keep_map:
			for (island_file, ) in self.savegame_db('SELECT file FROM island'):
				if island_file[:7] != 'random:': # random islands don't exist as files
					os.remove(island_file)

		self.savegame_db.close()
		# Finally remove savegame
		if remove_savegame:
			os.remove(self.savegame)

	@classmethod
	def cleanup(cls):
		"""
		If a test uses manual session management, we cannot be sure that session.end was
		called before a crash, leaving the game in an unclean state. This method should
		return the game to a valid state.
		"""
		Scheduler.destroy_instance()

	def run(self, ticks=1, seconds=None):
		"""
		Run the scheduler the given count of ticks or (in-game) seconds. Default is 1 tick,
		if seconds are passed, they will overwrite the tick count.
#.........这里部分代码省略.........
开发者ID:perher,项目名称:unknown-horizons,代码行数:103,代码来源:__init__.py

示例6: Session

# 需要导入模块: from horizons.world import World [as 别名]
# 或者: from horizons.world.World import _init [as 别名]
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,代码行数:103,代码来源:session.py


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