示例#1
0
    def __readNodeLines(self, parentCD, nation, xmlCtx, section, shared):
        linesSec = section['lines']
        if linesSec is None:
            linesSec = {}
        result = defaultdict(_makeLines)
        nextLevel = self.__nextLevels[parentCD].keys()
        _, xPath = xmlCtx
        xPath = '{0:>s}/lines'.format(xPath)
        getIDsByName = vehicles.g_list.getIDsByName
        makeIntCDByID = vehicles.makeIntCompactDescrByID
        for name, sub in linesSec.items():
            xmlCtx = (None, '{0:>s}/lines/{1:>1}'.format(xPath, name))
            uName = '{0:>s}:{1:>s}'.format(nation, name)
            try:
                nodeCD = makeIntCDByID(_VEHICLE_TYPE_NAME, *getIDsByName(uName))
            except Exception:
                raise _ConfigError(xmlCtx, 'Unknown vehicle type name {0:>s}'.format(uName))

            if IS_DEVELOPMENT:
                if nodeCD not in nextLevel:
                    _, nationID, vTypeID = vehicles.parseIntCompactDescr(parentCD)
                    pName = vehicles.g_list.getList(nationID)[vTypeID]['name']
                    LOG_ERROR('{0:>s} does not have relation with {1:>s}'.format(pName, uName))
                else:
                    nextLevel.remove(nodeCD)
            data = shared['default'].copy()
            tags = sub.keys()
            lineShared = shared['lines']
            line = data['line']
            if 'line' in tags:
                line = sub.readString('line')
                if line in lineShared:
                    data.update(lineShared[line]['default'])
            outPin = data['outPin']
            if 'outPin' in tags:
                outPin = sub.readString('outPin')
            inPin = data['inPin']
            if 'inPin' in tags:
                inPin = sub.readString('inPin')
            outPos, lineInfo = self.__getLineInfo(xmlCtx, line, nodeCD, outPin, inPin, lineShared)
            result[outPin]['outPin'] = outPos
            result[outPin]['outLiteral'] = outPin
            result[outPin]['inPins'].append(lineInfo)

        if IS_DEVELOPMENT and len(nextLevel):
            _, nationID, vTypeID = vehicles.parseIntCompactDescr(parentCD)
            pName = vehicles.g_list.getList(nationID)[vTypeID]['name']
            for itemCD in nextLevel:
                _, nationID, vTypeID = vehicles.parseIntCompactDescr(itemCD)
                uName = vehicles.g_list.getList(nationID)[vTypeID]['name']
                LOG_ERROR('Relation between {0:>s} and {1:>s} are not defined'.format(pName, uName))

        return result.values()
示例#2
0
    def __readBonus_tankmen(self, eventType, bonus, vehTypeCompDescr, section, _gFinishTime):
        lst = []
        for subsection in section.values():
            tmanDescr = subsection.asString
            if tmanDescr:
                try:
                    tman = tankmen.TankmanDescr(tmanDescr)
                    if type(vehTypeCompDescr) == int:
                        _, vehNationID, vehicleTypeID = vehicles.parseIntCompactDescr(vehTypeCompDescr)
                        if vehNationID != tman.nationID or vehicleTypeID != tman.vehicleTypeID:
                            raise Exception, 'Vehicle and tankman mismatch.'
                except Exception as e:
                    raise Exception, 'Invalid tankmen compact descr. Error: %s' % (e,)

                lst.append(tmanDescr)
                continue
            tmanData = {'isFemale': subsection.readBool('isFemale', False),
             'firstNameID': subsection.readInt('firstNameID', -1),
             'lastNameID': subsection.readInt('lastNameID', -1),
             'role': subsection.readString('role', ''),
             'iconID': subsection.readInt('iconID', -1),
             'roleLevel': subsection.readInt('roleLevel', 50),
             'freeXP': subsection.readInt('freeXP', 0),
             'fnGroupID': subsection.readInt('fnGroupID', 0),
             'lnGroupID': subsection.readInt('lnGroupID', 0),
             'iGroupID': subsection.readInt('iGroupID', 0),
             'isPremium': subsection.readBool('isPremium', False),
             'nationID': subsection.readInt('nationID', -1),
             'vehicleTypeID': subsection.readInt('vehicleTypeID', -1),
             'skills': subsection.readString('skills', '').split(),
             'freeSkills': subsection.readString('freeSkills', '').split()}
            for record in ('firstNameID', 'lastNameID', 'iconID'):
                if tmanData[record] == -1:
                    tmanData[record] = None

            try:
                if type(vehTypeCompDescr) == int:
                    _, vehNationID, vehicleTypeID = vehicles.parseIntCompactDescr(vehTypeCompDescr)
                    if vehNationID != tmanData['nationID'] or vehicleTypeID != tmanData['vehicleTypeID']:
                        raise Exception, 'Vehicle and tankman mismatch.'
                if eventType != EVENT_TYPE.POTAPOV_QUEST:
                    lst.append(tankmen.makeTmanDescrByTmanData(tmanData))
                else:
                    lst.append(tmanData)
            except Exception as e:
                raise Exception, '%s: %s' % (e, tmanData)

        bonus['tankmen'] = lst
        return
示例#3
0
def __readBonus_tankmen(bonus, vehTypeCompDescr, section):
    lst = []
    for subsection in section.values():
        tmanDescr = subsection.asString
        if tmanDescr:
            try:
                tman = tankmen.TankmanDescr(tmanDescr)
                if type(vehTypeCompDescr) == int:
                    _, vehNationID, vehicleTypeID = vehicles.parseIntCompactDescr(vehTypeCompDescr)
                    if vehNationID != tman.nationID or vehicleTypeID != tman.vehicleTypeID:
                        raise Exception, "Vehicle and tankman mismatch."
            except Exception as e:
                raise Exception, "Invalid tankmen compact descr. Error: %s" % (e,)

            lst.append(tmanDescr)
            continue
        tmanData = {
            "isFemale": subsection.readBool("isFemale", False),
            "firstNameID": subsection.readInt("firstNameID", -1),
            "lastNameID": subsection.readInt("lastNameID", -1),
            "role": subsection.readString("role", ""),
            "iconID": subsection.readInt("iconID", -1),
            "roleLevel": subsection.readInt("roleLevel", 50),
            "freeXP": subsection.readInt("freeXP", 0),
            "fnGroupID": subsection.readInt("fnGroupID", 0),
            "lnGroupID": subsection.readInt("lnGroupID", 0),
            "iGroupID": subsection.readInt("iGroupID", 0),
            "isPremium": subsection.readBool("isPremium", False),
            "nationID": subsection.readInt("nationID", -1),
            "vehicleTypeID": subsection.readInt("vehicleTypeID", -1),
            "skills": subsection.readString("skills", "").split(),
            "freeSkills": subsection.readString("freeSkills", "").split(),
        }
        for record in ("firstNameID", "lastNameID", "iconID"):
            if tmanData[record] == -1:
                tmanData[record] = None

        try:
            if type(vehTypeCompDescr) == int:
                _, vehNationID, vehicleTypeID = vehicles.parseIntCompactDescr(vehTypeCompDescr)
                if vehNationID != tmanData["nationID"] or vehicleTypeID != tmanData["vehicleTypeID"]:
                    raise Exception, "Vehicle and tankman mismatch."
            lst.append(tmanData)
        except Exception as e:
            raise Exception, "%s: %s" % (e, tmanData)

    bonus["tankmen"] = lst
    return
示例#4
0
    def _findNext2UnlockItems(self, nodes):
        """
        Finds nodes that statuses changed to "next to unlock".
        :param nodes: list of nodes data.
        :return: [(<int:vehicle compact descriptor>, <new state>,
            <new UnlockProps>), ... ].
        """
        result = []
        topLevelCDs = self._topLevelCDs.keys()
        unlockStats = self.getUnlockStats()
        unlockKwargs = unlockStats._asdict()
        for node in nodes:
            nodeCD = node['id']
            state = node['state']
            itemTypeID, _, _ = vehicles.parseIntCompactDescr(nodeCD)
            if itemTypeID == GUI_ITEM_TYPE.VEHICLE and (nodeCD in topLevelCDs or nodeCD == self.getRootCD()):
                available, unlockProps = g_techTreeDP.isNext2Unlock(nodeCD, **unlockKwargs)
                xp = g_techTreeDP.getAllVehiclePossibleXP(unlockProps.parentID, unlockStats)
            else:
                unlockProps = node['unlockProps']
                required = unlockProps.required
                available = len(required) and unlockStats.isSeqUnlocked(required) and not unlockStats.isUnlocked(nodeCD)
                xp = g_techTreeDP.getAllVehiclePossibleXP(self.getRootCD(), unlockStats)
            if available and state & NODE_STATE_FLAGS.LOCKED > 0:
                state ^= NODE_STATE_FLAGS.LOCKED
                state = NODE_STATE.addIfNot(state, NODE_STATE_FLAGS.NEXT_2_UNLOCK)
                if xp >= unlockProps.xpCost:
                    state = NODE_STATE.addIfNot(state, NODE_STATE_FLAGS.ENOUGH_XP)
                else:
                    state = NODE_STATE.removeIfHas(state, NODE_STATE_FLAGS.ENOUGH_XP)
                node['state'] = state
                result.append((node['id'], state, unlockProps._makeTuple()))

        return result
示例#5
0
    def _findNext2UnlockItems(self, nodes):
        result = []
        topLevelCDs = self._topLevelCDs.keys()
        freeXP = max(self._accFreeXP, 0)
        for node in nodes:
            nodeCD = node['id']
            state = node['state']
            itemTypeID, _, _ = vehicles.parseIntCompactDescr(nodeCD)
            if itemTypeID == _VEHICLE and nodeCD in topLevelCDs:
                available, unlockProps = g_techTreeDP.isNext2Unlock(nodeCD, unlocked=self._unlocks, xps=self._xps, freeXP=freeXP)
                xp = freeXP + self._xps.get(unlockProps.parentID, 0)
            else:
                unlockProps = node['unlockProps']
                required = unlockProps.required
                available = len(required) and required.issubset(self._unlocks) and nodeCD not in self._unlocks
                xp = freeXP + self._earnedXP
            if available and state & NODE_STATE.LOCKED > 0:
                state ^= NODE_STATE.LOCKED
                state = NODE_STATE.addIfNot(state, NODE_STATE.NEXT_2_UNLOCK)
                if xp >= unlockProps.xpCost:
                    state = NODE_STATE.addIfNot(state, NODE_STATE.ENOUGH_XP)
                else:
                    state = NODE_STATE.removeIfHas(state, NODE_STATE.ENOUGH_XP)
                node['state'] = state
                result.append((node['id'], state, unlockProps._makeTuple()))

        return result
示例#6
0
 def buyAndInstallItem(self, itemCD, rootCD, state):
     itemTypeID, nationID, itemID = vehicles.parseIntCompactDescr(itemCD)
     raise itemTypeID in GUI_ITEM_TYPE.VEHICLE_MODULES or AssertionError
     vehicle = g_itemsCache.items.getItemByCD(rootCD)
     if not vehicle.isInInventory:
         raise AssertionError('Vehicle must be in inventory')
         item = g_itemsCache.items.getItemByCD(itemCD)
         conflictedEqs = item.getConflictedEquipments(vehicle)
         if not self._canBuy(item) and self._canBuyWithExchange(item):
             isOk, args = yield DialogsInterface.showDialog(ExchangeCreditsMeta(itemCD, vehicle.intCD))
             if not isOk:
                 return
         if self._canBuy(item):
             Waiting.show('buyAndInstall')
             vehicle = g_itemsCache.items.getItemByCD(rootCD)
             gunCD = getGunCD(item, vehicle)
             result = yield BuyAndInstallItemProcessor(vehicle, item, 0, gunCD, conflictedEqs=conflictedEqs).request()
             processMsg(result)
             if result.success and item.itemTypeID in (GUI_ITEM_TYPE.TURRET, GUI_ITEM_TYPE.GUN):
                 item = g_itemsCache.items.getItemByCD(itemCD)
                 vehicle = g_itemsCache.items.getItemByCD(rootCD)
                 item.isInstalled(vehicle) and (yield tryToLoadDefaultShellsLayout(vehicle))
         Waiting.hide('buyAndInstall')
     RequestState.received(state)
     yield lambda callback = None: callback
     return
示例#7
0
 def _canBuy(self, nodeCD):
     gameCredits, gold = self.getShopPrice(nodeCD)
     itemTypeID, _, _ = vehicles.parseIntCompactDescr(nodeCD)
     canBuy = True
     if itemTypeID == _VEHICLE:
         canBuy = not getattr(BigWorld.player(), 'isLongDisconnectedFromCenter', False)
     return canBuy and self._accCredits >= gameCredits and self._accGold >= gold
示例#8
0
    def buyAndInstallItem(self, itemCD, state, inInventory = False):
        itemTypeID, nationID, itemID = vehicles.parseIntCompactDescr(itemCD)
        raise itemTypeID in _RESEARCH_ITEMS or AssertionError
        oldStyleVehicle = self._data.getInvItem(self._data.getRootCD())
        if not oldStyleVehicle is not None:
            raise AssertionError, 'Vehicle has be in inventory'
            eqs = functions.findConflictedEquipments(itemCD, itemTypeID, oldStyleVehicle)
            item = g_itemsCache.items.getItemByCD(itemCD)
            vehicle = g_itemsCache.items.getItemByCD(self._data.getRootCD())
            if not inInventory:
                Waiting.show('buyItem')
                buyResult = yield ModuleBuyer(item, count=1, buyForCredits=True, conflictedEqs=eqs, install=True).request()
                if len(buyResult.userMsg):
                    SystemMessages.g_instance.pushI18nMessage(buyResult.userMsg, type=buyResult.sysMsgType)
                Waiting.hide('buyItem')
            else:
                RequestState.sent(state)
            item = g_itemsCache.items.getItemByCD(itemCD)
            if item is not None and item.isInInventory:
                Waiting.show('applyModule')
                result = yield getInstallerProcessor(vehicle, item).request()
                success = result.success
                if result and result.auxData:
                    for m in result.auxData:
                        SystemMessages.g_instance.pushI18nMessage(m.userMsg, type=m.sysMsgType)

                if result and len(result.userMsg):
                    SystemMessages.g_instance.pushI18nMessage(result.userMsg, type=result.sysMsgType)
                success and itemTypeID in (_GUN, _TURRET) and self.tryLoadShells()
            Waiting.hide('applyModule')
        RequestState.received(state)
        return
示例#9
0
 def request4Sell(self, itemCD):
     itemCD = int(itemCD)
     itemTypeID, _, _ = vehicles.parseIntCompactDescr(itemCD)
     if itemTypeID == _VEHICLE:
         self.sellVehicle(itemCD)
     else:
         self.sellItem(itemCD)
示例#10
0
    def _findNext2UnlockItems(self, nodes):
        result = []
        topLevelCDs = self._topLevelCDs.keys()
        unlockStats = self.getUnlockStats()
        unlockKwargs = unlockStats._asdict()
        for node in nodes:
            nodeCD = node['id']
            state = node['state']
            itemTypeID, _, _ = vehicles.parseIntCompactDescr(nodeCD)
            if itemTypeID == GUI_ITEM_TYPE.VEHICLE and (nodeCD in topLevelCDs or nodeCD == self.getRootCD()):
                available, unlockProps = g_techTreeDP.isNext2Unlock(nodeCD, **unlockKwargs)
                xp = self._getAllPossibleXP(unlockProps.parentID, unlockStats)
            else:
                unlockProps = node['unlockProps']
                required = unlockProps.required
                available = len(required) and unlockStats.isSeqUnlocked(required) and not unlockStats.isUnlocked(nodeCD)
                xp = self._getAllPossibleXP(self.getRootCD(), unlockStats)
            if available and state & NODE_STATE.LOCKED > 0:
                state ^= NODE_STATE.LOCKED
                state = NODE_STATE.addIfNot(state, NODE_STATE.NEXT_2_UNLOCK)
                if xp >= unlockProps.xpCost:
                    state = NODE_STATE.addIfNot(state, NODE_STATE.ENOUGH_XP)
                else:
                    state = NODE_STATE.removeIfHas(state, NODE_STATE.ENOUGH_XP)
                node['state'] = state
                result.append((node['id'], state, unlockProps._makeTuple()))

        return result
示例#11
0
    def buyAndInstallItem(self, itemCD, state, inInventory = False):
        itemTypeID, nationID, itemID = vehicles.parseIntCompactDescr(itemCD)
        assert itemTypeID in GUI_ITEM_TYPE.VEHICLE_MODULES
        vehicle = self._data.getRootItem()
        assert vehicle.isInInventory, 'Vehicle must be in inventory'
        item = self._data.getItem(itemCD)
        conflictedEqs = item.getConflictedEquipments(vehicle)
        if not inInventory:
            Waiting.show('buyItem')
            buyResult = yield ModuleBuyer(item, count=1, buyForCredits=True, conflictedEqs=conflictedEqs, install=True).request()
            Waiting.hide('buyItem')
            if len(buyResult.userMsg):
                SystemMessages.g_instance.pushI18nMessage(buyResult.userMsg, type=buyResult.sysMsgType)
            if buyResult.success:
                item = self._data.getItem(itemCD)
            else:
                return
        else:
            RequestState.sent(state)
        if item.isInInventory:
            Waiting.show('applyModule')
            result = yield getInstallerProcessor(vehicle, item, conflictedEqs=conflictedEqs).request()
            if result and result.auxData:
                for m in result.auxData:
                    SystemMessages.g_instance.pushI18nMessage(m.userMsg, type=m.sysMsgType)

            if result and len(result.userMsg):
                SystemMessages.g_instance.pushI18nMessage(result.userMsg, type=result.sysMsgType)
            if result.success and item.itemTypeID in (GUI_ITEM_TYPE.TURRET, GUI_ITEM_TYPE.GUN):
                vehicle = g_itemsCache.items.getItemByCD(vehicle.intCD)
                yield tryToLoadDefaultShellsLayout(vehicle)
            Waiting.hide('applyModule')
        RequestState.received(state)
示例#12
0
    def __loadItems(self, rootCD, unlocksDs):
        xpGetter = self._xps.get
        maxPath = 0
        nodes = []
        for unlockIdx, data in enumerate(unlocksDs):
            nodeCD = data[1]
            itemTypeID, _, _ = vehicles.parseIntCompactDescr(nodeCD)
            required = set(data[2:])
            required.add(rootCD)
            path = set(data[2:])
            path.add(rootCD)
            path = self.__fixPath(itemTypeID, path)
            maxPath = max(len(path), maxPath)
            nodes.append((nodeCD,
             itemTypeID,
             UnlockProps(rootCD, unlockIdx, data[0], required),
             path))

        invID = g_currentVehicle.invID if g_currentVehicle.isPresent() else -1
        for nodeCD, itemTypeID, props, path in nodes:
            node = self._getNodeData(nodeCD, xpGetter(nodeCD, 0), props, path, level=self.__fixLevel(itemTypeID, path, maxPath))
            if itemTypeID == _VEHICLE:
                item = self.getInvItem(nodeCD)
                if item is not None and invID == item.inventoryId:
                    node['state'] |= NODE_STATE.SELECTED
            self._nodesIdx[nodeCD] = len(self._nodes)
            self._nodes.append(node)

        return
示例#13
0
 def _showMessage4Item(self, scope, msg, itemCD, msgType = SystemMessages.SM_TYPE.Error, **kwargs):
     itemTypeID, nationID, itemID = vehicles.parseIntCompactDescr(itemCD)
     raise itemTypeID != _VEHICLE or AssertionError
     key = scope('item', msg)
     kwargs.update({'typeString': getTypeInfoByIndex(itemTypeID)['userString'],
      'userString': vehicles.getDictDescr(itemCD)['userString']})
     SystemMessages.pushMessage(i18n.makeString(key, **kwargs), type=msgType)
示例#14
0
def unpackPostBattleUniqueSubUrl(packedData):
    arenaUniqueID, value = struct.unpack('>QQ', base64.urlsafe_b64decode(str(packedData) + '=='))
    version = int(value & 255)
    value >>= 8
    if version > _POST_BATTLE_PACK_METHOD_VERSION:
        raise RuntimeError('url version is not valid', version)
    xp = int(value & 65535)
    value >>= 16
    vehTypeCompDescr = int(value & 65535)
    value >>= 16
    typeID, nationID, vehTypeID = vehicles.parseIntCompactDescr(vehTypeCompDescr)
    if typeID != _ITEM_TYPE_VEHICLE:
        raise RuntimeError('item type is not vehicle', vehTypeCompDescr)
    try:
        vehicles.g_cache.vehicle(nationID, vehTypeID)
    except Exception as e:
        raise RuntimeError('unknown vehicle', nationID, vehTypeID, e.message)

    if value not in ArenaType.g_cache:
        raise RuntimeError('unknown arena type id', value)
    return (arenaUniqueID,
     int(value),
     vehTypeCompDescr,
     xp,
     version)
示例#15
0
def isVehicleValid(vehDescr, vehAmmo, limits):
    minLevel, maxLevel = limits['level']
    classLevelLimits = limits['classLevel']
    for classTag in VEHICLE_CLASSES:
        if classTag not in vehDescr.type.tags:
            continue
        if classTag in classLevelLimits:
            classMinLevel, classMaxLevel = classLevelLimits[classTag]
            if not classMinLevel <= vehDescr.level <= classMaxLevel:
                return (False, 'limits/classLevel')
        elif not minLevel <= vehDescr.level <= maxLevel:
            return (False, 'limits/level')

    classesLimits = limits['classes']
    if classesLimits is not None:
        for classTag in VEHICLE_CLASSES:
            if classTag in vehDescr.type.tags and classTag not in classesLimits:
                return (False, 'limits/classes')

    nationLimits = limits['nations']
    if nationLimits is not None and nations.NAMES[vehDescr.type.id[0]] not in nationLimits:
        return (False, 'limits/nations')
    else:
        vehTypeCompDescr = vehDescr.type.compactDescr
        vehicleLimits = limits['vehicles']
        if vehicleLimits is not None and vehTypeCompDescr not in vehicleLimits:
            return (False, 'limits/vehicles')
        componentLimits = limits['components'].get(vehTypeCompDescr, None)
        if componentLimits is not None:
            isValid, components = componentLimits
            for compDescr in _collectCurrentReplaceableVehicleComponents(vehDescr):
                if isValid and compDescr not in components:
                    return (False, 'limits/components')
                if not isValid and compDescr in components:
                    return (False, 'limits/components')

        ammoLimits = limits['ammo']
        if ammoLimits is not None:
            isValid, ammoSet = ammoLimits
            for compDescr, count in AmmoIterator(vehAmmo):
                if compDescr == 0 or count == 0:
                    continue
                if isValid and compDescr not in ammoSet:
                    return (False, 'limits/ammo')
                if not isValid and compDescr in ammoSet:
                    return (False, 'limits/ammo')

        shellsLimits = limits['shells']
        if shellsLimits:
            for compDescr, count in AmmoIterator(vehAmmo):
                if compDescr == 0 or count == 0:
                    continue
                itemTypeIdx = vehicles.parseIntCompactDescr(compDescr)[0]
                if itemTypeIdx != ITEM_TYPES.shell:
                    continue
                if count > shellsLimits.get(compDescr, 65535):
                    return (False, 'limits/shells')

        return (True, None)
示例#16
0
 def _canSell(self, nodeCD):
     itemTypeID, _, _ = vehicles.parseIntCompactDescr(nodeCD)
     item = self.getInvItem(nodeCD)
     if itemTypeID == _VEHICLE:
         canSell = item.canSell
     else:
         canSell = nodeCD not in self._installed
     return canSell
示例#17
0
 def _parseIntCompDescr(self, intCompactDescr):
     """
     Parses int compact descriptor. Will be overidden by
     inherited items classes.
     
     @return: ( item type id, nation id, innation id )
     """
     return vehicles.parseIntCompactDescr(intCompactDescr)
示例#18
0
 def __init__(self, compactDescr):
     self.__descriptor = None
     itemTypeID, nationID, compTypeID = vehicles.parseIntCompactDescr(compactDescr)
     itemTypeName = ITEM_TYPE_NAMES[itemTypeID]
     FittingItem.__init__(self, compactDescr, itemTypeName)
     self.compTypeID = compTypeID
     self.nationID = nationID
     return
示例#19
0
 def request4Buy(self, itemCD):
     itemCD = int(itemCD)
     itemTypeID, _, _ = vehicles.parseIntCompactDescr(itemCD)
     if itemTypeID == _VEHICLE:
         self.buyVehicle(itemCD)
     else:
         if RequestState.inProcess('buyAndInstall'):
             SystemMessages.pushI18nMessage('#system_messages:shop/item/buy_and_equip_in_processing', type=SystemMessages.SM_TYPE.Warning)
         self.buyAndInstallItem(itemCD, 'buyAndInstall')
示例#20
0
 def sellVehicle(self, vehCD):
     itemTypeID, nationID, itemID = vehicles.parseIntCompactDescr(vehCD)
     if itemTypeID is not _VEHICLE:
         LOG_ERROR('Value of int-type descriptor is not refer to vehicle', vehCD)
         return
     if self._data.hasInvItem(vehCD):
         self.fireEvent(events.ShowWindowEvent(events.ShowWindowEvent.SHOW_VEHICLE_SELL_DIALOG, {'vehInvID': self._data.getInvItem(vehCD).inventoryId}))
     else:
         self._showMessage4Vehicle(self.MSG_SCOPE.Inventory, 'not_found', vehCD)
示例#21
0
 def __cb_onCreditsReceived(self, resultID, credits):
     self._gui.hideWaiting('request-credits')
     if resultID < 0:
         LOG_ERROR('Server return error credits request: ', resultID)
         self.isRunning = False
         return
     self._accCredits = credits
     self._gui.showWaiting('request-shop')
     itemTypeID, nationID, _ = vehicles.parseIntCompactDescr(self.getVar())
     BigWorld.player().shop.getAllItems(self.__cb_onShopItemsReceived)
示例#22
0
def _convert4ToolTip(dump, price):
    item = getItemByCompact(dump)
    if isinstance(item, _ResearchItem):
        itemCD = item.compactDescr
        itemTypeID, nationID, itemID = vehicles.parseIntCompactDescr(itemCD)
        if itemTypeID == vehicles._VEHICLE:
            item = _makeShopVehicle(itemID, nationID, price)
        else:
            item = _makeShopItem(itemCD, itemTypeID, nationID, price)
    return item
示例#23
0
 def _showMessage(self, scope, msg, itemCD, msgType = SystemMessages.SM_TYPE.Error, **kwargs):
     itemTypeID, nationID, itemID = vehicles.parseIntCompactDescr(itemCD)
     if itemTypeID == _VEHICLE:
         key = scope('vehicle', msg)
         kwargs['userString'] = vehicles.getVehicleType(itemCD).userString
     else:
         key = scope('item', msg)
         kwargs.update({'typeString': getTypeInfoByIndex(itemTypeID)['userString'],
          'userString': vehicles.getDictDescr(itemCD)['userString']})
     SystemMessages.pushMessage(i18n.makeString(key, **kwargs), type=msgType)
示例#24
0
文件: shop.py 项目: Infernux/Projects
 def __onGetComponentPriceResponse(self, resultID, compDescr, isSellPrice, callback):
     if resultID < 0:
         if callback is not None:
             callback(resultID, None, self.__getCacheRevision())
         return 
     (itemTypeIdx, _, _,) = vehicles.parseIntCompactDescr(compDescr)
     price = self.__getPriceFromCache(compDescr)
     if isSellPrice:
         price = self.getSellPrice(price, self.__getSellPriceModifiersFromCache(compDescr), itemTypeIdx)
     if callback is not None:
         callback(resultID, price, self.__getCacheRevision())
示例#25
0
    def parseVehicles(data, nationId):
        if data is None or not len(data):
            return []
        else:
            result = []
            parser = ShopDataParser(data)
            for intCD, price, isHidden, sellForGold in parser.getItemsIterator(nationId, GUI_ITEM_TYPE.VEHICLE):
                _, _, innationID = vehicles.parseIntCompactDescr(intCD)
                result.append(ShopItem(itemTypeName=ITEM_TYPE_NAMES[GUI_ITEM_TYPE.VEHICLE], compactDescr=innationID, priceOrder=price, nation=nationId, hidden=isHidden))

            return result
示例#26
0
 def getParameters(self, itemDescr, vehicleDescr = None):
     if isinstance(itemDescr, vehicles.VehicleDescr):
         itemTypeIdx = vehicles._VEHICLE
     else:
         itemTypeIdx, _, _ = vehicles.parseIntCompactDescr(itemDescr['compactDescr'])
     try:
         handler = self.__itemTypeHandlers.get(itemTypeIdx, lambda *args: None)
         return handler(itemDescr, vehicleDescr)
     except Exception:
         LOG_CURRENT_EXCEPTION()
         return dict()
示例#27
0
 def _getBuyConfirmMeta(self, itemCD, price, conflictedEqs):
     itemTypeID, nationID, itemID = vehicles.parseIntCompactDescr(itemCD)
     conflictedEqs = self._getConflictedEqsMeta(conflictedEqs).getMessage()
     ctx = {'credits': BigWorld.wg_getIntegralFormat(price[0]),
      'typeString': getTypeInfoByIndex(itemTypeID)['userString'],
      'conflictedEqs': conflictedEqs if conflictedEqs else ''}
     if itemTypeID == _VEHICLE:
         ctx['userString'] = vehicles.getVehicleType(itemCD).userString
     else:
         ctx['userString'] = vehicles.getDictDescr(itemCD)['userString']
     return HtmlMessageDialogMeta('html_templates:lobby/dialogs', 'confirmBuyAndInstall', ctx=ctx)
示例#28
0
    def __getComponentVehiclesNames(self, typeCompactDescr):
        from gui.shared.gui_items import getVehicleSuitablesByType
        itemTypeIdx, nationIdx, typeIdx = vehicles.parseIntCompactDescr(typeCompactDescr)
        result = list()
        for vDescr in self.__getItems(vehicles._VEHICLE, nationIdx):
            components, _ = getVehicleSuitablesByType(vDescr, itemTypeIdx)
            filtered = filter(lambda item: item['compactDescr'] == typeCompactDescr, components)
            if len(filtered):
                result.append(vDescr.type.userString)

        return result
示例#29
0
 def efficiencyOnVehicle(self, vehicleDescr):
     _, nationID, vehicleTypeID = vehicles.parseIntCompactDescr(vehicleDescr.type.historicalModelOf)
     assert nationID == self.nationID
     factor = 1.0
     if vehicleTypeID != self.vehicleTypeID:
         isPremium, isSameClass = self.__paramsOnVehicle(vehicleDescr.type)
         if isSameClass:
             factor = 1.0 if isPremium else 0.75
         else:
             factor = 0.75 if isPremium else 0.5
     addition = vehicleDescr.miscAttrs['crewLevelIncrease']
     return (factor, addition)
示例#30
0
 def efficiencyOnVehicle(self, vehicleDescr):
     _, nationID, vehicleTypeID = vehicles.parseIntCompactDescr(vehicleDescr.type.compactDescr)
     if not nationID == self.nationID:
         raise AssertionError
         factor = 1.0
         if vehicleTypeID != self.vehicleTypeID:
             isPremium, isSameClass = self.__paramsOnVehicle(vehicleDescr.type)
             factor = isSameClass and (1.0 if isPremium else 0.75)
         else:
             factor = 0.75 if isPremium else 0.5
     addition = vehicleDescr.miscAttrs['crewLevelIncrease']
     return (factor, addition)
示例#31
0
 def _getBuyConfirmMeta(self, itemCD, price, conflictedEqs):
     itemTypeID, nationID, itemID = vehicles.parseIntCompactDescr(itemCD)
     conflictedEqs = self._getConflictedEqsMeta(conflictedEqs).getMessage()
     ctx = {
         'credits': BigWorld.wg_getIntegralFormat(price[0]),
         'typeString': getTypeInfoByIndex(itemTypeID)['userString'],
         'conflictedEqs': conflictedEqs if conflictedEqs else ''
     }
     if itemTypeID == _VEHICLE:
         ctx['userString'] = vehicles.getVehicleType(itemCD).userString
     else:
         ctx['userString'] = vehicles.getDictDescr(itemCD)['userString']
     return HtmlMessageDialogMeta('html_templates:lobby/dialogs',
                                  'confirmBuyAndInstall',
                                  ctx=ctx)
示例#32
0
 def equip(self, vehInvID, itemCompDescr, callback):
     if self.__ignore:
         if callback is not None:
             callback(AccountCommands.RES_NON_PLAYER, 0, [])
         return
     else:
         itemTypeIdx = vehicles.parseIntCompactDescr(itemCompDescr)[0]
         if callback is not None:
             proxy = lambda requestID, resultID, errorStr, ext={}: callback(
                 resultID, ext)
         else:
             proxy = None
         self.__account._doCmdInt3(AccountCommands.CMD_EQUIP, vehInvID,
                                   itemCompDescr, 0, proxy)
         return
示例#33
0
 def isOn(self):
     itemCompDescr = self.getVar()
     vehCompDescr = self.vars().get(self._vehicleVarID)
     itemTypeID, nationID, compTypeID = vehicles.parseIntCompactDescr(
         vehCompDescr)
     if not itemTypeID == _VEHICLE:
         raise AssertionError
         vehType = vehicles.g_cache.vehicle(nationID, compTypeID)
         unlocksDescrs = vehType.unlocksDescrs
         filtered = filter(lambda info: info[1] == itemCompDescr,
                           unlocksDescrs)
         vehTypeXP = self._vehTypeXPs.get(vehCompDescr, 0)
         result = False
         result = len(
             filtered) and vehTypeXP + self._freeXP >= filtered[0][0]
     return result
示例#34
0
    def getComponentVehiclesNames(self, typeCompactDescr):
        itemTypeIdx, nationIdx, _ = vehicles.parseIntCompactDescr(
            typeCompactDescr)
        getter = vehicles.g_cache.vehicle
        result = []
        for itemID in vehicles.g_list.getList(nationIdx).iterkeys():
            vehicleType = getter(nationIdx, itemID)
            components = _getVehicleSuitablesByType(vehicleType, itemTypeIdx)
            filtered = [
                item for item in components
                if item.compactDescr == typeCompactDescr
            ]
            if filtered:
                result.append(vehicleType.userString)

        return result
示例#35
0
    def parseVehicles(data, nationId):
        if data is None or not len(data):
            return []
        result = []
        parser = ShopDataParser(data)
        for intCD, price, isHidden, sellForGold in parser.getItemsIterator(
                nationId, GUI_ITEM_TYPE.VEHICLE):
            _, _, innationID = vehicles.parseIntCompactDescr(intCD)
            result.append(
                ShopItem(itemTypeName=ITEM_TYPE_NAMES[GUI_ITEM_TYPE.VEHICLE],
                         compactDescr=innationID,
                         priceOrder=price,
                         nation=nationId,
                         hidden=isHidden))

        return result
示例#36
0
    def setInvItems(self, data):
        currentID = self._data.getNationID()
        result = set()
        for itemCD, count in data.iteritems():
            itemTypeID, nationID, _ = vehicles.parseIntCompactDescr(itemCD)
            if nationID != currentID:
                continue
            if count > 0:
                self._data.setInvItem(
                    itemCD,
                    custom_items._makeInventoryItem(itemTypeID, itemCD, count))
            else:
                self._data.removeInvItem(itemCD=itemCD)
            result.add(itemCD)

        return result
 def __onGetComponentPriceResponse(self, resultID, compDescr, isSellPrice,
                                   callback):
     if resultID < 0:
         if callback is not None:
             callback(resultID, None, self.__getCacheRevision())
         return
     else:
         itemTypeIdx, _, _ = vehicles.parseIntCompactDescr(compDescr)
         price = self.__getPriceFromCache(compDescr)
         if isSellPrice:
             price = self.getSellPrice(
                 price, self.__getSellPriceModifiersFromCache(compDescr),
                 itemTypeIdx)
         if callback is not None:
             callback(resultID, price, self.__getCacheRevision())
         return
示例#38
0
 def _getUnlockConfirmMeta(self, itemCD, costCtx):
     itemTypeID, nationID, itemID = vehicles.parseIntCompactDescr(itemCD)
     ctx = {
         'xpCost': BigWorld.wg_getIntegralFormat(costCtx['xpCost']),
         'freeXP': BigWorld.wg_getIntegralFormat(costCtx['freeXP']),
         'typeString': getTypeInfoByIndex(itemTypeID)['userString']
     }
     if itemTypeID == _VEHICLE:
         key = 'confirmUnlockVehicle'
         ctx['userString'] = vehicles.getVehicleType(itemCD).userString
     else:
         key = 'confirmUnlockItem'
         ctx['userString'] = vehicles.getDictDescr(itemCD)['userString']
     return HtmlMessageLocalDialogMeta('html_templates:lobby/dialogs',
                                       key,
                                       ctx=ctx)
    def __validateInventoryOutfit(self):
        c11nData = self.itemsCache.items.inventory.getCacheValue(GUI_ITEM_TYPE.CUSTOMIZATION, {})
        for vehIntCD, outfitsData in c11nData.get(constants.CustomizationInvData.OUTFITS, {}).iteritems():
            vehicleData = self.itemsCache.items.inventory.getItemData(vehIntCD)
            if vehicleData is not None:
                vehicleCD = vehicleData.compDescr
            else:
                _, nationID, vehicleTypeID = vehicles.parseIntCompactDescr(vehIntCD)
                vehicleDesc = vehicles.VehicleDescr(typeID=(nationID, vehicleTypeID))
                vehicleCD = vehicleDesc.makeCompactDescr()
            for outfitCD in outfitsData.itervalues():
                try:
                    self.itemsFactory.createOutfit(strCompactDescr=outfitCD, vehicleCD=vehicleCD)
                except Exception as e:
                    raise ValidateException(e.message, ValidationCodes.OUTFIT_MISMATCH, _packItemData(GUI_ITEM_TYPE.CUSTOMIZATION, (vehIntCD, outfitCD)))

        return
示例#40
0
 def _showMessage4Item(self,
                       scope,
                       msg,
                       itemCD,
                       msgType=SystemMessages.SM_TYPE.Error,
                       **kwargs):
     itemTypeID, nationID, itemID = vehicles.parseIntCompactDescr(itemCD)
     raise itemTypeID != _VEHICLE or AssertionError
     key = scope('item', msg)
     kwargs.update({
         'typeString':
         getTypeInfoByIndex(itemTypeID)['userString'],
         'userString':
         vehicles.getDictDescr(itemCD)['userString']
     })
     SystemMessages.pushMessage(i18n.makeString(key, **kwargs),
                                type=msgType)
示例#41
0
    def __createCrew(self, crewXml, vCompDescr):
        crew = {}
        if not crewXml:
            return crew
        else:
            crewStr = '<root>{}</root>'.format(crewXml.encode('ascii'))
            crewSection = ResMgr.DataSection().createSectionFromString(crewStr)
            if crewSection is not None:
                crew['tankmen'] = []
                _, nationId, vehTypeId = vehicles.parseIntCompactDescr(
                    vCompDescr)
                for tankmanSection in crewSection.values():
                    tmanDict = {}
                    tmanId = tankmanSection.readString('name')
                    if not tmanId:
                        continue
                    tData = None
                    tIdx = None
                    for idx, tMan in tankmen.getNationConfig(
                            nationId).premiumGroups.iteritems():
                        if tMan.name == tmanId:
                            tData = tMan
                            tIdx = idx
                            break

                    if tData is None:
                        continue
                    tmanDict['isPremium'] = True
                    tmanDict['gId'] = tIdx
                    tmanDict['nationID'] = nationId
                    tmanDict['firstNameID'] = first(tData.firstNames)
                    tmanDict['lastNameID'] = first(tData.lastNames)
                    tmanDict['iconID'] = first(tData.icons)
                    tmanDict['vehicleTypeID'] = vehTypeId
                    tmanDict['role'] = tankmanSection.readString('role')
                    for param in ('roleLevel', 'freeXP'):
                        tmanDict[param] = tankmanSection.readInt(param)

                    for param in ('skills', 'freeSkills'):
                        paramAsStr = tankmanSection.readString(param)
                        tmanDict[param] = paramAsStr.split(
                            ' ') if paramAsStr else []

                    crew['tankmen'].append(tmanDict)

            return crew
    def _packBlocks(self, itemCD, itemStatus):
        items = super(BattleOptDeviceTooltipData, self)._packBlocks()
        _, _, deviceID = vehicles.parseIntCompactDescr(itemCD)
        itemInBattle = self.guiSessionProvider.shared.optionalDevices.getOptDeviceInBattle(
            deviceID)
        if not itemInBattle:
            return items
        descriptor = itemInBattle.getDescriptor()
        leftPadding = 20
        rightPadding = 20
        topPadding = 20
        battleDescr = R.strings.artefacts.dyn(
            descriptor.groupName).battle_descr
        if battleDescr:
            desc = backport.text(battleDescr())
        else:
            desc = descriptor.shortDescriptionSpecial.format(colorTagOpen='',
                                                             colorTagClose='')
        items.append(
            formatters.packBuildUpBlockData([
                formatters.packTitleDescBlock(
                    title=text_styles.middleTitle(
                        backport.text(
                            R.strings.artefacts.dyn(
                                descriptor.tierlessName).name())),
                    desc=text_styles.main(desc),
                    padding=formatters.packPadding(bottom=-10))
            ],
                                            padding=formatters.packPadding(
                                                left=leftPadding,
                                                right=rightPadding,
                                                top=topPadding)))
        battleStatuses = itemInBattle.getBattleStatus()
        for ind, statusStr in enumerate(battleStatuses):
            items.append(
                formatters.packBuildUpBlockData([
                    formatters.packAlignedTextBlockData(
                        text=statusStr,
                        align=BLOCKS_TOOLTIP_TYPES.ALIGN_CENTER,
                        padding=formatters.packPadding(
                            bottom=-26 if ind +
                            1 != len(battleStatuses) else -10))
                ]))

        return items
def getUnlockPrice(compactDescr, parentCD=None):
    item_type_id, _, _ = vehicles.parseIntCompactDescr(compactDescr)
    itemsCache = dependency.instance(IItemsCache)
    freeXP = itemsCache.items.stats.actualFreeXP
    unlocks = itemsCache.items.stats.unlocks
    xpVehs = itemsCache.items.stats.vehiclesXPs
    g_techTreeDP.load()
    pricesDict = g_techTreeDP.getUnlockPrices(compactDescr)

    def getUnlockProps(isAvailable, vehCompDescr):
        unlockPrice = pricesDict.get(vehCompDescr, 0)
        pVehXp = xpVehs.get(vehCompDescr, 0)
        need = unlockPrice - pVehXp
        needWithFreeXP = need - freeXP
        return (isAvailable, unlockPrice, min(need, needWithFreeXP))

    if item_type_id == vehicles._VEHICLE:
        isAvailable, props = g_techTreeDP.isNext2Unlock(
            compactDescr, unlocks, xpVehs, freeXP)
        if parentCD is not None:
            return getUnlockProps(isAvailable, parentCD)
        return getUnlockProps(isAvailable, props.parentID)
    else:
        isAvailable = compactDescr in unlocks
        if not pricesDict:
            return (isAvailable, 0, 0)
        if parentCD is not None:
            return getUnlockProps(isAvailable, parentCD)
        vehsCompDescrs = [
            compDescr for compDescr in pricesDict.keys()
            if compDescr in unlocks
        ]
        if not vehsCompDescrs:
            vehsCompDescrs = pricesDict.keys()
        minUnlockPrice = sys.maxint
        minUnlockPriceVehCD = None
        for vcd in vehsCompDescrs:
            if pricesDict[vcd] <= minUnlockPrice:
                minUnlockPrice = pricesDict[vcd]
                minUnlockPriceVehCD = vcd

        if minUnlockPriceVehCD is None:
            return (isAvailable, 0, 0)
        return getUnlockProps(isAvailable, minUnlockPriceVehCD)
        return
示例#44
0
 def installItem(self, itemCD, rootCD, state):
     itemTypeID, nationID, itemID = vehicles.parseIntCompactDescr(itemCD)
     assert itemTypeID in GUI_ITEM_TYPE.VEHICLE_MODULES
     vehicle = g_itemsCache.items.getItemByCD(rootCD)
     assert vehicle.isInInventory, 'Vehicle must be in inventory'
     item = g_itemsCache.items.getItemByCD(itemCD)
     conflictedEqs = item.getConflictedEquipments(vehicle)
     RequestState.sent(state)
     if item.isInInventory:
         Waiting.show('applyModule')
         result = yield getInstallerProcessor(vehicle, item, conflictedEqs=conflictedEqs).request()
         processMsg(result)
         if result.success and item.itemTypeID in (GUI_ITEM_TYPE.TURRET, GUI_ITEM_TYPE.GUN):
             vehicle = g_itemsCache.items.getItemByCD(vehicle.intCD)
             yield tryToLoadDefaultShellsLayout(vehicle)
         Waiting.hide('applyModule')
     RequestState.received(state)
     yield lambda callback = None: callback
示例#45
0
    def __onGetComponentsPriceResponse(self, resultID, compDescrs, callback):
        if resultID < 0:
            if callback is not None:
                callback(resultID, None, self.__getCacheRevision())
            return
        prices = []
        for compDescr in compDescrs:
            itemTypeIdx, _, _ = vehicles.parseIntCompactDescr(compDescr)
            if itemTypeIdx == _VEHICLE:
                continue
            price = self.__getPriceFromCache(compDescr, None)
            if price is None:
                prices = None
                break
            prices.append(self.getSellPrice(price, self.__getSellPriceModifiersFromCache(compDescr), itemTypeIdx))

        if callback is not None:
            callback(resultID, prices, self.__getCacheRevision())
示例#46
0
 def equip(self, vehInvID, itemCompDescr, callback):
     if self.__ignore:
         if callback is not None:
             callback(AccountCommands.RES_NON_PLAYER, 0, [])
         return
     else:
         itemTypeIdx = vehicles.parseIntCompactDescr(itemCompDescr)[0]
         if not itemTypeIdx in (_CHASSIS, _GUN, _ENGINE, _FUEL_TANK,
                                _RADIO):
             raise AssertionError
             proxy = callback is not None and (
                 lambda requestID, resultID, errorStr, ext={}: callback(
                     resultID, ext))
         else:
             proxy = None
         self.__account._doCmdInt3(AccountCommands.CMD_EQUIP, vehInvID,
                                   itemCompDescr, 0, proxy)
         return
示例#47
0
    def _findNext2UnlockItems(self, nodes):
        """
        Finds nodes that statuses changed to "next to unlock".
        :param nodes: list of nodes data.
        :return: [(<int:vehicle compact descriptor>, <new state>,
            <new UnlockProps>), ... ].
        """
        result = []
        topLevelCDs = self._topLevelCDs.keys()
        unlockStats = self.getUnlockStats()
        unlockKwargs = unlockStats._asdict()
        for node in nodes:
            nodeCD = node.getNodeCD()
            state = node.getState()
            itemTypeID, _, _ = vehicles_core.parseIntCompactDescr(nodeCD)
            if itemTypeID == GUI_ITEM_TYPE.VEHICLE and (
                    nodeCD in topLevelCDs or nodeCD == self.getRootCD()):
                available, unlockProps = g_techTreeDP.isNext2Unlock(
                    nodeCD, **unlockKwargs)
                xp = g_techTreeDP.getAllVehiclePossibleXP(
                    unlockProps.parentID, unlockStats)
            else:
                unlockProps = node.getUnlockProps()
                required = unlockProps.required
                available = len(required) and unlockStats.isSeqUnlocked(
                    required) and not unlockStats.isUnlocked(nodeCD)
                xp = g_techTreeDP.getAllVehiclePossibleXP(
                    self.getRootCD(), unlockStats)
            if available and state & NODE_STATE_FLAGS.LOCKED > 0:
                state ^= NODE_STATE_FLAGS.LOCKED
                state = NODE_STATE.addIfNot(state,
                                            NODE_STATE_FLAGS.NEXT_2_UNLOCK)
                if xp >= unlockProps.xpCost:
                    state = NODE_STATE.addIfNot(state,
                                                NODE_STATE_FLAGS.ENOUGH_XP)
                else:
                    state = NODE_STATE.removeIfHas(state,
                                                   NODE_STATE_FLAGS.ENOUGH_XP)
                node.setState(state)
                result.append(
                    (node.getNodeCD(), state, unlockProps.makeTuple()))

        return result
示例#48
0
    def isNext2Unlock(self, nodeCD):
        itemTypeID, _, _ = vehicles.parseIntCompactDescr(nodeCD)
        topLevelCDs = []
        if itemTypeID == _VEHICLE:
            topLevelCDs = map(lambda node: node['id'], self._topLevel)
        if nodeCD in topLevelCDs:
            result, _ = g_techTreeDP.isNext2Unlock(nodeCD,
                                                   unlocked=self._unlocks,
                                                   xps=self._xps,
                                                   freeXP=max(
                                                       self._accFreeXP, 0))
        else:
            try:
                node = self._nodes[self._nodesIdx[nodeCD]]
                result = node['unlockProps'].required.issubset(self._unlocks)
            except (KeyError, IndexError):
                result = False

        return result
示例#49
0
def validateCustomizationItem(custData):
    """Check customization data
    
    :returns: (False, reason) if validation failed or (True, customizationItem) if success
    """
    custID = custData.get('id', None)
    custType = custData.get('custType', None)
    value = custData.get('value', None)
    vehTypeCompDescr = custData.get('vehTypeCompDescr', None)
    if custID is None:
        return (False, 'Cust id is not specified')
    elif not custType:
        return (False, 'Cust type is not specified')
    else:
        custTypeId = getattr(CustomizationType, str(custType).upper(), None)
        if not custTypeId:
            return (False, 'Invalid customization type')
        elif value == 0 or not isinstance(value, int):
            return (False, 'Invalid value')
        c20cache = vehicles.g_cache.customization20()
        c11nItems = c20cache.itemTypes[custTypeId]
        c11nItem = c11nItems.get(custID)
        if not c11nItem:
            return (False, 'Invalid customization item id')
        if vehTypeCompDescr is not None:
            itemTypeID, vehNationID, vehInnationID = vehicles.parseIntCompactDescr(
                vehTypeCompDescr)
            if itemTypeID != ITEM_TYPES.vehicle:
                return (False, 'Invalid type compact descriptor')
            try:
                vehTypeDescr = vehicles.g_cache.vehicle(
                    vehNationID, vehInnationID)
            except:
                LOG_CURRENT_EXCEPTION()
                return (False, 'Invalid type compact descriptor')

            if not c11nItem.matchVehicleType(vehTypeDescr):
                return (
                    False,
                    'Customization item {} and vehTypeCompDescr {} mismatch'.
                    format(c11nItem.id, vehTypeCompDescr))
        return (True, c11nItem)
示例#50
0
 def _showMessage(self,
                  scope,
                  msg,
                  itemCD,
                  msgType=SystemMessages.SM_TYPE.Error,
                  **kwargs):
     itemTypeID, nationID, itemID = vehicles.parseIntCompactDescr(itemCD)
     if itemTypeID == _VEHICLE:
         key = scope('vehicle', msg)
         kwargs['userString'] = vehicles.getVehicleType(itemCD).userString
     else:
         key = scope('item', msg)
         kwargs.update({
             'typeString':
             getTypeInfoByIndex(itemTypeID)['userString'],
             'userString':
             vehicles.getDictDescr(itemCD)['userString']
         })
     SystemMessages.pushMessage(i18n.makeString(key, **kwargs),
                                type=msgType)
示例#51
0
    def buyAndInstallItem(self, itemCD, state, inInventory=False):
        itemTypeID, nationID, itemID = vehicles.parseIntCompactDescr(itemCD)
        raise itemTypeID in _RESEARCH_ITEMS or AssertionError
        oldStyleVehicle = self._data.getInvItem(self._data.getRootCD())
        if not oldStyleVehicle is not None:
            raise AssertionError, 'Vehicle has be in inventory'
            eqs = functions.findConflictedEquipments(itemCD, itemTypeID,
                                                     oldStyleVehicle)
            item = g_itemsCache.items.getItemByCD(itemCD)
            vehicle = g_itemsCache.items.getItemByCD(self._data.getRootCD())
            if not inInventory:
                Waiting.show('buyItem')
                buyResult = yield ModuleBuyer(item,
                                              count=1,
                                              buyForCredits=True,
                                              conflictedEqs=eqs,
                                              install=True).request()
                if len(buyResult.userMsg):
                    SystemMessages.g_instance.pushI18nMessage(
                        buyResult.userMsg, type=buyResult.sysMsgType)
                Waiting.hide('buyItem')
            else:
                RequestState.sent(state)
            item = g_itemsCache.items.getItemByCD(itemCD)
            if item is not None and item.isInInventory:
                Waiting.show('applyModule')
                result = yield getInstallerProcessor(vehicle, item).request()
                success = result.success
                if result and result.auxData:
                    for m in result.auxData:
                        SystemMessages.g_instance.pushI18nMessage(
                            m.userMsg, type=m.sysMsgType)

                if result and len(result.userMsg):
                    SystemMessages.g_instance.pushI18nMessage(
                        result.userMsg, type=result.sysMsgType)
                success and itemTypeID in (_GUN,
                                           _TURRET) and self.tryLoadShells()
            Waiting.hide('applyModule')
        RequestState.received(state)
        return
示例#52
0
    def __parseCDs(self):
        cache()
        from items import vehicles, ITEM_TYPE_NAMES
        err = ''
        results = []
        for intCD in self._intCDs.getValue():
            try:
                itemTypeID, nationID, vehID = vehicles.parseIntCompactDescr(
                    intCD)
                item = vehicles.getItemByCompactDescr(intCD)
            except Exception as e:
                err += '{}: {}\n'.format(intCD, e)
                results.append(err)
                continue

            results.append('{} {} {}\n'.format(
                intCD,
                (nations.NAMES[nationID], ITEM_TYPE_NAMES[itemTypeID], vehID),
                item.name))

        return (results, err)
示例#53
0
    def invoke(self, content, varID):
        self._gui.showWaiting('request-item-params')
        itemCD = self.getVar(varID)
        if itemCD is None:
            return
        itemTypeID, nationID, compTypeID = vehicles.parseIntCompactDescr(itemCD)
        assert itemTypeID != ITEM_TYPE_NAMES[1]
        try:
            guiItem = InventoryItem(itemTypeName=ITEM_TYPE_NAMES[itemTypeID], compactDescr=itemCD)
            content['itemTypeName'] = guiItem.itemTypeName
            content['itemLevel'] = guiItem.level
            params = guiItem.getParams(g_currentVehicle.item)
            itemParams = []
            for param in params['parameters']:
                itemParams.extend(param)

            content['itemParams'] = itemParams
        except Exception:
            LOG_CURRENT_EXCEPTION()

        self._gui.hideWaiting('request-item-params')
示例#54
0
 def installItem(self, itemCD, rootCD, state):
     itemTypeID, _, __ = vehicles.parseIntCompactDescr(itemCD)
     if itemTypeID not in GUI_ITEM_TYPE.VEHICLE_MODULES:
         raise SoftException('Specified type (itemTypeID={}) is not type of module'.format(itemTypeID))
     vehicle = self.itemsCache.items.getItemByCD(rootCD)
     if not vehicle.isInInventory:
         raise SoftException('Vehicle (intCD={}) must be in inventory'.format(rootCD))
     item = self.itemsCache.items.getItemByCD(itemCD)
     conflictedEqs = item.getConflictedEquipments(vehicle)
     RequestState.sent(state)
     if item.isInInventory:
         Waiting.show('applyModule')
         result = yield getInstallerProcessor(vehicle, item, conflictedEqs=conflictedEqs, skipConfirm=self.skipConfirm).request()
         processMsg(result)
         if result.success and item.itemTypeID in (GUI_ITEM_TYPE.TURRET, GUI_ITEM_TYPE.GUN):
             vehicle = self.itemsCache.items.getItemByCD(vehicle.intCD)
             yield tryToLoadDefaultShellsLayout(vehicle)
         Waiting.hide('applyModule')
     RequestState.received(state)
     yield lambda callback=None: callback
     return
示例#55
0
def validateCustomizationItem(custData):
    custID = custData.get('id', None)
    splitted = custData.get('custType', '').split(':')
    custType = splitted[0]
    isProgression = len(splitted) == 2 and splitted[1] == 'progression'
    value = custData.get('value', None)
    vehTypeCompDescr = custData.get('vehTypeCompDescr', None)
    if custID is None:
        return (False, 'Cust id is not specified')
    elif not custType:
        return (False, 'Cust type is not specified')
    elif not isinstance(value, int) or value == 0 and not isProgression:
        return (False, 'Invalid value')
    else:
        c11nItem, errStr = getCustomizationItem(custType, custID)
        if not c11nItem:
            return (False, errStr)
        elif custType == CustomizationType.STYLE and 'serialNumberSequence' in custData and not c11nItem.isWithSerialNumber:
            return (
                False,
                'Only styles with serial numbers can have serialNumberSequence'
            )
        if vehTypeCompDescr is not None:
            itemTypeID, vehNationID, vehInnationID = vehicles.parseIntCompactDescr(
                vehTypeCompDescr)
            if itemTypeID != ITEM_TYPES.vehicle:
                return (False, 'Invalid type compact descriptor')
            try:
                vehTypeDescr = vehicles.g_cache.vehicle(
                    vehNationID, vehInnationID)
            except:
                LOG_CURRENT_EXCEPTION()
                return (False, 'Invalid type compact descriptor')

            if not c11nItem.matchVehicleType(vehTypeDescr):
                return (
                    False,
                    'Customization item {} and vehTypeCompDescr {} mismatch'.
                    format(c11nItem.id, vehTypeCompDescr))
        return (True, c11nItem)
示例#56
0
 def buyAndInstallItem(self, itemCD, rootCD, state):
     itemTypeID, _, __ = vehicles.parseIntCompactDescr(itemCD)
     if itemTypeID not in GUI_ITEM_TYPE.VEHICLE_MODULES:
         raise SoftException(
             'Specified type (itemTypeID={}) is not type of module'.format(
                 itemTypeID))
     vehicle = self.itemsCache.items.getItemByCD(rootCD)
     if not vehicle.isInInventory:
         raise SoftException(
             'Vehicle (intCD={}) must be in inventory'.format(rootCD))
     item = self.itemsCache.items.getItemByCD(itemCD)
     conflictedEqs = item.getConflictedEquipments(vehicle)
     if not self._mayObtainForMoney(
             item) and self._mayObtainWithMoneyExchange(item):
         isOk, _ = yield DialogsInterface.showDialog(
             ExchangeCreditsSingleItemMeta(itemCD, vehicle.intCD))
         if not isOk:
             return
     if self._mayObtainForMoney(item):
         Waiting.show('buyAndInstall')
         vehicle = self.itemsCache.items.getItemByCD(rootCD)
         gunCD = getGunCD(item, vehicle)
         result = yield BuyAndInstallItemProcessor(
             vehicle,
             item,
             0,
             gunCD,
             conflictedEqs=conflictedEqs,
             skipConfirm=self.skipConfirm).request()
         processMsg(result)
         if result.success and item.itemTypeID in (GUI_ITEM_TYPE.TURRET,
                                                   GUI_ITEM_TYPE.GUN):
             item = self.itemsCache.items.getItemByCD(itemCD)
             vehicle = self.itemsCache.items.getItemByCD(rootCD)
             if item.isInstalled(vehicle):
                 yield tryToLoadDefaultShellsLayout(vehicle)
         Waiting.hide('buyAndInstall')
     RequestState.received(state)
     yield lambda callback=None: callback
     return
示例#57
0
    def invoke(self, content, varID):
        self._gui.showWaiting('request-item-params')
        itemCD = self.getVar(varID)
        if itemCD is None:
            return
        else:
            itemTypeID, nationID, compTypeID = vehicles.parseIntCompactDescr(
                itemCD)
            raise itemTypeID != ITEM_TYPE_NAMES[1] or AssertionError
            try:
                guiItem = game_vars.getItemByIntCD(itemCD)
                content['itemTypeName'] = guiItem.itemTypeName
                content['itemLevel'] = guiItem.level
                params = guiItem.getParams(g_currentVehicle.item).get(
                    'parameters', dict())
                content['itemParams'] = formatters.getFormattedParamsList(
                    g_currentVehicle.item.descriptor, params)
            except Exception:
                LOG_CURRENT_EXCEPTION()

            self._gui.hideWaiting('request-item-params')
            return
示例#58
0
 def _validateItem2Unlock(self, unlockCD, vehCD, unlockIdx, xpCost):
     itemTypeID, nationID, itemID = vehicles.parseIntCompactDescr(vehCD)
     if itemTypeID != _VEHICLE:
         LOG_ERROR('Int compact descriptor is not for vehicle', vehCD)
         return False
     if not self._data.isUnlocked(vehCD):
         LOG_ERROR('Vehicle is not unlocked', unlockCD, vehCD)
         return False
     if self._data.isUnlocked(unlockCD):
         self._showAlreadyUnlockedMsg(vehCD)
         return False
     if not self._data.isNext2Unlock(unlockCD):
         LOG_ERROR('Required items are not unlocked', unlockCD, vehCD)
         return False
     if max(self._data._accFreeXP, 0) + self._data.getVehXP(vehCD) < xpCost:
         LOG_ERROR('XP not enough for unlock', vehCD, unlockIdx, xpCost)
         return False
     if RequestState.inProcess('unlock'):
         SystemMessages.pushI18nMessage(
             '#system_messages:unlocks/in_processing',
             type=SystemMessages.SM_TYPE.Warning)
         return False
     return True
示例#59
0
    def __validateInventoryItem(self, type, errorCode):
        """
        Method validates inventory items' data.
        
        @param type: <int> type index of item
        @param errorCode: <CODES> code to return in error case
        
        @return: <CODES> eror code
        """
        for intCompactDescr in self.__inventory.getItems(type).iterkeys():
            try:
                vehicles.getDictDescr(intCompactDescr)
            except Exception:
                item_type_id, nationIdx, innation_id = vehicles.parseIntCompactDescr(
                    intCompactDescr)
                LOG_ERROR(
                    'There is exception while validation item (%s)' %
                    ITEM_TYPE_NAMES[type], intCompactDescr,
                    (item_type_id, nationIdx, innation_id))
                LOG_CURRENT_EXCEPTION()
                return errorCode

        return self.CODES.OK
示例#60
0
def commanderTutorXpBonusFactorForCrew(crew, ammo):
    tutorLevel = component_constants.ZERO_FLOAT
    haveBrotherhood = True
    for t in crew:
        if t.role == 'commander':
            tutorLevel = t.skillLevel('commander_tutor')
            if not tutorLevel:
                return component_constants.ZERO_FLOAT
        if t.skillLevel('brotherhood') != MAX_SKILL_LEVEL:
            haveBrotherhood = False

    skillsConfig = getSkillsConfig()
    if haveBrotherhood:
        tutorLevel += skillsConfig.getSkill('brotherhood').crewLevelIncrease
    equipCrewLevelIncrease = component_constants.ZERO_FLOAT
    cache = vehicles.g_cache
    for compDescr, count in AmmoIterator(ammo):
        itemTypeIdx, _, itemIdx = vehicles.parseIntCompactDescr(compDescr)
        if itemTypeIdx == ITEM_TYPES.equipment:
            equipCrewLevelIncrease += getattr(cache.equipments()[itemIdx], 'crewLevelIncrease', component_constants.ZERO_FLOAT)

    tutorLevel += equipCrewLevelIncrease
    return tutorLevel * skillsConfig.getSkill('commander_tutor').xpBonusFactorPerLevel