示例#1
0
 def getChainVehicleClass(self, chainID):
     firstQuest = findFirst(None,
                            self.__quests.get(chainID, {}).itervalues())
     if firstQuest is not None:
         return findFirst(None, firstQuest.getVehicleClasses())
     else:
         return
示例#2
0
 def getMaxRank(self, vehicle=None):
     if vehicle is not None:
         result = findFirst(operator.methodcaller('isMax'),
                            self.getVehicleRanksChain(vehicle))
         if result is not None:
             return result
     return findFirst(operator.methodcaller('isMax'), self.getRanksChain())
示例#3
0
    def getConditionsData(self, main, add):
        result = {}
        if self._storage:
            headerProgresses = self._storage.getHeaderProgresses()
            bodyProgresses = self._storage.getBodyProgresses()
            mainBodyProgresses, addBodyProgresses = [], []
            if bodyProgresses:
                for progress in bodyProgresses.itervalues():
                    if progress.isMain():
                        mainBodyProgresses.append(progress)
                    addBodyProgresses.append(progress)

            if headerProgresses:
                mainIterateProgressData, addIterateProgressData = {}, {}
                mainHeaderProgress = findFirst(lambda p: p.isMain(),
                                               headerProgresses.itervalues())
                addHeaderProgress = findFirst(lambda p: not p.isMain(),
                                              headerProgresses.itervalues())
                if mainHeaderProgress:
                    mainIterateProgressData = self._getIterateData(
                        mainHeaderProgress, first(mainBodyProgresses))
                if addHeaderProgress:
                    addIterateProgressData = self._getIterateData(
                        addHeaderProgress, first(addBodyProgresses))
                if main and mainIterateProgressData:
                    result[self.MAIN_PROGRESS_DATA] = mainIterateProgressData
                if add and addIterateProgressData:
                    result[self.ADD_PROGRESS_DATA] = addIterateProgressData
            if main and self.MAIN_PROGRESS_DATA not in result:
                result[self.MAIN_VALUE_DATA] = self._getValueData(
                    mainBodyProgresses)
            if add and self.ADD_PROGRESS_DATA not in result:
                result[self.ADD_VALUE_DATA] = self._getValueData(
                    addBodyProgresses)
        return result
    def __loadFromSection(self, section, bDelOldCmds=True, asDefault=False):
        needsResave = False
        tempList = []
        for commandName in section.keys():
            subsec = section[commandName]
            fireKeyName = subsec.readString('fireKey')
            satelliteKeyNames = []
            if subsec.has_key('satelliteKeys'):
                satelliteKeyNames = subsec.readString('satelliteKeys').split()
            if bDelOldCmds:
                self.remove(commandName)
            if commandName.find('_SHORTCAT_') != -1:
                commandName = commandName.replace('_SHORTCAT_', '_SHORTCUT_')
                needsResave = True
            tempList.append((commandName, fireKeyName, satelliteKeyNames))

        if asDefault is False:
            for commandNameTarget, commandNameSrc in CO_DEPENDENT_KEYS.iteritems():
                if findFirst(lambda a: a[0] == commandNameTarget, tempList, None) is None:
                    src = findFirst(lambda a: a[0] == commandNameSrc, tempList, None)
                    if src is not None:
                        self.remove(commandNameTarget)
                        tempList.append((commandNameTarget, src[1], src[2]))

        for commandName, fireKeyName, satelliteKeyNames in tempList:
            if not self.add(commandName, fireKeyName, satelliteKeyNames, asDefault):
                LOG_DEBUG('<__loadFromSection>: ' + ('default' if asDefault else 'user') + ' command ' + str(commandName) + ' was not loaded')

        if needsResave:
            self.save()
        return
示例#5
0
 def _getValue(self):
     result = list()
     shell = self._tooltip.item
     configuration = self._tooltip.context.getParamsConfiguration(shell)
     vehicle = configuration.vehicle
     params = configuration.params
     historicalBattleID = configuration.historicalBattleID
     battle = g_eventsCache.getHistoricalBattles().get(historicalBattleID)
     vDescr = vehicle.descriptor if vehicle is not None else None
     vCompDescr = vehicle.intCD if vehicle is not None else None
     if vehicle is not None and battle is not None and battle.canParticipateWith(vCompDescr):
         vDescr = battle.getVehicleModifiedDescr(vehicle)
     result.append([])
     if params:
         result = [ItemsParameters.g_instance.getParameters(shell.descriptor, vDescr)]
     result.append([])
     if vehicle is not None:
         gun = VehicleItem(vDescr.gun)
         vehicleShell = findFirst(lambda s: s.intCD == shell.intCD, vehicle.shells)
         shellCount = vehicleShell.count if vehicleShell else getattr(shell, 'count', 0)
         if battle is not None and battle.canParticipateWith(vCompDescr):
             _, shellCount = findFirst(lambda x: x[0].intCD == shell.intCD, battle.getShellsLayout(vCompDescr), (None, 0))
         result[-1].append({'label': 'ammo',
          'current': shellCount,
          'total': gun.descriptor['maxAmmo']})
     return result
 def __updateResourceModels(self, resourceType):
     with self.viewModel.transaction() as model:
         tabModel = findFirst(lambda tab: tab.getType() == resourceType,
                              model.getResourcesTabs())
         for resourceModel in tabModel.getResources():
             resources = self.__resources[resourceType]
             resource = findFirst(
                 lambda r, m=resourceModel: m.getType() == r.guiName,
                 resources)
             resourceModel.setInventoryCount(resource.inventoryCount)
示例#7
0
 def getCurrentRank(self, vehicle=None):
     """
     Current account rank.
     """
     if vehicle is not None:
         result = findFirst(operator.methodcaller('isCurrent'),
                            self.getVehicleRanksChain(vehicle))
         if result is not None:
             return result
     return findFirst(operator.methodcaller('isCurrent'),
                      self.getRanksChain())
def getQuestsByTokenAndBonus(quests, tokenFinder=None, bonusFinder=None):
    result = {}
    for questID, quest in quests.iteritems():
        token = findFirst(tokenFinder, quest.accountReqs.getTokens())
        if token is None:
            continue
        bonus = findFirst(bonusFinder, quest.getBonuses())
        if bonus is not None:
            result[questID] = quest

    return result
示例#9
0
 def getLastRank(self, vehicle=None):
     """
     Last rank for which client animation was shown.
     """
     if vehicle is not None:
         result = findFirst(operator.methodcaller('isLastSeenByPlayer'),
                            self.getVehicleRanksChain(vehicle))
         if result is not None:
             return result
     return findFirst(operator.methodcaller('isLastSeenByPlayer'),
                      self.getRanksChain())
示例#10
0
 def parseTag(self, pyGlooxTag):
     igrID, igrRoomID, gameHost, arenaLabel = (0, 0, '', '')
     tag = findFirst(None, pyGlooxTag.filterXPath(self.getXPath(suffix='igr-id')))
     if tag:
         igrID = tag.getCData()
     tag = findFirst(None, pyGlooxTag.filterXPath(self.getXPath(suffix='igr-room-id')))
     if tag:
         igrRoomID = tag.getCData()
     tag = findFirst(None, pyGlooxTag.filterXPath(self.getXPath(suffix='game-host')))
     if tag:
         gameHost = tag.getCData()
     tag = findFirst(None, pyGlooxTag.filterXPath(self.getXPath(suffix='arena-label')))
     if tag:
         arenaLabel = tag.getCData()
     return makeClientInfo(igrID, igrRoomID, gameHost, arenaLabel)
 def parseTag(self, pyGlooxTag):
     igrID, igrRoomID, gameHost, arenaLabel = (0, 0, '', '')
     tag = findFirst(None, pyGlooxTag.filterXPath(self.getXPath(suffix='igr-id')))
     if tag:
         igrID = tag.getCData()
     tag = findFirst(None, pyGlooxTag.filterXPath(self.getXPath(suffix='igr-room-id')))
     if tag:
         igrRoomID = tag.getCData()
     tag = findFirst(None, pyGlooxTag.filterXPath(self.getXPath(suffix='game-host')))
     if tag:
         gameHost = tag.getCData()
     tag = findFirst(None, pyGlooxTag.filterXPath(self.getXPath(suffix='arena-label')))
     if tag:
         arenaLabel = tag.getCData()
     return makeClientInfo(igrID, igrRoomID, gameHost, arenaLabel)
示例#12
0
 def __getFinalQuestAwardsVO(self, quest):
     tokenAward = findFirst(lambda q: q.getName() == 'completionTokens',
                            quest.getBonuses(isMain=True))
     formatter = getPersonalMissionAwardsFormatter()
     mainAwards = formatter.getFormattedBonuses(
         (tokenAward, ),
         size=COMPLETION_TOKENS_SIZES.HUGE,
         obtainedImage=RES_ICONS.
         MAPS_ICONS_PERSONALMISSIONS_OPERATIONS_STATES_COMPLETED,
         obtainedImageOffset=0)
     chainID = self.getChainID()
     operationID = self.getOperationID()
     mainAwardTextID = chainID
     if self.getBranch() == PM_BRANCH.REGULAR:
         if chainID == HT_CHAIN_ID and (operationID == OPERATION_ID_T55A
                                        or operationID
                                        == OPERATION_ID_OBJECT_260):
             mainAwardTextID = MAIN_AWARD_TEXT_ID_HULL
         mainAwardText = _ms(_MAIN_AWARD_TEXT[mainAwardTextID])
     else:
         if chainID == ALLIANCE_CHAIN_ID and (
                 operationID == OPERATION_ID_CHIMERA
                 or operationID == OPERATION_ID_OBJECT_279):
             mainAwardTextID = MAIN_AWARD_TEXT_PM2_ID_HULL
         mainAwardText = _ms(_MAIN_AWARD_TEXT_PM2[mainAwardTextID])
     return {'mainAwardText': mainAwardText, 'mainAward': first(mainAwards)}
示例#13
0
    def getShellsLayoutPrice(self):
        """
        @return: price that should be paid to fill layout
        """
        if self.shellsLayoutHelper is None:
            return MONEY_UNDEFINED
        else:
            price = MONEY_UNDEFINED
            if g_bootcamp.isRunning():
                return price
            for shellCompDescr, count, isBuyingForAltPrice in LayoutIterator(
                    self.shellsLayoutHelper.getRawLayout()):
                if not shellCompDescr or not count:
                    continue
                shell = self.itemsCache.items.getItemByCD(int(shellCompDescr))
                vehShell = findFirst(
                    lambda s, intCD=shellCompDescr: s.intCD == intCD,
                    self.vehicle.shells)
                vehCount = vehShell.count if vehShell is not None else 0
                buyCount = count - shell.inventoryCount - vehCount
                if buyCount:
                    itemPrice = shell.buyPrices.itemAltPrice if isBuyingForAltPrice else shell.buyPrices.itemPrice
                    buyPrice = buyCount * itemPrice.price
                    price += buyPrice

            return price
示例#14
0
 def cancel(self):
     item = findFirst(lambda item: item.getStage() == EQUIPMENT_STAGES.PREPARING, self._equipments.itervalues())
     if item is not None:
         item.deactivate()
         return True
     else:
         return False
def itemOnVehicleComparator(vehicle, item):
    vehicleParams = params.VehicleParams(vehicle).getParamsDict()
    withItemParams = vehicleParams
    mayInstall, reason = vehicle.descriptor.mayInstallComponent(item.intCD)
    if item.itemTypeID == ITEM_TYPES.vehicleTurret:
        mayInstall, reason = vehicle.descriptor.mayInstallTurret(item.intCD, vehicle.gun.intCD)
        if not mayInstall:
            properGun = findFirst(lambda gun: vehicle.descriptor.mayInstallComponent(gun['compactDescr'])[0], item.descriptor['guns'])
            if properGun is not None:
                removedModules = vehicle.descriptor.installTurret(item.intCD, properGun['compactDescr'])
                withItemParams = params.VehicleParams(vehicle).getParamsDict()
                vehicle.descriptor.installTurret(*removedModules)
            else:
                LOG_ERROR('not possible to install turret', item, reason)
        else:
            removedModules = vehicle.descriptor.installTurret(item.intCD, vehicle.gun.intCD)
            withItemParams = params.VehicleParams(vehicle).getParamsDict()
            vehicle.descriptor.installTurret(*removedModules)
    elif not mayInstall and reason == 'not for current vehicle' and item.itemTypeID == ITEM_TYPES.vehicleGun:
        turret = g_paramsCache.getPrecachedParameters(item.intCD).getTurretsForVehicle(vehicle.intCD)[0]
        removedModules = vehicle.descriptor.installTurret(turret, vehicle.gun.intCD)
        vehicleParams = params.VehicleParams(vehicle).getParamsDict()
        vehicle.descriptor.installTurret(turret, item.intCD)
        withItemParams = params.VehicleParams(vehicle).getParamsDict()
        vehicle.descriptor.installTurret(*removedModules)
    else:
        removedModule = vehicle.descriptor.installComponent(item.intCD)
        withItemParams = params.VehicleParams(vehicle).getParamsDict()
        vehicle.descriptor.installComponent(removedModule[0])
    return VehiclesComparator(withItemParams, vehicleParams)
示例#16
0
    def validateVehicles(self, vInfos, flags):
        from gui.shared.gui_items.Vehicle import Vehicle

        if not findFirst(lambda v: not v.isEmpty(), vInfos, False):
            return (False, UNIT_RESTRICTION.FALLOUT_VEHICLE_MIN)
        else:
            for vInfo in vInfos:
                vehicle = vInfo.getVehicle()
                if vehicle is None:
                    continue
                isReadyToBattle = vehicle.isReadyToPrebattle(checkForRent=not flags.isInPreArena())
                if vehicle and not isReadyToBattle:
                    if vehicle.isBroken:
                        return (False, UNIT_RESTRICTION.VEHICLE_BROKEN)
                    if not vehicle.isCrewFull:
                        return (False, UNIT_RESTRICTION.VEHICLE_CREW_NOT_FULL)
                    if not flags.isInPreArena() and vehicle.rentalIsOver:
                        return (False, UNIT_RESTRICTION.VEHICLE_RENT_IS_OVER)
                    if vehicle.isInBattle:
                        return (False, UNIT_RESTRICTION.VEHICLE_IS_IN_BATTLE)
                    isGroupReady, state = vehicle.isGroupReady()
                    if not isGroupReady:
                        if state == Vehicle.VEHICLE_STATE.FALLOUT_REQUIRED:
                            return (False, UNIT_RESTRICTION.FALLOUT_VEHICLE_LEVEL_REQUIRED)
                        if state == Vehicle.VEHICLE_STATE.FALLOUT_MIN:
                            return (False, UNIT_RESTRICTION.FALLOUT_VEHICLE_MIN)
                        if state == Vehicle.VEHICLE_STATE.FALLOUT_MAX:
                            return (False, UNIT_RESTRICTION.FALLOUT_VEHICLE_MAX)
                        if state == Vehicle.VEHICLE_STATE.FALLOUT_BROKEN:
                            return (False, UNIT_RESTRICTION.FALLOUT_VEHICLE_BROKEN)
                    return (False, UNIT_RESTRICTION.VEHICLE_NOT_VALID)

            return (True, UNIT_RESTRICTION.UNDEFINED)
 def _packBlocks(self, operationID, vehicleType):
     pmController = dependency.instance(IEventsCache).personalMissions
     operation = pmController.getOperations()[operationID]
     chainID, _ = operation.getChainByVehicleType(vehicleType)
     finalQuest = operation.getFinalQuests()[chainID]
     bonus = findFirst(lambda q: q.getName() == 'completionTokens',
                       finalQuest.getBonuses('tokens'))
     formattedBonus = first(CompletionTokensBonusFormatter().format(bonus))
     operationTitle = str(operation.getVehicleBonus().userName).replace(
         ' ', '&nbsp;')
     if finalQuest.isCompleted():
         statusText = self.__getObtainedStatus()
     elif pmController.mayPawnQuest(finalQuest):
         statusText = self.__getAvailableStatus(finalQuest.getPawnCost())
     else:
         statusText = self.__getNotObtainedStatus()
     vehIcon = RES_ICONS.vehicleTypeInactiveOutline(vehicleType)
     blocks = [
         formatters.packImageTextBlockData(
             title=text_styles.highTitle(formattedBonus.userName),
             desc=text_styles.standard(
                 _ms(PERSONAL_MISSIONS.OPERATIONTITLE_TITLE,
                     title=operationTitle)),
             img=formattedBonus.getImage(AWARDS_SIZES.BIG),
             imgPadding=formatters.packPadding(right=20),
             txtPadding=formatters.packPadding(top=10)),
         formatters.packBuildUpBlockData(
             [
                 formatters.packImageTextBlockData(
                     title=text_styles.main(
                         _ms(PERSONAL_MISSIONS.TANKMODULETOOLTIPDATA_INFO,
                             vehName=text_styles.neutral(operationTitle))),
                     img=RES_ICONS.MAPS_ICONS_LIBRARY_ATTENTIONICONFILLED,
                     imgPadding=formatters.packPadding(
                         left=8, right=10, top=2))
             ],
             linkage=BLOCKS_TOOLTIP_TYPES.
             TOOLTIP_BUILDUP_BLOCK_WHITE_BG_LINKAGE,
             padding=formatters.packPadding(top=-7, bottom=-3))
     ]
     if not finalQuest.isCompleted():
         blocks.append(
             formatters.packBuildUpBlockData([
                 formatters.packTextBlockData(text_styles.middleTitle(
                     PERSONAL_MISSIONS.TANKMODULETOOLTIPDATA_HELP_TITLE),
                                              padding=formatters.
                                              packPadding(bottom=4)),
                 formatters.packImageTextBlockData(title=text_styles.main(
                     _ms(PERSONAL_MISSIONS.TANKMODULETOOLTIPDATA_HELP_BODY,
                         vehType=_ms(
                             PERSONAL_MISSIONS.chainNameByVehicleType(
                                 vehicleType)))),
                                                   img=vehIcon,
                                                   imgPadding=formatters.
                                                   packPadding(right=2))
             ]))
     blocks.append(
         formatters.packAlignedTextBlockData(
             text=statusText, align=BLOCKS_TOOLTIP_TYPES.ALIGN_CENTER))
     return blocks
    def isTransportationAvailable(self):
        forImport = self.getBuildingsAvailableForImport()

        def filter(item):
            return len(self.getBuildingsAvailableForExport(item)) > 0

        return findFirst(filter, forImport) is not None
示例#19
0
    def getShellsLayoutPrice(self):
        """
        @return: price that should be paid to fill layout
        """
        goldPrice = 0
        creditsPrice = 0
        if self.shellsLayout is None:
            return (creditsPrice, goldPrice)
        else:
            for shellCompDescr, count, isBoughtForCredits in LayoutIterator(self.shellsLayout):
                if not shellCompDescr or not count:
                    continue
                shell = g_itemsCache.items.getItemByCD(int(shellCompDescr))
                vehShell = findFirst(lambda s: s.intCD == shellCompDescr, self.vehicle.shells)
                vehCount = vehShell.count if vehShell is not None else 0
                buyCount = count - shell.inventoryCount - vehCount
                if buyCount:
                    if shell.buyPrice[1] and not isBoughtForCredits:
                        goldPrice += shell.buyPrice[1] * buyCount
                    elif shell.buyPrice[1] and isBoughtForCredits:
                        creditsPrice += shell.buyPrice[1] * buyCount * g_itemsCache.items.shop.exchangeRateForShellsAndEqs
                    elif shell.buyPrice[0]:
                        creditsPrice += shell.buyPrice[0] * buyCount

            return (creditsPrice, goldPrice)
示例#20
0
    def _format(self, condition, event):
        result = []
        if not event.isGuiDisabled():
            mapsLabels = set()
            for atID in condition.getMaps():
                iconData = formatters.packMissionkMapElement(atID)
                if iconData is not None:
                    mapsLabels.add(iconData.iconLabel)

            if len(mapsLabels) > 1:
                labelKey = '#quests:missionDetails/conditions/maps'
                tooltipHeaderKey = '#quests:details/conditions/maps'
                if condition.isNegative():
                    tooltipHeaderKey = '#quests:missionDetails/conditions/maps/not'
                    labelKey = '#quests:details/conditions/maps/not'
            else:
                labelKey = findFirst(None, mapsLabels)
                tooltipHeaderKey = '#quests:details/conditions/map'
                if condition.isNegative():
                    tooltipHeaderKey = '#quests:details/conditions/maps/not'
                    labelKey = '#quests:missionDetails/conditions/maps/not'
            tooltipHeader = i18n.makeString(tooltipHeaderKey)
            tooltipBody = ', '.join(mapsLabels)
            tooltip = makeTooltip(tooltipHeader, tooltipBody)
            result.append(formatters.packMissionPrebattleCondition(text_styles.main(labelKey), icons=icons.makeImageTag(RES_ICONS.MAPS_ICONS_QUESTS_PREBATTLECONDITIONS_MAPS, width=ICON_SIZE, height=ICON_SIZE, vSpace=VERTICAL_SPACE), tooltip=tooltip))
        return result
 def _format(self, bonus):
     tokens = bonus.getTokens()
     unlockTokenID = findFirst(lambda ID: ID.endswith(self.__TOKEN_POSTFIX),
                               tokens.keys())
     if unlockTokenID is not None:
         camouflages = self.c11n.getCamouflages(
             criteria=REQ_CRITERIA.CUSTOMIZATION.UNLOCKED_BY(unlockTokenID))
         images = {
             size: RES_ICONS.getBonusIcon(size, self.__ICON_NAME)
             for size in AWARDS_SIZES.ALL()
         }
         result = [
             PreformattedBonus(
                 bonusName=bonus.getName(),
                 label=formatCountLabel(len(camouflages)),
                 align=LABEL_ALIGN.RIGHT,
                 images=images,
                 isSpecial=False,
                 tooltip=makeTooltip(
                     TOOLTIPS.PERSONALMISSIONS_AWARDS_CAMOUFLAGE_HEADER,
                     TOOLTIPS.PERSONALMISSIONS_AWARDS_CAMOUFLAGE_BODY))
         ]
     else:
         result = []
     return result
示例#22
0
    def isTransportationAvailable(self):
        forImport = self.getBuildingsAvailableForImport()

        def filter(item):
            return len(self.getBuildingsAvailableForExport(item)) > 0

        return findFirst(filter, forImport) is not None
 def loadPersonalMissionsView(self, event):
     settingsCore = dependency.instance(ISettingsCore)
     eventsCache = dependency.instance(IEventsCache)
     uiStorage = settingsCore.serverSettings.getUIStorage()
     goByDefault = True
     if not uiStorage.get(PM_TUTOR_FIELDS.GREETING_SCREEN_SHOWN):
         self.loadViewByCtxEvent(
             LoadViewEvent(PERSONAL_MISSIONS_ALIASES.
                           PERSONAL_MISSION_FIRST_ENTRY_VIEW_ALIAS,
                           ctx=event.ctx))
         goByDefault = False
     elif not uiStorage.get(PM_TUTOR_FIELDS.FIRST_ENTRY_AWARDS_SHOWN):
         if findFirst(
                 methodcaller('isAwardAchieved'),
                 eventsCache.getPersonalMissions().getAllOperations().
                 values()):
             self.loadViewByCtxEvent(
                 LoadViewEvent(
                     PERSONAL_MISSIONS_ALIASES.
                     PERSONAL_MISSION_FIRST_ENTRY_AWARD_VIEW_ALIAS,
                     ctx=event.ctx))
             goByDefault = False
         else:
             settingsCore.serverSettings.saveInUIStorage(
                 {PM_TUTOR_FIELDS.FIRST_ENTRY_AWARDS_SHOWN: True})
     if goByDefault:
         if event.eventType == VIEW_ALIAS.LOBBY_PERSONAL_MISSIONS:
             self.loadViewByCtxEvent(
                 LoadViewEvent(
                     PERSONAL_MISSIONS_ALIASES.PERSONAL_MISSIONS_OPERATIONS,
                     ctx=event.ctx))
         else:
             self.loadViewByCtxEvent(event)
示例#24
0
 def cancel(self):
     item = findFirst(lambda item: item.getStage() == EQUIPMENT_STAGES.PREPARING, self._equipments.itervalues())
     if item is not None:
         item.deactivate()
         return True
     else:
         return False
示例#25
0
    def format(self, message, callback):
        from new_year.celebrity.celebrity_quests_helpers import marathonTokenCountExtractor
        isSynced = yield self._waitForSyncItems()
        if isSynced:
            templateName = self._TEMPLATE_NAME
            messageSubtype = None
            data = message.data or {}
            completedQuestIDs = data.get('completedQuestIDs', set())
            quests = self._eventsCache.getAllQuests(lambda q: q.getID() in completedQuestIDs)
            completedCount = 0
            for quest in quests.values():
                bonuses = quest.getBonuses()
                extraSlotBonus = findFirst(lambda b: b.getName() == 'battleToken' and VEH_BRANCH_EXTRA_SLOT_TOKEN in b.getTokens(), bonuses)
                if extraSlotBonus:
                    templateName = self._TEMPLATE_BUTTON_NAME
                    messageSubtype = SCH_CLIENT_MSG_TYPE.NY_CELEBRITY_REWARD
                completedCount = max(completedCount, marathonTokenCountExtractor(quest))

            fmt = QuestAchievesFormatter.formatQuestAchieves(data, asBattleFormatter=False)
            text = backport.text(R.strings.system_messages.newYear.celebrityChallenge.progressReward(), value=completedCount)
            formatted = g_settings.msgTemplates.format(templateName, ctx={'text': text,
             'rewards': fmt})
            settings = self._getGuiSettings(message, templateName, messageSubtype=messageSubtype)
            callback([MessageData(formatted, settings)])
        else:
            callback([MessageData(None, None)])
        return
示例#26
0
    def setModules(self, modules):
        if modules:
            notFittedReasons = []
            oldGunIntCD = self.__vehicle.gun.intCD
            _installModulesSet(self.__vehicle, list(modules[:]),
                               notFittedReasons)
            if notFittedReasons:
                for notFitReason in notFittedReasons:
                    LOG_DEBUG(
                        'Module has not been installed properly, reason: {}'.
                        format(notFitReason))

            if oldGunIntCD != self.__vehicle.gun.intCD:
                firstShellIndex = 0
                newShellIndex = -1
                if self.__updateSelectedShell(firstShellIndex):
                    newShellIndex = firstShellIndex
                self.__notifyViews('onShellsUpdated',
                                   updateShells=True,
                                   selectedIndex=newShellIndex)
            else:
                newGunToInstall = findFirst(
                    lambda module: module.itemTypeID == GUI_ITEM_TYPE.GUN,
                    modules, None)
                if newGunToInstall is not None:
                    self.__vehicle.descriptor.activeGunShotIndex = self.__selectedShellIndex
            self.__notifyViews('onModulesUpdated')
        return
示例#27
0
 def add(self, action):
     applicableRule = findFirst(lambda r: r.applicableTo(action),
                                self.__compositionRules)
     if applicableRule is not None:
         ruleType = applicableRule.getType()
         collections = self.__collections.setdefault(ruleType, [])
         collection = findFirst(lambda c: applicableRule.canAdd(c, action),
                                collections)
         if collection is not None:
             collection.add(action)
         else:
             self.__collections[ruleType].append(
                 applicableRule.collectionClass(action))
     else:
         self.__singleActions.append(action)
     return
示例#28
0
    def _prepareModule(self, modulesData, vehicle, slotType, slotId):
        if slotType == FITTING_TYPES.BOOSTER:
            vehicleModule = vehicle.equipment.battleBoosterConsumables[0]
            if vehicleModule is not None:
                affectsAtTTC = vehicleModule.isAffectsOnVehicle(vehicle)
                self['affectsAtTTC'] = affectsAtTTC
                if affectsAtTTC:
                    if vehicleModule.isCrewBooster():
                        isPerkReplace = not vehicleModule.isAffectedSkillLearnt(
                            vehicle)
                        bgType = SLOT_HIGHLIGHT_TYPES.BATTLE_BOOSTER_CREW_REPLACE if isPerkReplace else SLOT_HIGHLIGHT_TYPES.BATTLE_BOOSTER
                        self['bgHighlightType'] = bgType
                    else:
                        self['highlight'] = affectsAtTTC
                        self[
                            'bgHighlightType'] = SLOT_HIGHLIGHT_TYPES.BATTLE_BOOSTER
        else:
            vehicleModule = super(_ConfigFittingSlotVO,
                                  self)._prepareModule(modulesData, vehicle,
                                                       slotType, slotId)
            if slotType == FITTING_TYPES.OPTIONAL_DEVICE:
                moduleInSlot = findFirst(
                    lambda item: item.isInstalled(vehicle, slotId),
                    modulesData)
                for battleBooster in vehicle.equipment.battleBoosterConsumables:
                    if battleBooster is not None and battleBooster.isOptionalDeviceCompatible(
                            moduleInSlot):
                        self['highlight'] = True
                        break

        return vehicleModule
示例#29
0
 def __getSelectedFilterType(self):
     cache = self.fortCtrl.getPublicInfoCache()
     if cache:
         uiMapping = findFirst(
             lambda k: self.FILTER_TYPE_MAPPING[k] == cache.getFilterType(),
             self.FILTER_TYPE_MAPPING)
         return uiMapping or FORTIFICATION_ALIASES.CLAN_TYPE_FILTER_STATE_ALL
示例#30
0
 def setPlayerAssistResult(self, assistType, details):
     if not self.__isPEEnabled:
         return
     else:
         eventID = None
         series = 1
         if assistType == _SET.SPOTTED:
             eventID = _EVENT_ID.PLAYER_SPOTTED_ENEMY
             series = self.__getSeries(details)
         elif assistType in (_SET.RADIO_HIT_ASSIST, _SET.RADIO_KILL_ASSIST, _SET.TRACK_ASSIST):
             if assistType == _SET.TRACK_ASSIST:
                 series = self.__getSeries(details)
             eventID = _EVENT_ID.PLAYER_ASSIST_TO_KILL_ENEMY
         elif assistType == _SET.BASE_CAPTURE_POINTS:
             eventID = _EVENT_ID.PLAYER_CAPTURED_BASE
         elif assistType == _SET.BASE_CAPTURE_DROPPED:
             eventID = _EVENT_ID.PLAYER_DROPPED_CAPTURE
         elif assistType == _SET.TANKING:
             eventID = _EVENT_ID.PLAYER_USED_ARMOR
             series = findFirst(None, details, default=1)
         else:
             LOG_CODEPOINT_WARNING(assistType)
         if eventID:
             self.__pushPlayerEvent(eventID, series)
         return
示例#31
0
 def canSelectVehicle(self, vehicle):
     if not self.isSelected():
         return (False, '')
     cfg = self.getConfig()
     if findFirst(lambda v: v.level == cfg.vehicleLevelRequired, self.getSelectedVehicles()) is None and vehicle.level != cfg.vehicleLevelRequired:
         return (False, i18n.makeString(FALLOUT.TANKCAROUSELSLOT_SELECTIONBUTTONTOOLTIP, requiredLevel=int2roman(cfg.vehicleLevelRequired), level=toRomanRangeString(list(cfg.allowedLevels - {cfg.vehicleLevelRequired}), 1)))
     return (True, '')
    def _validate(self):
        vInfos = self._getVehiclesInfo()
        if not findFirst(lambda v: not v.isEmpty(), vInfos, False):
            return ValidationResult(False,
                                    UNIT_RESTRICTION.VEHICLE_NOT_SELECTED)
        else:
            for vInfo in vInfos:
                vehicle = vInfo.getVehicle()
                if vehicle is not None:
                    vehicleIsNotSuitableForMode = self._isVehicleSuitableForMode(
                        vehicle)
                    if vehicleIsNotSuitableForMode is not None:
                        return vehicleIsNotSuitableForMode
                    if not vehicle.isReadyToPrebattle(
                            checkForRent=self._isCheckForRent()):
                        if vehicle.isBroken:
                            return ValidationResult(
                                False, UNIT_RESTRICTION.VEHICLE_BROKEN)
                        if not vehicle.isCrewFull:
                            return ValidationResult(
                                False, UNIT_RESTRICTION.VEHICLE_CREW_NOT_FULL)
                        if vehicle.rentalIsOver:
                            return ValidationResult(
                                False, UNIT_RESTRICTION.VEHICLE_RENT_IS_OVER)
                        if vehicle.isInBattle:
                            return ValidationResult(
                                False, UNIT_RESTRICTION.VEHICLE_IS_IN_BATTLE)
                        return ValidationResult(
                            False, UNIT_RESTRICTION.VEHICLE_NOT_VALID)
                    state, _ = vehicle.getState()
                    if state == Vehicle.VEHICLE_STATE.UNSUITABLE_TO_QUEUE:
                        return ValidationResult(
                            False, UNIT_RESTRICTION.VEHICLE_WRONG_MODE)

            return super(UnitVehiclesValidator, self)._validate()
def itemOnVehicleComparator(vehicle, item):
    vehicleParams = params.VehicleParams(vehicle).getParamsDict()
    withItemParams = vehicleParams
    mayInstall, reason = vehicle.descriptor.mayInstallComponent(item.intCD)
    if item.itemTypeID == ITEM_TYPES.vehicleTurret:
        mayInstall, reason = vehicle.descriptor.mayInstallTurret(item.intCD, vehicle.gun.intCD)
        if not mayInstall:
            properGun = findFirst(lambda gun: vehicle.descriptor.mayInstallComponent(gun.compactDescr)[0], item.descriptor.guns)
            if properGun is not None:
                removedModules = vehicle.descriptor.installTurret(item.intCD, properGun.compactDescr)
                withItemParams = params.VehicleParams(vehicle).getParamsDict()
                vehicle.descriptor.installTurret(*removedModules)
            else:
                LOG_ERROR('not possible to install turret', item, reason)
        else:
            removedModules = vehicle.descriptor.installTurret(item.intCD, vehicle.gun.intCD)
            withItemParams = params.VehicleParams(vehicle).getParamsDict()
            vehicle.descriptor.installTurret(*removedModules)
    elif not mayInstall:
        if reason == 'not for current vehicle' and item.itemTypeID == ITEM_TYPES.vehicleGun:
            turret = g_paramsCache.getPrecachedParameters(item.intCD).getTurretsForVehicle(vehicle.intCD)[0]
            removedModules = vehicle.descriptor.installTurret(turret, vehicle.gun.intCD)
            vehicleParams = params.VehicleParams(vehicle).getParamsDict()
            vehicle.descriptor.installTurret(turret, item.intCD)
            withItemParams = params.VehicleParams(vehicle).getParamsDict()
            vehicle.descriptor.installTurret(*removedModules)
        else:
            LOG_WARNING('Module {} cannot be installed on vehicle {}'.format(item, vehicle))
            return VehiclesComparator(withItemParams, vehicleParams)
    else:
        removedModule = vehicle.descriptor.installComponent(item.intCD)
        withItemParams = params.VehicleParams(vehicle).getParamsDict()
        vehicle.descriptor.installComponent(removedModule[0])
    return VehiclesComparator(withItemParams, vehicleParams)
示例#34
0
 def showMarker(self, eq, pos, direction, time):
     item = findFirst(lambda e: e.getEquipmentID() == eq.id[1],
                      self._equipments.itervalues())
     if item is None:
         item = self.createItem(eq, 0, -1, 0, 0)
     self.onEquipmentMarkerShown(item, pos, direction, time)
     return
示例#35
0
    def _format(self, condition, event):
        result = []
        if event is None or not event.isGuiDisabled():
            camos = []
            for camoTypeName, camoID in CAMOUFLAGE_KINDS.iteritems():
                if camoID in condition.getValue():
                    camos.append(
                        formatters.packMissionCamoElement(camoTypeName))

            if camos:
                mapsTypesStr = i18n.makeString(
                    '#quests:details/conditions/mapsType')
                mapsTypeLabels = [iconData.iconLabel for iconData in camos]
                maps = ', '.join(mapsTypeLabels)
                tooltipBody = i18n.makeString(
                    QUESTS.MISSIONDETAILS_CONDITIONS_MAPSTYPE_BODY, maps=maps)
                tooltip = makeTooltip(mapsTypesStr, tooltipBody)
                if len(camos) > 1:
                    label = text_styles.main(
                        '#quests:missionDetails/conditions/mapsType')
                    iconsData = ''.join([iconData.icon for iconData in camos])
                else:
                    iconData = findFirst(None, camos)
                    label = text_styles.main(iconData.iconLabel)
                    iconsData = iconData.icon
                result.append(
                    formatters.packMissionPrebattleCondition(label,
                                                             icons=iconsData,
                                                             tooltip=tooltip))
        return result
示例#36
0
 def __onItemsChanged(self, updateReason, invalidItems):
     vehiclesDiff = invalidItems.get(GUI_ITEM_TYPE.VEHICLE)
     if vehiclesDiff is not None:
         falloutVehicle = findFirst(lambda v: v.intCD in vehiclesDiff, getFalloutCtrl().getSelectedVehicles())
         if falloutVehicle is not None:
             self.__updatePrebattleControls()
     return
示例#37
0
 def swap(self):
     defaultQueue = AccountSettings.getSettings(DEFAULT_QUEUE)
     if self.lobbyContext.getServerSettings().isBootcampEnabled():
         defaultQueue = QUEUE_TYPE.RANDOMS
     if defaultQueue == QUEUE_TYPE.SANDBOX:
         isSelected = True
         dossier = self.itemsCache.items.getAccountDossier()
         criteria = REQ_CRITERIA.INVENTORY | REQ_CRITERIA.VEHICLE.LEVELS(
             range(3, 10)
         ) | ~REQ_CRITERIA.VEHICLE.EXPIRED_RENT | ~REQ_CRITERIA.VEHICLE.EVENT_BATTLE
         vehicles = sorted(
             self.itemsCache.items.getVehicles(criteria=criteria).values(),
             key=lambda item: item.level)
         vehicle = findFirst(None, vehicles)
         if vehicle is not None:
             AccountSettings.setSettings(DEFAULT_QUEUE, QUEUE_TYPE.RANDOMS)
             isSelected = False
         if dossier is not None and isSelected:
             count = dossier.getRandomStats().getBattlesCount()
             if count >= BATTLES_TO_SELECT_RANDOM_MIN_LIMIT:
                 AccountSettings.setSettings(DEFAULT_QUEUE,
                                             QUEUE_TYPE.RANDOMS)
                 isSelected = False
     else:
         isSelected = False
     self._isSelected = isSelected
     return
示例#38
0
    def __updateUsersData(self, userDBIDs):
        diff = []
        userGetter = storage_getter('users')().getUser
        colorGetter = g_settings.getColorScheme('rosters').getColors
        for userDBID in userDBIDs:
            data = findFirst(lambda d: d['creator'].get('dbID') == userDBID, self.collection)
            if data is not None:
                clubDBID = data['cfdUnitID']
                try:
                    index = self.mapping[clubDBID]
                    item = self.collection[index]
                except (KeyError, IndexError):
                    LOG_ERROR('Item not found', clubDBID)
                    continue

                creator = userGetter(userDBID)
                creatorVO = makeUserVO(creator, colorGetter)
                creatorName = creator.getName()
                item.update({'creatorName': creatorName,
                 'rating': self.getGuiUserRating(userDBID)})
                if creator.hasValidName():
                    item['creator'] = creatorVO
                diff.append(index)

        if len(diff):
            self.updateItems(diff)
        return
    def getPenalties(self, vehicle):
        crew, emptySlots, otherVehicleSlots = functions.extractCrewDescrs(vehicle, replaceNone=False)
        crewFactors = items_utils.getCrewAffectedFactors(vehicle.descriptor, crew)
        result = {}
        currParams = self.getParamsDict(True)
        for slotId, factors in crewFactors.iteritems():
            for factor, factorValue in factors.iteritems():
                if factor in _FACTOR_TO_SKILL_PENALTY_MAP:
                    oldFactor = copy.copy(self.__factors[factor])
                    self.__factors[factor] = _universalSum(oldFactor, factorValue)
                    params = _FACTOR_TO_SKILL_PENALTY_MAP[factor]
                    for paramName in params:
                        paramPenalties = result.setdefault(paramName, {})
                        if slotId not in emptySlots:
                            newValue = getattr(self, paramName)
                            if newValue is None:
                                continue
                            state = rateParameterState(paramName, currParams[paramName], newValue)
                            if isinstance(currParams[paramName], collections.Iterable):
                                states, deltas = zip(*state)
                                if findFirst(lambda v: v == PARAM_STATE.WORSE, states):
                                    paramPenalties[slotId] = deltas
                            elif state[0] == PARAM_STATE.WORSE:
                                paramPenalties[slotId] = state[1]
                        paramPenalties[slotId] = 0

                    self.__factors[factor] = oldFactor

        roles = vehicle.descriptor.type.crewRoles
        for paramName, penalties in result.items():
            result[paramName] = [ _PenaltyInfo(roles[slotId][0], value, slotId in otherVehicleSlots) for slotId, value in penalties.iteritems() ]

        return {k:v for k, v in result.iteritems() if v}
示例#40
0
    def __updateUsersData(self, userDBIDs):
        diff = []
        userGetter = storage_getter('users')().getUser
        colorGetter = g_settings.getColorScheme('rosters').getColors
        for userDBID in userDBIDs:
            data = findFirst(lambda d: d['creator'].get('dbID') == userDBID,
                             self.collection)
            if data is not None:
                clubDBID = data['cfdUnitID']
                try:
                    index = self.mapping[clubDBID]
                    item = self.collection[index]
                except (KeyError, IndexError):
                    LOG_ERROR('Item not found', clubDBID)
                    continue

                creator = userGetter(userDBID)
                creatorVO = makeUserVO(creator, colorGetter)
                creatorName = creator.getName()
                item.update({
                    'creatorName': creatorName,
                    'rating': self.getGuiUserRating(userDBID)
                })
                if creator.hasValidName():
                    item['creator'] = creatorVO
                diff.append(index)

        if len(diff):
            self.updateItems(diff)
        return
    def updateList(self):
        directions = []
        openedDirectionsCount = len(self.fortCtrl.getFort().getOpenedDirections())
        fightsForDirections = self.fortCtrl.getFort().getDirectionsInBattle()
        for direction in range(1, g_fortCache.maxDirections + 1):
            buildings = self.fortCtrl.getFort().getBuildingsByDirections().get(direction)
            isOpened = buildings is not None
            inBattle = direction in fightsForDirections
            canBeClosed = isOpened and not inBattle and findFirst(lambda b: b is not None, buildings) is None
            buildingsData = []
            if isOpened:
                for building in buildings:
                    data = None
                    if building is not None:
                        uid = self.getBuildingUIDbyID(building.typeID)
                        data = {'uid': uid,
                         'progress': self._getProgress(building.typeID, building.level),
                         'toolTipData': [i18n.makeString('#fortifications:Buildings/buildingName/%s' % uid), self.getCommonBuildTooltipData(building)],
                         'iconSource': FortViewHelper.getSmallIconSource(uid, building.level)}
                    buildingsData.append(data)

            directions.append({'uid': direction,
             'fullName': i18n.makeString('#fortifications:General/direction', value=i18n.makeString('#fortifications:General/directionName%d' % direction)),
             'isOpened': isOpened,
             'canBeClosed': canBeClosed,
             'closeButtonVisible': isOpened and openedDirectionsCount > 1,
             'buildings': buildingsData})

        self.as_setDirectionsS(directions)
        return
 def onUnitSettingChanged(self, opCode, value):
     if opCode == UNIT_OP.CHANGE_FALLOUT_TYPE:
         rosterType = self.unitFunctional.getRosterType()
         self.__battleType, _ = findFirst(lambda (k, v): v == rosterType, FALLOUT_QUEUE_TYPE_TO_ROSTER.iteritems(), (QUEUE_TYPE.UNKNOWN, None))
         self.__updateVehicles()
         self._proxy.onSettingsChanged()
     return
 def __processPromo(self, promos):
     if not self.__isPromoOpen and not self.__waitingForWebBridgeData:
         logData = {
             'action': PromoLogActions.OPEN_IN_OLD,
             'type': PromoLogSubjectType.PROMO_SCREEN
         }
         if self.__pendingPromo is not None:
             promoData = self.__pendingPromo
             logData.update({
                 'source': promoData.source,
                 'url': promoData.url
             })
             loadingCallback = self.__logger.getLoggingFuture(**logData)
             self.__registerAndShowPromoBrowser(promoData.url,
                                                promoData.closeCallback,
                                                loadingCallback)
             self.__pendingPromo = None
             return
         promo = findFirst(
             lambda item: item.eventType.startswith(
                 gc_constants.PROMO.TEMPLATE.ACTION), promos)
         if promo:
             logData.update({
                 'source': PromoLogSourceType.SSE,
                 'url': promo.data
             })
             self.__showBrowserView(
                 promo.data, self.__logger.getLoggingFuture(**logData))
     return
示例#44
0
 def _getValidatedVehicles(vInfos):
     if not findFirst(lambda v: not v.isEmpty(), vInfos, False):
         if g_currentVehicle.isPresent():
             vehicle = g_currentVehicle.item
             vInfos = (unit_items.VehicleInfo(vehicle.invID, vehicle.intCD, vehicle.level),)
         else:
             vInfos = (unit_items.VehicleInfo(),)
     return vInfos
示例#45
0
 def parseTag(self, pyGlooxTag):
     tag = findFirst(None, pyGlooxTag.filterXPath(self.getXPath(suffix='status')))
     code = self.getDefaultData()
     if tag is not None:
         found = tag.findAttribute('code')
         if found and found.isdigit():
             code = int(found)
     return code
示例#46
0
 def getBackgroundImage(self):
     if self.__potapovQuest.getQuestBranch() == potapov_quests.PQ_BRANCH.FALLOUT:
         return _BG_IMG_FALLOUT[self.__potapovQuest.getMajorTag()]
     else:
         vehType = findFirst(None, self.__potapovQuest.getVehicleClasses())
         if vehType in _BG_IMG_BY_VEH_TYPE:
             return _BG_IMG_BY_VEH_TYPE[vehType]
         return random.choice(_BG_IMG_BY_VEH_TYPE.values())
示例#47
0
 def parseTag(self, pyGlooxTag):
     tag = findFirst(None, pyGlooxTag.filterXPath(self.getXPath(suffix='count')))
     if tag:
         count = int(tag.getCData())
     else:
         count = 0
     tag = findFirst(None, pyGlooxTag.filterXPath(self.getXPath(suffix='first')))
     if tag:
         first = self._converter(tag.getCData())
     else:
         first = None
     tag = findFirst(None, pyGlooxTag.filterXPath(self.getXPath(suffix='last')))
     if tag:
         last = self._converter(tag.getCData())
     else:
         last = None
     return (count, first, last)
示例#48
0
 def parseTag(self, pyGlooxTag):
     fieldType = pyGlooxTag.findAttribute('type')
     fieldVar = pyGlooxTag.findAttribute('var')
     tag = findFirst(None, pyGlooxTag.filterXPath(self.getXPath(suffix='value')))
     if tag:
         value = tag.getCData()
     else:
         value = ''
     return Field(fieldType, fieldVar, value)
示例#49
0
 def __updateQuests(self):
     self.__clearQuestsData()
     refSystemQuests = g_eventsCache.getHiddenQuests(lambda x: x.getType() == EVENT_TYPE.REF_SYSTEM_QUEST)
     if refSystemQuests:
         self.__quests = self.__mapQuests(refSystemQuests.values())
         self.__totalXP, _ = self.__quests[-1]
         notCompleted = findFirst(lambda q: not q.isCompleted(), refSystemQuests.values())
         self.__isTotallyCompleted = notCompleted is None
     self.onQuestsUpdated()
 def init(self):
     rosterType = self.unitFunctional.getRosterType()
     self.__battleType, _ = findFirst(lambda (k, v): v == rosterType, FALLOUT_QUEUE_TYPE_TO_ROSTER.iteritems(), (QUEUE_TYPE.UNKNOWN, None))
     self.__updateVehicles()
     self.startGlobalListening()
     if self.isEnabled():
         g_eventDispatcher.addFalloutToCarousel()
     super(_SquadDataStorage, self).init()
     return
示例#51
0
    def __getNextMotiveQuest(self):
        quests = g_eventsCache.getMotiveQuests(lambda q: q.isAvailable() and not q.isCompleted())
        sortedQuests = sorted(quests.values(), key=lambda q: q.getPriority())
        nextQuest = findFirst(None, sortedQuests)
        for quest in sortedQuests:
            if quest.getPriority() > self.__quest.getPriority():
                return quest

        return nextQuest
示例#52
0
def formatRecoveryLeftValue(secondsLeft):
    closestUnit = findFirst(lambda (k, v): v < secondsLeft, _TIME_FORMAT_UNITS)
    if closestUnit is not None:
        name, factor = closestUnit
        timeLeft = int(math.ceil(float(secondsLeft) / factor))
        return makeString(TOOLTIPS.template_all_short(name), value=timeLeft)
    else:
        return makeString(TOOLTIPS.TEMPLATE_TIME_LESSTHENMINUTE)
        return
示例#53
0
 def parseTag(self, pyGlooxTag):
     info = self.getDefaultData()
     tag = findFirst(None, pyGlooxTag.filterXPath(self.getXPath(suffix='nickname')))
     if tag:
         info['name'] = tag.getCData()
     tag = findFirst(None, pyGlooxTag.filterXPath(self.getXPath(suffix='userid')))
     if tag:
         info['dbID'] = long(tag.getCData())
     clanDBID, clanAbbrev = (0L, '')
     tag = findFirst(None, pyGlooxTag.filterXPath(self.getXPath(suffix='clanid')))
     if tag:
         clanDBID = tag.getCData()
     tag = findFirst(None, pyGlooxTag.filterXPath(self.getXPath(suffix='clantag')))
     if tag:
         clanAbbrev = tag.getCData()
     if clanDBID and clanAbbrev:
         info['clanInfo'] = makeClanInfo(clanDBID, clanAbbrev)
     return info
示例#54
0
 def parseTag(self, pyGlooxTag):
     info = self.getDefaultData()
     tag = findFirst(None, pyGlooxTag.filterXPath(self.getXPath(suffix="nickname")))
     if tag:
         info["name"] = tag.getCData()
     tag = findFirst(None, pyGlooxTag.filterXPath(self.getXPath(suffix="userid")))
     if tag:
         info["dbID"] = long(tag.getCData())
     clanDBID, clanAbbrev = (0, "")
     tag = findFirst(None, pyGlooxTag.filterXPath(self.getXPath(suffix="clanid")))
     if tag:
         clanDBID = tag.getCData()
     tag = findFirst(None, pyGlooxTag.filterXPath(self.getXPath(suffix="clantag")))
     if tag:
         clanAbbrev = tag.getCData()
     if clanDBID and clanAbbrev:
         info["clanInfo"] = makeClanInfo(clanDBID, clanAbbrev)
     return info
示例#55
0
    def __updateNewItemsByType(self, newItemsByType, newItems, interfaceType):
        byType = newItemsByType[interfaceType]
        if newItems is not None:

            def matcher(x, y):
                return x['id'] == y['id'] and x['price']['isGold'] == y['price']['isGold'] and x['price']['isGold']

            for i in newItems:
                if i['price']['isGold'] and not findFirst(partial(matcher, i), byType, False):
                    byType.append(i)
示例#56
0
 def set(self, pyGlooxTag):
     result = blocking_cmd.BlockItemHandler().handleTag(pyGlooxTag)
     jid, info = findFirst(None, result, ('', {}))
     if jid != self._jid:
         return
     user = _syncBlockItem(self.usersStorage, self._jid, **info)
     if user:
         g_logOutput.debug(CLIENT_LOG_AREA.BLOCK_LIST, 'Block item is added', jid, info)
         self._doNotify(USER_ACTION_ID.IGNORED_ADDED, user)
         self._doNotify(USER_ACTION_ID.MUTE_SET, user, False)
     self._result = TASK_RESULT.REMOVE
示例#57
0
 def __updateQueueInfo(self):
     if prb_getters.isCompany():
         qType = constants.QUEUE_TYPE.COMPANIES
     elif self.prbDispatcher is not None and self.prbDispatcher.getFunctionalState().isInUnit():
         rosterType = self.prbDispatcher.getFunctionalState().rosterType
         qType, _ = findFirst(lambda (k, v): v == rosterType, FALLOUT_QUEUE_TYPE_TO_ROSTER.iteritems(), (constants.QUEUE_TYPE.RANDOMS, None))
     else:
         qType = prb_getters.getQueueType()
     self.__provider = _providerFactory(self, qType)
     self.__provider.start()
     return
示例#58
0
 def _showAward(self, ctx):
     data = ctx[1].data
     if data:
         newGoodies = data.get('newGoodies', [])
         if len(newGoodies) > 0:
             discountID = findFirst(None, newGoodies)
             shopDiscounts = g_itemsCache.items.shop.premiumPacketsDiscounts
             discount = shopDiscounts.get(discountID, None)
             if discount is not None and discount.targetID == GOODIE_TARGET_TYPE.ON_BUY_PREMIUM:
                 packet = discount.getTargetValue()
                 discountPrc = getPremiumCostActionPrc(shopDiscounts, packet, g_itemsCache.items)
                 shared_events.showPremiumDiscountAward(discount.condition[1], packet, discountPrc)
示例#59
0
 def _selectQuest(self, questID):
     motiveQuests = g_eventsCache.getMotiveQuests(filterFunc=self._filterFunc)
     if questID in motiveQuests or self.__questsDescriptor is not None and self.__questsDescriptor.getChapter(questID) is not None:
         return self.as_setSelectedQuestS(questID)
     else:
         if questID in g_eventsCache.getMotiveQuests(filterFunc=lambda q: q.isCompleted()):
             sortedQuests = sorted(motiveQuests.values(), key=lambda q: q.getPriority())
             nextQuest = findFirst(None, sortedQuests)
             if nextQuest:
                 return self.as_setSelectedQuestS(nextQuest.getID())
         SystemMessages.pushI18nMessage(SYSTEM_MESSAGES.QUESTS_NOQUESTSWITHGIVENID)
         return
    def __makeRosters(self):
        result = []
        for dbID in self.__fixedPlayers:
            player = findFirst(lambda m: m.getID() == dbID, g_clanCache.clanMembers)
            if player is not None:
                intTotalMining, intWeekMining = self.fortCtrl.getFort().getPlayerContributions(dbID)
                role = text_styles.standard(i18n.makeString(getClanRoleString(player.getClanRole())))
                roleID = self.CLAN_MEMBER_ROLES.index(player.getClanRole())
                vo = vo_converters.makeSimpleClanListRenderVO(player, intTotalMining, intWeekMining, role, roleID)
                result.append(vo)

        return result