def __packLadderData(self, clubs): formations = [] club = self.clubsCtrl.getClub(self._clubDbID) ladderInfo = club.getLadderInfo() if club and ladderInfo.isInLadder(): for clubInfo in sorted(clubs, key=lambda club: club.ladderRank): self.requestClubEmblem32x32(clubInfo.clubDBID, clubInfo.clubEmblemUrl) battlesCount = BigWorld.wg_getNiceNumberFormat(clubInfo.battlesCount) winsPercent = 0 if clubInfo.battlesCount > 0: winsPercent = clubInfo.winsCount / float(clubInfo.battlesCount) * 100 winsPercentStr = BigWorld.wg_getNiceNumberFormat(winsPercent) + '%' clubName = clubInfo.clubName ladderPoints = clubInfo.getRatingPoints(ladderInfo.getDivision()) emblem = self._clubEmblems.get(clubInfo.clubDBID, None) texturePath = self.getMemoryTexturePath(emblem) if emblem else '' formations.append({'formationId': str(clubInfo.clubDBID), 'showProfileBtnText': _ms(CYBERSPORT.STATICFORMATION_LADDERVIEW_SHOWFORMATIONPROFILEBTN_TEXT), 'showProfileBtnTooltip': TOOLTIPS.STATICFORMATIONLADDERVIEW_SHOWFORMATIONPROFILEBTN, 'emblemIconPath': texturePath, 'place': text_styles.standard(str(clubInfo.ladderRank)), 'placeSortValue': clubInfo.ladderRank, 'points': text_styles.middleTitle(str(ladderPoints)), 'pointsSortValue': ladderPoints, 'formationName': text_styles.highTitle(clubName), 'formationNameSortValue': clubName, 'battlesCount': text_styles.stats(battlesCount), 'battlesCountSortValue': clubInfo.battlesCount, 'winPercent': text_styles.stats(winsPercentStr), 'winPercentSortValue': winsPercent, 'isCurrentTeam': self._clubDbID == clubInfo.clubDBID}) return {'formations': formations}
def construct(self): block = [] if self.configuration.crew: totalCrewSize = len(self.vehicle.descriptor.type.crewRoles) if self.configuration.externalCrewParam and self._roleLevel is not None: block.append( formatters.packTextParameterBlockData( name=text_styles.main(_ms(TOOLTIPS.VEHICLE_CREW_AWARD, self._roleLevel)), value=text_styles.stats(str(totalCrewSize)), valueWidth=self._valueWidth, padding=formatters.packPadding(left=-2), ) ) elif self.vehicle.isInInventory and not self.configuration.externalCrewParam: currentCrewSize = len([x for _, x in self.vehicle.crew if x is not None]) currentCrewSizeStr = str(currentCrewSize) if currentCrewSize < totalCrewSize: currentCrewSizeStr = text_styles.error(currentCrewSizeStr) block.append(self._makeStatBlock(currentCrewSizeStr, totalCrewSize, TOOLTIPS.VEHICLE_CREW)) else: block.append( formatters.packTextParameterBlockData( name=text_styles.main(_ms(TOOLTIPS.VEHICLE_CREW)), value=text_styles.stats(str(totalCrewSize)), valueWidth=self._valueWidth, padding=formatters.packPadding(left=-2), ) ) lockBlock = self._makeLockBlock() if lockBlock is not None: block.append(lockBlock) return block
def _makeRequestTooltip(self, status, date, user=None): if status == CLAN_INVITE_STATES.ACCEPTED: return text_styles.concatStylesToMultiLine( text_styles.standard(_ms(CLANS.CLANINVITESWINDOW_TOOLTIPS_INVITE_INVITEACCEPTED)), text_styles.main(date), text_styles.main(""), text_styles.standard(_ms(CLANS.CLANINVITESWINDOW_TOOLTIPS_INVITE_BYUSER)), text_styles.stats(user), ) if status == CLAN_INVITE_STATES.DECLINED or status == CLAN_INVITE_STATES.DECLINED_RESENT: return text_styles.concatStylesToMultiLine( text_styles.standard(_ms(CLANS.CLANINVITESWINDOW_TOOLTIPS_INVITE_INVITEDECLINED)), text_styles.main(date), text_styles.main(""), text_styles.standard(_ms(CLANS.CLANINVITESWINDOW_TOOLTIPS_INVITE_BYUSER)), text_styles.stats(user), ) if ( status == CLAN_INVITE_STATES.ACTIVE or status == CLAN_INVITE_STATES.EXPIRED or status == CLAN_INVITE_STATES.EXPIRED_RESENT ): return text_styles.concatStylesToMultiLine( text_styles.standard(_ms(CLANS.CLANINVITESWINDOW_TOOLTIPS_INVITE_INVITESENT)), text_styles.main(date), text_styles.main(""), text_styles.standard(_ms(CLANS.CLANINVITESWINDOW_TOOLTIPS_INVITE_SENDER)), text_styles.stats(user), )
def _getKilledTanksStats(stats): killedTanks = stats.getKilledVehiclesCount() lostTanks = stats.getLostVehiclesCount() killedLostRatio = stats.getKilledLostVehiclesRatio() or 0 return [{'label': text_styles.main(CYBERSPORT.STATICFORMATIONSTATSVIEW_ADDSTATS_KILLED), 'value': text_styles.stats(BigWorld.wg_getIntegralFormat(killedTanks))}, {'label': text_styles.main(CYBERSPORT.STATICFORMATIONSTATSVIEW_ADDSTATS_LOST), 'value': text_styles.stats(BigWorld.wg_getIntegralFormat(lostTanks))}, {'label': text_styles.main(CYBERSPORT.STATICFORMATIONSTATSVIEW_ADDSTATS_KILLEDLOSTRATIO), 'value': text_styles.stats(BigWorld.wg_getNiceNumberFormat(killedLostRatio))}]
def _getDamageStats(totalStats): dmgInflicted = totalStats.getDamageDealt() dmgReceived = totalStats.getDamageReceived() damageEfficiency = totalStats.getDamageEfficiency() or 0 return [{'label': text_styles.main(CYBERSPORT.STATICFORMATIONSTATSVIEW_ADDSTATS_DMGINFLICTED), 'value': text_styles.stats(BigWorld.wg_getIntegralFormat(dmgInflicted))}, {'label': text_styles.main(CYBERSPORT.STATICFORMATIONSTATSVIEW_ADDSTATS_DMGRECEIVED), 'value': text_styles.stats(BigWorld.wg_getIntegralFormat(dmgReceived))}, {'label': text_styles.main(CYBERSPORT.STATICFORMATIONSTATSVIEW_ADDSTATS_DMGRATIO), 'value': text_styles.stats(BigWorld.wg_getNiceNumberFormat(damageEfficiency))}]
def getDescription(self): localKey = '#menu:awardWindow/boosterAward/description/timeValue/%s' if self._booster.expiryTime: timeValue = text_styles.stats(i18n.makeString(localKey % 'defined', effectTime=self._booster.getEffectTimeStr(), tillTime=self._booster.getExpiryDate())) else: timeValue = text_styles.stats(i18n.makeString(localKey % 'undefined', effectTime=self._booster.getEffectTimeStr())) description = text_styles.main(MENU.AWARDWINDOW_BOOSTERAWARD_DESCRIPTION_TILLTIME) return description + timeValue
def __setData(self, club): ladderInfo = club.getLadderInfo() seasonDossier = club.getSeasonDossier() totalStats = seasonDossier.getTotalStats() battlesNumData, winsPercentData, attackDamageEfficiency, defenceDamageEfficiency = _makeStats(totalStats) battleCounts = totalStats.getBattlesCount() ladderIconSource = getLadderChevron256x256(ladderInfo.getDivision() if battleCounts else None) globalStats = seasonDossier.getGlobalStats() registeredDate = text_styles.main(BigWorld.wg_getShortDateFormat(club.getCreationTime())) registeredText = text_styles.standard( _ms(CYBERSPORT.STATICFORMATIONSUMMARYVIEW_REGISTERED, date=registeredDate) ) lastBattleText = _getLastBattleText(battleCounts, globalStats) bestTanksText = text_styles.stats(CYBERSPORT.STATICFORMATIONSUMMARYVIEW_BESTTANKS) bestMapsText = text_styles.stats(CYBERSPORT.STATICFORMATIONSUMMARYVIEW_BESTMAPS) notEnoughTanksText = notEnoughMapsText = text_styles.standard( CYBERSPORT.STATICFORMATIONSUMMARYVIEW_NOTENOUGHTANKSMAPS ) bestTanks = _getVehiclesList(totalStats) bestMaps = _getMapsList(totalStats) noAwardsText = text_styles.stats(CYBERSPORT.STATICFORMATIONSUMMARYVIEW_NOAWARDS) ribbonSource = RES_ICONS.MAPS_ICONS_LIBRARY_CYBERSPORT_RIBBON self.as_setDataS( { "clubId": club.getClubDbID(), "placeText": _getPositionText(ladderInfo), "leagueDivisionText": _getDivisionText(ladderInfo), "ladderPtsText": _getLadderPointsText(ladderInfo), "bestTanksText": bestTanksText, "bestMapsText": bestMapsText, "notEnoughTanksText": notEnoughTanksText, "notEnoughMapsText": notEnoughMapsText, "registeredText": registeredText, "lastBattleText": lastBattleText, "ladderIconSource": ladderIconSource, "noAwardsText": noAwardsText, "ribbonSource": ribbonSource, "battlesNumData": battlesNumData, "winsPercentData": winsPercentData, "attackDamageEfficiencyData": attackDamageEfficiency, "defenceDamageEfficiencyData": defenceDamageEfficiency, "bestTanks": bestTanks, "notEnoughTanksTFVisible": not len(bestTanks), "bestMaps": bestMaps, "notEnoughMapsTFVisible": not len(bestMaps), "achievements": _makeAchievements(seasonDossier), "bestTanksGroupWidth": BEST_TANKS_GROUP_WIDTH, "bestMapsGroupWidth": BEST_MAPS_GROUP_WIDTH, } ) return
def __setCarouselData(self, blData): itemVOs = [] selectedIndex = -1 for item in blData['items']: element = item['element'] isInQuest = checkInQuest(element, self.__controller.filter.purchaseType) if item['installedInCurrentSlot']: label = text_styles.main(VEHICLE_CUSTOMIZATION.CAROUSEL_ITEMLABEL_APPLIED) elif element.isInDossier: label = text_styles.main(VEHICLE_CUSTOMIZATION.CAROUSEL_ITEMLABEL_PURCHASED) elif element.getIgrType() != IGR_TYPE.NONE: if element.getIgrType() == getIGRCtrl().getRoomType(): label = text_styles.main(VEHICLE_CUSTOMIZATION.CAROUSEL_ITEMLABEL_PURCHASED) else: label = icons.premiumIgrSmall() elif isInQuest: label = icons.quest() else: if item['duration'] == DURATION.PERMANENT: priceFormatter = text_styles.gold priceIcon = icons.gold() else: priceFormatter = text_styles.credits priceIcon = icons.credits() label = priceFormatter('{0}{1}'.format(element.getPrice(item['duration']), priceIcon)) data = {'id': element.getID(), 'icon': element.getTexturePath(), 'bonusType': element.qualifier.getIcon16x16(), 'bonusPower': text_styles.stats('+{0}%{1}'.format(element.qualifier.getValue(), '*' if element.qualifier.getDescription() is not None else '')), 'label': label, 'selected': item['appliedToCurrentSlot'] or item['installedInCurrentSlot'] and not blData['hasAppliedItem'], 'goToTaskBtnVisible': isInQuest, 'goToTaskBtnText': _ms(VEHICLE_CUSTOMIZATION.CUSTOMIZATION_ITEMCAROUSEL_RENDERER_GOTOTASK), 'newElementIndicatorVisible': item['isNewElement']} if data['selected']: selectedIndex = blData['items'].index(item) if element.isOnSale(item['duration']) and not element.isInDossier and not item['installedInCurrentSlot'] and not isInQuest: data['salePrice'] = getSalePriceString(self.__controller.slots.currentType, element, item['duration']) itemVOs.append(data) carouselLength = len(itemVOs) self.as_setCarouselDataS({'rendererList': itemVOs, 'rendererWidth': blData['rendererWidth'], 'filterCounter': '{0}{1}'.format(text_styles.stats(carouselLength) if carouselLength > 0 else text_styles.error(carouselLength), text_styles.main(_ms(VEHICLE_CUSTOMIZATION.CAROUSEL_FILTER_COUNTER, all=blData['unfilteredLength']))), 'messageVisible': carouselLength == 0, 'counterVisible': True, 'goToIndex': blData['goToIndex'], 'selectedIndex': selectedIndex}) return
def __setCarouselData(self, blData): itemVOs = [] for item in blData['items']: enable = True if item['installedInSlot']: label = text_styles.main(CUSTOMIZATION.CAROUSEL_ITEMLABEL_APPLIED) elif item['isInDossier']: label = text_styles.main(CUSTOMIZATION.CAROUSEL_ITEMLABEL_PURCHASED) elif item['object'].getIgrType() != IGR_TYPE.NONE: if item['object'].getIgrType() == getIGRCtrl().getRoomType(): label = text_styles.main(CUSTOMIZATION.CAROUSEL_ITEMLABEL_PURCHASED) else: label = icons.premiumIgrSmall() enable = False else: if item['priceIsGold']: priceFormatter = text_styles.gold priceIcon = icons.gold() else: priceFormatter = text_styles.credits priceIcon = icons.credits() label = priceFormatter('{0}{1}'.format(item['price'], priceIcon)) data = {'id': item['id'], 'icon': item['object'].getTexturePath(), 'bonusType': item['object'].qualifier.getIcon16x16(), 'bonusPower': text_styles.stats('+{0}%{1}'.format(item['object'].qualifier.getValue(), '*' if item['object'].qualifier.getDescription() is not None else '')), 'label': label, 'installed': item['appliedToCurrentSlot'], 'btnSelect': self.__getLabelOfSelectBtn(item), 'btnShoot': VEHICLE_CUSTOMIZATION.CUSTOMIZATIONITEMCAROUSEL_RENDERER_SHOOT, 'btnTooltip': item['buttonTooltip'], 'btnSelectEnable': enable, 'doubleclickEnable': enable, 'btnShootEnable': True} cType = g_customizationController.carousel.currentType if isSale(cType, item['duration']) and not item['isInDossier'] and not item['installedInSlot']: isGold = item['priceIsGold'] data['salePrice'] = getSalePriceString(isGold, item['price']) itemVOs.append(data) carouselLength = len(itemVOs) self.as_setCarouselDataS({'rendererList': itemVOs, 'rendererWidth': blData['rendererWidth'], 'filterCounter': '{0}{1}'.format(text_styles.stats(carouselLength) if carouselLength > 0 else text_styles.error(carouselLength), text_styles.main(_ms(VEHICLE_CUSTOMIZATION.CAROUSEL_FILTER_COUNTER, all=blData['unfilteredLength']))), 'messageVisible': carouselLength == 0, 'counterVisible': True, 'goToIndex': blData['goToIndex'], 'selectedIndex': blData['selectedIndex']}) return
def _getDataObject(key, i18nFunc, value, ratingOutdated = False, tooltipData = None): tooltip = _getTooltip(i18nFunc(key + '/tooltip/header'), i18nFunc(key + '/tooltip/body'), ratingOutdated) if ratingOutdated: value = text_styles.standard(value) else: value = text_styles.stats(value) return SUtils.getDetailedDataObject(i18nFunc(key), value, tooltip, tooltipData)
def buildList(self, cartItems): self.clear() elementGroups = [[], [], []] for item in cartItems: element = item['object'] dropdownItem = {'id': element.getID(), 'slotIdx': item['idx'], 'selected': item['isSelected'], 'cType': item['type'], 'itemName': element.getName(), 'imgBonus': element.qualifier.getIcon16x16(), 'price': element.getPrice(item['duration']), 'lblBonus': text_styles.stats('+{0}%{1}'.format(element.qualifier.getValue(), '*' if element.qualifier.getDescription() is not None else '')), 'titleMode': False, 'DDPrice': _getDropdownPriceVO(element), 'selectIndex': DURATION.ALL.index(item['duration']), 'isDuplicatePrice': item['isDuplicate'], 'duplicatePriceText': icons.info() + _ms(VEHICLE_CUSTOMIZATION.BUYWINDOW_BUYTIME_COPY), 'duplicatePriceTooltip': makeTooltip(_ms(VEHICLE_CUSTOMIZATION.CUSTOMIZATION_BUYWINDOW_COPY_HEADER), _ms(VEHICLE_CUSTOMIZATION.CUSTOMIZATION_BUYWINDOW_COPY_BODY))} elementGroups[item['type']].append(dropdownItem) for elements, title in zip(elementGroups, _CUSTOMIZATION_TYPE_TITLES): if elements: elements.insert(0, {'titleMode': True, 'titleText': _ms(text_styles.middleTitle(title))}) self._list = list(itertools.chain(*elementGroups)) return
def __buildList(self): modulesList = [] typeId = GUI_ITEM_TYPE_INDICES[self._slotType] data = g_itemsCache.items.getItems(typeId, REQ_CRITERIA.VEHICLE.SUITABLE([self._vehicle], [typeId])).values() data.sort(reverse=True) currXp = g_itemsCache.items.stats.vehiclesXPs.get(self._vehicle.intCD, 0) stats = { "money": g_itemsCache.items.stats.money, "exchangeRate": g_itemsCache.items.shop.exchangeRate, "currXP": currXp, "totalXP": currXp + g_itemsCache.items.stats.freeXP, } for idx, module in enumerate(data): isInstalled = module.isInstalled(self._vehicle, self._slotIndex) if isInstalled: self._selectedIdx = idx moduleData = self._buildModuleData(module, isInstalled, stats) if self._slotType == "optionalDevice": moduleData["slotIndex"] = self._slotIndex moduleData["removable"] = module.isRemovable moduleData["desc"] = text_styles.main(module.getShortInfo()) moduleData["name"] = text_styles.stats(module.userName) else: values, names = self.__buildParams(module) moduleData["level"] = module.level moduleData["paramValues"] = values moduleData["paramNames"] = names moduleData["name"] = text_styles.middleTitle(module.userName) if self._slotType == "vehicleGun": if module.isClipGun(self._vehicle.descriptor): moduleData[EXTRA_MODULE_INFO] = CLIP_ICON_PATH modulesList.append(moduleData) return modulesList
def __makeAccountsData(self, accounts, label = None): listData = [] isPlayerSpeaking = self.bwProto.voipController.isPlayerSpeaking accounts = sorted(accounts, cmp=getPlayersComparator()) getUser = self.usersStorage.getUser for account in accounts: vContourIcon = '' vShortName = '' vLevel = '' dbID = account.dbID user = getUser(dbID) if account.isVehicleSpecified(): vehicle = account.getVehicle() vContourIcon = vehicle.iconContour vShortName = vehicle.shortUserName vLevel = int2roman(vehicle.level) listData.append({'accID': account.accID, 'dbID': account.dbID, 'userName': account.name, 'fullName': account.getFullName(), 'stateString': formatters.getPlayerStateString(account.state), 'icon': vContourIcon, 'vShortName': vShortName, 'vLevel': vLevel, 'tags': list(user.getTags()) if user else [], 'isPlayerSpeaking': bool(isPlayerSpeaking(account.dbID)), 'clanAbbrev': account.clanAbbrev, 'region': g_lobbyContext.getRegionCode(account.dbID), 'igrType': account.igrType}) if label is not None: label = text_styles.main(i18n.makeString(label, total=text_styles.stats(str(len(listData))))) result = {'listData': listData, 'teamLabel': label} return result
def _makeMapVO(idx, mapID, mapInfo): label = str(idx + 1) + '.' mapName = text_styles.main(getArenaFullName(mapID)) winsEfficiency = mapInfo.wins / float(mapInfo.battlesCount) * 100 winsEfficiencyStr = BigWorld.wg_getNiceNumberFormat(winsEfficiency) + '%' return {'label': text_styles.standard(label + ' ' + mapName), 'value': text_styles.stats(winsEfficiencyStr)}
def __initControls(self): self.as_setInitDataS({'ratingDescription': text_styles.stats(_ms(CLANS.SEARCH_INFO_RATINGDESCRIPTION)), 'ratingTooltip': CLANS.SEARCH_INFO_RATINGDESCRIPTION_TOOLTIP, 'requestSent': text_styles.success(_ms(CLANS.SEARCH_INFO_REQUESTSENT)), 'clanProfileBtnLabel': _ms(CLANS.SEARCH_INFO_CLANPROFILEBTN), 'sendRequestBtnLabel': _ms(CLANS.SEARCH_INFO_SENDREQUESTBTN)}) self.as_setWaitingVisibleS(False)
def _makePriceBlock(self, price, text, currencyType, neededValue = None, oldPrice = None, percent = 0): needFormatted = '' oldPriceText = '' hasAction = percent != 0 if currencyType == ICON_TEXT_FRAMES.CREDITS: valueFormatted = text_styles.credits(_int(price)) icon = icons.credits() if neededValue is not None: needFormatted = text_styles.credits(_int(neededValue)) if hasAction: oldPriceText = text_styles.concatStylesToSingleLine(icons.credits(), text_styles.credits(_int(oldPrice))) elif currencyType == ICON_TEXT_FRAMES.GOLD: valueFormatted = text_styles.gold(_int(price)) icon = icons.gold() if neededValue is not None: needFormatted = text_styles.gold(_int(neededValue)) if hasAction: oldPriceText = text_styles.concatStylesToSingleLine(icons.gold(), text_styles.gold(_int(oldPrice))) elif currencyType == ICON_TEXT_FRAMES.XP: valueFormatted = text_styles.expText(_int(price)) icon = icons.xp() if neededValue is not None: needFormatted = text_styles.expText(_int(neededValue)) else: LOG_ERROR('Unsupported currency type "' + currencyType + '"!') return neededText = '' if neededValue is not None: neededText = text_styles.concatStylesToSingleLine(text_styles.main('( '), text_styles.error(TOOLTIPS.VEHICLE_GRAPH_BODY_NOTENOUGH), ' ', needFormatted, ' ', icon, text_styles.main(' )')) text = text_styles.concatStylesWithSpace(text_styles.main(text), neededText) if hasAction: actionText = text_styles.main(_ms(TOOLTIPS.VEHICLE_ACTION_PRC, actionPrc=text_styles.stats(str(percent) + '%'), oldPrice=oldPriceText)) text = text_styles.concatStylesToMultiLine(text, actionText) return formatters.packTextParameterWithIconBlockData(name=text, value=valueFormatted, icon=currencyType, valueWidth=self._valueWidth, padding=formatters.packPadding(left=self.leftPadding, right=20))
def __setList(self, cartItems): self._list = [] emblemItems = [] camouflageItems = [] inscriptionItems = [] for item in cartItems: dpItem = {'id': item['itemID'], 'slotIdx': item['idx'], 'selected': item['isSelected'], 'cType': item['type'], 'itemName': item['name'], 'imgBonus': item['bonusIcon'], 'price': item['object'].getPrice(item['duration']), 'lblBonus': text_styles.stats('+{0}%{1}'.format(item['bonusValue'], item['isConditional'])), 'titleMode': False, 'DDPrice': self.__getDropdownPriceVO(item), 'selectIndex': DURATION.ALL.index(item['duration']), 'isDuplicatePrice': item['isDuplicate'], 'duplicatePriceText': icons.info() + _ms(CUSTOMIZATION.BUYWINDOW_BUYTIME_COPY), 'duplicatePriceTooltip': makeTooltip(_ms(TOOLTIPS.CUSTOMIZATION_BUYWINDOW_COPY_HEADER), _ms(TOOLTIPS.CUSTOMIZATION_BUYWINDOW_COPY_BODY))} if item['type'] == data_aggregator.CUSTOMIZATION_TYPE.CAMOUFLAGE: camouflageItems.append(dpItem) elif item['type'] == data_aggregator.CUSTOMIZATION_TYPE.EMBLEM: emblemItems.append(dpItem) elif item['type'] == data_aggregator.CUSTOMIZATION_TYPE.INSCRIPTION: inscriptionItems.append(dpItem) if camouflageItems: camouflageItems.insert(0, self.__getTitle(CUSTOMIZATION.BUYWINDOW_TITLE_CAMOUFLAGE)) if inscriptionItems: inscriptionItems.insert(0, self.__getTitle(CUSTOMIZATION.BUYWINDOW_TITLE_INSCRIPTION)) if emblemItems: emblemItems.insert(0, self.__getTitle(CUSTOMIZATION.BUYWINDOW_TITLE_EMBLEM)) self._list = camouflageItems + emblemItems + inscriptionItems
def _packBlocks(self, uid, level): description = _ms(FORTIFICATIONS.buildingsprocess_longdescr(uid)) self._description = _ms(CLANS.SECTION_FORT_BUILDING_TOOLTIP_BODY, level=text_styles.stats(int2roman(level)), description=description) self._title = _ms(FORTIFICATIONS.buildings_buildingname(uid)) items = super(ClanProfileFortBuildingTooltipData, self)._packBlocks() items.append(formatters.packTitleDescBlock(text_styles.highTitle(self._title), desc=text_styles.main(self._description) if self._description else None)) return items
def _makeVehicleVO(idx, vehCD): label = str(idx + 1) + "." vehicle = g_itemsCache.items.getItemByCD(vehCD) return { "label": text_styles.standard(label), "value": text_styles.stats(vehicle.shortUserName), "iconSource": vehicle.iconContour, }
def getBuildingInfoTooltipData(self, buildingDescr): body = None if buildingDescr is not None: uid = self.getBuildingUIDbyID(buildingDescr.typeID) description = i18n.makeString(FORTIFICATIONS.buildingsprocess_longdescr(uid)) level = text_styles.stats(buildingDescr.getUserLevel()) body = i18n.makeString(CLANS.SECTION_FORT_BUILDING_TOOLTIP_BODY, level=level, description=description) return body
def __makeTableData(self): ms = i18n.makeString result = [] refSystem = game_control.g_instance.refSystem referrals = refSystem.getReferrals() numOfReferrals = len(referrals) for i, item in enumerate(referrals): referralNumber = text_styles.stats(ms('%d.' % (i + 1))) dbID = item.getAccountDBID() user = self.usersStorage.getUser(dbID) if not user: raise AssertionError('User must be defined') contactConverter = ContactConverter() contactData = contactConverter.makeVO(user) xpIcon = RES_ICONS.MAPS_ICONS_LIBRARY_NORMALXPICON icon = icons.makeImageTag(xpIcon, 16, 16, -3, 0) bonus, timeLeft = item.getBonus() if bonus == 1: multiplier = '-' multiplierTooltip = TOOLTIPS.REFERRALMANAGEMENTWINDOW_MULTIPLIER_X1 icon = '' else: multiplier = 'x%s' % BigWorld.wg_getNiceNumberFormat(bonus) multiplierTooltip = '' if timeLeft: multiplierTime = text_styles.main(ms(item.getBonusTimeLeftStr())) expMultiplierText = text_styles.standard(ms(MENU.REFERRALMANAGEMENTWINDOW_REFERRALSTABLE_LEFTTIME, time=multiplierTime)) else: expMultiplierText = '' multiplierFactor = text_styles.credits(multiplier) multiplierStr = ms(icon + '<nobr>' + multiplierFactor + ' ' + expMultiplierText) referralData = {'accID': dbID, 'fullName': user.getFullName(), 'userName': user.getName(), 'clanAbbrev': user.getClanAbbrev()} canInviteToSquad = self.prbFunctional.getEntityType() in (PREBATTLE_TYPE.NONE, PREBATTLE_TYPE.TRAINING) or self.prbFunctional.getEntityType() == PREBATTLE_TYPE.SQUAD and self.prbFunctional.getPermissions().canSendInvite() btnEnabled = canInviteToSquad or False btnTooltip = TOOLTIPS.REFERRALMANAGEMENTWINDOW_CREATESQUADBTN_DISABLED_SQUADISFULL else: btnEnabled = True btnTooltip = TOOLTIPS.REFERRALMANAGEMENTWINDOW_CREATESQUADBTN_ENABLED result.append({'isEmpty': False, 'contactData': contactData, 'referralNo': referralNumber, 'referralVO': referralData, 'exp': BigWorld.wg_getNiceNumberFormat(item.getXPPool()), 'multiplier': multiplierStr, 'multiplierTooltip': multiplierTooltip, 'btnEnabled': btnEnabled, 'btnTooltip': btnTooltip}) if numOfReferrals < self.MIN_REF_NUMBER: for i in xrange(numOfReferrals, self.MIN_REF_NUMBER): referralNumber = text_styles.disabled(ms(MENU.REFERRALMANAGEMENTWINDOW_REFERRALSTABLE_EMPTYLINE, lineNo=str(i + 1))) result.append({'isEmpty': True, 'referralNo': referralNumber}) self.as_setTableDataS(result)
def getFormattedStats(self): """ Get stats formatted as a single string with applied style. """ clusterUsers, regionUsers, tooltipType = self.getStats() if tooltipType == STATS_TYPE.CLUSTER: statsStr = clusterUsers else: statsStr = text_styles.concatStylesToSingleLine(text_styles.stats(clusterUsers), text_styles.main(MENU.ONLINECOUNTER_DELIMITER), text_styles.main(regionUsers)) return (statsStr, tooltipType)
def __updateHeaderMessage(self): message = '' isDefHourEnabled = self.fortCtrl.getFort().isDefenceHourEnabled() if self._isFortFrozen(): message = i18n.makeString(FORTIFICATIONS.FORTMAINVIEW_HEADER_FORTFROZEN) message = text_styles.error(message) elif isDefHourEnabled: periodStr = self.fortCtrl.getFort().getDefencePeriodStr() message = i18n.makeString(FORTIFICATIONS.FORTMAINVIEW_HEADER_DEFENCEPERIOD, period=periodStr) message = text_styles.stats(message) self.as_setHeaderMessageS(message, self._isWrongLocalTime() and isDefHourEnabled)
def __buildBaseList(self): parameters = params_helper.getParameters(self._cache.item) if parameters is not None: formattedParameters = formatters.getFormattedParamsList(self._cache.item.descriptor, parameters) for paramName, value in formattedParameters: if not formatters.isRelativeParameter(paramName): self._list.append({'titleText': formatters.formatVehicleParamName(paramName), 'valueText': text_styles.stats(value), 'isEnabled': False}) return
def __getItemRestoreInfo(self, item): """ Get formatted vehicle restore info :param item: <Vehicle> :return: <str> """ if item.isRestorePossible(): if constants.IS_CHINA and item.rentalIsActive: return text_styles.alert(MENU.VEHICLE_RESTORELEFT_DISABLEDBYRENT) if item.hasLimitedRestore(): restoreLeftTime = item.restoreInfo.getRestoreTimeLeft() timeKey, formattedTime = getTimeLeftInfo(restoreLeftTime) msg = i18n.makeString('#menu:vehicle/restoreLeft/%s' % timeKey, time=formattedTime) if restoreLeftTime < time_utils.ONE_DAY: return icons.alert() + text_styles.alert(msg) return text_styles.stats(msg) if item.hasRestoreCooldown(): timeKey, formattedTime = getTimeLeftInfo(item.restoreInfo.getRestoreCooldownTimeLeft()) msg = i18n.makeString('#menu:vehicle/restoreCooldownLeft/%s' % timeKey, time=formattedTime) return text_styles.stats(msg) return ''
def _makeVO(self, item): vo = {'players': text_styles.main(str(item.getMembersCount())), 'creationDate': text_styles.main(formatField(getter=item.getCreationDate, formatter=BigWorld.wg_getShortDateFormat)), 'rating': text_styles.stats(formatField(getter=item.getPersonalRating, formatter=BigWorld.wg_getIntegralFormat)), 'arrowIcon': RES_ICONS.MAPS_ICONS_LIBRARY_ARROWORANGERIGHTICON8X8, 'clanInfo': {'dbID': item.getClanDbID(), 'clanAbbrev': formatField(getter=item.getClanAbbrev), 'clanName': formatField(getter=item.getClanName), 'fullName': formatField(getter=item.getClanFullName), 'isActive': item.isClanActive(), 'showIcon': True, 'iconSource': None}} return vo
def __getAvailabilityStr(self): battle = g_eventsCache.getCompanyBattles() if not battle.isValid(): return else: startTimeLeft = battle.getCreationTimeLeft() finishTimeLeft = battle.getDestroyingTimeLeft() if startTimeLeft is not None and startTimeLeft > 0: if startTimeLeft < time_utils.ONE_DAY: return text_styles.alert( i18n.makeString( MENU.HEADERBUTTONS_BATTLE_AVAILABLESINCESOON, time=text_styles.stats(time_formatters.getTimeDurationStr(startTimeLeft, True)), ) ) else: return text_styles.stats( i18n.makeString( MENU.HEADERBUTTONS_BATTLE_AVAILABLESINCE, datetime=self._getDateTimeString(battle.startTime) ) ) elif finishTimeLeft is not None and finishTimeLeft > 0: if finishTimeLeft < time_utils.ONE_DAY: return text_styles.success( i18n.makeString( MENU.HEADERBUTTONS_BATTLE_AVAILABLEUNTILSOON, time=text_styles.stats(time_formatters.getTimeDurationStr(finishTimeLeft, True)), ) ) else: return text_styles.success( i18n.makeString( MENU.HEADERBUTTONS_BATTLE_AVAILABLEUNTIL, datetime=self._getDateTimeString(battle.finishTime), ) ) return
def _packBlocks(self, role): blocks = [] bodyStr = '%s/%s' % (TOOLTIPS.VEHICLEPREVIEW_CREW, role) crewParams = [ text_styles.neutral(param) for param in _CREW_TOOLTIP_PARAMS[role] ] blocks.append(formatters.packTitleDescBlock(text_styles.highTitle(ITEM_TYPES.tankman_roles(role)), text_styles.main(_ms(bodyStr, *crewParams)))) vehicle = self.context.getVehicle() for idx, tankman in vehicle.crew: if tankman.role == role: otherRoles = list(vehicle.descriptor.type.crewRoles[idx]) otherRoles.remove(tankman.role) if otherRoles: rolesStr = ', '.join([ text_styles.stats(_ms(ITEM_TYPES.tankman_roles(r))) for r in otherRoles ]) blocks.append(formatters.packTextBlockData(text_styles.main(_ms(TOOLTIPS.VEHICLEPREVIEW_CREW_ADDITIONALROLES, roles=rolesStr)))) return blocks
def _updateServersList(self): hostsList = g_preDefinedHosts.getSimpleHostsList(g_preDefinedHosts.hostsWithRoaming()) serversList = [] for hostName, name, csisStatus, peripheryID in hostsList: if peripheryID not in self.__ctx.getForbiddenPeripherieIDs(): serversList.append({'label': name, 'id': peripheryID, 'csisStatus': csisStatus, 'data': hostName}) label = _ms(self.__ctx.getSelectServerLabel()) if len(serversList) == 1: label = _ms(self.__ctx.getApplySwitchLabel(), server=text_styles.stats(serversList[0]['label'])) self._serversDP.rebuildList(serversList) self.as_setServerParamsS(label, len(serversList) > 1) self.as_setSelectedIndexS(0)
def showAcceptClanInviteDialog(clanName, clanAbbrev, callback): from gui import DialogsInterface DialogsInterface.showDialog( I18nConfirmDialogMeta( "clanConfirmJoining", messageCtx={ "icon": icons.makeImageTag(RES_ICONS.MAPS_ICONS_LIBRARY_ATTENTIONICON, 16, 16, -4, 0), "clanName": text_styles.stats( i18n.makeString(DIALOGS.CLANCONFIRMJOINING_MESSAGE_CLANNAME, clanAbbr=clanAbbrev, clanName=clanName) ), "clanExit": text_styles.standard(i18n.makeString(DIALOGS.CLANCONFIRMJOINING_MESSAGE_CLANEXIT)), }, ), callback, )
def _makeRequestTooltip(self, status, date, user = None): if status == CLAN_INVITE_STATES.ACCEPTED: return text_styles.concatStylesToMultiLine(text_styles.standard(_ms(CLANS.CLANINVITESWINDOW_TOOLTIPS_REQUEST_REQUESTACCEPTED)), text_styles.main(date), text_styles.main(''), text_styles.standard(_ms(CLANS.CLANINVITESWINDOW_TOOLTIPS_REQUEST_BYUSER)), text_styles.stats(user)) if status == CLAN_INVITE_STATES.DECLINED or status == CLAN_INVITE_STATES.DECLINED_RESENT: return text_styles.concatStylesToMultiLine(text_styles.standard(_ms(CLANS.CLANINVITESWINDOW_TOOLTIPS_REQUEST_REQUESTDECLINED)), text_styles.main(date), text_styles.main(''), text_styles.standard(_ms(CLANS.CLANINVITESWINDOW_TOOLTIPS_REQUEST_BYUSER)), text_styles.stats(user)) if status == CLAN_INVITE_STATES.EXPIRED or status == CLAN_INVITE_STATES.EXPIRED_RESENT or status == CLAN_INVITE_STATES.ACTIVE: return text_styles.concatStylesToMultiLine(text_styles.standard(_ms(CLANS.CLANINVITESWINDOW_TOOLTIPS_REQUEST_REQUESTSENT)), text_styles.main(date))
def __init__(self, berthsPrice, berthsCount): super(TankmanBerthsBuyer, self).__init__((plugins.MessageInformator('barracksExpandNotEnoughMoney', activeHandler=lambda : not plugins.MoneyValidator(berthsPrice).validate().success), plugins.MessageConfirmator('barracksExpand', ctx={'price': text_styles.concatStylesWithSpace(text_styles.gold(str(berthsPrice.gold)), icons.makeImageTag(RES_ICONS.MAPS_ICONS_LIBRARY_GOLDICON_2)), 'count': text_styles.stats(berthsCount)}), plugins.MoneyValidator(berthsPrice))) self.berthsPrice = berthsPrice
def _getActiveTimeDateText(self): timeStr = self._getActiveDateTimeString() return text_styles.stats(timeStr)
def __getTradeInContentFields(self, vehicle): if self.selectedTab == _TABS.UNDEFINED: if vehicle.mayPurchase(self.itemsCache.items.stats.money)[0]: self.selectedTab = _TABS.BUY else: self.selectedTab = _TABS.TRADE return {'tradeInPriceLabel': i18n.makeString(DIALOGS.BUYVEHICLEWINDOW_TRADEIN_PRICELABEL, vehiclename=vehicle.shortUserName), 'tradeInCrewCheckbox': i18n.makeString(DIALOGS.BUYVEHICLEWINDOW_TRADEIN_TANKMENCHECKBOX), 'tradeInVehiclePrices': self._getVehiclePrice(vehicle).price.toMoneyTuple(), 'tradeInVehiclePricesActionData': self._getItemPriceActionData(vehicle), 'tradeInStudyLabel': i18n.makeString(DIALOGS.BUYVEHICLEWINDOW_TRADEIN_STUDYLABEL, count=text_styles.stats(str(len(vehicle.crew)))), 'hasTradeOffVehicles': self.tradeIn.getTradeInDiscounts(vehicle) is not None, 'selectedTab': self.selectedTab}
def _getImageWithBottomTitleBlock(imagePath, imageTitle, blockPadding=None): titleBlock = formatters.packAlignedTextBlockData(text=text_styles.stats(imageTitle), align=BLOCKS_TOOLTIP_TYPES.ALIGN_CENTER, padding=formatters.packPadding(top=-5)) imageBlock = formatters.packImageBlockData(img=imagePath, align=BLOCKS_TOOLTIP_TYPES.ALIGN_CENTER) return formatters.packBuildUpBlockData(blocks=[imageBlock, titleBlock], align=BLOCKS_TOOLTIP_TYPES.ALIGN_CENTER, blockWidth=140, padding=blockPadding)
def _getLabel(cls, preFormattedCondition): return text_styles.stats(preFormattedCondition.title)
def construct(self): block = [] module = self.module slotIdx = self.configuration.slotIdx vehicle = self.configuration.vehicle sellPrice = self.configuration.sellPrice buyPrice = self.configuration.buyPrice unlockPrice = self.configuration.unlockPrice inventoryCount = self.configuration.inventoryCount vehiclesCount = self.configuration.vehiclesCount researchNode = self.configuration.node if buyPrice and sellPrice: LOG_ERROR('You are not allowed to use buyPrice and sellPrice at the same time') return else: def checkState(state): if researchNode is not None: return bool(int(researchNode.state) & state) else: return False isEqOrDev = module.itemTypeID in GUI_ITEM_TYPE.ARTEFACTS isNextToUnlock = checkState(NODE_STATE.NEXT_2_UNLOCK) isInstalled = checkState(NODE_STATE.INSTALLED) isInInventory = checkState(NODE_STATE.IN_INVENTORY) isUnlocked = checkState(NODE_STATE.UNLOCKED) isAutoUnlock = checkState(NODE_STATE.AUTO_UNLOCKED) items = g_itemsCache.items money = items.stats.money itemPrice = ZERO_MONEY if module is not None: itemPrice = module.buyPrice isMoneyEnough = money >= itemPrice leftPadding = 92 if unlockPrice and not isEqOrDev: parentCD = vehicle.intCD if vehicle is not None else None isAvailable, cost, need = getUnlockPrice(module.intCD, parentCD) neededValue = None if not isUnlocked and isNextToUnlock and need > 0: neededValue = need if cost > 0: block.append(makePriceBlock(cost, CURRENCY_SETTINGS.UNLOCK_PRICE, neededValue, leftPadding=leftPadding, valueWidth=self._valueWidth)) creditsActionPercent, goldActionPercent = (0, 0) need = ZERO_MONEY if buyPrice and not isAutoUnlock: price = module.altPrice or module.buyPrice defPrice = module.defaultAltPrice or module.defaultPrice rootInInv = vehicle is not None and vehicle.isInInventory if researchNode: showNeeded = rootInInv and not isMoneyEnough and (isNextToUnlock or isUnlocked) and not (isInstalled or isInInventory) else: isModuleUnlocked = module.isUnlocked isModuleInInventory = module.isInInventory showNeeded = not isModuleInInventory and isModuleUnlocked if isEqOrDev or showNeeded: need = price - money need = need.toNonNegative() if price.credits > 0: creditsActionPercent = getActionPrc(price.credits, defPrice.credits) block.append(makePriceBlock(price.credits, CURRENCY_SETTINGS.BUY_CREDITS_PRICE, need.credits if need.credits > 0 else None, defPrice.credits if defPrice.credits > 0 else None, creditsActionPercent, self._valueWidth, leftPadding)) if price.gold > 0: goldActionPercent = getActionPrc(price.gold, defPrice.gold) block.append(formatters.packTextBlockData(text=text_styles.standard(TOOLTIPS.VEHICLE_TEXTDELIMITER_OR), padding=formatters.packPadding(left=(101 if goldActionPercent > 0 else 81) + self.leftPadding))) block.append(makePriceBlock(price.gold, CURRENCY_SETTINGS.BUY_GOLD_PRICE, need.gold if need.gold > 0 else None, defPrice.gold if defPrice.gold > 0 else None, goldActionPercent, self._valueWidth, leftPadding)) if sellPrice: block.append(makePriceBlock(module.sellPrice.credits, CURRENCY_SETTINGS.SELL_PRICE, oldPrice=module.defaultSellPrice.credits, percent=module.sellActionPrc, valueWidth=self._valueWidth, leftPadding=leftPadding)) if inventoryCount: count = module.inventoryCount if count > 0: block.append(formatters.packTextParameterBlockData(name=text_styles.main(TOOLTIPS.VEHICLE_INVENTORYCOUNT), value=text_styles.stats(count), valueWidth=self._valueWidth, padding=formatters.packPadding(left=-5))) if vehiclesCount: inventoryVehicles = items.getVehicles(REQ_CRITERIA.INVENTORY) count = len(module.getInstalledVehicles(inventoryVehicles.itervalues())) if count > 0: block.append(formatters.packTextParameterBlockData(name=text_styles.main(TOOLTIPS.VEHICLE_VEHICLECOUNT), value=text_styles.stats(count), valueWidth=self._valueWidth, padding=formatters.packPadding(left=-5))) notEnoughMoney = need > ZERO_MONEY hasAction = creditsActionPercent > 0 or goldActionPercent > 0 or module.sellActionPrc > 0 return (block, notEnoughMoney or hasAction)
def getNewUserStr(self): stepsSeenByPlayer = filter(lambda s: not s.isNewForPlayer(), self.getSteps()) return text_styles.main(' / '.join( (text_styles.stats(len(stepsSeenByPlayer)), str(len(self.getSteps())))))
def getUserStr(self): return text_styles.main(' / '.join( (text_styles.stats(len(self.getAcquiredSteps())), str(len(self.getSteps())))))
def _getPersonalDailyStatusLabel(cls, statusLabel, bonusLimit, bonusCount): dailyLeftLabel = text_styles.standard( _ms(QUESTS.MISSIONDETAILS_PERSONALQUEST_COMPLETE_LEFT_DAILY, count=text_styles.stats(max(bonusLimit - bonusCount, 0)))) return '%s\n%s' % (statusLabel, dailyLeftLabel)
def __packLadderData(self, clubs): formations = [] clubsState = self.clubsCtrl.getState() if clubsState.getStateID() == CLIENT_CLUB_STATE.HAS_CLUB: myClubDbID = clubsState.getClubDbID() else: myClubDbID = None club = self.clubsCtrl.getClub(self._clubDbID) ladderInfo = club.getLadderInfo() if club and ladderInfo.isInLadder(): for clubInfo in sorted(clubs, key=lambda club: club.ladderRank): self.requestClubEmblem32x32(clubInfo.clubDBID, clubInfo.clubEmblemUrl) battlesCount = BigWorld.wg_getNiceNumberFormat( clubInfo.battlesCount) winsPercent = 0 if clubInfo.battlesCount > 0: winsPercent = clubInfo.winsCount / float( clubInfo.battlesCount) * 100 winsPercentStr = BigWorld.wg_getNiceNumberFormat( winsPercent) + '%' clubName = clubInfo.clubName ladderPoints = clubInfo.getRatingPoints( ladderInfo.getDivision()) emblem = self._clubEmblems.get(clubInfo.clubDBID, None) texturePath = self.getMemoryTexturePath( emblem) if emblem else '' formations.append({ 'formationId': clubInfo.clubDBID, 'showProfileBtnText': _ms(CYBERSPORT. STATICFORMATION_LADDERVIEW_SHOWFORMATIONPROFILEBTN_TEXT ), 'showProfileBtnTooltip': TOOLTIPS.STATICFORMATIONLADDERVIEW_SHOWFORMATIONPROFILEBTN, 'emblemIconPath': texturePath, 'place': text_styles.standard(str(clubInfo.ladderRank)), 'placeSortValue': clubInfo.ladderRank, 'points': text_styles.middleTitle(str(ladderPoints)), 'pointsSortValue': ladderPoints, 'formationName': text_styles.highTitle(clubName), 'formationNameSortValue': clubName, 'battlesCount': text_styles.stats(battlesCount), 'battlesCountSortValue': clubInfo.battlesCount, 'winPercent': text_styles.stats(winsPercentStr), 'winPercentSortValue': winsPercent, 'isCurrentTeam': self._clubDbID == clubInfo.clubDBID, 'isMyClub': myClubDbID == clubInfo.clubDBID }) return {'formations': formations}
def _getPersonalDailyStatusLabel(cls, statusLabel, bonusLimit, bonusCount): text = _ms( QUESTS.MISSIONDETAILS_PERSONALQUEST_DETAILS_COMPLETE_LEFT_DAILY, count=text_styles.stats(max(bonusLimit - bonusCount, 0))) return text_styles.standard('%s (%s)' % (statusLabel, text_styles.standard(text)))
def construct(self): block = [] shell = self.shell configuration = self.configuration buyPrice = configuration.buyPrice sellPrice = configuration.sellPrice if buyPrice and sellPrice: LOG_ERROR('You are not allowed to use buyPrice and sellPrice at the same time') return else: notEnoughMoney = False showDelimiter = False shop = self.itemsCache.items.shop money = self.itemsCache.items.stats.money if buyPrice and shell.buyPrices: for itemPrice in shell.buyPrices.iteritems(directOrder=False): if not isItemBuyPriceAvailable(shell, itemPrice, shop) or not itemPrice.price: continue currency = itemPrice.getCurrency() value = itemPrice.price.getSignValue(currency) defValue = itemPrice.defPrice.getSignValue(currency) actionPercent = itemPrice.getActionPrc() needValue = value - money.getSignValue(currency) if needValue > 0: notEnoughMoney = True else: needValue = None if showDelimiter: block.append(formatters.packTextBlockData(text=text_styles.standard(TOOLTIPS.VEHICLE_TEXTDELIMITER_OR), padding=formatters.packPadding(left=81 + self.leftPadding))) block.append(makePriceBlock(value, CURRENCY_SETTINGS.getBuySetting(currency), needValue, defValue if defValue > 0 else None, actionPercent, valueWidth=self._valueWidth)) showDelimiter = True if sellPrice and shell.sellPrices: block.append(makePriceBlock(shell.sellPrices.itemPrice.price.credits, CURRENCY_SETTINGS.SELL_PRICE, oldPrice=shell.sellPrices.itemPrice.defPrice.credits, percent=shell.sellPrices.itemPrice.getActionPrc(), valueWidth=self._valueWidth)) inventoryCount = shell.inventoryCount if inventoryCount: block.append(formatters.packTextParameterBlockData(name=text_styles.main(TOOLTIPS.VEHICLE_INVENTORYCOUNT), value=text_styles.stats(inventoryCount), valueWidth=self._valueWidth, padding=formatters.packPadding(left=-5))) hasAction = shell.buyPrices.itemPrice.isActionPrice() or shell.sellPrices.itemPrice.isActionPrice() return (block, notEnoughMoney or hasAction)
def __initControls(self): headers = [packHeaderColumnData('nationID', 40, 40, tooltip=DIALOGS.TRADEINPOPOVER_SORTING_NATION, icon=RES_ICONS.MAPS_ICONS_FILTERS_NATIONS_ALL, enabled=True), packHeaderColumnData('typeIndex', 40, 40, tooltip=DIALOGS.TRADEINPOPOVER_SORTING_VEHTYPE, icon=RES_ICONS.MAPS_ICONS_FILTERS_TANKS_ALL, enabled=True), packHeaderColumnData('level', 40, 40, tooltip=DIALOGS.TRADEINPOPOVER_SORTING_VEHLVL, icon=RES_ICONS.MAPS_ICONS_FILTERS_LEVELS_LEVEL_ALL, enabled=True), packHeaderColumnData('shortUserName', 152, 40, label=DIALOGS.TRADEINPOPOVER_SORTING_VEHNAME_HEADER, tooltip=DIALOGS.TRADEINPOPOVER_SORTING_VEHNAME, enabled=True, verticalTextAlign='center', showSeparator=False)] if not self._nyController.isPostEvent(): description = '' cooldown = self.__slot.getDefaultSlotCooldown() if cooldown > 0: timeLeft = backport.getTillTimeStringByRClass(cooldown, R.strings.menu.Time.timeValueShort) description = backport.text(R.strings.ny.vehiclesView.selectVehiclePopover.description(), time=text_styles.stats(timeLeft)) else: description = backport.text(R.strings.ny.vehiclesView.selectVehiclePopover.postEvent.description()) self.as_setInitDataS({'title': backport.text(R.strings.ny.vehiclesView.selectVehiclePopover.header(), level=self.__slot.getLevelStr()), 'description': description, 'defaultSortField': 'level', 'defaultSortDirection': 'descending', 'tableHeaders': headers, 'filters': self.initFilters()})
def _packBlocks(self, *args): items = super(RankedSelectorTooltip, self)._packBlocks() items.append(self._packHeaderBlock()) timeTableBlocks = [self._packTimeTableHeaderBlock()] primeTime = self.rankedController.getPrimeTimes().get(self.connectionMgr.peripheryID) currentCycleEnd = self.rankedController.getCurrentSeason().getCycleEndDate() todayStart, todayEnd = time_utils.getDayTimeBoundsForLocal() todayEnd += 1 tomorrowStart, tomorrowEnd = todayStart + time_utils.ONE_DAY, todayEnd + time_utils.ONE_DAY tomorrowEnd += 1 todayPeriods = () tomorrowPeriods = () if primeTime is not None: todayPeriods = primeTime.getPeriodsBetween(todayStart, min(todayEnd, currentCycleEnd)) if tomorrowStart < currentCycleEnd: tomorrowPeriods = primeTime.getPeriodsBetween(tomorrowStart, min(tomorrowEnd, currentCycleEnd)) todayStr = self._packPeriods(todayPeriods) timeTableBlocks.append(self._packTimeBlock(message=text_styles.main(RANKED_BATTLES.SELECTORTOOLTIP_TIMETABLE_TODAY), timeStr=text_styles.bonusPreviewText(todayStr))) tomorrowStr = self._packPeriods(tomorrowPeriods) timeTableBlocks.append(self._packTimeBlock(message=text_styles.main(RANKED_BATTLES.SELECTORTOOLTIP_TIMETABLE_TOMORROW), timeStr=text_styles.stats(tomorrowStr))) items.append(formatters.packBuildUpBlockData(timeTableBlocks, 7, BLOCKS_TOOLTIP_TYPES.TOOLTIP_BUILDUP_BLOCK_WHITE_BG_LINKAGE)) items.append(self._getTillEndBlock(time_utils.getTimeDeltaFromNow(time_utils.makeLocalServerTime(currentCycleEnd)))) return items
def _getTillEndBlock(self, timeLeft): return formatters.packTextBlockData(text_styles.main(RANKED_BATTLES.SELECTORTOOLTIP_TILLEND) + ' ' + text_styles.stats(time_utils.getTillTimeString(timeLeft, MENU.HEADERBUTTONS_BATTLE_TYPES_RANKED_AVAILABILITY)))
def getTillBlock(isSeasonStarted, tillEnd, timeLeft, leftPadding=0): if isSeasonStarted: tillStartStr = R.strings.tooltips.battleTypes.battleRoyale.tillStart tillEndStr = R.strings.tooltips.battleTypes.battleRoyale.tillEnd else: tillStartStr = R.strings.tooltips.battleTypes.battleRoyale.tillStartCycle tillEndStr = R.strings.tooltips.battleTypes.battleRoyale.tillEndCycle return formatters.packTextBlockData(text_styles.main(backport.text(tillEndStr() if tillEnd else tillStartStr())) + ' ' + text_styles.stats(backport.getTillTimeStringByRClass(timeLeft, R.strings.menu.headerButtons.battle.types.ranked.availability)), padding=formatters.packPadding(left=leftPadding))
def _packTimeTableHeaderBlock(self): return formatters.packImageTextBlockData(title=text_styles.stats(RANKED_BATTLES.SELECTORTOOLTIP_TIMETABLE_TITLE), img=RES_ICONS.MAPS_ICONS_BUTTONS_CALENDAR, imgPadding=formatters.packPadding(top=2), txtPadding=formatters.packPadding(left=5))
def _getStatus(self): block = [] module = self.module configuration = self.configuration vehicle = configuration.vehicle slotIdx = configuration.slotIdx eqs = configuration.eqs checkBuying = configuration.checkBuying isEqOrDev = module.itemTypeID in GUI_ITEM_TYPE.ARTEFACTS isFit = True reason = '' titleFormatter = text_styles.middleTitle cachedEqs = [None, None, None] currentVehicleEqs = [None, None, None] if vehicle is not None and vehicle.isInInventory: if vehicle is not None and vehicle.isInInventory: currentVehicleEqs = list(vehicle.eqs) vehicle.eqs = [None, None, None] if eqs: for i, e in enumerate(eqs): if e is not None: intCD = int(e) eq = g_itemsCache.items.getItemByCD(intCD) cachedEqs[i] = eq vehicle.eqs = cachedEqs isFit, reason = module.mayInstall(vehicle, slotIdx) vehicle.eqs = currentVehicleEqs inventoryVehicles = g_itemsCache.items.getVehicles(REQ_CRITERIA.INVENTORY).itervalues() totalInstalledVehicles = map(lambda x: x.shortUserName, module.getInstalledVehicles(inventoryVehicles)) installedVehicles = totalInstalledVehicles[:self.MAX_INSTALLED_LIST_LEN] tooltipHeader = None tooltipText = None if not isFit: reason = reason.replace(' ', '_') tooltipHeader, tooltipText = getComplexStatus('#tooltips:moduleFits/%s' % reason) if reason == 'not_with_installed_equipment': if vehicle is not None: vehicle.eqs = cachedEqs conflictEqs = module.getConflictedEquipments(vehicle) tooltipText %= {'eqs': ', '.join([ _ms(e.userName) for e in conflictEqs ])} vehicle.eqs = currentVehicleEqs elif reason == 'already_installed' and isEqOrDev and len(installedVehicles): tooltipHeader, _ = getComplexStatus('#tooltips:deviceFits/already_installed' if module.itemTypeName == GUI_ITEM_TYPE.OPTIONALDEVICE else '#tooltips:moduleFits/already_installed') tooltipText = ', '.join(installedVehicles) elif len(installedVehicles): tooltipHeader, _ = getComplexStatus('#tooltips:deviceFits/already_installed' if module.itemTypeName == GUI_ITEM_TYPE.OPTIONALDEVICE else '#tooltips:moduleFits/already_installed') tooltipText = ', '.join(installedVehicles) if tooltipHeader is not None or tooltipText is not None: if len(totalInstalledVehicles) > self.MAX_INSTALLED_LIST_LEN: hiddenVehicleCount = len(totalInstalledVehicles) - self.MAX_INSTALLED_LIST_LEN hiddenTxt = '%s %s' % (text_styles.main(TOOLTIPS.SUITABLEVEHICLE_HIDDENVEHICLECOUNT), text_styles.stats(hiddenVehicleCount)) tooltipText = '%s\n%s' % (tooltipText, hiddenTxt) block.append(self._packStatusBlock(tooltipHeader, tooltipText, titleFormatter)) if checkBuying: isFit, reason = module.mayPurchase(g_itemsCache.items.stats.money) if not isFit: reason = reason.replace(' ', '_') if reason in ('gold_error', 'credits_error'): titleFormatter = text_styles.critical tooltipHeader, tooltipText = getComplexStatus('#tooltips:moduleFits/%s' % reason) if tooltipHeader is not None or tooltipText is not None: if len(block): padding = formatters.packPadding(bottom=15) block.insert(0, self._packStatusBlock(tooltipHeader, tooltipText, titleFormatter, padding)) else: block.append(self._packStatusBlock(tooltipHeader, tooltipText, titleFormatter)) return block
def setClanDossier(self, clanDossier): super(ClanProfilePersonnelView, self).setClanDossier(clanDossier) self._showWaiting() clanInfo = yield clanDossier.requestClanInfo() if not clanInfo.isValid(): self._dummyMustBeShown = True self._updateDummy() self._hideWaiting() return members = yield clanDossier.requestMembers() if self.isDisposed(): return self.__membersDP = _ClanMembersDataProvider() self.__membersDP.setFlashObject(self.as_getMembersDPS()) self._updateClanInfo(clanInfo) membersCount = len(members) self.__membersDP.buildList(members, syncUserInfo=True) statistics = [ _packStat(CLANS.PERSONNELVIEW_CLANSTATS_AVGPERSONALRATING, CLANS.PERSONNELVIEW_CLANSTATS_AVGPERSONALRATING_TOOLTIP, 'avgPersonalRating40x32.png', *self.__membersDP.getAvgGlobalRating()), _packStat(CLANS.PERSONNELVIEW_CLANSTATS_AVGBATTLESCOUNT, CLANS.PERSONNELVIEW_CLANSTATS_AVGBATTLESCOUNT_TOOLTIP, 'avgBattlesCount40x32.png', *self.__membersDP.getAvgBattlesCount()), _packStat(CLANS.PERSONNELVIEW_CLANSTATS_AVGWINS, CLANS.PERSONNELVIEW_CLANSTATS_AVGWINS_TOOLTIP, 'avgWins40x32.png', *self.__membersDP.getAvgPerformanceBattles()), _packStat(CLANS.PERSONNELVIEW_CLANSTATS_AVGEXP, CLANS.PERSONNELVIEW_CLANSTATS_AVGEXP_TOOLTIP, 'avgExp40x32.png', *self.__membersDP.getAvgXp()) ] headers = [ _packColumn(_SORT_IDS.USER_NAME, CLANS.PERSONNELVIEW_TABLE_PLAYER, 223, CLANS.PERSONNELVIEW_TABLE_PLAYER_TOOLTIP), _packColumn(_SORT_IDS.POST, CLANS.PERSONNELVIEW_TABLE_POST, 275, CLANS.PERSONNELVIEW_TABLE_POST_TOOLTIP), _packColumn(_SORT_IDS.RATING, '', 100, CLANS.PERSONNELVIEW_TABLE_PERSONALRATING_TOOLTIP, RES_ICONS.MAPS_ICONS_STATISTIC_RATING24), _packColumn(_SORT_IDS.BATTLES_COUNT, '', 100, CLANS.PERSONNELVIEW_TABLE_BATTLESCOUNT_TOOLTIP, RES_ICONS.MAPS_ICONS_STATISTIC_BATTLES24), _packColumn(_SORT_IDS.BATTLES_PERFORMANCE, '', 100, CLANS.PERSONNELVIEW_TABLE_WINS_TOOLTIP, RES_ICONS.MAPS_ICONS_STATISTIC_WINS24), _packColumn(_SORT_IDS.AWG_XP, '', 100, CLANS.PERSONNELVIEW_TABLE_AVGEXP_TOOLTIP, RES_ICONS.MAPS_ICONS_STATISTIC_AVGEXP24), _packColumn(_SORT_IDS.DAYS_IN_CLAN, '', 100, CLANS.PERSONNELVIEW_TABLE_DAYSINCLAN_TOOLTIP, RES_ICONS.MAPS_ICONS_STATISTIC_DAYSINCLAN24, showSeparator=False) ] self.as_setDataS({ 'membersCount': _ms(CLANS.PERSONNELVIEW_MEMBERSCOUNT, count=text_styles.stats(str(membersCount)), max=str(MAX_MEMBERS_IN_CLAN)), 'tableHeaders': headers, 'statistics': statistics, 'defaultSortField': _SORT_IDS.POST, 'defaultSortDirection': 'descending' }) self._updateHeaderState() self._hideWaiting()
def requestMissionData(self, index): isObtained = not self._bootcamp.needAwarding() vehicleSelector = self.getComponent(QUESTS_ALIASES.MISSIONS_VEHICLE_SELECTOR_ALIAS) if vehicleSelector is not None: criteria = REQ_CRITERIA.VEHICLE.LEVELS([self._TANK_LEVEL]) | REQ_CRITERIA.IN_OWNERSHIP vehicleSelector.setCriteria(criteria, []) bTypesData = formatters.packMissionBonusTypeElements([ARENA_BONUS_TYPE.REGULAR]) bTypes = self._COMMA.join([ iconData.iconLabel for iconData in bTypesData ]) tooltipBody = makeString(QUESTS.MISSIONDETAILS_CONDITIONS_BATTLEBONUSTYPE_BODY, battleBonusTypes=bTypes) missionData = {'title': text_styles.promoSubTitle(backport.text(R.strings.bootcamp.quest.title())), 'battleConditions': [{'rendererLinkage': MISSIONS_ALIASES.BATTLE_CONDITION, 'linkageBig': MISSIONS_ALIASES.ANG_GROUP_BIG_LINKAGE, 'isDetailed': True, 'data': [{'title': text_styles.promoSubTitle(backport.text(R.strings.bootcamp.quest.name())), 'description': text_styles.highlightText(backport.text(R.strings.bootcamp.quest.condition())), 'state': MISSIONS_ALIASES.NONE, 'icon': backport.image(R.images.gui.maps.icons.quests.battleCondition.c_128.icon_battle_condition_battles_128x128()), 'maxDescLines': self._LINES_IN_DESCR}], 'linkage': MISSIONS_ALIASES.ANG_GROUP_DETAILED_LINKAGE}], 'statusLabel': text_styles.concatStylesWithSpace(icons.inProgress(), text_styles.standard(backport.text(R.strings.quests.missionDetails.missionsComplete(), count=text_styles.stats(self._MISSIONS_DONE), total=text_styles.standard(self._MISSIONS_COUNT)))), 'awards': [{'label': text_styles.gold(backport.text(R.strings.menu.premium.packet.days3())), 'padding': self._AWARD_LABEL_PADDING, 'imgSource': backport.image(R.images.gui.maps.icons.quests.bonuses.big.premium_3()), 'align': LABEL_ALIGN.RIGHT, 'tooltip': TOOLTIPS.AWARDITEM_PREMIUM, 'obtainedImage': backport.image(R.images.gui.maps.icons.library.awardObtained()), 'isObtained': isObtained, 'obtainedImageOffset': self._OBTAINED_IMAGE_OFFSET}, {'label': text_styles.gold(self._GOLD_LABEL), 'padding': self._AWARD_LABEL_PADDING, 'imgSource': backport.image(R.images.gui.maps.icons.quests.bonuses.big.gold()), 'align': LABEL_ALIGN.RIGHT, 'tooltip': TOOLTIPS.AWARDITEM_GOLD, 'obtainedImage': backport.image(R.images.gui.maps.icons.library.awardObtained()), 'isObtained': isObtained, 'obtainedImageOffset': self._OBTAINED_IMAGE_OFFSET}], 'background': 'default', 'prebattleConditions': [formatters.packMissionPrebattleCondition(text_styles.main(bTypesData[0].iconLabel), ''.join([ iconData.icon for iconData in bTypesData ]), makeTooltip(QUESTS.MISSIONDETAILS_CONDITIONS_BATTLEBONUSTYPE, tooltipBody))], 'uiDecoration': backport.image(R.images.gui.maps.icons.quests.decorations.default_750x264()), 'statusTooltipData': {}} self.as_setMissionDataS(missionData) return
def getHeader(self): return text_styles.stats( _ms('#quests:tileChainsView/title', name=self._operation.getShortUserName()))
def _getAllianceTextWithIcon(alliance): allianceIcon = icons.makeImageTag(backport.image(R.images.gui.maps.icons.blueprints.fragment.conversion.dyn(alliance)()), width=13, height=16) return text_styles.concatStylesToSingleLine(allianceIcon, text_styles.stats(backport.text(R.strings.blueprints.conversionView.alliance.name.dyn(alliance)())))
def __setCarouselData(self, blData): itemVOs = [] selectedIndex = -1 for item in blData['items']: element = item['element'] isInQuest = checkInQuest(element, self.__controller.filter.purchaseType) if item['installedInCurrentSlot']: label = text_styles.main( VEHICLE_CUSTOMIZATION.CAROUSEL_ITEMLABEL_APPLIED) elif element.isInDossier: label = text_styles.main( VEHICLE_CUSTOMIZATION.CAROUSEL_ITEMLABEL_PURCHASED) elif element.getIgrType() != IGR_TYPE.NONE: if element.getIgrType() == getIGRCtrl().getRoomType(): label = text_styles.main( VEHICLE_CUSTOMIZATION.CAROUSEL_ITEMLABEL_PURCHASED) else: label = icons.premiumIgrSmall() elif isInQuest: label = icons.quest() else: if item['duration'] == DURATION.PERMANENT: priceFormatter = text_styles.gold priceIcon = icons.gold() else: priceFormatter = text_styles.credits priceIcon = icons.credits() label = priceFormatter('{0}{1}'.format( element.getPrice(item['duration']), priceIcon)) data = { 'id': element.getID(), 'icon': element.getTexturePath(), 'bonusType': element.qualifier.getIcon16x16(), 'bonusPower': text_styles.stats('+{0}%{1}'.format( element.qualifier.getValue(), '*' if element.qualifier.getDescription() is not None else '')), 'label': label, 'selected': item['appliedToCurrentSlot'] or item['installedInCurrentSlot'] and not blData['hasAppliedItem'], 'goToTaskBtnVisible': isInQuest, 'goToTaskBtnText': _ms(VEHICLE_CUSTOMIZATION. CUSTOMIZATION_ITEMCAROUSEL_RENDERER_GOTOTASK), 'newElementIndicatorVisible': item['isNewElement'] } if data['selected']: selectedIndex = blData['items'].index(item) if element.isOnSale( item['duration']) and not element.isInDossier and not item[ 'installedInCurrentSlot'] and not isInQuest: data['salePrice'] = getSalePriceString( self.__controller.slots.currentType, element, item['duration']) itemVOs.append(data) carouselLength = len(itemVOs) self.as_setCarouselDataS({ 'rendererList': itemVOs, 'rendererWidth': blData['rendererWidth'], 'filterCounter': '{0}{1}'.format( text_styles.stats(carouselLength) if carouselLength > 0 else text_styles.error(carouselLength), text_styles.main( _ms(VEHICLE_CUSTOMIZATION.CAROUSEL_FILTER_COUNTER, all=blData['unfilteredLength']))), 'messageVisible': carouselLength == 0, 'counterVisible': True, 'goToIndex': blData['goToIndex'], 'selectedIndex': selectedIndex }) return
def getHeader(self): return text_styles.stats( i18n.makeString('#quests:tileChainsView/title', name=self._tile.getUserName()))
def __packInStorageBlock(count=0): inStorageStr = text_styles.concatStylesWithSpace(text_styles.stats(int(count)), icons.makeImageTag(source=RES_ICONS.MAPS_ICONS_LIBRARY_STORAGE_ICON, width=30, height=24, vSpace=-6), text_styles.main(TOOLTIPS.BLUEPRINT_BLUEPRINTFRAGMENTTOOLTIP_INSTORAGE)) return formatters.packTextBlockData(text=inStorageStr, padding=formatters.packPadding(left=69, bottom=-2, top=1))
def _getVehicleDescrStr(vehicle): if vehicle.isElite: vehTypeIcon = icons.makeImageTag(source=RES_ICONS.maps_icons_vehicletypes_elite_all_png(vehicle.type), width=24, height=24, vSpace=-6) else: vehTypeIcon = icons.makeImageTag(RES_ICONS.maps_icons_vehicletypes_all_png(vehicle.type)) return text_styles.concatStylesToSingleLine(text_styles.stats(int2roman(vehicle.level)), vehTypeIcon, text_styles.main(vehicle.userName))
def _formatChainsProgress(self, completedCountStr, totalCount, chainID): return _ms(QUESTS.QUESTSCHAINPROGRESSVIEW_FALLOUTCHAINPROGRESSCOUNT, name=text_styles.neutral( _ms('#potapov_quests:chain_%s_fallout' % chainID)), count=text_styles.stats(completedCountStr), total=text_styles.standard(str(totalCount)))
def _packBlocks(self, vehicleCD): items = super(ConvertInfoBlueprintTooltipData, self)._packBlocks(vehicleCD) self.__vehicle, self.__blueprintData, self.__convertibleCount = self.context.getVehicleBlueprintData(vehicleCD) titleBlock = formatters.packTextBlockData(text=text_styles.middleTitle(TOOLTIPS.TECHTREEPAGE_BLUEPRINTCONVERTTOOLTIP_HEADER), blockWidth=190) description1Block = formatters.packTextBlockData(text=text_styles.main(i18n.makeString(TOOLTIPS.TECHTREEPAGE_BLUEPRINTCONVERTTOOLTIP_BODY, fragCount=text_styles.stats(str(self.__convertibleCount)))), blockWidth=190) items.append(formatters.packBuildUpBlockData(blocks=[titleBlock, description1Block], stretchLast=True, padding=formatters.packPadding(1, -1, -10, 0), gap=3)) return self._items
def _packParameterBlock(self, name, value, measureUnits): return formatters.packTextParameterBlockData(name=text_styles.main(name) + text_styles.standard(measureUnits), value=text_styles.stats(value), valueWidth=self._valueWidth, padding=formatters.packPadding(left=-5))