本文整理汇总了Python中Event.EventManager.clear方法的典型用法代码示例。如果您正苦于以下问题:Python EventManager.clear方法的具体用法?Python EventManager.clear怎么用?Python EventManager.clear使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Event.EventManager
的用法示例。
在下文中一共展示了EventManager.clear方法的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: AbstractContextMenuHandler
# 需要导入模块: from Event import EventManager [as 别名]
# 或者: from Event.EventManager import clear [as 别名]
class AbstractContextMenuHandler(object):
__metaclass__ = ABCMeta
def __init__(self, cmProxy, ctx = None, handlers = None):
self._eManager = EventManager()
self.onContextMenuHide = Event(self._eManager)
super(AbstractContextMenuHandler, self).__init__()
self.__cmProxy = weakref.proxy(cmProxy)
self.__handlers = handlers or {}
self._initFlashValues(ctx)
@property
def app(self):
return self.__cmProxy.app
def fini(self):
self._eManager.clear()
self.__handlers = None
self.__cmProxy = None
self._clearFlashValues()
return
def getOptions(self, ctx = None):
return self._generateOptions(ctx)
def onOptionSelect(self, optionId):
if optionId in self.__handlers:
return getattr(self, self.__handlers[optionId])()
LOG_WARNING('Unknown context menu option', self, self.__cmProxy, optionId)
def _dispatchChanges(self, options):
if self.__cmProxy is not None:
self.__cmProxy._onOptionsChanged(options)
return
@classmethod
def _makeItem(cls, optId, optLabel = None, optInitData = None, optSubMenu = None):
return {'id': optId,
'label': optLabel,
'initData': optInitData,
'submenu': optSubMenu}
def _makeSeparator(self):
return self._makeItem(_SEPARATOR_ID)
@abstractmethod
def _generateOptions(self, ctx = None):
raise NotImplementedError
def _initFlashValues(self, ctx):
pass
def _clearFlashValues(self):
pass
示例2: CalendarComponent
# 需要导入模块: from Event import EventManager [as 别名]
# 或者: from Event.EventManager import clear [as 别名]
class CalendarComponent(CalendarMeta):
def __init__(self):
super(CalendarComponent, self).__init__()
self.__em = EventManager()
self.onMonthChangedEvent = Event(self.__em)
self.onDateSelectedEvent = Event(self.__em)
def onMonthChanged(self, timestamp):
self.onMonthChangedEvent(timestamp)
def onDateSelected(self, timestamp):
self.onDateSelectedEvent(timestamp)
def formatYMHeader(self, rawDate):
return BigWorld.wg_getYMDateFormat(rawDate)
def _dispose(self):
self.__em.clear()
super(CalendarComponent, self)._dispose()
示例3: ConnectionManager
# 需要导入模块: from Event import EventManager [as 别名]
# 或者: from Event.EventManager import clear [as 别名]
class ConnectionManager(object):
def __init__(self):
self.__connectionData = ConnectionData()
self.__connectionUrl = None
self.__connectionMethod = CONNECTION_METHOD.BASIC
self.__connectionStatus = LOGIN_STATUS.NOT_SET
self.__lastLoginName = None
self.__hostItem = g_preDefinedHosts._makeHostItem('', '', '')
self.__retryConnectionPeriod = _MIN_RECONNECTION_TIMEOUT
self.__retryConnectionCallbackID = None
g_playerEvents.onKickWhileLoginReceived += self.__processKick
g_playerEvents.onLoginQueueNumberReceived += self.__processQueue
self.__eManager = EventManager()
self.onLoggedOn = Event(self.__eManager)
self.onConnected = Event(self.__eManager)
self.onRejected = Event(self.__eManager)
self.onDisconnected = Event(self.__eManager)
self.onKickedFromServer = Event(self.__eManager)
self.onKickWhileLoginReceived = Event(self.__eManager)
self.onQueued = Event(self.__eManager)
return
def __del__(self):
g_playerEvents.onKickWhileLoginReceived -= self.__processKick
g_playerEvents.onLoginQueueNumberReceived -= self.__processQueue
self.__eManager.clear()
self.stopRetryConnection()
def initiateConnection(self, params, password, serverName):
self.__setConnectionData(params, password)
if serverName == AUTO_LOGIN_QUERY_URL:
g_preDefinedHosts.autoLoginQuery(self.__setHostDataAndConnect)
else:
self.__setHostDataAndConnect(g_preDefinedHosts.byUrl(serverName))
def stopRetryConnection(self):
if self.__retryConnectionCallbackID is not None:
BigWorld.cancelCallback(self.__retryConnectionCallbackID)
self.__retryConnectionPeriod = 0
self.__retryConnectionCallbackID = None
return
def __connect(self):
self.__retryConnectionCallbackID = None
if constants.IS_DEVELOPMENT:
LOG_DEBUG('Calling BigWorld.connect with params: {0}, serverName: {1}, inactivityTimeout: {2}, publicKeyPath: {3}'.format(self.__connectionData.username, self.__connectionUrl, constants.CLIENT_INACTIVITY_TIMEOUT, self.__connectionData.publicKeyPath))
nextTick(lambda : BigWorld.connect(self.__connectionUrl, self.__connectionData, self.__serverResponseHandler))()
if g_preDefinedHosts.predefined(self.__connectionUrl) or g_preDefinedHosts.roaming(self.__connectionUrl):
self.__hostItem = g_preDefinedHosts.byUrl(self.__connectionUrl)
else:
for server in BigWorld.serverDiscovery.servers:
if server.serverString == self.__connectionUrl:
self.__hostItem = self.__hostItem._replace(name=server.ownerName)
break
return
def __serverResponseHandler(self, stage, status, responseDataJSON):
if constants.IS_DEVELOPMENT:
LOG_DEBUG('Received server response with stage: {0}, status: {1}, responseData: {2}'.format(stage, status, responseDataJSON))
self.__connectionStatus = status
try:
responseData = json.loads(responseDataJSON)
except ValueError:
responseData = {'errorMessage': responseDataJSON}
if status == LOGIN_STATUS.LOGGED_ON:
if stage == 1:
if self.__connectionMethod == CONNECTION_METHOD.TOKEN and 'token2' in responseData:
self.__swtichToToken2(responseData['token2'])
self.onLoggedOn(responseData)
self.onConnected()
else:
if self.__retryConnectionCallbackID is None:
status_ = self.__connectionStatus
if responseData.get('errorMessage', '') == _INVALID_PASSWORD_TOKEN2_EXPIRED:
status_ = LOGIN_STATUS.SESSION_END
self.onRejected(status_, responseData)
if status == LOGIN_STATUS.LOGIN_REJECTED_RATE_LIMITED:
self.__reconnect()
if stage == 6:
self.onDisconnected()
return
def __setConnectionData(self, params, password):
self.__lastLoginName = params['login']
self.__connectionMethod = params['auth_method']
params['auth_realm'] = constants.AUTH_REALM
m = hashlib.md5()
m.update(params['session'])
params['session'] = m.hexdigest()
if constants.IS_IGR_ENABLED:
params['is_igr'] = '1'
username_ = json.dumps(params, encoding='utf-8')
LOG_NOTE('User authentication method: {0}'.format(params['auth_method']))
if 'token2' in params and params['token2']:
password = ''
else:
password = pwd_token.generate(password)
#.........这里部分代码省略.........
示例4: _EventsCache
# 需要导入模块: from Event import EventManager [as 别名]
# 或者: from Event.EventManager import clear [as 别名]
class _EventsCache(object):
USER_QUESTS = (EVENT_TYPE.BATTLE_QUEST,
EVENT_TYPE.TOKEN_QUEST,
EVENT_TYPE.FORT_QUEST,
EVENT_TYPE.PERSONAL_QUEST,
EVENT_TYPE.POTAPOV_QUEST)
SYSTEM_QUESTS = (EVENT_TYPE.REF_SYSTEM_QUEST,)
def __init__(self):
self.__waitForSync = False
self.__invalidateCbID = None
self.__cache = defaultdict(dict)
self.__potapovHidden = {}
self.__actionsCache = defaultdict(lambda : defaultdict(dict))
self.__questsDossierBonuses = defaultdict(set)
self.__random = RandomPQController()
self.__fallout = FalloutPQController()
self.__potapovComposer = _PotapovComposer(self.__random, self.__fallout)
self.__questsProgress = QuestsProgressRequester()
self.__companies = CompanyBattleController(self)
self.__em = EventManager()
self.onSyncStarted = Event(self.__em)
self.onSyncCompleted = Event(self.__em)
self.onSelectedQuestsChanged = Event(self.__em)
self.onSlotsCountChanged = Event(self.__em)
self.onProgressUpdated = Event(self.__em)
return
def init(self):
self.__random.init()
self.__fallout.init()
def fini(self):
self.__fallout.fini()
self.__random.fini()
self.__em.clear()
self.__clearInvalidateCallback()
def start(self):
self.__companies.start()
def stop(self):
self.__companies.stop()
def clear(self):
self.stop()
quests_caches.clearNavInfo()
@property
def waitForSync(self):
return self.__waitForSync
@property
def falloutQuestsProgress(self):
return self.__fallout.questsProgress
@property
def randomQuestsProgress(self):
return self.__random.questsProgress
@property
def random(self):
return self.__random
@property
def fallout(self):
return self.__fallout
@property
def questsProgress(self):
return self.__questsProgress
@property
def potapov(self):
return self.__potapovComposer
@property
def companies(self):
return self.__companies
@async
@process
def update(self, diff = None, callback = None):
if diff is not None:
if diff.get('eventsData', {}).get(EVENT_CLIENT_DATA.INGAME_EVENTS):
self.__companies.setNotificators()
yield self.falloutQuestsProgress.request()
yield self.randomQuestsProgress.request()
yield self.__questsProgress.request()
isNeedToInvalidate = True
isNeedToClearItemsCaches = False
def _cbWrapper(*args):
self.__random.update(self, diff)
self.__fallout.update(self, diff)
callback(*args)
if diff is not None:
isQPUpdated = 'quests' in diff
isEventsDataUpdated = ('eventsData', '_r') in diff or diff.get('eventsData', {})
#.........这里部分代码省略.........
示例5: _CachedVehicle
# 需要导入模块: from Event import EventManager [as 别名]
# 或者: from Event.EventManager import clear [as 别名]
class _CachedVehicle(object):
def __init__(self):
self._eManager = EventManager()
self.onChanged = Event(self._eManager)
self.onChangeStarted = Event(self._eManager)
self.__changeCallbackID = None
return
def init(self):
self._addListeners()
def destroy(self):
self._eManager.clear()
self._clearChangeCallback()
self._removeListeners()
def selectVehicle(self, vehID):
raise NotImplementedError
def selectNoVehicle(self):
raise NotImplementedError
def isPresent(self):
return self.item is not None
def onInventoryUpdate(self, invDiff):
raise NotImplementedError
def refreshModel(self):
raise NotImplementedError
@property
def item(self):
raise NotImplementedError
@property
def invID(self):
raise NotImplementedError
@property
def hangarSpace(self):
return _getHangarSpace()
def _addListeners(self):
g_clientUpdateManager.addCallbacks({'inventory': self.onInventoryUpdate})
def _removeListeners(self):
g_clientUpdateManager.removeObjectCallbacks(self)
def _changeDone(self):
self._clearChangeCallback()
if isPlayerAccount():
self.onChanged()
Waiting.hide('updateCurrentVehicle')
def _setChangeCallback(self):
if not self.__changeCallbackID:
self.__changeCallbackID = BigWorld.callback(0.2, self._changeDone)
def _clearChangeCallback(self):
if self.__changeCallbackID is not None:
BigWorld.cancelCallback(self.__changeCallbackID)
self.__changeCallbackID = None
return
def _selectVehicle(self, vehID):
raise NotImplementedError
示例6: PQController
# 需要导入模块: from Event import EventManager [as 别名]
# 或者: from Event.EventManager import clear [as 别名]
class PQController(object):
def __init__(self, eventsCache):
self.__clearCaches()
self.__eventsCache = weakref.proxy(eventsCache)
self.__em = EventManager()
self.__hasQuestsForSelect = False
self.__hasQuestsForReward = False
self.onSelectedQuestsChanged = Event(self.__em)
self.onSlotsCountChanged = Event(self.__em)
self.onProgressUpdated = Event(self.__em)
def init(self):
for _, potapovQuestID in potapov_quests.g_cache:
quest = self.__makeQuest(potapovQuestID)
tile = self.__makeTile(quest.getTileID())
tile._addQuest(quest)
season = self.__makeSeason(tile.getSeasonID())
season._addTile(tile)
quest.setSeasonID(season.getID())
def fini(self):
self.__em.clear()
self.__clearCaches()
def update(self, diff=None):
if diff is not None:
potapovQuestsDiff = diff.get("potapovQuests", {})
if "selected" in potapovQuestsDiff:
self.onSelectedQuestsChanged(potapovQuestsDiff["selected"])
if "slots" in potapovQuestsDiff:
self.onSlotsCountChanged(potapovQuestsDiff["slots"])
isNeedToUpdateProgress = len(potapovQuestsDiff)
else:
isNeedToUpdateProgress = True
if isNeedToUpdateProgress:
self.__hasQuestsForSelect = False
self.__hasQuestsForReward = False
freeSlotsCount = self.__eventsCache.questsProgress.getPotapovQuestsFreeSlots()
for qID, quest in self.__quests.iteritems():
quest.updateProgress(self.__eventsCache)
selectedQuests = self.__eventsCache.questsProgress.getSelectedPotapovQuestsIDs()
selectedChains = set([self.__quests[questID].getChainID() for questID in selectedQuests])
for qID, quest in self.__quests.iteritems():
if (
not self.__hasQuestsForSelect
and freeSlotsCount
and quest.canBeSelected()
and quest.getChainID() not in selectedChains
):
self.__hasQuestsForSelect = True
if not self.__hasQuestsForReward and quest.needToGetReward():
self.__hasQuestsForReward = True
if self.__hasQuestsForSelect and self.__hasQuestsForReward:
break
for tile in self.__tiles.itervalues():
tile.updateProgress(self.__eventsCache)
for season in self.__seasons.itervalues():
season.updateProgress(self.__eventsCache)
self.onProgressUpdated()
return
def getNextTankwomanIDs(self, nationID, isPremium, fnGroup, lnGroup, iGroupID):
lastFirstNameID, lastLastNameID, lastIconID = self.__eventsCache.questsProgress.getTankmanLastIDs(nationID)
return map(
operator.itemgetter(1),
tankmen.getNextUniqueIDs(
BigWorld.player().databaseID,
lastFirstNameID,
lastLastNameID,
lastIconID,
nationID,
isPremium,
fnGroup,
lnGroup,
iGroupID,
),
)
def getQuests(self):
return self.__quests
def getTiles(self):
return self.__tiles
def getSeasons(self):
return self.__seasons
def getSelectedQuests(self):
result = {}
for qID in self.__eventsCache.questsProgress.getSelectedPotapovQuestsIDs():
result[qID] = self.__quests[qID]
return result
def getTokens(self):
result = set()
#.........这里部分代码省略.........
示例7: TabsContainer
# 需要导入模块: from Event import EventManager [as 别名]
# 或者: from Event.EventManager import clear [as 别名]
class TabsContainer(object):
def __init__(self):
self.__tabs = {
TABS_IDS.INVENTORY: InventoryBoostersTab(),
TABS_IDS.QUESTS: QuestsBoostersTab(),
TABS_IDS.SHOP: ShopBoostersTab(),
}
self.__currentTabIdx = None
self.__activeBoostersCount = None
self.__eManager = EventManager()
self.onTabsUpdate = Event(self.__eManager)
return
def init(self):
self.__activeBoostersCount = len(g_goodiesCache.getBoosters(criteria=REQ_CRITERIA.BOOSTER.ACTIVE).values())
g_clientUpdateManager.addCallbacks(
{"goodies": self.__onUpdateBoosters, "shop": self.__onUpdateBoosters, "stats": self.__onStatsChanged}
)
g_eventsCache.onSyncCompleted += self.__onQuestsUpdate
def setCurrentTabIdx(self, currentTabIdx):
self.__currentTabIdx = currentTabIdx
@property
def currentTab(self):
return self.__tabs[self.__currentTabIdx]
@property
def inventoryTab(self):
return self.__tabs[TABS_IDS.INVENTORY]
@property
def shopTab(self):
return self.__tabs[TABS_IDS.SHOP]
@property
def questsTab(self):
return self.__tabs[TABS_IDS.QUESTS]
def getTabs(self):
return self.__tabs
def setFilters(self, qualities, boosterTypes):
for tab in self.__tabs.itervalues():
tab.setFilters(qualities, boosterTypes)
def getActiveBoostersCount(self):
return self.__activeBoostersCount
def fini(self):
self.__currentTabIdx = None
self.__eManager.clear()
g_clientUpdateManager.removeObjectCallbacks(self)
g_eventsCache.onSyncCompleted -= self.__onQuestsUpdate
for tab in self.__tabs.itervalues():
tab.fini()
self.__tabs.clear()
self.__activeBoostersCount = None
return
def __onUpdateBoosters(self, *args):
for tab in self.__tabs.itervalues():
tab.update()
self.__activeBoostersCount = len(g_goodiesCache.getBoosters(criteria=REQ_CRITERIA.BOOSTER.ACTIVE).values())
self.onTabsUpdate()
def __onQuestsUpdate(self, *args):
self.questsTab.updateQuests()
self.__onUpdateBoosters()
def __onStatsChanged(self, stats):
if "credits" in stats or "gold" in stats:
self.shopTab.updateBalance()
self.onTabsUpdate()
示例8: _PreDefinedHostList
# 需要导入模块: from Event import EventManager [as 别名]
# 或者: from Event.EventManager import clear [as 别名]
class _PreDefinedHostList(object):
def __init__(self):
super(_PreDefinedHostList, self).__init__()
self._eManager = EventManager()
self.onCsisQueryStart = Event(self._eManager)
self.onCsisQueryComplete = Event(self._eManager)
self._hosts = []
self._urlMap = {}
self._nameMap = {}
self._peripheryMap = {}
self._isDataLoaded = False
self._isCSISQueryInProgress = False
self.__pingResult = {}
self.__csisUrl = ''
self.__csisResponse = {}
self.__lastRoamingHosts = []
self.__csisCallbackID = None
self.__lastCsisUpdateTime = 0
self.__queryCallback = None
self.__autoLoginQueryState = AUTO_LOGIN_QUERY_STATE.DEFAULT
self.__csisAction = CSIS_ACTION.DEFAULT
self.__recommended = []
self.__setPingCallback = False
try:
BigWorld.WGPinger.setOnPingCallback(self.__onPingPerformed)
self.__setPingCallback = True
except AttributeError:
LOG_CURRENT_EXCEPTION()
return
def fini(self):
self._hosts = []
self._urlMap.clear()
self._nameMap.clear()
self._peripheryMap.clear()
self._isDataLoaded = False
self.__pingResult.clear()
self.__csisResponse.clear()
self.__csisUrl = ''
self.__lastCsisUpdateTime = None
self.__queryCallback = None
self.__autoLoginQueryState = AUTO_LOGIN_QUERY_STATE.DEFAULT
self.__csisAction = CSIS_ACTION.DEFAULT
self._eManager.clear()
self.__setPingCallback = False
self.__cleanCsisTimerCallback()
try:
BigWorld.WGPinger.clearOnPingCallback()
except AttributeError:
LOG_CURRENT_EXCEPTION()
return
@property
def lastRoamingHosts(self):
return self.__lastRoamingHosts
def startCSISUpdate(self):
if len(self.hosts()) > 1:
self.__csisAction = CSIS_ACTION.addIfNot(self.__csisAction, CSIS_ACTION.UPDATE_ON_TIME)
self.__sendCsisQuery()
def stopCSISUpdate(self):
self.__csisAction = CSIS_ACTION.removeIfHas(self.__csisAction, CSIS_ACTION.UPDATE_ON_TIME)
self.__cleanCsisTimerCallback()
def autoLoginQuery(self, callback):
if callback is None:
LOG_WARNING('Callback is not defined.')
return
elif self.__autoLoginQueryState != AUTO_LOGIN_QUERY_STATE.DEFAULT:
LOG_WARNING('Auto login query in process.')
return
elif len(self._hosts) < 2:
callback(self.first())
return
else:
peripheryID, expired = self.readPeripheryTL()
if peripheryID > 0 and expired > 0:
if expired > time.time():
host = self.periphery(peripheryID)
if host is not None:
LOG_DEBUG('Recommended host taken from cache', host)
callback(host)
return
if len(self.__recommended):
LOG_DEBUG('Gets recommended from previous query', self.__recommended)
host = self.__choiceFromRecommended()
LOG_DEBUG('Recommended host', host)
callback(host)
return
self.__autoLoginQueryState = AUTO_LOGIN_QUERY_STATE.START
self.__queryCallback = callback
self.__ping()
self.__csisAction = CSIS_ACTION.addIfNot(self.__csisAction, CSIS_ACTION.AUTO_LOGIN_REQUEST)
self.__sendCsisQuery()
return
#.........这里部分代码省略.........
示例9: RefSystem
# 需要导入模块: from Event import EventManager [as 别名]
# 或者: from Event.EventManager import clear [as 别名]
class RefSystem(Controller):
def __init__(self, proxy):
super(RefSystem, self).__init__(proxy)
self.__referrers = []
self.__referrals = []
self.__quests = []
self.__xpPoolOfDeletedRals = 0
self.__totalXP = 0
self.__isTotallyCompleted = False
self.__posByXPinTeam = 0
self.__eventMgr = EventManager()
self.onUpdated = Event(self.__eventMgr)
self.onQuestsUpdated = Event(self.__eventMgr)
self.onPlayerBecomeReferrer = Event(self.__eventMgr)
self.onPlayerBecomeReferral = Event(self.__eventMgr)
@storage_getter('users')
def usersStorage(self):
return None
def fini(self):
self.__referrers = None
self.__referrals = None
self.__eventMgr.clear()
self.__clearQuestsData()
super(RefSystem, self).fini()
def onLobbyStarted(self, ctx):
g_clientUpdateManager.addCallbacks({'stats.refSystem': self.__onRefStatsUpdated})
g_eventsCache.onSyncCompleted += self.__onEventsUpdated
g_playerEvents.onShopResync += self.__onShopUpdated
self.__update(g_itemsCache.items.stats.refSystem)
self.__updateQuests()
def onAvatarBecomePlayer(self):
self.__stop()
def onDisconnected(self):
self.__stop()
def getReferrers(self):
return self.__referrers
def getReferrals(self):
return self.__referrals
def getQuests(self):
return self.__quests
def isTotallyCompleted(self):
return self.__isTotallyCompleted
def getPosByXPinTeam(self):
return self.__posByXPinTeam
def getTotalXP(self):
return self.__totalXP
def getReferralsXPPool(self):
result = self.__xpPoolOfDeletedRals
for i in self.getReferrals():
result += i.getXPPool()
return result
def getAvailableReferralsCount(self):
return _getMaxNumberOfReferrals() - len(self.__referrals)
def showTankmanAwardWindow(self, tankman, completedQuestIDs):
LOG_DEBUG('Referrer has been get tankman award', tankman, completedQuestIDs)
curXp, nextXp, _ = self.__getAwardParams(completedQuestIDs)
shared_events.showAwardWindow(TankmanAward(tankman, curXp, nextXp))
def showVehicleAwardWindow(self, vehicle, completedQuestIDs):
LOG_DEBUG('Referrer has been get vehicle award', vehicle, completedQuestIDs)
curXp, nextXp, isBoughtVehicle = self.__getAwardParams(completedQuestIDs)
shared_events.showAwardWindow(VehicleAward(vehicle, isBoughtVehicle, curXp))
def showCreditsAwardWindow(self, creditsValue, completedQuestIDs):
if creditsValue > 0:
LOG_DEBUG('Referrer has been get credits award', creditsValue, completedQuestIDs)
shared_events.showAwardWindow(CreditsAward(creditsValue))
@classmethod
def getRefPeriods(cls):
return _getRefSystemPeriods()
@classmethod
def getMaxReferralXPPool(cls):
return _getMaxReferralXPPool()
@classmethod
def getMaxNumberOfReferrals(cls):
return _getMaxNumberOfReferrals()
@classmethod
def isReferrer(cls):
refSystemStats = g_itemsCache.items.stats.refSystem
return refSystemStats.get('activeInvitations', 0) > 0 or len(refSystemStats.get('referrals', {})) > 0
#.........这里部分代码省略.........
示例10: BuyBoosterMeta
# 需要导入模块: from Event import EventManager [as 别名]
# 或者: from Event.EventManager import clear [as 别名]
class BuyBoosterMeta(I18nConfirmDialogMeta):
def __init__(self, boosterID, balance):
super(BuyBoosterMeta, self).__init__('buyConfirmation', scope=ScopeTemplates.LOBBY_SUB_SCOPE)
self.__booster = g_goodiesCache.getBooster(boosterID)
self.__balance = balance
self._eManager = EventManager()
self.onInvalidate = Event(self._eManager)
g_clientUpdateManager.addCallbacks({'stats': self.__onStatsChanged})
def getEventType(self):
return events.ShowDialogEvent.SHOW_CONFIRM_BOOSTER
def getBoosterID(self):
return self.__booster.boosterID
def getBooster(self):
return self.__booster
def destroy(self):
self.__booster = None
self.__balance = None
self._eManager.clear()
g_clientUpdateManager.removeObjectCallbacks(self)
return
def getMaxAvailableItemsCount(self):
return (self.__getMaxCount(Currency.CREDITS), self.__getMaxCount(Currency.GOLD))
def getActionVO(self):
buyPrice = self.__booster.buyPrice
defaultPrice = self.__booster.defaultPrice
if buyPrice != defaultPrice:
return packActionTooltipData(ACTION_TOOLTIPS_TYPE.BOOSTER, str(self.__booster.boosterID), True, buyPrice, defaultPrice)
else:
return None
def getCurrency(self):
return self.__booster.getBuyPriceCurrency()
def getPrice(self):
return self.__booster.buyPrice
@process('buyItem')
def submit(self, count, currency):
result = yield BoosterBuyer(self.__booster, count, currency == Currency.GOLD).request()
if len(result.userMsg):
SystemMessages.g_instance.pushI18nMessage(result.userMsg, type=result.sysMsgType)
def __onStatsChanged(self, stats):
if 'credits' in stats:
self.__balance = self.__balance.replace(Currency.CREDITS, stats['credits'])
self.onInvalidate()
if 'gold' in stats:
self.__balance = self.__balance.replace(Currency.GOLD, stats['gold'])
self.onInvalidate()
def __getMaxCount(self, currency):
result = 0
boosterPrice = self.__booster.buyPrice
if boosterPrice.get(currency) > 0:
result = math.floor(self.__balance.get(currency) / boosterPrice.get(currency))
return min(result, MAX_BOOSTERS_FOR_OPERATION)
示例11: _PreDefinedHostList
# 需要导入模块: from Event import EventManager [as 别名]
# 或者: from Event.EventManager import clear [as 别名]
class _PreDefinedHostList(object):
def __init__(self):
super(_PreDefinedHostList, self).__init__()
self._eManager = EventManager()
self.onCsisQueryStart = Event(self._eManager)
self.onCsisQueryComplete = Event(self._eManager)
self.onPingPerformed = Event(self._eManager)
self._hosts = []
self._urlMap = {}
self._nameMap = {}
self._peripheryMap = {}
self._isDataLoaded = False
self._isCSISQueryInProgress = False
self.__csisUrl = ''
self.__csisResponse = {}
self.__lastRoamingHosts = []
self.__csisCallbackID = None
self.__lastCsisUpdateTime = 0
self.__queryCallback = None
self.__autoLoginQueryState = AUTO_LOGIN_QUERY_STATE.DEFAULT
self.__csisAction = CSIS_ACTION.DEFAULT
self.__recommended = []
self.__pingRequester = _PingRequester(self.__onPingPerformed)
return
def fini(self):
self._hosts = []
self._urlMap.clear()
self._nameMap.clear()
self._peripheryMap.clear()
self._isDataLoaded = False
self.__csisResponse.clear()
self.__csisUrl = ''
self.__lastCsisUpdateTime = None
self.__queryCallback = None
self.__autoLoginQueryState = AUTO_LOGIN_QUERY_STATE.DEFAULT
self.__csisAction = CSIS_ACTION.DEFAULT
self._eManager.clear()
self.__pingRequester.fini()
self.__cleanCsisTimerCallback()
return
@property
def lastRoamingHosts(self):
return self.__lastRoamingHosts
def startCSISUpdate(self):
if len(self.hosts()) > 1:
self.__csisAction = CSIS_ACTION.addIfNot(self.__csisAction, CSIS_ACTION.UPDATE_ON_TIME)
self.__sendCsisQuery()
def stopCSISUpdate(self):
self.__csisAction = CSIS_ACTION.removeIfHas(self.__csisAction, CSIS_ACTION.UPDATE_ON_TIME)
self.__cleanCsisTimerCallback()
def requestPing(self, forced = False):
self.__pingRequester.request(self._hosts, forced)
def getPingResult(self):
return self.__pingRequester.result()
def autoLoginQuery(self, callback):
if callback is None:
LOG_WARNING('Callback is not defined.')
return
elif self.__autoLoginQueryState != AUTO_LOGIN_QUERY_STATE.DEFAULT:
LOG_WARNING('Auto login query in process. Current state: {}'.format(self.__autoLoginQueryState))
return
elif len(self._hosts) < 2:
callback(self.first())
return
elif len(self.__recommended):
LOG_DEBUG('Gets recommended from previous query', self.__recommended)
host = self.__choiceFromRecommended()
LOG_DEBUG('Recommended host', host)
callback(host)
return
else:
self.__autoLoginQueryState = AUTO_LOGIN_QUERY_STATE.START
self.__queryCallback = callback
self.__pingRequester.request(self.peripheries())
self.__csisAction = CSIS_ACTION.addIfNot(self.__csisAction, CSIS_ACTION.AUTO_LOGIN_REQUEST)
self.__sendCsisQuery()
return
def resetQueryResult(self):
self.__recommended = []
self.__pingRequester.clear()
def readScriptConfig(self, dataSection, userDataSection = None):
if self._isDataLoaded or dataSection is None:
return
else:
def _readSvrList(section, nodeName):
if section is not None and section.has_key(nodeName):
return section[nodeName].items()
else:
return []
#.........这里部分代码省略.........