def __setData(self, *args): items = g_itemsCache.items tankman = items.getTankman(self.tmanInvID) if tankman is None: self.onWindowClose() return else: dropSkillsCost = [] for k in sorted(items.shop.dropSkillsCost.keys()): skillCost = items.shop.dropSkillsCost[k] defaultSkillCots = items.shop.defaults.dropSkillsCost[k] price = Money(**skillCost) defaultPrice = Money(**defaultSkillCots) action = None if price != defaultPrice: key = '{}DropSkillsCost'.format(price.getCurrency(byWeight=True)) action = packActionTooltipData(ACTION_TOOLTIPS_TYPE.ECONOMICS, key, True, price, defaultPrice) skillCost['action'] = action dropSkillsCost.append(skillCost) skills_count = list(tankmen.ACTIVE_SKILLS) availableSkillsCount = len(skills_count) - len(tankman.skills) hasNewSkills = tankman.roleLevel == tankmen.MAX_SKILL_LEVEL and availableSkillsCount and (tankman.descriptor.lastSkillLevel == tankmen.MAX_SKILL_LEVEL or not len(tankman.skills)) self.as_setDataS({'money': items.stats.money, 'tankman': packTankman(tankman, isCountPermanentSkills=False), 'dropSkillsCost': dropSkillsCost, 'hasNewSkills': hasNewSkills, 'newSkills': tankman.newSkillCount, 'defaultSavingMode': 0, 'texts': self.__getTexts()}) return
def __getSlotPrice(self): if self.__frozenSlotPrice is not None: return self.__frozenSlotPrice else: price = g_itemsCache.items.shop.getVehicleSlotsPrice(g_itemsCache.items.stats.vehicleSlots) if self.__hasDiscounts: self.__frozenSlotPrice = Money(gold=price) return Money(gold=price)
def __getConversionPrice(self, xp): def computeCost(xp, rate, cost): return round(cost * xp / rate) rate, cost = self.itemsCache.items.shop.freeXPConversionWithDiscount defRate, defCost = self.itemsCache.items.shop.defaults.freeXPConversion return ItemPrice(Money(gold=computeCost(xp, rate, cost)), Money(gold=computeCost(xp, defRate, defCost)))
def getVehicleSlotsItemPrice(self, currentSlotsCount): defPrice = self.defaults.getVehicleSlotsPrice(currentSlotsCount) price = self.getVehicleSlotsPrice(currentSlotsCount) slotGoodies = self.personalSlotDiscounts if slotGoodies: bestGoody = self.bestGoody(slotGoodies) price = getPriceWithDiscount(price, bestGoody.resource) return ItemPrice(price=Money.makeFrom(Currency.GOLD, price), defPrice=Money.makeFrom(Currency.GOLD, defPrice))
def __getPriceWithDiscount(price, resourceData): resourceType, _, _ = resourceData if resourceType == GOODIE_RESOURCE_TYPE.CREDITS: return Money( credits=getPriceWithDiscount(price.credits, resourceData)) return Money( gold=getPriceWithDiscount(price.gold, resourceData) ) if resourceType == GOODIE_RESOURCE_TYPE.GOLD else MONEY_UNDEFINED
def __getAction(self, cost, defaultCost, period): if cost != defaultCost: return packActionTooltipData(ACTION_TOOLTIPS_TYPE.ECONOMICS, 'premiumPacket%dCost' % period, True, Money(gold=cost), Money(gold=defaultCost)) else: return None
def _getByuContentData(self, vehicle, stats, isTradeIn): shop = self.itemsCache.items.shop shopDefaults = shop.defaults tankMenCount = len(vehicle.crew) vehiclePricesActionData = self._getItemPriceActionData(vehicle) ammoPrice = ITEM_PRICE_EMPTY for shell in vehicle.gun.defaultAmmo: ammoPrice += shell.buyPrices.itemPrice * shell.defaultCount ammoActionPriceData = None if ammoPrice.isActionPrice(): ammoActionPriceData = packActionTooltipData(ACTION_TOOLTIPS_TYPE.AMMO, str(vehicle.intCD), True, ammoPrice.price, ammoPrice.defPrice) slotPrice = shop.getVehicleSlotsPrice(stats.vehicleSlots) slotDefaultPrice = shopDefaults.getVehicleSlotsPrice(stats.vehicleSlots) slotActionPriceData = None if slotPrice != slotDefaultPrice: slotActionPriceData = packActionTooltipData(ACTION_TOOLTIPS_TYPE.ECONOMICS, 'slotsPrices', True, Money(gold=slotPrice), Money(gold=slotDefaultPrice)) tankmenTotalLabel = i18n.makeString(DIALOGS.BUYVEHICLEWINDOW_TANKMENTOTALLABEL, count=str(tankMenCount)) studyData = [] for index, (tCost, defTCost, typeID) in enumerate(zip(shop.tankmanCostWithGoodyDiscount, shopDefaults.tankmanCost, ('free', 'school', 'academy'))): if tCost['isPremium']: currency = Currency.GOLD else: currency = Currency.CREDITS price = tCost[currency] * tankMenCount defPrice = defTCost[currency] * tankMenCount totalPrice = Money.makeFrom(currency, price) totalDefPrice = Money.makeFrom(currency, defPrice) if typeID == 'free': formatedPrice = i18n.makeString(MENU.TANKMANTRAININGWINDOW_FREE_PRICE) else: formatedPrice = moneyWithIcon(totalPrice, currType=currency) studyPriceActionData = None if price != defPrice: studyPriceActionData = packActionTooltipData(ACTION_TOOLTIPS_TYPE.ECONOMICS, '%sTankmanCost' % currency, True, totalPrice, totalDefPrice) studyData.insert(0, {'id': typeID, 'price': price, 'crewType': index, 'actionPrice': studyPriceActionData, 'label': '%d%% - %s' % (tCost['roleLevel'], formatedPrice)}) initData = {'tankmenTotalLabel': tankmenTotalLabel, 'vehiclePrices': self._getVehiclePrice(vehicle).toMoneyTuple(), 'vehiclePricesActionData': vehiclePricesActionData, 'isRentable': vehicle.isRentable, 'rentDataDD': self._getRentData(vehicle, vehiclePricesActionData), 'ammoPrice': ammoPrice.price.getSignValue(Currency.CREDITS), 'ammoActionPriceData': ammoActionPriceData, 'slotPrice': slotPrice, 'slotActionPriceData': slotActionPriceData, 'isStudyDisabled': vehicle.hasCrew, 'isNoAmmo': not vehicle.hasShells, 'studyData': studyData, 'nation': self.nationID} initData.update(self._getContentFields(vehicle)) if isTradeIn: initData.update(self.__getTradeInContentFields(vehicle)) return initData
def __init__(self, intCompactDescr, proxy=None, isBoughtForAltPrice=False): """ Ctr. :param intCompactDescr: item's int compact descriptor :param proxy: instance of ItemsRequester :param isBoughtForAltPrice: indicates whether the item has been bought for credits(alt price) """ GUIItem.__init__(self, proxy) HasIntCD.__init__(self, intCompactDescr) self._isBoughtForAltPrice = isBoughtForAltPrice self._rentInfo = RentalInfoProvider() self._restoreInfo = None self._personalDiscountPrice = None if proxy is not None and proxy.isSynced(): self._mayConsumeWalletResources = proxy.stats.mayConsumeWalletResources defaultPrice = proxy.shop.defaults.getItemPrice(self.intCD) if defaultPrice is None: defaultPrice = MONEY_UNDEFINED buyPrice, self._isHidden = proxy.shop.getItem(self.intCD) if buyPrice is None: buyPrice = MONEY_UNDEFINED altPrice = self._getAltPrice(buyPrice, proxy.shop) defaultAltPrice = self._getAltPrice(defaultPrice, proxy.shop.defaults) self._buyPrices = ItemPrices( itemPrice=ItemPrice(price=buyPrice, defPrice=defaultPrice), itemAltPrice=ItemPrice(price=altPrice, defPrice=defaultAltPrice)) defaultSellPrice = Money.makeFromMoneyTuple( BigWorld.player().shop.getSellPrice( defaultPrice, proxy.shop.defaults.sellPriceModifiers(intCompactDescr), self.itemTypeID)) sellPrice = Money.makeFromMoneyTuple( BigWorld.player().shop.getSellPrice( buyPrice, proxy.shop.sellPriceModifiers(intCompactDescr), self.itemTypeID)) self._sellPrices = ItemPrices(itemPrice=ItemPrice( price=sellPrice, defPrice=defaultSellPrice), itemAltPrice=ITEM_PRICE_EMPTY) self._inventoryCount = proxy.inventory.getItems( self.itemTypeID, self.intCD) if self._inventoryCount is None: self._inventoryCount = 0 self._isUnlocked = self.intCD in proxy.stats.unlocks self._isInitiallyUnlocked = self.intCD in proxy.stats.initialUnlocks self._fullyConfigured = True else: self._buyPrices = ITEM_PRICES_EMPTY self._sellPrices = ITEM_PRICES_EMPTY self._isHidden = False self._inventoryCount = 0 self._isUnlocked = False self._mayConsumeWalletResources = False self._isInitiallyUnlocked = False self._fullyConfigured = False return
def tankmenRestoreConfig(self): config = self.__getRestoreConfig().get('tankmen', {}) if IS_CHINA: duration = config.get('goldDuration', 0) price = Money(gold=config.get('goldCost', 0)) else: duration = config.get('creditsDuration', 0) price = Money(credits=config.get('creditsCost', 0)) return _TankmenRestoreConfig(config.get('freeDuration', 0), duration, price, config.get('limit', 100))
def __init__(self, intCompactDescr, proxy=None, isBoughtForAltPrice=False, strCD=None): super(FittingItem, self).__init__(intCD=HasIntCD(intCompactDescr), strCD=strCD) self._isBoughtForAltPrice = isBoughtForAltPrice self._rentInfo = RentalInfoProvider(None, None, None, None, None, None) self._restoreInfo = None self._personalDiscountPrice = None self._descriptor = self._getDescriptor() if proxy is not None and proxy.inventory.isSynced( ) and proxy.stats.isSynced() and proxy.shop.isSynced(): self._mayConsumeWalletResources = proxy.stats.mayConsumeWalletResources defaultPrice = proxy.shop.defaults.getItemPrice(self.intCD) if defaultPrice is None: defaultPrice = MONEY_UNDEFINED buyPrice, self._isHidden = proxy.shop.getItem(self.intCD) if buyPrice is None: buyPrice = MONEY_UNDEFINED altPrice = self._getAltPrice(buyPrice, proxy.shop) defaultAltPrice = self._getAltPrice(defaultPrice, proxy.shop.defaults) self._buyPrices = ItemPrices( itemPrice=ItemPrice(price=buyPrice, defPrice=defaultPrice), itemAltPrice=ItemPrice(price=altPrice, defPrice=defaultAltPrice)) defaultSellPrice = Money.makeFromMoneyTuple( BigWorld.player().shop.getSellPrice( defaultPrice, proxy.shop.defaults.sellPriceModifiers(intCompactDescr), self.itemTypeID)) sellPrice = Money.makeFromMoneyTuple( BigWorld.player().shop.getSellPrice( buyPrice, proxy.shop.sellPriceModifiers(intCompactDescr), self.itemTypeID)) self._sellPrices = ItemPrices(itemPrice=ItemPrice( price=sellPrice, defPrice=defaultSellPrice), itemAltPrice=ITEM_PRICE_EMPTY) self._inventoryCount = proxy.inventory.getItems( self.itemTypeID, self.intCD) if self._inventoryCount is None: self._inventoryCount = 0 self._isUnlocked = self.intCD in proxy.stats.unlocks self._isInitiallyUnlocked = self.intCD in proxy.stats.initialUnlocks self._fullyConfigured = True else: self._buyPrices = ITEM_PRICES_EMPTY self._sellPrices = ITEM_PRICES_EMPTY self._isHidden = False self._inventoryCount = 0 self._isUnlocked = False self._mayConsumeWalletResources = False self._isInitiallyUnlocked = False self._fullyConfigured = False return
def _initialize(self, *args, **kwargs): super(BuyVehicleView, self)._initialize() self._blur = GUI.WGUIBackgroundBlur() self._blur.enable = True self.__addListeners() isElite = self.__vehicle.isElite vehType = self.__vehicle.type.replace('-', '_') with self.viewModel.transaction() as model: model.setTankType( '{}_elite'.format(vehType) if isElite else vehType) vehicleTooltip = i18n.makeString( getTypeUserName(self.__vehicle.type, isElite)) model.setVehicleNameTooltip(vehicleTooltip) model.setNation(nations.NAMES[self.__vehicle.nationID]) model.setTankLvl(int2roman(self.__vehicle.level)) model.setTankName(self.__vehicle.shortUserName) model.setCountCrew(len(self.__vehicle.crew)) model.setBuyVehicleIntCD(self.__vehicle.intCD) model.setIsToggleBtnVisible(self.__isTradeIn() and self.__vehicle.hasRentPackages) model.setIsElite(isElite) model.setIsRentVisible(self.__isRentVisible) model.setIsInBootcamp(self.__isBootcampBuyVehicle()) model.setIsMovingTextEnabled(constants.IS_CHINA and GUI_SETTINGS.movingText.show) if self.__vehicle.hasCrew: model.setWithoutCommanderAltText( R.strings.store.buyVehicleWindow.crewInVehicle) equipmentBlock = model.equipmentBlock equipmentBlock.setIsRentVisible(self.__isRentVisible) equipmentBlock.setTradeInIsEnabled(self.__isTradeIn()) emtySlotAvailable = self.itemsCache.items.inventory.getFreeSlots( self.__stats.vehicleSlots) > 0 equipmentBlock.setEmtySlotAvailable(emtySlotAvailable) equipmentBlock.setIsRestore(self.__vehicle.isRestoreAvailable()) if self.__vehicle.hasRentPackages and not self.__vehicle.isRestoreAvailable( ): self.__selectedRentIdx = 0 self.__selectedRentTerm = self.__vehicle.rentPackages[ self.__selectedRentIdx]['days'] tankPriceArray = model.getTankPrice() self.__addVMsInActionPriceList(tankPriceArray, self.__vehicle.buyPrices.itemPrice) self.__updateTankPrice() self.__updateCommanderCards() self.__updateSlotPrice() self.__updateAmmoPrice() self.__updateTradeInInfo() self.__updateRentInfo() self.__updateBuyBtnLabel() totalPriceArray = equipmentBlock.getTotalPrice() self.__addVMsInActionPriceList( totalPriceArray, ItemPrice(price=Money(credits=0, gold=0), defPrice=Money(credits=0, gold=0))) self.__updateTotalPrice()
def getCouponDiscountForItemPack(itemsPack, price=maxint): discount = 0 if itemsPack is None: return Money(gold=discount) else: for item in itemsPack: if item.type in ItemPackTypeGroup.DISCOUNT: discount += item.count return Money(gold=min(discount, price))
def __getPriceWithDiscount(price, resourceData): """ Translates goodie value into the final price in Money """ resourceType, _, _ = resourceData if resourceType == GOODIE_RESOURCE_TYPE.CREDITS: return Money(credits=getPriceWithDiscount(price.credits, resourceData)) if resourceType == GOODIE_RESOURCE_TYPE.GOLD: return Money(gold=getPriceWithDiscount(price.gold, resourceData)) return MONEY_UNDEFINED
def _initialize(self, *args, **kwargs): super(BuyVehicleView, self)._initialize() self._blur = CachedBlur(enabled=True) self.__addListeners() isElite = self.__vehicle.isElite vehType = self.__vehicle.type.replace('-', '_') isRestore = self.__vehicle.isRestoreAvailable() if self.__showOnlyCongrats: self.viewModel.setIsContentHidden(True) with self.viewModel.transaction() as vm: vm.setIsRestore(isRestore) vm.setBgSource( R.images.gui.maps.icons.store.shop_2_background_arsenal()) vm.setTankType('{}_elite'.format(vehType) if isElite else vehType) vehicleTooltip = i18n.makeString( getTypeUserName(self.__vehicle.type, isElite)) noCrewLabelPath = R.strings.store.buyVehicleWindow.checkBox vm.setVehicleNameTooltip(vehicleTooltip) vm.setNation(nations.NAMES[self.__vehicle.nationID]) vm.setNoCrewCheckboxLabel(noCrewLabelPath.restore.withoutCrew( ) if isRestore else noCrewLabelPath.buy.withoutCrew()) vm.setTankLvl(int2roman(self.__vehicle.level)) vm.setTankName(self.__vehicle.shortUserName) vm.setCountCrew(len(self.__vehicle.crew)) vm.setBuyVehicleIntCD(self.__vehicle.intCD) vm.setIsElite(isElite) if self.__vehicle.hasCrew: vm.setWithoutCommanderAltText( R.strings.store.buyVehicleWindow.crewInVehicle()) equipmentBlock = vm.equipmentBlock equipmentBlock.setIsRentVisible(self.__isRentVisible) equipmentBlock.setTradeInIsEnabled(self.__isTradeIn()) emtySlotAvailable = self.__itemsCache.items.inventory.getFreeSlots( self.__stats.vehicleSlots) > 0 equipmentBlock.setEmtySlotAvailable(emtySlotAvailable) equipmentBlock.setIsRestore(isRestore) if self.__vehicle.hasRentPackages and ( not isRestore or self.__actionType == VehicleBuyActionTypes.RENT ) and self.__actionType != VehicleBuyActionTypes.BUY: self.__selectedRentIdx = 0 self.__selectedRentID = self.__vehicle.rentPackages[ self.__selectedRentIdx]['rentID'] self.__updateCommanderCards() self.__updateSlotPrice() self.__updateAmmoPrice() self.__updateTradeInInfo() self.__updateRentInfo() self.__updateBuyBtnLabel() totalPriceArray = equipmentBlock.totalPrice.getItems() self.__addVMsInActionPriceList( totalPriceArray, ItemPrice(price=Money(credits=0, gold=0), defPrice=Money(credits=0, gold=0))) self.__updateTotalPrice()
def getRemovalPrice(self, proxy=None): if not self.isRemovable and proxy is not None: if self.isDeluxe(): cost = proxy.shop.paidDeluxeRemovalCost defaultCost = proxy.shop.defaults.paidDeluxeRemovalCost return ItemPrice(price=cost, defPrice=defaultCost) cost = proxy.shop.paidRemovalCost defaultCost = proxy.shop.defaults.paidRemovalCost return ItemPrice(price=Money(gold=cost), defPrice=Money(gold=defaultCost)) else: return super(OptionalDevice, self).getRemovalPrice(proxy)
def getStylePurchaseItems(style, modifiedOutfits, c11nService=None, prolongRent=False, progressionLevel=-1): purchaseItems = [] vehicle = g_currentVehicle.item vehicleCD = vehicle.descriptor.makeCompactDescr() isStyleInstalled = c11nService.getCurrentOutfit(SeasonType.SUMMER).id == style.id inventoryCounts = __getInventoryCounts(modifiedOutfits, vehicleCD) styleCount = style.fullInventoryCount(vehicle.intCD) isFromInventory = not prolongRent and (styleCount > 0 or isStyleInstalled) if style.isProgressive: totalPrice = ItemPrice(Money(), Money()) currentProgressionLvl = style.getLatestOpenedProgressionLevel(vehicle) progressivePrice = style.getUpgradePrice(currentProgressionLvl, progressionLevel) if style.isProgressionPurchasable(progressionLevel): totalPrice = progressivePrice if not style.isHidden and not isFromInventory: totalPrice += style.getBuyPrice() isFromInventory = False if progressionLevel > currentProgressionLvl else isFromInventory purchaseItem = PurchaseItem(style, totalPrice, areaID=None, slotType=None, regionIdx=None, selected=True, group=AdditionalPurchaseGroups.STYLES_GROUP_ID, isFromInventory=isFromInventory, locked=True, progressionLevel=progressionLevel) purchaseItems.append(purchaseItem) else: purchaseItem = PurchaseItem(style, style.getBuyPrice(), areaID=None, slotType=None, regionIdx=None, selected=True, group=AdditionalPurchaseGroups.STYLES_GROUP_ID, isFromInventory=isFromInventory, locked=True) purchaseItems.append(purchaseItem) for season in SeasonType.COMMON_SEASONS: modifiedOutfit = modifiedOutfits[season] if style.isProgressive: modifiedOutfit = c11nService.removeAdditionalProgressionData(outfit=modifiedOutfit, style=style, vehCD=vehicleCD, season=season) baseOutfit = style.getOutfit(season, vehicleCD) for intCD, component, regionIdx, container, _ in modifiedOutfit.itemsFull(): item = c11nService.getItemByCD(intCD) itemTypeID = item.itemTypeID slotType = ITEM_TYPE_TO_SLOT_TYPE.get(itemTypeID) if slotType is None: continue slotId = C11nId(container.getAreaID(), slotType, regionIdx) modifiedSlotData = SlotData(intCD, component) baseSlotData = getSlotDataFromSlot(baseOutfit, slotId) isEdited = baseSlotData.intCD != modifiedSlotData.intCD if isEdited: if slotId != correctSlot(slotId): continue price = item.getBuyPrice() isFromInventory = inventoryCounts[intCD] > 0 or item.isStyleOnly locked = bool(style.getDependenciesIntCDs()) and itemTypeID in EDITABLE_STYLE_IRREMOVABLE_TYPES and itemTypeID != GUI_ITEM_TYPE.CAMOUFLAGE else: price = ItemPrice(Money(credits=0), Money()) isFromInventory = True locked = isPurchaseItemLocked(item, style) purchaseItem = PurchaseItem(item, price=price, areaID=slotId.areaId, slotType=slotId.slotType, regionIdx=slotId.regionIdx, selected=True, group=season, isFromInventory=isFromInventory, component=component, locked=locked, isEdited=isEdited) purchaseItems.append(purchaseItem) inventoryCounts[intCD] -= 1 return purchaseItems
def packDropSkill(tankman, itemsCache=None, goodiesCache=None, lobbyContext=None): items = itemsCache.items vehicle = items.getItemByCD(tankman.vehicleNativeDescr.type.compactDescr) currentMoney = items.stats.money prices = items.shop.dropSkillsCost.values() trainingCosts = [ Money(credits=price[Currency.CREDITS] or None, gold=price[Currency.GOLD] or None) for price in prices ] defaultCosts = [ Money(credits=price[Currency.CREDITS] or None, gold=price[Currency.GOLD] or None) for price in items.shop.defaults.dropSkillsCost.itervalues() ] states = [ cost <= currentMoney or cost.get(Currency.GOLD) is not None for cost in trainingCosts ] factors = [price['xpReuseFraction'] for price in prices] tankmanLevels = [ math.floor(tankman.efficiencyRoleLevel * factor) for factor in factors ] result = [{ 'level': '{}%'.format(int(lvl)), 'enabled': state, 'price': [cost.getCurrency(), cost.getSignValue(cost.getCurrency())], 'isMoneyEnough': cost <= currentMoney, 'isNativeVehicle': True, 'nation': vehicle.nationName, 'showAction': cost != defCost } for lvl, state, cost, defCost in zip(tankmanLevels, states, trainingCosts, defaultCosts)] rfo = copy.deepcopy(result[0]) rfo['level'] = '100%' recertificationFormGoodie = goodiesCache.getRecertificationForm( currency='gold') rfo['enabled'] = SwitchState.ENABLED.value == lobbyContext.getServerSettings( ).recertificationFormState( ) and recertificationFormGoodie.enabled and recertificationFormGoodie.count > 0 result.append(rfo) return result
def __init__(self, vehicle, item, slotIdx, install=True, isUseGold=False, conflictedEqs=None): """ Ctor. @param vehicle: vehicle @param item: module to install @param slotIdx: vehicle equipment slot index to install @param install: flag to designated process @param conflictedEqs: conflicted items """ super(OptDeviceInstaller, self).__init__(vehicle, item, (GUI_ITEM_TYPE.OPTIONALDEVICE, ), slotIdx, install, conflictedEqs) self.cost = g_itemsCache.items.shop.paidRemovalCost defaultCost = g_itemsCache.items.shop.defaults.paidRemovalCost action = None if self.cost != defaultCost: action = packActionTooltipData(ACTION_TOOLTIPS_TYPE.ECONOMICS, 'paidRemovalCost', True, Money(gold=self.cost), Money(gold=defaultCost)) addPlugins = [] if install: addPlugins += (plugins.MessageConfirmator( 'installConfirmationNotRemovable', ctx={'name': item.userName}, isEnabled=not item.isRemovable), ) else: addPlugins += (plugins.DemountDeviceConfirmator( 'removeConfirmationNotRemovableGold', ctx={ 'name': item.userName, 'price': self.cost, 'action': action }, isEnabled=not item.isRemovable and isUseGold), plugins.DestroyDeviceConfirmator( 'removeConfirmationNotRemovable', itemName=item.userName, isEnabled=not item.isRemovable and not isUseGold)) self.addPlugins(addPlugins) self.useGold = isUseGold return
def getUpgradePrice(self, proxy=None): if self.isUpgradable and proxy is not None: price = proxy.shop.getOperationPrices().get( ITEM_OPERATION.UPGRADE, {}).get( (self.intCD, self.descriptor.upgradeInfo.upgradedCompDescr), None) defaultPrice = proxy.shop.defaults.getOperationPrices().get( ITEM_OPERATION.UPGRADE, {}).get( (self.intCD, self.descriptor.upgradeInfo.upgradedCompDescr), None) return ItemPrice(price=Money(**price), defPrice=Money(**defaultPrice)) else: return ITEM_PRICE_EMPTY
def calcRentPackages(vehicle, proxy): result = [] if proxy is not None and vehicle.isRentable: rentCost = proxy.shop.getVehicleRentPrices().get(vehicle.intCD, {}) defaultRentCost = proxy.shop.defaults.getVehicleRentPrices().get(vehicle.intCD, {}) if len(rentCost) and len(defaultRentCost) is not None: for key in sorted(rentCost.keys()): rentPrice = Money.makeFromMoneyTuple(rentCost[key].get('cost', ())) defaultRentPrice = Money.makeFromMoneyTuple(defaultRentCost.get(key, {}).get('cost', rentPrice)) result.append({'days': key, 'rentPrice': rentPrice, 'defaultRentPrice': defaultRentPrice}) return result
def _buildSupplyItems(self): self._supplyItems = [] items = self._itemsCache.items slots = items.stats.vehicleSlots vehicles = self.getTotalVehiclesCount() slotPrice = items.shop.getVehicleSlotsPrice(slots) defaultSlotPrice = items.shop.defaults.getVehicleSlotsPrice(slots) if slotPrice != defaultSlotPrice: discount = packActionTooltipData(ACTION_TOOLTIPS_TYPE.ECONOMICS, 'slotsPrices', True, Money(gold=slotPrice), Money(gold=defaultSlotPrice)) else: discount = None self._emptySlotsCount = slots - vehicles smallBuySlotString, buySlotString = getStatusStrings('buySlot') smallBuyTankString, buyTankString = getStatusStrings('buyTank') smallEmptySlotsString, emptySlotsString = getStatusStrings( 'buyTankEmptyCount', style=text_styles.main, ctx={'count': self._emptySlotsCount}) self._supplyItems.append({ 'buyTank': True, 'smallInfoText': text_styles.concatStylesToMultiLine(smallBuyTankString, smallEmptySlotsString), 'infoText': text_styles.concatStylesToMultiLine(buyTankString, emptySlotsString), 'icon': RES_ICONS.MAPS_ICONS_LIBRARY_TANKITEM_BUY_TANK, 'tooltip': TOOLTIPS.TANKS_CAROUSEL_BUY_VEHICLE_NEW if isIngameShopEnabled() else TOOLTIPS.TANKS_CAROUSEL_BUY_VEHICLE }) buySlotVO = { 'buySlot': True, 'slotPrice': slotPrice, 'icon': RES_ICONS.MAPS_ICONS_LIBRARY_TANKITEM_BUY_SLOT, 'infoText': buySlotString, 'smallInfoText': smallBuySlotString, 'hasSale': discount is not None, 'tooltip': TOOLTIPS.TANKS_CAROUSEL_BUY_SLOT } if discount is not None: buySlotVO.update({'slotPriceActionData': discount}) self._supplyItems.append(buySlotVO) return
def __setRepairPrice(self): vehicle = g_currentVehicle.item if isIncorrectVehicle(vehicle): return items = self.viewModel.repairPrice.getItems() items.clear() repairCost = vehicle.repairCost itemPrice = ItemPrice(price=Money(credits=repairCost), defPrice=Money(credits=repairCost)) actionPriceModels = getItemPricesViewModel( self.__itemsCache.items.stats.money, itemPrice)[0] for model in actionPriceModels: items.addViewModel(model) items.invalidate()
def _errorHandler(self, code, errStr='', ctx=None): needed = Money(credits=self._repairCost.credits - self.itemsCache.items.stats.credits) return makeI18nError('vehicle_repair/%s' % errStr, defaultSysMsgKey='vehicle_repair/server_error', vehName=self.item.userName, needed=formatPrice(needed))
def _getLevelPrice(level): levelDescr = self.descriptor.progression.levels.get(level) if levelDescr is not None: price = Money(**levelDescr['price']) return ItemPrice(price=price, defPrice=price) else: return ITEM_PRICE_EMPTY
def compensation(self): bonuses = [] substitutes = [] cache = vehicles.g_cache.customization20() for customizationItem in self._value: c11nItem = self.__getC11nItem(customizationItem) itemType, itemId = cc.splitIntDescr(c11nItem.intCD) c11nComponent = cache.itemTypes[itemType][itemId] count = customizationItem.get('value') inventoryCount = c11nItem.inventoryCount maxNumber = c11nComponent.maxNumber compensationCount = count - max(0, maxNumber - inventoryCount) if compensationCount > 0 and maxNumber != 0: realCount = count - compensationCount if realCount > 0: substituteItem = copy.deepcopy(customizationItem) substituteItem['value'] = realCount substitutes.append(substituteItem) compensation = customizationItem.get('customCompensation') money = Money.makeMoney(compensation) for currency, value in money.iteritems(): if value: cls = _BONUSES.get(currency) bonuses.append( cls(currency, value * compensationCount, isCompensation=True)) substitutes.append(copy.deepcopy(customizationItem)) bonuses.insert(0, CustomizationsBonus('customizations', substitutes)) return bonuses
def __init__(self, intCompactDescr, proxy = None, isBoughtForCredits = False): GUIItem.__init__(self, proxy) HasIntCD.__init__(self, intCompactDescr) self.defaultPrice = ZERO_MONEY self._buyPrice = ZERO_MONEY self.sellPrice = ZERO_MONEY self.defaultSellPrice = ZERO_MONEY self.altPrice = None self.defaultAltPrice = None self.sellActionPrc = 0 self.isHidden = False self.inventoryCount = 0 self.sellForGold = False self.isUnlocked = False self.isBoughtForCredits = isBoughtForCredits self.rentInfo = RentalInfoProvider() if proxy is not None and proxy.isSynced(): self.defaultPrice = proxy.shop.defaults.getItemPrice(self.intCompactDescr) if self.defaultPrice is None: self.defaultPrice = ZERO_MONEY self._buyPrice, self.isHidden, self.sellForGold = proxy.shop.getItem(self.intCompactDescr) if self._buyPrice is None: self._buyPrice = ZERO_MONEY self.defaultSellPrice = Money(*BigWorld.player().shop.getSellPrice(self.defaultPrice, proxy.shop.defaults.sellPriceModifiers(intCompactDescr), self.itemTypeID)) self.sellPrice = Money(*BigWorld.player().shop.getSellPrice(self.buyPrice, proxy.shop.sellPriceModifiers(intCompactDescr), self.itemTypeID)) self.inventoryCount = proxy.inventory.getItems(self.itemTypeID, self.intCompactDescr) if self.inventoryCount is None: self.inventoryCount = 0 self.isUnlocked = self.intCD in proxy.stats.unlocks self.isInitiallyUnlocked = self.intCD in proxy.stats.initialUnlocks self.altPrice = self._getAltPrice(self.buyPrice, proxy.shop) self.defaultAltPrice = self._getAltPrice(self.defaultPrice, proxy.shop.defaults) self.sellActionPrc = -1 * getActionPrc(self.sellPrice, self.defaultSellPrice) return
def tankmenRestoreConfig(self): config = self.__getRestoreConfig().get('tankmen', {}) return _TankmenRestoreConfig( config.get('freeDuration', 0), config.get('creditsDuration', 0), config.get('goldDuration', 0), Money(credits=config.get('creditsCost', 0)), config.get('limit', 100))
def _successHandler(self, code, ctx=None): msgType = SM_TYPE.FinancialTransactionWithGold vehicle = self.itemsCache.items.getItemByCD(self.__vehTypeCompDescr) additionalMsgs = [] if self.__compensationRequired: additionalMsgs.append( makeCrewSkinCompensationMessage( self.__compensationPriceObject)) if ctx == EQUIP_TMAN_CODE.OK: additionalMsgs.append( makeI18nSuccess(sysMsgKey='change_tankman_role/installed', vehicle=vehicle.shortUserName)) elif ctx == EQUIP_TMAN_CODE.NO_FREE_SLOT: roleStr = Tankman.getRoleUserName(SKILL_NAMES[self.__roleIdx]) additionalMsgs.append( makeI18nSuccess(sysMsgKey='change_tankman_role/slot_is_taken', vehicle=vehicle.shortUserName, role=roleStr)) else: additionalMsgs.append( makeI18nSuccess(sysMsgKey='change_tankman_role/no_vehicle')) return makeI18nSuccess('change_tankman_role/success', money=formatPrice( Money(gold=self.__changeRoleCost)), type=msgType, auxData=additionalMsgs)
def _successHandler(self, code, ctx=None): msgType = self.__getTankmanSysMsgType(self.dropSkillCostIdx) price = self.itemsCache.items.shop.dropSkillsCost.get( self.dropSkillCostIdx) return makeI18nSuccess('drop_tankman_skill/success', money=formatPrice(Money(**price)), type=msgType)
def changeRetrainType(self, operationId): operationId = int(operationId) items = g_itemsCache.items vehicle = g_currentVehicle.item shopPrices = items.shop.tankmanCost currentSelection = shopPrices[operationId] crewInfo = [] for idx, tMan in vehicle.crew: if tMan is not None: if tMan.vehicleNativeDescr.type.compactDescr != tMan.vehicleDescr.type.compactDescr: crewInfo.append(self.__getTankmanRoleInfo(tMan)) elif tMan.roleLevel != tankmen.MAX_SKILL_LEVEL and tMan.efficiencyRoleLevel < currentSelection[ 'roleLevel']: crewInfo.append(self.__getTankmanRoleInfo(tMan)) crewSize = len(crewInfo) price = crewSize * Money(**currentSelection) self.as_setCrewDataS({ 'price': price, 'crew': crewInfo, 'crewMembersText': text_styles.concatStylesWithSpace( _ms(RETRAIN_CREW.LABEL_CREWMEMBERS), text_styles.middleTitle(crewSize)) }) return
def calcVehicleRestorePrice(defaultPrice, proxy): exchangeRate = proxy.exchangeRate sellPriceFactor = proxy.sellPriceModif restorePriceModif = proxy.vehiclesRestoreConfig.restorePriceModif return Money.makeFromMoneyTuple( getVehicleRestorePrice(defaultPrice, exchangeRate, sellPriceFactor, restorePriceModif))
def as_setDataS(self, data): for shell in data['shells']: shell['prices'] = Money(credits=0).toMoneyTuple() if self.__isLesson: data['autoEquipVisible'] = False super(BCTechnicalMaintenanceMeta, self).as_setDataS(data)
def getTankmanCostWithDefaults(self): """ @return: tankman studying cost tmanCost, action - ( tmanCostType, ), ( actionData, ) where tmanCostType = { 'roleLevel' : minimal role level after operation, 'credits' : cost in credits, 'defCredits' : cost in credits, 'gold' : default cost in gold, 'defGold' : default cost in gold, 'baseRoleLoss' : float in [0, 1], fraction of role to drop, 'classChangeRoleLoss' : float in [0, 1], fraction of role to drop additionally if classes of self.vehicleTypeID and newVehicleTypeID are different, 'isPremium' : tankman becomes premium, }. List is sorted by role level. actionData = Action data for each level of retraining """ from gui.shared.tooltips import ACTION_TOOLTIPS_TYPE from gui.shared.tooltips.formatters import packActionTooltipData shopPrices = self.tankmanCost defaultPrices = self.defaults.tankmanCost action = [] tmanCost = [] for idx, price in enumerate(shopPrices): data = price.copy() shopPrice = Money(**price) defaultPrice = Money(**defaultPrices[idx]) actionData = None if shopPrice != defaultPrice: key = '{}TankmanCost'.format(shopPrice.getCurrency(byWeight=True)) actionData = packActionTooltipData(ACTION_TOOLTIPS_TYPE.ECONOMICS, key, True, shopPrice, defaultPrice) tmanCost.append(data) action.append(actionData) return (tmanCost, action)
class FittingItem(GUIItem, HasIntCD): class TARGETS(object): CURRENT = 1 IN_INVENTORY = 2 OTHER = 3 def __init__(self, intCompactDescr, proxy = None, isBoughtForCredits = False): GUIItem.__init__(self, proxy) HasIntCD.__init__(self, intCompactDescr) self.defaultPrice = ZERO_MONEY self._buyPrice = ZERO_MONEY self.sellPrice = ZERO_MONEY self.defaultSellPrice = ZERO_MONEY self.altPrice = None self.defaultAltPrice = None self.sellActionPrc = 0 self.isHidden = False self.inventoryCount = 0 self.sellForGold = False self.isUnlocked = False self.isBoughtForCredits = isBoughtForCredits self.rentInfo = RentalInfoProvider() if proxy is not None and proxy.isSynced(): self.defaultPrice = proxy.shop.defaults.getItemPrice(self.intCompactDescr) if self.defaultPrice is None: self.defaultPrice = ZERO_MONEY self._buyPrice, self.isHidden, self.sellForGold = proxy.shop.getItem(self.intCompactDescr) if self._buyPrice is None: self._buyPrice = ZERO_MONEY self.defaultSellPrice = Money(*BigWorld.player().shop.getSellPrice(self.defaultPrice, proxy.shop.defaults.sellPriceModifiers(intCompactDescr), self.itemTypeID)) self.sellPrice = Money(*BigWorld.player().shop.getSellPrice(self.buyPrice, proxy.shop.sellPriceModifiers(intCompactDescr), self.itemTypeID)) self.inventoryCount = proxy.inventory.getItems(self.itemTypeID, self.intCompactDescr) if self.inventoryCount is None: self.inventoryCount = 0 self.isUnlocked = self.intCD in proxy.stats.unlocks self.isInitiallyUnlocked = self.intCD in proxy.stats.initialUnlocks self.altPrice = self._getAltPrice(self.buyPrice, proxy.shop) self.defaultAltPrice = self._getAltPrice(self.defaultPrice, proxy.shop.defaults) self.sellActionPrc = -1 * getActionPrc(self.sellPrice, self.defaultSellPrice) return def _getAltPrice(self, buyPrice, proxy): return None @property def buyPrice(self): return self._buyPrice @property def rentOrBuyPrice(self): price = self.altPrice or self.buyPrice minRentPricePackage = self.getRentPackage() if minRentPricePackage: return minRentPricePackage['rentPrice'] return price @property def actionPrc(self): return getActionPrc(self.altPrice or self.buyPrice, self.defaultAltPrice or self.defaultPrice) @property def isSecret(self): return False @property def isPremium(self): return self.buyPrice.isSet(Currency.GOLD) @property def isPremiumIGR(self): return False @property def isRentable(self): return False @property def isRented(self): return False @property def descriptor(self): return vehicles.getDictDescr(self.intCompactDescr) @property def isRemovable(self): return True @property def minRentPrice(self): return None @property def rentLeftTime(self): return 0 def isPreviewAllowed(self): return False @property def userType(self): return getTypeInfoByName(self.itemTypeName)['userString'] @property def userName(self): return self.descriptor.get('userString', '') @property def longUserName(self): return self.userType + ' ' + self.userName @property def shortUserName(self): return self.descriptor.get('shortUserString', '') @property def shortDescription(self): return getShortDescr(self.descriptor.get('description', '')) @property def fullDescription(self): return stripShortDescrTags(self.descriptor.get('description', '')) @property def name(self): return self.descriptor.get('name', '') @property def level(self): return self.descriptor.get('level', 0) @property def isInInventory(self): return self.inventoryCount > 0 def _getShortInfo(self, vehicle = None, expanded = False): try: description = i18n.makeString('#menu:descriptions/' + self.itemTypeName + ('Full' if expanded else '')) vehicleDescr = vehicle.descriptor if vehicle is not None else None params = params_helper.getParameters(self, vehicleDescr) formattedParametersDict = dict(formatters.getFormattedParamsList(self.descriptor, params)) if self.itemTypeName == vehicles._VEHICLE: formattedParametersDict['caliber'] = BigWorld.wg_getIntegralFormat(self.descriptor.gun['shots'][0]['shell']['caliber']) result = description % formattedParametersDict return result except Exception: LOG_CURRENT_EXCEPTION() return '' return def getShortInfo(self, vehicle = None, expanded = False): if not GUI_SETTINGS.technicalInfo: return '' return self._getShortInfo(vehicle, expanded) def getParams(self, vehicle = None): return dict(params_helper.get(self, vehicle.descriptor if vehicle is not None else None)) def getRentPackage(self, days = None): return None def getGUIEmblemID(self): return 'notFound' @property def icon(self): return _ICONS_MASK % {'type': self.itemTypeName, 'subtype': '', 'unicName': self.name.replace(':', '-')} @property def iconSmall(self): return _ICONS_MASK % {'type': self.itemTypeName, 'subtype': 'small/', 'unicName': self.name.replace(':', '-')} def getBuyPriceCurrency(self): if self.altPrice is not None: if self.altPrice.gold and not self.isBoughtForCredits: return Currency.GOLD elif self.buyPrice.gold: return Currency.GOLD return Currency.CREDITS def getSellPriceCurrency(self): return self.sellPrice.getCurrency() def isInstalled(self, vehicle, slotIdx = None): return False def mayInstall(self, vehicle, slotIdx = None): return vehicle.descriptor.mayInstallComponent(self.intCD) def mayRemove(self, vehicle): return (True, '') def mayRent(self, money): return (False, '') def mayRentOrBuy(self, money): return self.mayPurchase(money) def mayPurchaseWithExchange(self, money, exchangeRate): price = self.altPrice or self.buyPrice money = money.exchange(Currency.GOLD, Currency.CREDITS, exchangeRate) return price <= money def isPurchaseEnabled(self, money, exchangeRate): canBuy, buyReason = self.mayPurchase(money) canRentOrBuy, rentReason = self.mayRentOrBuy(money) canBuyWithExchange = self.mayPurchaseWithExchange(money, exchangeRate) return canRentOrBuy or canBuy or canBuyWithExchange and buyReason == 'credits_error' def mayPurchase(self, money): if getattr(BigWorld.player(), 'isLongDisconnectedFromCenter', False): return (False, 'center_unavailable') if self.itemTypeID not in (GUI_ITEM_TYPE.EQUIPMENT, GUI_ITEM_TYPE.OPTIONALDEVICE, GUI_ITEM_TYPE.SHELL) and not self.isUnlocked: return (False, 'unlock_error') if self.isHidden: return (False, 'isHidden') price = self.altPrice or self.buyPrice if not price: return (True, '') for c in price.getSetCurrencies(): if money.get(c) >= price.get(c): return (True, '') return (False, '%s_error' % Currency.BY_WEIGHT[-1]) def getTarget(self, vehicle): if self.isInstalled(vehicle): return self.TARGETS.CURRENT if self.isInInventory: return self.TARGETS.IN_INVENTORY return self.TARGETS.OTHER def getConflictedEquipments(self, vehicle): return () def getInstalledVehicles(self, vehs): return set() def _sortByType(self, other): return 0 def __cmp__(self, other): if other is None: return 1 res = HasIntCD.__cmp__(self, other) if res: return res res = self._sortByType(other) if res: return res res = self.level - other.level if res: return res res = self.buyPrice.gold - other.buyPrice.gold if res: return res res = self.buyPrice.credits - other.buyPrice.credits if res: return res else: return cmp(self.userName, other.userName) def __eq__(self, other): if other is None: return False else: return self.intCompactDescr == other.intCompactDescr def __repr__(self): return '%s<intCD:%d, type:%s, nation:%d>' % (self.__class__.__name__, self.intCD, self.itemTypeName, self.nationID)
def construct(self): xp = self.configuration.xp dailyXP = self.configuration.dailyXP buyPrice = self.configuration.buyPrice sellPrice = self.configuration.sellPrice unlockPrice = self.configuration.unlockPrice techTreeNode = self.configuration.node minRentPrice = self.configuration.minRentPrice rentals = self.configuration.rentals paddings = formatters.packPadding(left=-4) neededValue = 0 actionPrc = 0 if buyPrice and sellPrice: LOG_ERROR('You are not allowed to use buyPrice and sellPrice at the same time') return else: block = [] isUnlocked = self.vehicle.isUnlocked isInInventory = self.vehicle.isInInventory isNextToUnlock = False parentCD = None if techTreeNode is not None: isNextToUnlock = bool(int(techTreeNode.state) & NODE_STATE.NEXT_2_UNLOCK) parentCD = techTreeNode.unlockProps.parentID if xp: xpValue = self.vehicle.xp if xpValue: xPText = text_styles.expText(_int(xpValue)) icon = ICON_TEXT_FRAMES.FREE_XP if self.vehicle.isPremium else ICON_TEXT_FRAMES.XP block.append(formatters.packTextParameterWithIconBlockData(name=text_styles.main(TOOLTIPS.VEHICLE_XP), value=xPText, icon=icon, valueWidth=self._valueWidth, padding=paddings)) if dailyXP: attrs = g_itemsCache.items.stats.attributes if attrs & constants.ACCOUNT_ATTR.DAILY_MULTIPLIED_XP and self.vehicle.dailyXPFactor > 0: dailyXPText = text_styles.main(text_styles.expText('x' + _int(self.vehicle.dailyXPFactor))) block.append(formatters.packTextParameterWithIconBlockData(name=text_styles.main(TOOLTIPS.VEHICLE_DAILYXPFACTOR), value=dailyXPText, icon=ICON_TEXT_FRAMES.DOUBLE_XP_FACTOR, valueWidth=self._valueWidth, padding=paddings)) if unlockPrice: isAvailable, cost, need = getUnlockPrice(self.vehicle.intCD, parentCD) if cost > 0: neededValue = None if isAvailable and not isUnlocked and need > 0 and techTreeNode is not None: neededValue = need block.append(makePriceBlock(cost, CURRENCY_SETTINGS.UNLOCK_PRICE, neededValue, valueWidth=self._valueWidth)) if buyPrice and not (self.vehicle.isDisabledForBuy or self.vehicle.isPremiumIGR or self.vehicle.isTelecom): price = self.vehicle.buyPrice money = g_itemsCache.items.stats.money actionPrc = self.vehicle.actionPrc defaultPrice = self.vehicle.defaultPrice currency = price.getCurrency() buyPriceText = price.get(currency) oldPrice = defaultPrice.get(currency) neededValue = price.get(currency) - money.get(currency) neededValue = neededValue if neededValue > 0 else None if isInInventory or not isInInventory and not isUnlocked and not isNextToUnlock: neededValue = None block.append(makePriceBlock(buyPriceText, CURRENCY_SETTINGS.getBuySetting(currency), neededValue, oldPrice, actionPrc, valueWidth=self._valueWidth)) if sellPrice and not self.vehicle.isTelecom: sellPrice = self.vehicle.sellPrice if sellPrice.isSet(Currency.GOLD): sellPriceText = text_styles.gold(_int(sellPrice.gold)) sellPriceIcon = ICON_TEXT_FRAMES.GOLD else: sellPriceText = text_styles.credits(_int(sellPrice.credits)) sellPriceIcon = ICON_TEXT_FRAMES.CREDITS block.append(formatters.packTextParameterWithIconBlockData(name=text_styles.main(TOOLTIPS.VEHICLE_SELL_PRICE), value=sellPriceText, icon=sellPriceIcon, valueWidth=self._valueWidth, padding=paddings)) if minRentPrice and not self.vehicle.isPremiumIGR: minRentPricePackage = self.vehicle.getRentPackage() if minRentPricePackage: minRentPriceValue = Money(*minRentPricePackage['rentPrice']) minDefaultRentPriceValue = Money(*minRentPricePackage['defaultRentPrice']) actionPrc = self.vehicle.getRentPackageActionPrc(minRentPricePackage['days']) money = g_itemsCache.items.stats.money currency = minRentPriceValue.getCurrency() price = minRentPriceValue.get(currency) oldPrice = minDefaultRentPriceValue.get(currency) neededValue = minRentPriceValue.get(currency) - money.get(currency) neededValue = neededValue if neededValue > 0 else None block.append(makePriceBlock(price, CURRENCY_SETTINGS.getRentSetting(currency), neededValue, oldPrice, actionPrc, valueWidth=self._valueWidth)) if rentals and not self.vehicle.isPremiumIGR: rentFormatter = RentLeftFormatter(self.vehicle.rentInfo) rentLeftInfo = rentFormatter.getRentLeftStr('#tooltips:vehicle/rentLeft/%s', formatter=lambda key, countType, count, _ = None: {'left': count, 'descr': i18n.makeString(key % countType)}) if rentLeftInfo: block.append(formatters.packTextParameterWithIconBlockData(name=text_styles.main(rentLeftInfo['descr']), value=text_styles.main(rentLeftInfo['left']), icon=ICON_TEXT_FRAMES.RENTALS, valueWidth=self._valueWidth, padding=formatters.packPadding(left=-4, bottom=-16))) notEnoughMoney = neededValue > 0 hasAction = actionPrc > 0 return (block, notEnoughMoney or hasAction)
def construct(self): xp = self.configuration.xp dailyXP = self.configuration.dailyXP buyPrice = self.configuration.buyPrice sellPrice = self.configuration.sellPrice unlockPrice = self.configuration.unlockPrice techTreeNode = self.configuration.node minRentPrice = self.configuration.minRentPrice rentals = self.configuration.rentals futureRentals = self.configuration.futureRentals paddings = formatters.packPadding(left=-4) neededValue = 0 actionPrc = 0 if buyPrice and sellPrice: LOG_ERROR("You are not allowed to use buyPrice and sellPrice at the same time") return else: block = [] isUnlocked = self.vehicle.isUnlocked isInInventory = self.vehicle.isInInventory isNextToUnlock = False parentCD = None if techTreeNode is not None: isNextToUnlock = bool(int(techTreeNode.state) & NODE_STATE_FLAGS.NEXT_2_UNLOCK) parentCD = techTreeNode.unlockProps.parentID if xp: xpValue = self.vehicle.xp if xpValue: xPText = text_styles.expText(_int(xpValue)) icon = ICON_TEXT_FRAMES.FREE_XP if self.vehicle.isPremium else ICON_TEXT_FRAMES.XP block.append( formatters.packTextParameterWithIconBlockData( name=text_styles.main(TOOLTIPS.VEHICLE_XP), value=xPText, icon=icon, valueWidth=self._valueWidth, padding=paddings, ) ) if dailyXP: attrs = g_itemsCache.items.stats.attributes if attrs & constants.ACCOUNT_ATTR.DAILY_MULTIPLIED_XP and self.vehicle.dailyXPFactor > 0: dailyXPText = text_styles.main(text_styles.expText("x" + _int(self.vehicle.dailyXPFactor))) block.append( formatters.packTextParameterWithIconBlockData( name=text_styles.main(TOOLTIPS.VEHICLE_DAILYXPFACTOR), value=dailyXPText, icon=ICON_TEXT_FRAMES.DOUBLE_XP_FACTOR, valueWidth=self._valueWidth, padding=paddings, ) ) if unlockPrice: isAvailable, cost, need = getUnlockPrice(self.vehicle.intCD, parentCD) if cost > 0: neededValue = None if isAvailable and not isUnlocked and need > 0 and techTreeNode is not None: neededValue = need block.append( makePriceBlock(cost, CURRENCY_SETTINGS.UNLOCK_PRICE, neededValue, valueWidth=self._valueWidth) ) if buyPrice: if self.vehicle.isRestorePossible(): price = self.vehicle.restorePrice defaultPrice = price currency = price.getCurrency() buyPriceText = price.get(currency) oldPrice = defaultPrice.get(currency) neededValue = _getNeedValue(price, currency) if isInInventory or not isInInventory and not isUnlocked and not isNextToUnlock: neededValue = None block.append( makePriceBlock( buyPriceText, CURRENCY_SETTINGS.RESTORE_PRICE, neededValue, oldPrice, actionPrc, valueWidth=self._valueWidth, ) ) if self.vehicle.hasLimitedRestore(): timeKey, formattedTime = getTimeLeftInfo(self.vehicle.restoreInfo.getRestoreTimeLeft(), None) block.append( formatters.packTextParameterWithIconBlockData( name=text_styles.main("#tooltips:vehicle/restoreLeft/%s" % timeKey), value=text_styles.main(formattedTime), icon=ICON_TEXT_FRAMES.ALERT if timeKey == "hours" else ICON_TEXT_FRAMES.EMPTY, valueWidth=self._valueWidth, padding=formatters.packPadding(left=-4), ) ) elif not (self.vehicle.isDisabledForBuy or self.vehicle.isPremiumIGR or self.vehicle.isTelecom): price = self.vehicle.buyPrice actionPrc = self.vehicle.actionPrc defaultPrice = self.vehicle.defaultPrice currency = price.getCurrency() buyPriceText = price.get(currency) oldPrice = defaultPrice.get(currency) neededValue = _getNeedValue(price, currency) if isInInventory or not isInInventory and not isUnlocked and not isNextToUnlock: neededValue = None block.append( makePriceBlock( buyPriceText, CURRENCY_SETTINGS.getBuySetting(currency), neededValue, oldPrice, 0, valueWidth=self._valueWidth, ) ) if sellPrice and not self.vehicle.isTelecom: sellPrice = self.vehicle.sellPrice if sellPrice.isSet(Currency.GOLD): sellPriceText = text_styles.gold(_int(sellPrice.gold)) sellPriceIcon = ICON_TEXT_FRAMES.GOLD else: sellPriceText = text_styles.credits(_int(sellPrice.credits)) sellPriceIcon = ICON_TEXT_FRAMES.CREDITS block.append( formatters.packTextParameterWithIconBlockData( name=text_styles.main(TOOLTIPS.VEHICLE_SELL_PRICE), value=sellPriceText, icon=sellPriceIcon, valueWidth=self._valueWidth, padding=paddings, ) ) if minRentPrice and not self.vehicle.isPremiumIGR: minRentPricePackage = self.vehicle.getRentPackage() if minRentPricePackage: minRentPriceValue = Money(*minRentPricePackage["rentPrice"]) minDefaultRentPriceValue = Money(*minRentPricePackage["defaultRentPrice"]) actionPrc = self.vehicle.getRentPackageActionPrc(minRentPricePackage["days"]) currency = minRentPriceValue.getCurrency() price = minRentPriceValue.get(currency) oldPrice = minDefaultRentPriceValue.get(currency) neededValue = _getNeedValue(minRentPriceValue, currency) block.append( makePriceBlock( price, CURRENCY_SETTINGS.getRentSetting(currency), neededValue, oldPrice, actionPrc, valueWidth=self._valueWidth, ) ) if not self.vehicle.isRented or self.vehicle.rentalIsOver: block.append( formatters.packTextParameterWithIconBlockData( name=text_styles.main("#tooltips:vehicle/rentAvailable"), value="", icon=ICON_TEXT_FRAMES.RENTALS, valueWidth=self._valueWidth, padding=paddings, ) ) if rentals and not self.vehicle.isPremiumIGR: if futureRentals: rentLeftKey = "#tooltips:vehicle/rentLeftFuture/%s" rentInfo = RentalInfoProvider(time=self._rentExpiryTime, isRented=True) else: rentLeftKey = "#tooltips:vehicle/rentLeft/%s" rentInfo = self.vehicle.rentInfo rentFormatter = RentLeftFormatter(rentInfo) rentLeftInfo = rentFormatter.getRentLeftStr( rentLeftKey, formatter=lambda key, countType, count, _=None: { "left": count, "descr": i18n.makeString(key % countType), }, ) if rentLeftInfo: block.append( formatters.packTextParameterWithIconBlockData( name=text_styles.main(rentLeftInfo["descr"]), value=text_styles.main(rentLeftInfo["left"]), icon=ICON_TEXT_FRAMES.RENTALS, valueWidth=self._valueWidth, padding=formatters.packPadding(left=-4, bottom=-16), ) ) notEnoughMoney = neededValue > 0 hasAction = actionPrc > 0 return (block, notEnoughMoney or hasAction)