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


Python WeakMethodList.append方法代码示例

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


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

示例1: MovingObject

# 需要导入模块: from horizons.util.python.weakmethodlist import WeakMethodList [as 别名]
# 或者: from horizons.util.python.weakmethodlist.WeakMethodList import append [as 别名]

#.........这里部分代码省略.........
			self._movement_finished()
			return
		else:
			self.__is_moving = True

		# HACK: 2 different pathfinding systems are being used here and they
		# might not always match.
		# If the graphical location is too far away from the actual location,
		# then forcefully synchronize the locations.
		# This fixes the symptoms from issue #2859
		# https://github.com/unknown-horizons/unknown-horizons/issues/2859
		pos = fife.ExactModelCoordinate(self.position.x, self.position.y, 0)
		fpos = self.fife_instance.getLocationRef().getExactLayerCoordinates()
		if (pos - fpos).length() > 1.5:
			self.fife_instance.getLocationRef().setExactLayerCoordinates(pos)

		#setup movement
		move_time = self.get_unit_velocity()
		UnitClass.ensure_action_loaded(self._action_set_id, self._move_action) # lazy load move action

		self._exact_model_coords1.set(self.position.x, self.position.y, 0)
		self._fife_location1.setExactLayerCoordinates(self._exact_model_coords1)
		self._exact_model_coords2.set(self._next_target.x, self._next_target.y, 0)
		self._fife_location2.setExactLayerCoordinates(self._exact_model_coords2)
		self._route = fife.Route(self._fife_location1, self._fife_location2)
		# TODO/HACK the *5 provides slightly less flickery behavior of the moving
		# objects. This should be fixed properly by using the fife pathfinder for
		# the entire route and task
		location_list = fife.LocationList([self._fife_location2] * 5)
		self._route.setPath(location_list)

		self.act(self._move_action)
		diagonal = self._next_target.x != self.position.x and self._next_target.y != self.position.y
		speed = float(self.session.timer.get_ticks(1)) / move_time[0]
		action = self._instance.getCurrentAction().getId()
		self._instance.follow(action, self._route, speed)

		#self.log.debug("%s registering move tick in %s ticks", self, move_time[int(diagonal)])
		Scheduler().add_new_object(self._move_tick, self, move_time[int(diagonal)])

		# check if a conditional callback becomes true
		for cond in list(self._conditional_callbacks.keys()): # iterate of copy of keys to be able to delete
			if cond():
				# start callback when this function is done
				Scheduler().add_new_object(self._conditional_callbacks[cond], self)
				del self._conditional_callbacks[cond]

	def teleport(self, destination, callback=None, destination_in_building=False):
		"""Like move, but nearly instantaneous"""
		if hasattr(destination, "position"):
			destination_coord = destination.position.center.to_tuple()
		else:
			destination_coord = destination
		self.move(destination, callback=callback, destination_in_building=destination_in_building, path=[destination_coord])

	def add_move_callback(self, callback):
		"""Registers callback to be executed when movement of unit finishes.
		This has no effect if the unit isn't moving."""
		if self.is_moving():
			self.move_callbacks.append(callback)

	def add_blocked_callback(self, blocked_callback):
		"""Registers callback to be executed when movement of the unit gets blocked."""
		self.blocked_callbacks.append(blocked_callback)

	def add_conditional_callback(self, condition, callback):
		"""Adds a callback, that gets called, if, at any time of the movement, the condition becomes
		True. The condition is checked every move_tick. After calling the callback, it is removed."""
		assert callable(condition)
		assert callable(callback)
		self._conditional_callbacks[condition] = callback

	def get_unit_velocity(self):
		"""Returns the number of ticks that it takes to do a straight (i.e. vertical or horizontal)
		or diagonal movement as a tuple in this order.
		@return: (int, int)
		"""
		tile = self.session.world.get_tile(self.position)
		if self.id in tile.velocity:
			return tile.velocity[self.id]
		else:
			return (12, 17) # standard values

	def get_move_target(self):
		return self.path.get_move_target()

	def save(self, db):
		super().save(db)
		# NOTE: _move_action is currently not yet saved and neither is blocked_callback.
		self.path.save(db, self.worldid)

	def load(self, db, worldid):
		super().load(db, worldid)
		x, y = db("SELECT x, y FROM unit WHERE rowid = ?", worldid)[0]
		self.__init(x, y)
		path_loaded = self.path.load(db, worldid)
		if path_loaded:
			self.__is_moving = True
			self._setup_move()
			Scheduler().add_new_object(self._move_tick, self, run_in=0)
开发者ID:MarkusHackspacher,项目名称:unknown-horizons,代码行数:104,代码来源:movingobject.py

示例2: ChangeListener

# 需要导入模块: from horizons.util.python.weakmethodlist import WeakMethodList [as 别名]
# 或者: from horizons.util.python.weakmethodlist.WeakMethodList import append [as 别名]
class ChangeListener(object):
	"""Trivial ChangeListener.
	The object that changes and the object that listens have to inherit from this class.
	An object calls _changed everytime something has changed, obviously.
	This function calls every Callback, that has been registered to listen for a change.
	NOTE: ChangeListeners aren't saved, they have to be reregistered on load
	NOTE: RemoveListeners must not access the object, as it is in progress of being destroyed.
	"""
	def __init__(self, *args, **kwargs):
		super(ChangeListener, self).__init__()
		self.__init()

	def __init(self):
		self.__listeners = WeakMethodList()
		self.__remove_listeners = WeakMethodList()
		# number of event calls
		# if any event is triggered increase the number, after all callbacks are executed decrease it
		# if it reaches 0 it means that in the current object all event callbacks were executed
		self.__event_call_number = 0
		self.__hard_remove = True

	def __remove_listener(self, listener_list, listener):
		# check if the listener should be hard removed
		# if so switch it in the list to None
		try:
			if self.__hard_remove:
				listener_list.remove(listener)
			else:
				listener_list[listener_list.index(listener)] = None
		except ValueError as e: # nicer error:
			raise ValueError(str(e)+
			                 "\nTried to remove: "+str(listener)+"\nat "+str(self)+
			                 "\nList: "+str([str(i) for i in listener_list]))

	def __call_listeners(self, listener_list):
		# instead of removing from list, switch the listener in position to None
		# this way, iteration won't be affected while listeners may modify the list
		self.__hard_remove = False
		# increase the event call number
		self.__event_call_number += 1
		for listener in listener_list:
			if listener:
				try:
					listener()
				except ReferenceError as e:
					# listener object is dead, don't crash since it doesn't need updates now anyway
					print 'Warning: the dead are listening to', self, ': ', e
					traceback.print_stack()

		self.__event_call_number -= 1

		if self.__event_call_number == 0:
			self.__hard_remove = True
			listener_list[:] = [ l for l in listener_list if l ]

	## Normal change listener
	def add_change_listener(self, listener, call_listener_now=False, no_duplicates=False):
		assert callable(listener)
		if not no_duplicates or listener not in self.__listeners:
			self.__listeners.append(listener)
		if call_listener_now: # also call if duplicate is adde
			listener()

	def remove_change_listener(self, listener):
		self.__remove_listener(self.__listeners, listener)

	def has_change_listener(self, listener):
		return (listener in self.__listeners)

	def discard_change_listener(self, listener):
		"""Remove listener if it's there"""
		if self.has_change_listener(listener):
			self.remove_change_listener(listener)

	def clear_change_listeners(self):
		"""Removes all change listeners"""
		self.__listeners = WeakMethodList()

	def _changed(self):
		"""Calls every listener when an object changed"""
		self.__call_listeners(self.__listeners)

	## Removal change listener
	def add_remove_listener(self, listener, no_duplicates=False):
		"""A listener that listens for removal of the object"""
		assert callable(listener)
		if no_duplicates and listener in self.__remove_listeners:
			return # don't allow duplicate entries
		self.__remove_listeners.append(listener)

	def remove_remove_listener(self, listener):
		self.__remove_listener(self.__remove_listeners, listener)

	def has_remove_listener(self, listener):
		return (listener in self.__remove_listeners)

	def discard_remove_listener(self, listener):
		if self.has_remove_listener(listener):
			self.remove_remove_listener(listener)

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

示例3: MovingObject

# 需要导入模块: from horizons.util.python.weakmethodlist import WeakMethodList [as 别名]
# 或者: from horizons.util.python.weakmethodlist.WeakMethodList import append [as 别名]

#.........这里部分代码省略.........
					self.log.debug('PATH FOR UNIT %s is blocked. Delegating to owner %s', self, self.owner)
					self.owner.notify_unit_path_blocked(self)
					"""
				else:
					# generic solution: retry in 2 secs
					self.log.debug('PATH FOR UNIT %s is blocked. Retry in 2 secs', self)
					# technically, the ship doesn't move, but it is in the process of moving,
					# as it will continue soon in general. Needed in border cases for add_move_callback
					self.__is_moving = True
					Scheduler().add_new_object(self._move_tick, self,
					                           GAME_SPEED.TICKS_PER_SECOND * 2)
				self.log.debug("Unit %s: path is blocked, no way around", self)
				return

		if self._next_target is None:
			self._movement_finished()
			return
		else:
			self.__is_moving = True

		#setup movement

		# WORK IN PROGRESS
		move_time = self.get_unit_velocity()

		#location = fife.Location(self._instance.getLocation().getLayer())
		self._exact_model_coords.set(self._next_target.x, self._next_target.y, 0)
		self._fife_location.setExactLayerCoordinates(self._exact_model_coords)

		UnitClass.ensure_action_loaded(self._action_set_id, self._move_action) # lazy load move action

		# it's safe to use location here (thisown is 0, set by swig, and setLocation uses reference)
		self._instance.move(self._move_action+"_"+str(self._action_set_id), self._fife_location,
												float(self.session.timer.get_ticks(1)) / move_time[0])
		# coords per sec

		diagonal = self._next_target.x != self.position.x and self._next_target.y != self.position.y
		#self.log.debug("%s registering move tick in %s ticks", self, move_time[int(diagonal)])
		Scheduler().add_new_object(self._move_tick, self, move_time[int(diagonal)])

		# check if a conditional callback becomes true
		for cond in self._conditional_callbacks.keys(): # iterate of copy of keys to be able to delete
			if cond():
				# start callback when this function is done
				Scheduler().add_new_object(self._conditional_callbacks[cond], self)
				del self._conditional_callbacks[cond]

	def teleport(self, destination, callback=None, destination_in_building=False):
		"""Like move, but nearly instantaneous"""
		if hasattr(destination, "position"):
			destination_coord = destination.position.center.to_tuple()
		else:
			destination_coord = destination
		self.move(destination, callback=callback, destination_in_building=destination_in_building, path=[destination_coord])

	def add_move_callback(self, callback):
		"""Registers callback to be executed when movement of unit finishes.
		This has no effect if the unit isn't moving."""
		if self.is_moving():
			self.move_callbacks.append(callback)

	def add_blocked_callback(self, blocked_callback):
		"""Registers callback to be executed when movement of the unit gets blocked."""
		self.blocked_callbacks.append(blocked_callback)

	def add_conditional_callback(self, condition, callback):
		"""Adds a callback, that gets called, if, at any time of the movement, the condition becomes
		True. The condition is checked every move_tick. After calling the callback, it is removed."""
		assert callable(condition)
		assert callable(callback)
		self._conditional_callbacks[condition] = callback

	def get_unit_velocity(self):
		"""Returns the number of ticks that it takes to do a straight (i.e. vertical or horizontal)
		or diagonal movement as a tuple in this order.
		@return: (int, int)
		"""
		tile = self.session.world.get_tile(self.position)
		if self.id in tile.velocity:
			return tile.velocity[self.id]
		else:
			return (12, 17) # standard values

	def get_move_target(self):
		return self.path.get_move_target()

	def save(self, db):
		super(MovingObject, self).save(db)
		# NOTE: _move_action is currently not yet saved and neither is blocked_callback.
		self.path.save(db, self.worldid)

	def load(self, db, worldid):
		super(MovingObject, self).load(db, worldid)
		x, y = db("SELECT x, y FROM unit WHERE rowid = ?", worldid)[0]
		self.__init(x, y)
		path_loaded = self.path.load(db, worldid)
		if path_loaded:
			self.__is_moving = True
			self._setup_move()
			Scheduler().add_new_object(self._move_tick, self, run_in=0)
开发者ID:acieroid,项目名称:unknown-horizons,代码行数:104,代码来源:movingobject.py


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