def __onChangeVehicleCamouflage(self, price, kind, resultID):
     if resultID < 0:
         message = i18n.makeString(SYSTEM_MESSAGES.CUSTOMIZATION_CAMOUFLAGE_CHANGE_SERVER_ERROR)
         self.onCustomizationChangeFailed(message)
         return
     else:
         item = self.currentItemsByKind.get(kind)
         g_tankActiveCamouflage[g_currentVehicle.item.intCD] = kind
         item['id'] = item.get('newItemID')
         item['lifeCycle'] = None
         item['newItemID'] = None
         if CAMOUFLAGE_KINDS.get(self._itemsDP.currentGroup) == kind:
             self._itemsDP.currentItemID = item['id']
         cost, isGold = price
         if cost == 0:
             key = SYSTEM_MESSAGES.CUSTOMIZATION_CAMOUFLAGE_CHANGE_SUCCESS_FREE
             typeValue = SystemMessages.SM_TYPE.Information
             str = i18n.makeString(key)
         else:
             if isGold:
                 key = SYSTEM_MESSAGES.CUSTOMIZATION_CAMOUFLAGE_CHANGE_SUCCESS_GOLD
                 fCost = BigWorld.wg_getGoldFormat(cost)
                 typeValue = SystemMessages.SM_TYPE.CustomizationForGold
             else:
                 key = SYSTEM_MESSAGES.CUSTOMIZATION_CAMOUFLAGE_CHANGE_SUCCESS_CREDITS
                 fCost = BigWorld.wg_getIntegralFormat(cost)
                 typeValue = SystemMessages.SM_TYPE.CustomizationForCredits
             str = i18n.makeString(key, fCost)
         self.onCustomizationChangeSuccess(str, typeValue)
         return
Example #2
0
 def _getConditions(self, svrEvents):
     subBlocks = []
     bonus = self.event.bonusCond
     battlesLeft, battlesCount, inrow = None, None, False
     battles = bonus.getConditions().find('battles')
     if battles is not None:
         battlesCount = battles._getTotalValue()
         if not self.event.isCompleted() and bonus.getGroupByValue() is None:
             progress = battles.getProgressPerGroup()
             if None in progress:
                 curProg, totalProg, _, _ = progress[None]
                 battlesLeft = totalProg - curProg
     bonusFmtConds = bonus.format(svrEvents, event=self.event)
     if len(bonusFmtConds):
         subBlocks.extend(formatters.indexing(bonusFmtConds))
     postBattleFmtConds = self.event.postBattleCond.format(svrEvents, event=self.event)
     if len(postBattleFmtConds):
         if len(bonusFmtConds):
             subBlocks.append(formatters.packSeparator(label=i18n.makeString('#quests:details/conditions/postBattle/separator')))
         subBlocks.extend(formatters.indexing(postBattleFmtConds))
     if bonus.isDaily():
         resetHourOffset = (time_utils.ONE_DAY - self._getDailyProgressResetTimeOffset()) / 3600
         if resetHourOffset >= 0:
             subBlocks.append(formatters.packTextBlock(label=formatters.formatYellow('#quests:details/conditions/postBattle/dailyReset') % {'time': time.strftime(i18n.makeString('#quests:details/conditions/postBattle/dailyReset/timeFmt'), time_utils.getTimeStructInLocal(time_utils.getTimeTodayForUTC(hour=resetHourOffset)))}))
     result = []
     if len(subBlocks) or battlesCount:
         if not self.event.isGuiDisabled():
             result.append(formatters.packConditionsBlock(battlesCount, battlesLeft, bonus.isInRow(), conditions=subBlocks))
         else:
             result.append(formatters.packConditionsBlock(conditions=subBlocks))
     if bonus.getGroupByValue() is not None and not self.event.isGuiDisabled():
         progressesFmt = bonus.formatGroupByProgresses(svrEvents, self.event)
         if len(progressesFmt):
             result.append(formatters.packTopLevelContainer(i18n.makeString('#quests:details/conditions/groupBy/%s' % bonus.getGroupByValue()), subBlocks=progressesFmt, isResizable=len(progressesFmt) > 5))
     return formatters.todict(result)
 def __getTransportingBuildTooltipData(self, building):
     state = None
     headerArgs = {}
     bodyArgs = {}
     if building is not None:
         buildingName = building.userName
         if building.isInCooldown():
             state = 'cooldown'
             timeStr = time_formatters.getTimeDurationStr(building.getEstimatedCooldown())
             headerArgs = {'buildingName': buildingName}
             bodyArgs = {'time': timeStr}
         elif not building.hasStorageToExport():
             state = 'emptyStorage'
             headerArgs = {'buildingName': buildingName}
         elif not building.hasSpaceToImport() and self.isOnNextTransportingStep():
             state = 'notEmptySpace'
             headerArgs = {'buildingName': buildingName}
         elif not building.isReady():
             state = 'foundation'
     else:
         state = 'foundation'
     if state == 'foundation':
         headerArgs = {'buildingName': i18n.makeString(FORTIFICATIONS.BUILDINGS_TROWELLABEL)}
     if state is not None:
         header = TOOLTIPS.fortification_transporting(state + '/header')
         body = TOOLTIPS.fortification_transporting(state + '/body')
         return [i18n.makeString(header, **headerArgs), i18n.makeString(body, **bodyArgs)]
     else:
         return
         return
 def __onDropVehicleCamouflage(self, resultID, kind):
     if resultID < 0:
         message = i18n.makeString(SYSTEM_MESSAGES.CUSTOMIZATION_CAMOUFLAGE_DROP_SERVER_ERROR)
         self.onCustomizationDropFailed(message)
         return
     else:
         item = self.currentItemsByKind.get(kind)
         hangarItem = CustomizationHelper.getItemFromHangar(CUSTOMIZATION_ITEM_TYPE.CAMOUFLAGE_TYPE, item.get('id'), self._nationID)
         if hangarItem:
             intCD = g_currentVehicle.item.intCD
             vehicle = vehicles.getVehicleType(int(intCD))
             message = i18n.makeString(SYSTEM_MESSAGES.CUSTOMIZATION_CAMOUFLAGE_STORED_SUCCESS, vehicle=vehicle.userString)
         else:
             message = i18n.makeString(SYSTEM_MESSAGES.CUSTOMIZATION_CAMOUFLAGE_DROP_SUCCESS)
         if g_tankActiveCamouflage.has_key(g_currentVehicle.item.intCD):
             del g_tankActiveCamouflage[g_currentVehicle.item.intCD]
         newID = None
         newLifeCycle = None
         if gui.game_control.g_instance.igr.getRoomType() != IGR_TYPE.NONE:
             camouflages = g_currentVehicle.item.descriptor.camouflages
             camo = camouflages[kind]
             if camo[0] is not None:
                 newID = camo[0]
                 newLifeCycle = (camo[1], camo[2])
         item['id'] = newID
         item['lifeCycle'] = newLifeCycle
         if CAMOUFLAGE_KINDS.get(self._itemsDP.currentGroup) == kind:
             self._itemsDP.currentItemID = newID
         self.onCustomizationDropSuccess(message)
         return
    def _getRentData(self, vehicle, vehiclePricesActionData):
        result = []
        rentPackages = vehicle.rentPackages
        for rentPackage in rentPackages:
            days = rentPackage['days']
            actionRentPrice = None
            if rentPackage['rentPrice'] != rentPackage['defaultRentPrice']:
                actionRentPrice = getItemRentActionTooltipData(vehicle, rentPackage)
            result.append({'itemId': days,
             'label': i18n.makeString(MENU.SHOP_MENU_VEHICLE_RENT_DAYS, days=days),
             'price': rentPackage['rentPrice'],
             'enabled': vehicle.maxRentDuration - vehicle.rentLeftTime >= days * time_utils.ONE_DAY,
             'actionPrice': actionRentPrice})

        result.append({'itemId': -1,
         'label': i18n.makeString(MENU.SHOP_MENU_VEHICLE_RENT_FOREVER),
         'price': vehicle.buyPrice,
         'enabled': not vehicle.isDisabledForBuy and not vehicle.isHidden,
         'actionPrice': vehiclePricesActionData})
        selectedId = -1
        for ddItem in result:
            if ddItem['enabled']:
                selectedId = ddItem['itemId']
                break

        return {'data': result,
         'selectedId': selectedId}
 def _updateView(self):
     buildingName = i18n.makeString(FORTIFICATIONS.buildings_buildingname(self.__uid))
     windowTitle = i18n.makeString(FORTIFICATIONS.MODERNIZATION_WINDOWTITLE, buildingName=buildingName)
     self.as_windowTitleS(windowTitle)
     self.as_applyButtonLblS(FORTIFICATIONS.MODERNIZATION_APPLYBUTTON_LABEL)
     self.as_cancelButtonS(FORTIFICATIONS.MODERNIZATION_CANCELBUTTON_LABEL)
     self.__buildData()
Example #7
0
    def _getValue(self):
        records = {'current': None,
         'nearest': None}
        achievement = self._tooltip.item
        configuration = self._tooltip.context.getParamsConfiguration(achievement)
        dossier = configuration.dossier
        dossierType = configuration.dossierType
        isCurrentUserDossier = configuration.isCurrentUserDossier
        if achievement.getRecordName() == MARK_OF_MASTERY_RECORD:
            if achievement.getCompDescr() is not None:
                if achievement.getPrevMarkOfMastery() < achievement.getMarkOfMastery():
                    records['current'] = makeString('#tooltips:achievement/newRecord')
                records['nearest'] = [[makeString('#tooltips:achievement/recordOnVehicle', vehicleName=g_itemsCache.items.getItemByCD(int(achievement.getCompDescr())).shortUserName), max(achievement.getMarkOfMastery(), achievement.getPrevMarkOfMastery()) or achievement.MIN_LVL]]
        elif dossier is not None and dossierType == constants.DOSSIER_TYPE.ACCOUNT and isCurrentUserDossier:
            if achievement.getType() == 'series':
                vehicleRecords = set()
                vehsWereInBattle = set(dossier.getTotalStats().getVehicles().keys())
                for vehCD in vehsWereInBattle:
                    totalStats = g_itemsCache.items.getVehicleDossier(vehCD).getTotalStats()
                    if totalStats.isAchievementInLayout(achievement.getRecordName()):
                        vehAchieve = totalStats.getAchievement(achievement.getRecordName())
                        if vehAchieve and vehAchieve.getValue():
                            vehicle = g_itemsCache.items.getItemByCD(vehCD)
                            vehicleRecords.add((vehicle.userName, vehAchieve.getValue()))
                            if vehAchieve.getValue() == achievement.getValue():
                                records['current'] = vehicle.userName

                records['nearest'] = sorted(vehicleRecords, key=lambda x: x[1], reverse=True)[:3]
        return records
Example #8
0
    def handleLoginRejectedBan(self, status, message):
        try:
            LOG_DEBUG('handleLoginRejectedBan', message)
            msg_dict = json.loads(message)
            if not isinstance(msg_dict, dict):
                self.handleLoginCustomDefinedError(status, message)
                return
            self.__loginDataLoader.token2 = msg_dict.get('token2', '')
            self.__loginDataLoader.saveUserToken(self.__loginDataLoader.passLength, self.__loginDataLoader.token2)
            json_dict = msg_dict.get('bans')
            msg_dict = json.loads(json_dict)
        except Exception:
            LOG_CURRENT_EXCEPTION()
            self.handleLoginCustomDefinedError(status, message)
            return

        expiryTime = 0
        reason = ''
        if isinstance(msg_dict, dict):
            expiryTime = int(msg_dict.get('expiryTime', 0))
            reason = i18n.encodeUtf8(msg_dict.get('reason', ''))
        if reason == BAN_REASON.CHINA_MIGRATION:
            self.__handleMigrationNeeded()
        if reason.startswith('#'):
            reason = i18n.makeString(reason)
        if expiryTime > 0:
            expiryTime = makeLocalServerTime(expiryTime)
            expiryTime = BigWorld.wg_getLongDateFormat(expiryTime) + ' ' + BigWorld.wg_getLongTimeFormat(expiryTime)
            errorMessage = i18n.makeString(MENU.LOGIN_STATUS_LOGIN_REJECTED_BAN, time=expiryTime, reason=reason)
        else:
            errorMessage = i18n.makeString(MENU.LOGIN_STATUS_LOGIN_REJECTED_BAN_UNLIMITED, reason=reason)
        self.onSetStatus(errorMessage, self.ALL_VALID)
    def __makeBlocksData(self):
        result = []
        for blockName in ('block1', 'block2', 'block3'):
            result.append({'blockTitle': text_styles.promoSubTitle(i18n.makeString(QUESTS.questspersonalwelcomeview_textblock_header(blockName))),
             'blockBody': text_styles.main(i18n.makeString(QUESTS.questspersonalwelcomeview_textblock_body(blockName)))})

        return result
Example #10
0
    def _showAward(self, ctx):
        _, message = ctx
        for dataForVehicle in message.data.values():
            arenaTypeID = dataForVehicle.get('arenaTypeID', 0)
            if arenaTypeID > 0 and arenaTypeID in ArenaType.g_cache:
                arenaType = ArenaType.g_cache[arenaTypeID]
            else:
                arenaType = None
            arenaCreateTime = dataForVehicle.get('arenaCreateTime', None)
            fairplayViolations = dataForVehicle.get('fairplayViolations', None)
            if arenaCreateTime and arenaType and fairplayViolations is not None and fairplayViolations[:2] != (0, 0):
                penaltyType = None
                violation = None
                if fairplayViolations[1] != 0:
                    penaltyType = 'penalty'
                    violation = fairplayViolations[1]
                elif fairplayViolations[0] != 0:
                    penaltyType = 'warning'
                    violation = fairplayViolations[0]
                from gui.DialogsInterface import showDialog
                showDialog(I18PunishmentDialogMeta('punishmentWindow', None, {'penaltyType': penaltyType,
                 'arenaName': i18n.makeString(arenaType.name),
                 'time': TimeFormatter.getActualMsgTimeStr(arenaCreateTime),
                 'reason': i18n.makeString(DIALOGS.all('punishmentWindow/reason/%s' % getFairPlayViolationName(violation)))}), lambda *args: None)

        return
 def _makeVehicleListItemVO(self, vehicle):
     enabled = vehicle.invID != -1
     warnTTHeader = ''
     warnTTBody = ''
     if enabled:
         if vehicle.isReadyToFight or vehicle.lock == LOCK_REASON.IN_QUEUE:
             showWarning = False
         else:
             warnTTHeader = i18n.makeString(TOOLTIPS.HISTORICALBATTLES_VEHICLE_NOTREADY_HEADER)
             if not vehicle.isCrewFull:
                 warnTTBody = i18n.makeString(TOOLTIPS.HISTORICALBATTLES_VEHICLE_NOTREADY_CREW)
             elif vehicle.isInBattle:
                 warnTTBody = i18n.makeString(TOOLTIPS.HISTORICALBATTLES_VEHICLE_NOTREADY_INBATTLE)
             elif vehicle.isBroken:
                 warnTTBody = i18n.makeString(TOOLTIPS.HISTORICALBATTLES_VEHICLE_NOTREADY_BROKEN)
             showWarning = True
     else:
         showWarning = False
     item = {'intCD': vehicle.intCD,
      'invID': vehicle.invID,
      'name': vehicle.shortUserName,
      'image': '../maps/icons/vehicle/small/{0}.png'.format(vehicle.name.replace(':', '-')),
      'enabled': enabled,
      'showWarning': showWarning,
      'warnTTHeader': warnTTHeader,
      'warnTTBody': warnTTBody}
     return item
 def change(self, vehInvID, section, isAlreadyPurchased):
     if self._newItemID is None:
         message = i18n.makeString(SYSTEM_MESSAGES.CUSTOMIZATION_INSCRIPTION_NOT_SELECTED)
         self.onCustomizationChangeFailed(message)
         return
     if self._rentalPackageDP.selectedPackage is None:
         message = i18n.makeString(SYSTEM_MESSAGES.CUSTOMIZATION_INSCRIPTION_DAYS_NOT_SELECTED)
         self.onCustomizationChangeFailed(message)
         return
     cost, isGold = self._itemsDP.getCost(self._newItemID)
     if cost < 0:
         message = i18n.makeString(SYSTEM_MESSAGES.CUSTOMIZATION_INSCRIPTION_COST_NOT_FOUND)
         self.onCustomizationChangeFailed(message)
         return
     if isAlreadyPurchased:
         daysToWear = 0
         cost = 0
     elif CustomizationHelper.isItemInHangar(CUSTOMIZATION_ITEM_TYPE.INSCRIPTION, self._newItemID, self._nationID, self._itemsDP.position):
         hangarItem = CustomizationHelper.getItemFromHangar(CUSTOMIZATION_ITEM_TYPE.INSCRIPTION_TYPE, self._newItemID)
         daysToWear = 0 if hangarItem.get('isPermanent') else 7
     else:
         daysToWear = self._rentalPackageDP.selectedPackage.get('periodDays')
     newIdToSend = 0
     isNewInDefaultSetup = False
     isCurrIgr = self._itemsDP.isIGRItem(self._currentItemID)
     if isCurrIgr:
         isNewInDefaultSetup = CustomizationHelper.isIdInDefaultSetup(CUSTOMIZATION_ITEM_TYPE.INSCRIPTION, self._newItemID)
     if self._currentItemID is None or not isCurrIgr or isCurrIgr and not isNewInDefaultSetup or isCurrIgr and isNewInDefaultSetup and daysToWear > 0:
         newIdToSend = self._newItemID
     BigWorld.player().inventory.changeVehicleInscription(vehInvID, self.getRealPosition(), newIdToSend, daysToWear, 1, lambda resultID: self.__onChangeVehicleInscription(resultID, (cost, isGold)))
Example #13
0
def makeBuildingIndicatorsVO(buildingLevel, progress, hpVal, hpTotalVal, defResVal, maxDefResVal):
    FORMAT_PATTERN = '###'
    if progress == FORT_ALIAS.STATE_FOUNDATION_DEF or progress == FORT_ALIAS.STATE_FOUNDATION:
        hpValueFormatter = text_styles.alert(FORMAT_PATTERN)
    else:
        hpValueFormatter = text_styles.defRes(FORMAT_PATTERN)
    hpTotalFormatted = str(BigWorld.wg_getIntegralFormat(hpTotalVal)) + ' '
    formattedHpTotal = ''.join((text_styles.standard(hpTotalFormatted), icons.nut()))
    defResValueFormatter = text_styles.defRes(FORMAT_PATTERN)
    maxDefDerFormatted = str(BigWorld.wg_getIntegralFormat(maxDefResVal)) + ' '
    formattedDefResTotal = ''.join((text_styles.standard(maxDefDerFormatted), icons.nut()))
    hpProgressLabels = {'currentValue': str(BigWorld.wg_getIntegralFormat(hpVal)),
     'currentValueFormatter': hpValueFormatter,
     'totalValue': formattedHpTotal,
     'separator': '/'}
    storeProgressLabels = {'currentValue': str(BigWorld.wg_getIntegralFormat(defResVal)),
     'currentValueFormatter': defResValueFormatter,
     'totalValue': formattedDefResTotal,
     'separator': '/'}
    result = {'hpLabel': i18n.makeString(FORTIFICATIONS.BUILDINGPOPOVER_INDICATORS_HPLBL),
     'defResLabel': i18n.makeString(FORTIFICATIONS.BUILDINGPOPOVER_INDICATORS_DEFRESLBL),
     'hpCurrentValue': hpVal,
     'hpTotalValue': hpTotalVal,
     'defResCurrentValue': defResVal,
     'defResTotalValue': maxDefResVal,
     'hpProgressLabels': hpProgressLabels,
     'defResProgressLabels': storeProgressLabels}
    return result
 def __makeData(self):
     result = {}
     building = self.fortCtrl.getFort().getBuilding(self.__buildingId)
     self.__fixedPlayers = building.attachedPlayers
     self.__oldBuilding = self.getBuildingUIDbyID(self.fortCtrl.getFort().getAssignedBuildingID(BigWorld.player().databaseID))
     self.__isAssigned = self.__buildingUId == self.__oldBuilding
     self.__limitFixedPlayers = building.typeRef.attachedPlayersLimit
     isVisible = True
     isEnabled = True
     btnTooltipData = TOOLTIPS.FORTIFICATION_FIXEDPLAYERS_ASSIGNBTNENABLED
     if self.__isAssigned:
         isVisible = False
         result['playerIsAssigned'] = self.app.utilsManager.textManager.getText(TEXT_MANAGER_STYLES.NEUTRAL_TEXT, i18n.makeString(FORTIFICATIONS.FIXEDPLAYERS_HEADER_ISASSIGNED))
     if isVisible and len(self.__fixedPlayers) == self.__limitFixedPlayers:
         isEnabled = False
         btnTooltipData = TOOLTIPS.FORTIFICATION_FIXEDPLAYERS_ASSIGNBTNDISABLED
     result['windowTitle'] = i18n.makeString(FORTIFICATIONS.FIXEDPLAYERS_WINDOWTITLE, buildingName=i18n.makeString(FORTIFICATIONS.buildings_buildingname(self.__buildingUId)))
     result['buildingId'] = self.__buildingId
     result['buttonLbl'] = i18n.makeString(FORTIFICATIONS.FIXEDPLAYERS_HEADER_BTNLBL)
     result['isEnableBtn'] = isEnabled
     result['isVisibleBtn'] = isVisible
     generalToolTip = TOOLTIPS.FORTIFICATION_FIXEDPLAYERS_GENERALTOOLTIP
     if len(self.__fixedPlayers) == self.__limitFixedPlayers:
         generalToolTip = TOOLTIPS.FORTIFICATION_FIXEDPLAYERS_GENERALTOOLTIPMAXLIMIT
     result['generalTooltipData'] = generalToolTip
     result['btnTooltipData'] = btnTooltipData
     result['countLabel'] = self.__playersLabel()
     result['rosters'] = self.__makeRosters()
     self.as_setDataS(result)
 def __onChangeVehicleInscription(self, resultID, price):
     if resultID < 0:
         message = i18n.makeString(SYSTEM_MESSAGES.CUSTOMIZATION_INSCRIPTION_CHANGE_SERVER_ERROR)
         self.onCustomizationChangeFailed(message)
         return
     self._currentItemID = self._newItemID
     self._currentLifeCycle = None
     self._newItemID = None
     self._itemsDP.currentItemID = self._currentItemID
     cost, isGold = price
     if cost == 0:
         key = SYSTEM_MESSAGES.CUSTOMIZATION_INSCRIPTION_CHANGE_SUCCESS_FREE
         type = SystemMessages.SM_TYPE.Information
         str = i18n.makeString(key)
     else:
         if isGold:
             key = SYSTEM_MESSAGES.CUSTOMIZATION_INSCRIPTION_CHANGE_SUCCESS_GOLD
             fCost = BigWorld.wg_getGoldFormat(cost)
             type = SystemMessages.SM_TYPE.CustomizationForGold
         else:
             key = SYSTEM_MESSAGES.CUSTOMIZATION_INSCRIPTION_CHANGE_SUCCESS_CREDITS
             fCost = BigWorld.wg_getIntegralFormat(cost)
             type = SystemMessages.SM_TYPE.CustomizationForCredits
         str = i18n.makeString(key, fCost)
     self.onCustomizationChangeSuccess(str, type)
    def __makeDivisionsData(self, list):
        result = []
        for item in list:
            divisionType = {}
            title = i18n.makeString(item['label'])
            profit = fort_formatters.getDefRes(item['profit'])
            divisionID = item['level']
            divisionType['divisionName'] = highTitle(i18n.makeString(I18N_FORTIFICATIONS.CHOICEDIVISION_DIVISIONFULLNAME, divisionType=title))
            divisionType['divisionProfit'] = standard(i18n.makeString(I18N_FORTIFICATIONS.CHOICEDIVISION_DIVISIONPROFIT, defResCount=profit))
            minVehLvl, maxVehLvl = item['vehLvls']
            if maxVehLvl == minVehLvl:
                vehicleLevel = i18n.makeString(I18N_FORTIFICATIONS.CHOICEDIVISION_VEHICLELEVELSINGLE, level=_getTextLevels(maxVehLvl))
            else:
                vehicleLevel = i18n.makeString(I18N_FORTIFICATIONS.CHOICEDIVISION_VEHICLELEVEL, minLevel=_getTextLevels(minVehLvl), maxLevel=_getTextLevels(maxVehLvl))
            divisionType['vehicleLevel'] = standard(vehicleLevel)
            divisionType['divisionID'] = divisionID
            if divisionID == SORTIE_DIVISION.MIDDLE:
                minCount, maxCount = self.playersRange[0]
            elif divisionID == SORTIE_DIVISION.CHAMPION:
                minCount, maxCount = self.playersRange[1]
            else:
                minCount, maxCount = self.playersRange[2]
            divisionType['playerRange'] = main('{0}-{1}'.format(str(minCount), str(maxCount)))
            result.append(divisionType)

        return result
 def _getCooldownInfo(self, order):
     if not order.isPermanent:
         leftTime = order.getUsageLeftTime()
         leftTimeStr = time_formatters.getTimeDurationStr(leftTime)
         return i18n.makeString(TOOLTIPS.FORTIFICATION_ORDERPOPOVER_PROGRESSBAR_TIMELEFT, timeLeft=leftTimeStr)
     else:
         return i18n.makeString(TOOLTIPS.FORTIFICATION_ORDERPOPOVER_INDEFENSIVE)
 def __getNotEnoughMembersText(self, data):
     minClanSize = data.get('minClanSize', 0)
     text = text_styles.alert(i18n.makeString(FORTIFICATIONS.FORTWELCOMEVIEW_WARNING, minClanSize=minClanSize))
     header = i18n.makeString(TOOLTIPS.FORTIFICATION_WELCOME_CANTCREATEFORT_HEADER)
     body = i18n.makeString(TOOLTIPS.FORTIFICATION_WELCOME_CANTCREATEFORT_BODY, minClanSize=minClanSize)
     tooltip = makeTooltip(header, body)
     return (text, tooltip)
Example #19
0
def _readTips():
    result = defaultdict(lambda: defaultdict(lambda: defaultdict(lambda: defaultdict(lambda: defaultdict(list)))))
    tipsPattern = re.compile("^tip(\\d+)")
    try:
        translator = i18n.g_translators["tips"]
    except IOError:
        LOG_CURRENT_EXCEPTION()
        return result

    for key in translator._catalog.iterkeys():
        if len(key) > 0:
            sreMatch = tipsPattern.match(key)
            if sreMatch is not None and len(sreMatch.groups()) > 0:
                strTipsConditions = key.split("/")
                if len(strTipsConditions) == TIPS_PATTERN_PARTS_COUNT:
                    tipID, status, group, battlesCountConditions, arenaGuiType, vehicleTypeCondition, nation, vehLevel = (
                        strTipsConditions
                    )
                    battlesCountConditions = battlesCountConditions.split("_")
                    if len(battlesCountConditions) == BATTLE_CONDITIONS_PARTS_COUNT:
                        minBattlesCount = _getIntValue(battlesCountConditions[0])
                        maxBattlesCount = _getIntValue(battlesCountConditions[1])
                        if minBattlesCount is not None and maxBattlesCount is not None:
                            battleCondition = (minBattlesCount, maxBattlesCount)
                            arenaGuiTypeParts = arenaGuiType.split("_")
                            arenaGuiTypeCondition = _ArenaGuiTypeCondition(arenaGuiTypeParts[0], arenaGuiTypeParts[1:])
                            for arenaGuiType in ARENA_GUI_TYPE.RANGE:
                                if arenaGuiTypeCondition.validate(arenaGuiType):
                                    result[battleCondition][arenaGuiType][vehicleTypeCondition][nation][
                                        vehLevel
                                    ].append((i18n.makeString("#tips:%s" % status), i18n.makeString("#tips:%s" % key)))

    return result
Example #20
0
def getCommonInfo(userName, dossier, clanInfo, clanEmblemFile):
    clanNameProp = 'clanName'
    clanNameDescrProp = 'clanNameDescr'
    clanJoinTimeProp = 'clanJoinTime'
    clanPositionProp = 'clanPosition'
    clanEmblemProp = 'clanEmblem'
    import cgi
    lastBattleTimeUserString = None
    if dossier['total']['lastBattleTime']:
        lastBattleTimeUserString = '%s' % BigWorld.wg_getLongDateFormat(dossier['total']['lastBattleTime'])
    value = {'name': userName,
     'registrationDate': '%s' % BigWorld.wg_getLongDateFormat(dossier['total']['creationTime']),
     'lastBattleDate': lastBattleTimeUserString,
     clanNameProp: '',
     clanNameDescrProp: '',
     clanJoinTimeProp: '',
     clanPositionProp: '',
     clanEmblemProp: None}

    def getGoldFmt(str):
        return str

    if clanInfo is not None:
        value[clanNameProp] = cgi.escape(clanInfo[1])
        value[clanNameDescrProp] = cgi.escape(clanInfo[0])
        value[clanJoinTimeProp] = makeString(MENU.PROFILE_HEADER_CLAN_JOINDATE) % getGoldFmt(BigWorld.wg_getLongDateFormat(clanInfo[4]))
        clanPosition = makeString('#menu:profile/header/clan/position/%s' % CLAN_MEMBERS[clanInfo[3]] if clanInfo[3] in CLAN_MEMBERS else '')
        value[clanPositionProp] = getGoldFmt(clanPosition) if clanInfo[3] in CLAN_MEMBERS else ''
        clanEmblemId = None
        if clanEmblemFile:
            clanEmblemId = 'userInfoId' + userName
            BigWorld.wg_addTempScaleformTexture(clanEmblemId, clanEmblemFile)
        value[clanEmblemProp] = clanEmblemId
    return value
Example #21
0
    def buildList(self, costs, defaultCosts):
        items = {}
        if costs is not None:
            items = costs.copy()
        defaultItems = {}
        if defaultCosts is not None:
            defaultItems = defaultCosts.copy()
        self._items = items
        self._defaultItems = defaultItems
        result = []
        nations = {}
        if items.has_key('nations'):
            nations = items.get('nations', {})
            del items['nations']
        if nations.has_key(self.nationID):
            items.update(nations.get(self.nationID))
        for periodDays, (cost, isGold) in items.iteritems():
            if periodDays > 1:
                i18nPeriodDays = i18n.makeString(MENU.CUSTOMIZATION_PERIOD_DAYS, periodDays)
            elif periodDays == 1:
                i18nPeriodDays = i18n.makeString(MENU.CUSTOMIZATION_PERIOD_DAY)
            else:
                i18nPeriodDays = i18n.makeString(MENU.CUSTOMIZATION_PERIOD_INFINITY)
            result.append({'periodDays': periodDays,
             'cost': cost,
             'defCost': defaultCosts.get(periodDays, (0, 1))[0],
             'isGold': isGold == 1,
             'userString': i18nPeriodDays,
             'isIGR': False,
             'enabled': True})

        self._list = sorted(result, cmp=self._comparator, reverse=True)
        return
Example #22
0
 def _getEffectTimeStr(self, order):
     if order.isPermanent:
         return i18n.makeString(FORTIFICATIONS.ORDERS_ORDERPOPOVER_INDEFENSIVE)
     elif order.isConsumable:
         return i18n.makeString('#fortifications:Orders/orderPopover/battleConsumable')
     else:
         return self._getFormattedTimeStr(order.effectTime)
 def __prepareDefResInfo(self):
     result = {}
     icon = None
     level = None
     showAlertIcon = False
     alertIconTooltip = ''
     if self._isBaseBuilding:
         defResTitle = text_styles.middleTitle(i18n.makeString(FORT.BUILDINGPOPOVER_DEFRESINFO_BASEBUILDINGTITLE))
         defresDescr = text_styles.main(i18n.makeString(FORT.buildings_defresinfo(self._buildingUID)))
     else:
         order = self.fortCtrl.getFort().getOrder(self.__orderID)
         icon = order.icon
         level = order.level
         defResTitle = text_styles.middleTitle(i18n.makeString('#fortifications:General/orderType/%s' % self.getOrderUIDbyID(self.__orderID)))
         defresDescr = order.description
         showAlertIcon, alertIconTooltip = self._showOrderAlertIcon(order)
     result['showAlertIcon'] = showAlertIcon
     result['alertIconTooltip'] = alertIconTooltip
     result['title'] = defResTitle
     result['description'] = defresDescr
     result['iconSource'] = icon
     result['iconLevel'] = level
     if self.__orderID in constants.FORT_ORDER_TYPE.CONSUMABLES:
         result['orderID'] = self.__orderID
     return result
    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 __getBodyStatus(self, status, headerStyle, bodyStyle):
     headerLbl = headerStyle(i18n.makeString(FORT.buildingpopover_header_titlestatus(status)))
     if self.__isCommander:
         bodyLbl = bodyStyle(i18n.makeString(FORT.buildingpopover_commanderstatus_bodystatus(status)))
     else:
         bodyLbl = bodyStyle(i18n.makeString(FORT.buildingpopover_soldierstatus_bodystatus(status)))
     return (headerLbl, bodyLbl)
Example #26
0
 def __makeTimeOfBattle(self, item, battleItem, currentState):
     result = {}
     if currentState == FORTIFICATION_ALIASES.CLAN_BATTLE_IS_IN_BATTLE:
         icon = icons.makeImageTag(RES_ICONS.MAPS_ICONS_LIBRARY_BATTLERESULTICON_1, 16, 16, -3, 0)
         formattedText = text_styles.error(i18n.makeString(I18N_FORTIFICATIONS.FORTCLANBATTLELIST_RENDERCURRENTTIME_ISBATTLE))
         result['text'] = icon + ' ' + formattedText
     elif currentState == FORTIFICATION_ALIASES.CLAN_BATTLE_BEGINS:
         battleID = item.getBattleID()
         timer = {}
         htmlFormatter = text_styles.alert('###')
         locale = text_styles.main(i18n.makeString(I18N_FORTIFICATIONS.FORTCLANBATTLELIST_RENDERCURRENTTIME_BEFOREBATTLE))
         result['text'] = locale
         if battleItem:
             startTimeLeft = battleItem.getRoundStartTimeLeft()
         else:
             startTimeLeft = item.getStartTimeLeft()
         timer['useUniqueIdentifier'] = True
         timer['uniqueIdentifier'] = battleID
         timer['deltaTime'] = startTimeLeft
         timer['htmlFormatter'] = htmlFormatter
         timer['timerDefaultValue'] = '00'
         result['timer'] = timer
     else:
         lastBattleTimeUserString = '%s - %s' % (BigWorld.wg_getShortTimeFormat(item.getStartTime()), BigWorld.wg_getShortTimeFormat(item.getFinishTime()))
         result['text'] = text_styles.main(lastBattleTimeUserString)
     return result
 def __getButtonData(self):
     if self.fortState.getStateID() == CLIENT_FORT_STATE.HAS_FORT:
         fort = self.fortCtrl.getFort()
         if not fort.isDefenceHourEnabled():
             if self.fortCtrl.getPermissions().canChangeDefHour():
                 fortBattleBtnTooltip = TOOLTIPS.FORTIFICATION_INTROVIEW_CLANBATTLEBTN_DISABLED_LEADER
             else:
                 fortBattleBtnTooltip = TOOLTIPS.FORTIFICATION_INTROVIEW_CLANBATTLEBTN_DISABLED_NOTLEADER
             additionalText = i18n.makeString(FORTIFICATIONS.SORTIE_INTROVIEW_FORTBATTLES_NOTACTIVATEDDEFENCETIME)
             return (False, makeTooltip(None, fortBattleBtnTooltip), additionalText)
         attacksInOneDay = fort.getAttacksIn(timePeriod=time_utils.ONE_DAY)
         defencesInOneDay = fort.getDefencesIn(timePeriod=time_utils.ONE_DAY)
         if attacksInOneDay or defencesInOneDay:
             return (True, TOOLTIPS.FORTIFICATION_INTROVIEW_CLANBATTLEBTN_ENABLED, None)
         battlesInTwoWeeks = fort.getAttacksAndDefencesIn(timePeriod=2 * time_utils.ONE_WEEK)
         if battlesInTwoWeeks:
             closestBattle = battlesInTwoWeeks[0]
             battleDate = BigWorld.wg_getLongDateFormat(closestBattle.getStartTime())
             additionalText = i18n.makeString(FORTIFICATIONS.SORTIE_INTROVIEW_FORTBATTLES_NEXTTIMEOFBATTLE, nextDate=battleDate)
             fortBattleBtnTooltip = i18n.makeString(TOOLTIPS.FORTIFICATION_INTROVIEW_CLANBATTLEBTN_DISABLED_NEXTBATTLE, currentDate=battleDate)
             return (False, makeTooltip(None, fortBattleBtnTooltip), additionalText)
         if self.fortCtrl.getPermissions().canPlanAttack():
             fortBattleBtnTooltip = TOOLTIPS.FORTIFICATION_INTROVIEW_CLANBATTLEBTN_DISABLED_LEADERNOACTION
         else:
             fortBattleBtnTooltip = TOOLTIPS.FORTIFICATION_INTROVIEW_CLANBATTLEBTN_DISABLED_NOTLEADERNOACTION
         additionalText = i18n.makeString(FORTIFICATIONS.SORTIE_INTROVIEW_FORTBATTLES_NOTACTIVATED)
         return (False, makeTooltip(None, fortBattleBtnTooltip), additionalText)
     else:
         return (False, '', None)
 def __onDropVehicleInscription(self, resultID):
     if resultID < 0:
         message = i18n.makeString(SYSTEM_MESSAGES.CUSTOMIZATION_INSCRIPTION_DROP_SERVER_ERROR)
         self.onCustomizationDropFailed(message)
         return
     else:
         newID = None
         newLifeCycle = None
         if gui.game_control.g_instance.igr.getRoomType() != IGR_TYPE.NONE:
             inscriptions = g_currentVehicle.item.descriptor.playerInscriptions
             inscr = inscriptions[self.getRealPosition()]
             if inscr[0] is not None:
                 newID = inscr[0]
                 newLifeCycle = (inscr[1], inscr[2])
         hangarItem = CustomizationHelper.getItemFromHangar(CUSTOMIZATION_ITEM_TYPE.INSCRIPTION_TYPE, self._currentItemID, self._nationID)
         if hangarItem:
             intCD = g_currentVehicle.item.intCD
             vehicle = vehicles.getVehicleType(int(intCD))
             message = i18n.makeString(SYSTEM_MESSAGES.CUSTOMIZATION_INSCRIPTION_STORED_SUCCESS, vehicle=vehicle.userString)
         else:
             message = i18n.makeString(SYSTEM_MESSAGES.CUSTOMIZATION_INSCRIPTION_DROP_SUCCESS)
         self._currentItemID = newID
         self._currentLifeCycle = newLifeCycle
         self._itemsDP.currentItemID = newID
         self.updateVehicleCustomization(newID)
         self.onCustomizationDropSuccess(message)
         return
Example #29
0
    def __prepareAndPassVehiclesData(self):
        values = []
        for vehicleCD in g_itemsCache.items.stats.eliteVehicles:
            try:
                vehicle = g_itemsCache.items.getItemByCD(vehicleCD)
                if not vehicle.xp:
                    continue
                values.append({'id': vehicle.intCD,
                 'vehicleType': getVehicleTypeAssetPath(vehicle.type),
                 'vehicleName': vehicle.shortUserName,
                 'xp': vehicle.xp,
                 'xpStrValue': BigWorld.wg_getIntegralFormat(vehicle.xp),
                 'isSelectCandidate': vehicle.isFullyElite,
                 'vehicleIco': vehicle.iconSmall,
                 'nationIco': getNationsAssetPath(vehicle.nationID, namePrefix=NATION_ICON_PREFIX_131x31)})
            except:
                continue

        labelBuilder = builder().addStyledText('middleTitle', i18n.makeString(MENU.EXCHANGE_RATE))
        if self.__xpForFree is not None:
            labelBuilder.addStyledText(self.__getActionStyle(), i18n.makeString(MENU.EXCHANGEXP_AVAILABLE_FORFREE_LABEL))
            labelBuilder.addStyledText('expText', i18n.makeString(MENU.EXCHANGEXP_AVAILABLE_FORFREE_VALUE, icon=icons.makeImageTag(RES_ICONS.MAPS_ICONS_LIBRARY_ELITEXPICON_2), forFree=BigWorld.wg_getNiceNumberFormat(self.__xpForFree)))
        exchangeHeaderData = {'labelText': labelBuilder.render(),
         'rateFromIcon': ICON_TEXT_FRAMES.GOLD,
         'rateToIcon': ICON_TEXT_FRAMES.ELITE_XP,
         'rateFromTextColor': self.app.colorManager.getColorScheme('textColorGold').get('rgb'),
         'rateToTextColor': self.app.colorManager.getColorScheme('textColorCredits').get('rgb')}
        vehicleData = {'isHaveElite': bool(values),
         'vehicleList': values,
         'tableHeader': self._getTableHeader(),
         'xpForFree': self.__xpForFree,
         'exchangeHeaderData': exchangeHeaderData}
        self.as_vehiclesDataChangedS(vehicleData)
        return
Example #30
0
 def _getUseBtnTooltip(self, order, buildingDescr, isDisabled):
     hasBuilding = order.hasBuilding
     buildingID = self.getBuildingUIDbyID(order.buildingID)
     buildingStr = i18n.makeString(FORTIFICATIONS.buildings_buildingname(buildingID))
     body = None
     note = None
     if not isDisabled:
         header = TOOLTIPS.FORTIFICATION_ORDERPOPOVER_USEORDERBTN_HEADER
         body = TOOLTIPS.FORTIFICATION_ORDERPOPOVER_USEORDERBTN_DESCRIPTION
     else:
         header = TOOLTIPS.FORTIFICATION_ORDERPOPOVER_USEORDERBTN_CANTUSE_HEADER
         fort = self.fortCtrl.getFort()
         if not order.isSupported:
             body = TOOLTIPS.FORTIFICATION_ORDERPOPOVER_USEORDERBTN_NOTAVAILABLE
         elif not hasBuilding:
             body = i18n.makeString(TOOLTIPS.FORTIFICATION_ORDERPOPOVER_USEORDERBTN_NOBUILDING, building=buildingStr)
         elif order.inCooldown:
             body = TOOLTIPS.FORTIFICATION_ORDERPOPOVER_USEORDERBTN_WASUSED
         elif not order.isCompatible and fort.hasActivatedContinualOrders():
             body = TOOLTIPS.FORTIFICATION_ORDERSPANEL_CANTUSEORDER
         elif order.isPermanent and not fort.isDefenceHourEnabled():
             body = TOOLTIPS.FORTIFICATION_ORDERPOPOVER_USEORDERBTN_DEFENCEHOURDISABLED
         elif order.count < 1:
             body = TOOLTIPS.FORTIFICATION_ORDERPOPOVER_USEORDERBTN_NOORDERS
         elif self._isBuildingDamaged(buildingDescr) or self._isBaseBuildingDamaged() or self._isFortFrozen():
             body = TOOLTIPS.FORTIFICATION_ORDERPOPOVER_USEORDERBTN_CANTUSE_BODY
     return makeTooltip(header, body, note)
def getHotKeyList(command):
    keys = [
        makeString(READABLE_KEY_NAMES.key(vKey))
        for vKey in getHotKeyVkList(command)
    ]
    return keys
 def getUserDescription(self):
     return i18n.makeString('#achievements:%s_descr' %
                            self._getActualName())
 def getUserName(self):
     return i18n.makeString('#achievements:%s' % self._getActualName())
Example #34
0
 def __getStatusText(self):
     season = self.rankedController.getCurrentSeason()
     endTimeStr = self.__getTillTimeString(season.getCycleEndDate())
     key = RANKED_BATTLES.RANKEDBATTLEVIEW_STATUSBLOCK_STATUSTEXT
     return text_styles.stats(i18n.makeString(key)) + endTimeStr
Example #35
0
    def __readQuestList(self):
        xmlPath = _POTAPOV_QUEST_XML_PATH + '/list.xml'
        section = ResMgr.openSection(xmlPath)
        if section is None:
            _xml.raiseWrongXml(None, xmlPath, 'can not open or read')
        self.__potapovQuestIDToQuestType = idToQuest = {}
        self.__questUniqueIDToPotapovQuestID = questUniqueNameToPotapovQuestID = {}
        self.__tileIDchainIDToPotapovQuestID = tileIDchainIDToPotapovQuestID = {}
        self.__tileIDchainIDToFinalPotapovQuestID = tileIDchainIDToFinalPotapovQuestID = {}
        self.__tileIDchainIDToInitialPotapovQuestID = tileIDchainIDToInitialPotapovQuestID = {}
        ids = {}
        curTime = int(time.time())
        xmlSource = quest_xml_source.Source()
        for qname, qsection in section.items():
            splitted = qname.split('_')
            ctx = (None, xmlPath)
            if qname in ids:
                _xml.raiseWrongXml(ctx, '', 'potapov quest name is not unique')
            potapovQuestID = _xml.readInt(ctx, qsection, 'id', 0, 1023)
            if potapovQuestID in idToQuest:
                _xml.raiseWrongXml(ctx, 'id', 'is not unique')
            questBranchName, tileID, chainID, internalID = splitted
            tileInfo = g_tileCache.getTileInfo(int(tileID))
            if 1 <= chainID <= tileInfo['chainsCount']:
                _xml.raiseWrongXml(
                    ctx, '', 'quest chainID must be between 1 and %s' %
                    tileInfo['chainsCount'])
            if 1 <= internalID <= tileInfo['questsInChain']:
                _xml.raiseWrongXml(
                    ctx, '', 'quest internalID must be between 1 and %s' %
                    tileInfo['chainsCount'])
            minLevel = _xml.readInt(ctx, qsection, 'minLevel', 1, 10)
            maxLevel = _xml.readInt(ctx, qsection, 'maxLevel', minLevel, 10)
            basicInfo = {
                'name':
                qname,
                'id':
                potapovQuestID,
                'branch':
                PQ_BRANCH.NAME_TO_TYPE[questBranchName],
                'tileID':
                int(tileID),
                'chainID':
                int(chainID),
                'internalID':
                int(internalID),
                'minLevel':
                minLevel,
                'maxLevel':
                maxLevel,
                'requiredUnlocks':
                frozenset(
                    map(
                        int,
                        _xml.readString(ctx, qsection,
                                        'requiredUnlocks').split()))
            }
            rewardByDemand = qsection.readInt('rewardByDemand', 0)
            if rewardByDemand != 0 and rewardByDemand not in PQ_REWARD_BY_DEMAND.keys(
            ):
                raise Exception('Unexpected value for rewardByDemand')
            basicInfo['rewardByDemand'] = rewardByDemand
            tags = _readTags(ctx, qsection, 'tags')
            basicInfo['tags'] = tags
            if questBranchName == 'regular':
                if 0 == len(tags & VEHICLE_CLASS_TAGS):
                    _xml.raiseWrongXml(ctx, 'tags',
                                       'quest vehicle class is not specified')
            if questBranchName == 'fallout':
                if 0 == len(tags & _FALLOUT_BATTLE_TAGS):
                    _xml.raiseWrongXml(ctx, 'tags',
                                       'quest fallout type is not specified')
            if IS_CLIENT or IS_WEB:
                basicInfo['userString'] = i18n.makeString(
                    qsection.readString('userString'))
                basicInfo['description'] = i18n.makeString(
                    qsection.readString('description'))
                basicInfo['advice'] = i18n.makeString(
                    qsection.readString('advice'))
                basicInfo['condition_main'] = i18n.makeString(
                    qsection.readString('condition_main'))
                basicInfo['condition_add'] = i18n.makeString(
                    qsection.readString('condition_add'))
            questPath = ''.join([
                _POTAPOV_QUEST_XML_PATH, '/', questBranchName, '/tile_',
                tileID, '/chain_', chainID, '/', qname, '.xml'
            ])
            questCtx = (None, questPath)
            nodes = xmlSource.readFromInternalFile(questPath, curTime)
            nodes = nodes.get(EVENT_TYPE.POTAPOV_QUEST, None)
            if nodes is None:
                _xml.raiseWrongXml(questCtx, 'potapovQuest',
                                   'Potapov quests are not specified.')
            if len(nodes) != 2:
                _xml.raiseWrongXml(
                    questCtx, 'potapovQuest',
                    'Main and additional quest should be presented.')
            qinfo = nodes[0].info
            if not qinfo['id'].endswith('main'):
                _xml.raiseWrongXml(questCtx, 'potapovQuest',
                                   'Main quest must be first.')
            if qinfo['id'] in questUniqueNameToPotapovQuestID:
                _xml.raiseWrongXml(questCtx, 'potapovQuest',
                                   'Duplicate name detected.')
            questUniqueNameToPotapovQuestID[qinfo['id']] = potapovQuestID
            basicInfo['mainQuestID'] = qinfo['id']
            if IS_CLIENT or IS_WEB:
                basicInfo['mainQuestInfo'] = qinfo['questClientData']
            qinfo = nodes[1].info
            if not qinfo['id'].endswith('add'):
                _xml.raiseWrongXml(questCtx, 'potapovQuest',
                                   'Add quest must be second.')
            if qinfo['id'] in questUniqueNameToPotapovQuestID:
                _xml.raiseWrongXml(questCtx, 'potapovQuest',
                                   'Duplicate name detected.')
            questUniqueNameToPotapovQuestID[qinfo['id']] = potapovQuestID
            basicInfo['addQuestID'] = qinfo['id']
            if IS_CLIENT or IS_WEB:
                basicInfo['addQuestInfo'] = qinfo['questClientData']
            idToQuest[potapovQuestID] = PQType(basicInfo)
            ids[qname] = potapovQuestID
            key = (int(tileID), int(chainID))
            tileIDchainIDToPotapovQuestID.setdefault(key,
                                                     set()).add(potapovQuestID)
            if 'final' in tags:
                tileIDchainIDToFinalPotapovQuestID[key] = potapovQuestID
            if 'initial' in tags:
                tileIDchainIDToInitialPotapovQuestID[key] = potapovQuestID

        ResMgr.purge(xmlPath, True)
        return
Example #36
0
    def __readTiles(self):
        xmlPath = _POTAPOV_QUEST_XML_PATH + '/tiles.xml'
        section = ResMgr.openSection(xmlPath)
        if section is None:
            _xml.raiseWrongXml(None, xmlPath, 'can not open or read')
        self.__tilesInfo = idToTile = {}
        ids = {}
        for tname, tsection in section.items():
            if tname == 'quests':
                continue
            ctx = (None, xmlPath)
            if tname in ids:
                _xml.raiseWrongXml(ctx, '', 'tile name is not unique')
            seasonID = _xml.readInt(ctx, tsection, 'seasonID')
            g_seasonCache.getSeasonInfo(seasonID)
            tileID = _xml.readInt(ctx, tsection, 'id', 0, 15)
            if tileID in idToTile:
                _xml.raiseWrongXml(ctx, 'id', 'is not unique')
            chainsCount = _xml.readInt(ctx, tsection, 'chainsCount', 1, 15)
            chainsCountToUnlockNext = _xml.readInt(ctx, tsection,
                                                   'chainsCountToUnlockNext',
                                                   0, 15)
            nextTileID = _xml.readInt(ctx, tsection, 'nextTileID', 0, 15)
            achievements = {}
            basicInfo = {
                'name':
                tname,
                'chainsCount':
                chainsCount,
                'nextTileID':
                nextTileID,
                'chainsCountToUnlockNext':
                chainsCountToUnlockNext,
                'questsInChain':
                _xml.readInt(ctx, tsection, 'questsInChain', 1, 100),
                'price':
                _xml.readPrice(ctx, tsection, 'price'),
                'achievements':
                achievements,
                'seasonID':
                seasonID,
                'tokens':
                set(_xml.readString(ctx, tsection, 'tokens').split())
            }
            if tsection.has_key('achievements'):
                for aname, asection in tsection['achievements'].items():
                    _, aid = aname.split('_')
                    achievements[int(aid)] = asection.asString

                if len(achievements) < basicInfo['chainsCount']:
                    _xml.raiseWrongXml(ctx, 'achievements',
                                       'wrong achievement number')
            if IS_CLIENT or IS_WEB:
                basicInfo['userString'] = i18n.makeString(
                    tsection.readString('userString'))
                basicInfo['description'] = i18n.makeString(
                    tsection.readString('description'))
                basicInfo['iconID'] = i18n.makeString(
                    tsection.readString('iconID'))
            ids[tname] = tileID
            idToTile[tileID] = basicInfo

        return
Example #37
0
def makeHyperLink(linkType, textId):
    text = i18n.makeString(textId)
    attrs = {'linkType': linkType, 'text': text}
    linkHtml = makeHtmlString('html_templates:lobby/system_messages', 'link',
                              attrs)
    return linkHtml
 def roleFormat(role):
     return makeString(statusTemplate % 'inactiveSkillsRoleFormat') % makeString(getSkillsConfig().getSkill(role).userString)
Example #39
0
 def getCancelButtonLabel(self):
     return i18n.makeString(self.__cancelLabel)
    def _packBlocks(self, *args, **kwargs):
        items = super(TankmanTooltipDataBlock, self)._packBlocks()
        item = self.context.buildItem(*args, **kwargs)
        self.item = item
        vehicle = None
        if item.isInTank:
            vehicle = self._itemsCache.items.getVehicle(item.vehicleInvID)
        fullUserName = self._getFullUserName(item)
        items.append(formatters.packImageTextBlockData(title=text_styles.highTitle(fullUserName), desc=text_styles.main(self._getTankmanDescription(item))))
        innerBlock = []
        if vehicle:
            self._createLabel(innerBlock)
            self._createVehicleBlock(innerBlock, vehicle)
        if innerBlock:
            items.append(formatters.packBuildUpBlockData(innerBlock, padding=formatters.packPadding(left=0, right=50, top=-5, bottom=0), linkage=BLOCKS_TOOLTIP_TYPES.TOOLTIP_BUILDUP_BLOCK_WHITE_BG_LINKAGE))
        commonStatsBlock = [formatters.packTextBlockData(text=makeHtmlString('html_templates:lobby/textStyle', 'grayTitle', {'message': makeString(TOOLTIPS.HANGAR_CREW_SPECIALTY_SKILLS)}))]
        penalty = self._getBonusValue(item, [TankmanRoleBonusesField.BONUSES.PENALTY])
        addition = self._getBonusValue(item, [TankmanRoleBonusesField.BONUSES.COMMANDER,
         TankmanRoleBonusesField.BONUSES.EQUIPMENTS,
         TankmanRoleBonusesField.BONUSES.DEVICES,
         TankmanRoleBonusesField.BONUSES.BROTHERHOOD])
        addition_ = '' if addition == 0 else self._getSign(addition) + str(addition)
        penalty_ = '' if penalty == 0 else self._getSign(penalty) + str(penalty)
        if penalty != 0 or addition != 0:
            addRoleLevels = ' (' + str(item.roleLevel) + addition_ + penalty_ + ')'
        else:
            addRoleLevels = ''
        commonStatsBlock.append(formatters.packTextParameterBlockData(self._makeRoleName(item), text_styles.stats(str(item.roleLevel + penalty + addition) + '%' + addRoleLevels), valueWidth=90, padding=formatters.packPadding(left=0, right=0, top=5, bottom=0)))
        field = self._getSkillList()
        _, value = field.buildData()
        skills = value or []
        maxPopUpBlocks = 14
        for skill in skills[:maxPopUpBlocks]:
            commonStatsBlock.append(formatters.packTextParameterBlockData(text_styles.main(skill['label']), text_styles.stats(str(skill['level']) + '%'), valueWidth=90))

        if len(skills) > maxPopUpBlocks:
            diff = str(len(skills) - maxPopUpBlocks)
            commonStatsBlock.append(formatters.packAlignedTextBlockData(text=text_styles.middleTitle(makeString(TOOLTIPS.HANGAR_CREW_MORESKILLS, skill_cnt=diff)), align=BLOCKS_TOOLTIP_TYPES.ALIGN_CENTER))
        items.append(formatters.packBuildUpBlockData(commonStatsBlock, gap=5))
        self._createBlockForNewSkills(items)
        self._createMoreInfoBlock(items)
        return items
Example #41
0
 def getDescription(self):
     return i18n.makeString(self.__description)
Example #42
0
 def getCheckBoxButtonLabel(self):
     return i18n.makeString(self.__checkBoxLabel)
Example #43
0
 def __init__(self, unitEntity):
     super(ActionButtonStateVO, self).__init__()
     self._playerInfo = unitEntity.getPlayerInfo()
     result = unitEntity.canPlayerDoAction()
     self.__unitIsValid, self.__restrictionType = result.isValid, result.restriction
     self.__validationCtx = result.ctx
     self.__isEnabled = self._isEnabled(self.__unitIsValid,
                                        self.__restrictionType)
     self.__stats = unitEntity.getStats()
     self.__flags = unitEntity.getFlags()
     self.__settings = unitEntity.getRosterSettings()
     self.__canTakeSlot = not self._playerInfo.isLegionary()
     self.__INVALID_UNIT_MESSAGES = {
         UNIT_RESTRICTION.UNDEFINED: ('', {}),
         UNIT_RESTRICTION.UNIT_IS_FULL:
         (CYBERSPORT.WINDOW_UNIT_MESSAGE_UNITISFULL, {}),
         UNIT_RESTRICTION.UNIT_IS_LOCKED:
         (CYBERSPORT.WINDOW_UNIT_MESSAGE_UNITISLOCKED, {}),
         UNIT_RESTRICTION.VEHICLE_NOT_SELECTED:
         (CYBERSPORT.WINDOW_UNIT_MESSAGE_VEHICLENOTSELECTED, {}),
         UNIT_RESTRICTION.VEHICLE_NOT_VALID:
         (CYBERSPORT.WINDOW_UNIT_MESSAGE_VEHICLENOTVALID, {}),
         UNIT_RESTRICTION.VEHICLE_BROKEN:
         (CYBERSPORT.WINDOW_UNIT_MESSAGE_VEHICLEINNOTREADY_BROKEN, {}),
         UNIT_RESTRICTION.VEHICLE_CREW_NOT_FULL:
         (CYBERSPORT.WINDOW_UNIT_MESSAGE_VEHICLEINNOTREADY_CREWNOTFULL, {}),
         UNIT_RESTRICTION.VEHICLE_RENT_IS_OVER:
         (CYBERSPORT.WINDOW_UNIT_MESSAGE_VEHICLEINNOTREADY_RENTISOVER, {}),
         UNIT_RESTRICTION.VEHICLE_IS_IN_BATTLE:
         (CYBERSPORT.WINDOW_UNIT_MESSAGE_VEHICLEINNOTREADY_ISINBATTLE, {}),
         UNIT_RESTRICTION.MIN_SLOTS:
         (CYBERSPORT.WINDOW_UNIT_MESSAGE_MINSLOTS, {}),
         UNIT_RESTRICTION.NOT_READY_IN_SLOTS:
         (CYBERSPORT.WINDOW_UNIT_MESSAGE_WAITING, {}),
         UNIT_RESTRICTION.MIN_TOTAL_LEVEL:
         (CYBERSPORT.WINDOW_UNIT_MESSAGE_LEVEL, self.__validationCtx),
         UNIT_RESTRICTION.MAX_TOTAL_LEVEL:
         (CYBERSPORT.WINDOW_UNIT_MESSAGE_LEVEL, self.__validationCtx),
         UNIT_RESTRICTION.INVALID_TOTAL_LEVEL:
         ActionButtonStateVO.getInvalidVehicleLevelsMessage(
             self.__validationCtx),
         UNIT_RESTRICTION.IS_IN_IDLE:
         BoundMethodWeakref(self._getIdleStateStr),
         UNIT_RESTRICTION.IS_IN_ARENA:
         BoundMethodWeakref(self._getArenaStateStr),
         UNIT_RESTRICTION.NEED_PLAYERS_SEARCH: ('', {}),
         UNIT_RESTRICTION.ZERO_TOTAL_LEVEL: ('', {}),
         UNIT_RESTRICTION.IS_IN_PRE_ARENA:
         (CYBERSPORT.WINDOW_UNIT_MESSAGE_WAITCOMMANDER, {}),
         UNIT_RESTRICTION.NOT_IN_SLOT:
         BoundMethodWeakref(self._notInSlotMessage),
         UNIT_RESTRICTION.VEHICLE_NOT_VALID_FOR_EVENT:
         (CYBERSPORT.WINDOW_UNIT_MESSAGE_VEHICLENOTVALID, {}),
         UNIT_RESTRICTION.CURFEW: (CYBERSPORT.WINDOW_UNIT_MESSAGE_CURFEW,
                                   {}),
         UNIT_RESTRICTION.VEHICLE_WRONG_MODE:
         (CYBERSPORT.WINDOW_UNIT_MESSAGE_VEHICLEINNOTREADY_WRONGMODE, {}),
         UNIT_RESTRICTION.FALLOUT_NOT_ENOUGH_PLAYERS: ('', {}),
         UNIT_RESTRICTION.FALLOUT_VEHICLE_LEVEL_REQUIRED:
         BoundMethodWeakref(self._getFalloutVehLevelStr),
         UNIT_RESTRICTION.FALLOUT_VEHICLE_MIN:
         BoundMethodWeakref(self._getFalloutVehMinStr),
         UNIT_RESTRICTION.FALLOUT_VEHICLE_MAX: ('', {}),
         UNIT_RESTRICTION.FALLOUT_VEHICLE_BROKEN:
         BoundMethodWeakref(self._getFalloutVehBrokenStr),
         UNIT_RESTRICTION.FORT_DISABLED:
         (CYBERSPORT.WINDOW_UNIT_MESSAGE_FORTIFICATIONNOTAVAILABLE, {}),
         UNIT_RESTRICTION.VEHICLE_INVALID_LEVEL:
         (self.__getNotAvailableIcon() + i18n.makeString(
             MESSENGER.DIALOGS_SQUAD_MESSAGE_INVALIDVEHICLELEVEL), {}),
         UNIT_RESTRICTION.SPG_IS_FORBIDDEN:
         (self.__getNotAvailableIcon() +
          i18n.makeString(MESSENGER.DIALOGS_SQUAD_MESSAGE_SPGFORBIDDEN),
          {}),
         UNIT_RESTRICTION.SPG_IS_FULL:
         (self.__getNotAvailableIcon() +
          i18n.makeString(MESSENGER.DIALOGS_SQUAD_MESSAGE_SPGFULL), {}),
         UNIT_RESTRICTION.ROTATION_GROUP_LOCKED:
         BoundMethodWeakref(self._rotationGroupBlockMessage),
         UNIT_RESTRICTION.UNIT_MAINTENANCE:
         (CYBERSPORT.WINDOW_UNIT_MESSAGE_MAINTENANCE, {}),
         UNIT_RESTRICTION.UNIT_INACTIVE_PERIPHERY_UNDEF:
         (CYBERSPORT.WINDOW_UNIT_MESSAGE_INACTIVEPERIPHERY, {}),
         UNIT_RESTRICTION.UNIT_INACTIVE_PERIPHERY_SORTIE:
         (CYBERSPORT.WINDOW_UNIT_MESSAGE_INACTIVEPERIPHERYSORTIE, {}),
         UNIT_RESTRICTION.UNIT_INACTIVE_PERIPHERY_BATTLE:
         (CYBERSPORT.WINDOW_UNIT_MESSAGE_INACTIVEPERIPHERYBATTLE, {}),
         UNIT_RESTRICTION.UNIT_WAITINGFORDATA:
         (TOOLTIPS.STRONGHOLDS_TIMER_WAITINGFORDATA, {})
     }
     self.__WARNING_UNIT_MESSAGES = {
         UNIT_RESTRICTION.XP_PENALTY_VEHICLE_LEVELS:
         (MESSENGER.DIALOGS_SQUAD_MESSAGE_VEHICLES_DIFFERENTLEVELS, {})
     }
     stateKey, stateCtx = self.__getState()
     self['stateString'] = self.__stateTextStyleFormatter(
         i18n.makeString(stateKey, **stateCtx))
     self['label'] = self._getLabel()
     self['isEnabled'] = self.__isEnabled
     self['isReady'] = self._playerInfo.isReady
     self['toolTipData'] = self.__toolTipData
Example #44
0
 def getSubmitButtonLabel(self):
     return i18n.makeString(self.__submitLabel)
Example #45
0
 def getTitle(self):
     return i18n.makeString(I18N_MESSENGER.SERVER_ERRORS_CHATBANNED_TITLE)
Example #46
0
 def getTitle(self):
     return i18n.makeString(self.__title)
 def __packContentBlock(self, localeKey, iconSource, ctx = None, showLinkBtn = False):
     return {'iconSource': iconSource,
      'titleTF': text_styles.highTitle(i18n.makeString(MENU.referralreferrerintrowindow_textblock_title(localeKey))),
      'bodyTF': text_styles.main(i18n.makeString(MENU.referralreferrerintrowindow_textblock_body(localeKey), **(ctx or {}))),
      'showLinkBtn': showLinkBtn}
Example #48
0
 def getI18nName(self):
     name = self.getName()
     key = I18N_MESSENGER.client_action(name)
     if key:
         name = i18n.makeString(key)
     return name
Example #49
0
def getBattleSubTypeWinText(arenaTypeID, teamID):
    key = 'type/%s/description' % ArenaType.g_cache[arenaTypeID].gameplayName
    winText = i18n.makeString('#arenas:%s' % key)
    if winText == key:
        return i18n.makeString('#arenas:%s%d' % (key, teamID))
    return winText
 def __makeHyperLink(cls, linkType, textId):
     return makeHtmlString('html_templates:lobby/fortifications', 'link', {'linkType': linkType,
      'text': i18n.makeString(textId)})
Example #51
0
def _sysMsg(i18nKey, *args, **kwargs):
    return makeString(('#system_messages:%s' % i18nKey), *args, **kwargs)
 def _populate(self):
     super(ReferralReferrerIntroWindow, self)._populate()
     blocks = [self.__packContentBlock('invite_block', RES_ICONS.MAPS_ICONS_LIBRARY_REFERRALINVITEICON_1, ctx={'inviteCount': self.__invitesCount,
       'link': self.__makeHyperLink(OpenLinkEvent.INVIETES_MANAGEMENT, MENU.REFERRALREFERRERINTROWINDOW_TEXTBLOCK_LINK)}, showLinkBtn=True), self.__packContentBlock('squad_block', RES_ICONS.MAPS_ICONS_BATTLETYPES_40X40_SQUAD), self.__packContentBlock('referrals_block', RES_ICONS.MAPS_ICONS_REFERRAL_REFERRALHAND, ctx={'icon': icons.makeImageTag(RES_ICONS.MAPS_ICONS_REFERRAL_REFERRALSMALLHAND, 16, 16, -4, 0)})]
     self.as_setDataS({'titleMsg': text_styles.promoTitle(i18n.makeString(MENU.REFERRALREFERRERINTROWINDOW_TITLEMESSAGE)),
      'blocksVOs': blocks})
 def _initHeaderBtnStates(self):
     self.__headerBtnStates = {RES.NO_RESTRICTIONS: self._getHeaderButtonStateVO(True, i18n.makeString(CLANS.CLAN_HEADER_SENDREQUESTBTN), actionId=_JOIN_BTN_ACTION_ID, actionBtnTooltip=CLANS.CLAN_HEADER_SENDREQUESTBTN_TOOLTIP),
      RES.CLAN_APPLICATION_ALREADY_SENT: self._getHeaderButtonStateVO(middleTFVisible=True, middleTF=CLANS.CLAN_HEADER_REQUESTSENT)}
     return self.__headerBtnStates
Example #54
0
def getSeasonStateUserString(seasonState):
    return makeString('#cybersport:clubs/seasons/state/%s' % seasonState.getStateString())
Example #55
0
 def getDisplayableData(self, *args):
     return {
         'name': makeString('#achievements:globalRating'),
         'descr': makeString('#achievements:globalRating_descr'),
         'isInDossier': True
     }
Example #56
0
def getSeasonUserName(seasonInfo):
    return makeString('#cybersport:clubs/seasons/name', startTime=BigWorld.wg_getShortDateFormat(seasonInfo.start), finishTime=BigWorld.wg_getShortDateFormat(seasonInfo.finish))
Example #57
0
 def getShortUserName(self):
     return i18n.makeString('#personal_missions:operations/title%d' %
                            self.getID())
 def _updateClanInfo(self, clanInfo):
     creationDate = i18n.makeString(CLANS.CLAN_HEADER_CREATIONDATE, creationDate=items.formatField(getter=clanInfo.getCreatedAt, formatter=BigWorld.wg_getLongDateFormat))
     self.as_setClanInfoS({'name': items.formatField(getter=clanInfo.getFullName),
      'bgIcon': RES_ICONS.MAPS_ICONS_CLANS_CLAN_CARD_HEADER,
      'creationDate': creationDate})
Example #59
0
 def getUserType(self):
     return i18n.makeString(QUESTS.ITEM_TYPE_ACTION)
Example #60
0
 def getUserType(self):
     return i18n.makeString(QUESTS.ITEM_TYPE_PERSONALMISSION)